Description
Input
Output
Sample Input
3 3 0 1 0 0 0 1 1 0 0 4 4 0 0 0 1 1 0 0 0 1 1 0 1 0 1 0 0
Sample Output
Yes, I found it It is impossible
这是一道子集枚举的回溯题,针对当前行选不选进行回溯,并且进行剪枝。
#include<iostream> #include<cstdio> #include<cstring> using namespace std; #define maxn 1005 int n,m; int a[20][305]; int vis[305]; bool judge(){ for(int i=0;i<n;i++) if(vis[i]==0)return false; return true; } bool judges(){ for(int i=0;i<n;i++) if(vis[i]>1)return false; return true; } bool dfs(int cur) { if(judge())return true; if(cur>=m)return judge(); for(int i=0;i<n;i++){ if(a[cur][i]==1)vis[i]++; } if(judges()){ if(dfs(cur+1))return true; } for(int i=0;i<n;i++){ if(a[cur][i]==1)vis[i]--; } if(dfs(cur+1))return true; return false; } int main() { //freopen("in.txt","r",stdin); while(scanf("%d%d",&m,&n)!=EOF){ for(int i=0;i<m;i++) for(int j=0;j<n;j++) scanf("%d",&a[i][j]); memset(vis,0,sizeof vis); if(dfs(0))puts("Yes, I found it"); else puts("It is impossible"); } }
原文地址:http://blog.csdn.net/u013497977/article/details/43229593