拓扑排序的简单题,关键是证明当图有环必定存在三元环.
#include <iostream>
#include <cstdio>
#include <stack>
#include <cstring>
const int maxn = 2010;
using namespace std;
char mat[maxn][maxn];
int edge[maxn][maxn],ind[maxn],path[maxn];
bool toposort(int n){
int in[maxn];
stack<int> s;
memcpy(in,ind,sizeof(ind));
for(int i = 1; i <= n; ++i)
if(ind[i] == 0)
s.push(i);
if(s.empty()) return true;
int cnt = 0,temp;
while(!s.empty()){
temp = s.top();
s.pop();
path[cnt++] = temp;
for(int i = 1; i <= n; ++i)
if(edge[temp][i])
if(--ind[i] == 0)
s.push(i);
}
if(cnt != n) return true;
return false;
}
int main()
{
int t,cas = 0;
scanf("%d",&t);
while(t--){
int n;
scanf("%d",&n);
memset(ind,0,sizeof(ind));
memset(edge,0,sizeof(edge));
for(int i = 1; i <= n; ++i)
scanf("%s",mat[i]+1);
for(int i = 1; i <= n; ++i)
for(int j = 1; j <= n; ++j)
if(mat[i][j] == '1'){
ind[j]++;
edge[i][j] = 1;
}
if(toposort(n)) printf("Case #%d: Yes\n",++cas);
else printf("Case #%d: No\n",++cas);
}
return 0;
}