Triangle LOVE

来源:互联网 发布:隐形眼镜推荐 知乎 编辑:程序博客网 时间:2024/05/23 10:24
Problem Description
Recently, scientists find that there is love between any of two people. For example, between A and B, if A don’t love B, then B must love A, vice versa. And there is no possibility that two people love each other, what a crazy world!
Now, scientists want to know whether or not there is a “Triangle Love” among N people. “Triangle Love” means that among any three people (A,B and C) , A loves B, B loves C and C loves A.
  Your problem is writing a program to read the relationship among N people firstly, and return whether or not there is a “Triangle Love”.
 

Input
The first line contains a single integer t (1 <= t <= 15), the number of test cases.
For each case, the first line contains one integer N (0 < N <= 2000).
In the next N lines contain the adjacency matrix A of the relationship (without spaces). Ai,j = 1 means i-th people loves j-th people, otherwise Ai,j = 0.
It is guaranteed that the given relationship is a tournament, that is, Ai,i= 0, Ai,j ≠ Aj,i(1<=i, j<=n,i≠j).
 

Output
For each case, output the case number as shown and then print “Yes”, if there is a “Triangle Love” among these N people, otherwise print “No”.
Take the sample output for more details.
 

Sample Input
25001001000001001111011100050111100000010000110001110
 

Sample Output
Case #1: YesCase #2: No题解:用队列来做。不然超时。
#include <iostream>#include <cstdio>#include <cstring>#include <queue>#include <vector>using namespace std;vector<int> map[2005];int indegree[2005];bool topoSort(int n){queue<int> q;for(int i = 0;i < n;i++){if(0 == indegree[i]){q.push(i);}}int k = 0;while(!q.empty()){int t = q.front();q.pop();indegree[t]--;k++;for(int i = 0;i < map[t].size();i++){indegree[map[t][i]]--;if(indegree[map[t][i]] == 0){q.push(map[t][i]);}}}if(k == n){return false;}return true;}int main(){int t;cin>>t;int k = 1;while(t--){    memset(indegree,0,sizeof(indegree));int n;scanf("%d",&n);char s[2005];for(int i = 0;i < n;i++){scanf("%s",s);for(int k = 0;k < n;k++){if(s[k] == '1'){map[i].push_back(k);indegree[k]++;}}}printf("Case #%d: ",k++);if(topoSort(n)){printf("Yes\n");}else{printf("No\n");}for(int i = 0;i < n;i++){map[i].clear();}}return 0;}


二维数组(超时):

#include <iostream>#include <cstdio>#include <cstring>#include <queue>using namespace std;char map[2005][2005];int indegree[2005];bool topoSort(int n){for(int i = 1;i <= n;i++){int k = -1;for(int j = 1;j <= n;j++){if(indegree[j] == 0){k = j;indegree[j]--;break;}}if(-1 == k){return true;}for(int j = 1;j <= n;j++){if(map[k][j] == '1'){indegree[j]--;}}}return false;}int main(){int t;cin>>t;int k = 1;while(t--){    memset(indegree,0,sizeof(indegree));int n;scanf("%d",&n);for(int i = 1;i <= n;i++){for(int j = 1;j <= n;j++){scanf("%s",map[i]);if(map[i][j] == '1'){    indegree[j]++;}}}printf("Case #%d: ",k++);if(topoSort(n)){printf("Yes\n");}else{printf("No\n");}}return 0;}


0 0
原创粉丝点击