[ACM] POJ 3740 Easy Finding (DFS)

來源:互聯網
上載者:User

標籤:acm   dfs   


Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 16202   Accepted: 4349

Description

Given a M×N matrix A. Aij ∈ {0, 1} (0 ≤ i < M, 0 ≤ j < N), could you find some rows that let every cloumn contains and only contains one 1.

Input

There are multiple cases ended by EOF. Test case up to 500.The first line of input isM, N (M ≤ 16, N ≤ 300). The next M lines every line containsN integers separated by space.

Output

For each test case, if you could find it output "Yes, I found it", otherwise output "It is impossible" per line.

Sample Input

3 30 1 00 0 11 0 04 40 0 0 11 0 0 01 1 0 10 1 0 0

Sample Output

Yes, I found itIt is impossible

Source

POJ Monthly Contest - 2009.08.23, MasterLuo題意為:

給定由01構成的矩陣,問能不能選出幾行構成新矩陣,使得新矩陣每列有且只有一個1.

枚舉所有行,行號遞增,判斷每行是否可以選(是否與前面所選的行發生衝突),當前行可選時,第j列如果為1,則用vis[j]=1標記,當行號>n(行數)時,判斷每列是否都有1.

#include <iostream>#include <stdio.h>#include <string.h>const int maxn=18;const int maxm=310;int mp[maxn][maxm];bool vis[maxm];int n,m;bool yes;using namespace std;bool row_ok(int rth)//rth為行號,判斷第rth行可以選{    for(int j=1;j<=m;++j)        if(vis[j]&&mp[rth][j])//第j列已經有1了        return false;    for(int j=1;j<=m;++j)//可以選        if(mp[rth][j])            vis[j]=true;    return true;}bool judge()//當選的行號大於n時,判斷一下是不是每列都有1{    for(int j=1;j<=m;++j)        if(!vis[j])        return false;    return true;}void dfs(int rth){    if(rth>n+1)//因為當rth=n+1時,還需要判斷judge()        return;    if(judge())//注意這兩個if    {        yes=1;        return;    }    for(int i=rth;i<=n&&!yes;++i)    {        if(row_ok(i))        {            dfs(i+1);//注意這裡不是dfs(step+1),選的行號是遞增的            for(int j=1;j<=m;++j)//還原                if(mp[i][j])                    vis[j]=0;        }    }}int main(){    while(scanf("%d%d",&n,&m)!=EOF)    {        for(int i=1;i<=n;++i)            for(int j=1;j<=m;++j)                scanf("%d",&mp[i][j]);        memset(vis,0,sizeof(vis));        yes=0;        dfs(1);        if(yes)            printf("Yes, I found it\n");        if(!yes)            printf("It is impossible\n");    }    return 0;}


[ACM] POJ 3740 Easy Finding (DFS)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.