hdu 4324 Triangle LOVE
先进行拓扑排序,删除那些不会成环的节点。剩下的节点再重建一张图,进行DFS。
#include<cstdio> #include<cstring> #include<cmath> #include<string> #include<vector> #include<algorithm> using namespace std; const int maxn = 2000 + 5; int jz[maxn][maxn], rudu[maxn], flag[maxn]; vector<int>ljb[maxn]; int uu; char s[2005]; void dfs(int tott, int now,int tou) { int i; if (tott == 2) { if (jz[now][tou] == 1) uu = 1; return; } for (i = 0; i < ljb[now].size(); i++) { dfs(tott + 1, ljb[now][i], tou); if (uu == 1) return; } } int main() { int sb, bs; scanf("%d", &sb); for (bs = 1; bs <= sb; bs++) { int n, i, j; uu = 0; scanf("%d", &n); for (i = 0; i <= n; i++) ljb[i].clear(); memset(rudu, 0, sizeof(rudu)); memset(flag, 0, sizeof(flag)); for (i = 1; i <= n; i++) { scanf("%s", s); for (j = 1; j <= n; j++) { jz[i][j] = s[j - 1] - '0'; if (jz[i][j] == 1) { ljb[i].push_back(j); rudu[j]++; } } } int ff; while (1) { ff = 0; for (i = 1; i <= n; i++) { if (rudu[i] == 0) { ff = 1; rudu[i]--; for (j = 0; j < ljb[i].size(); j++) rudu[ljb[i][j]]--; } } if (ff == 0) break; } for (i = 1; i <= n; i++) if (rudu[i]>0) flag[i] = 1; for (i = 0; i <= n; i++) ljb[i].clear(); for (i = 1; i <= n; i++) { for (j = 1; j <= n; j++) { if (jz[i][j] == 1 && flag[i] == 1 && flag[j] == 1) { ljb[i].push_back(j); } } } for (i = 1; i <= n; i++) { if (flag[i] == 1) { uu = 0; dfs(0, i, i); if (uu == 1) break; } } printf("Case #%d: ", bs); if (uu == 1) printf("Yes\n"); else printf("No\n"); } return 0; }