標籤:c++
Problem DescriptionRecently, 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”.
InputThe 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).
OutputFor 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題意: 有n個人 然後下面有n行(i) 每行有n個數字 如果第j個數字為1,表示i對j有好感,判斷這些關係中是否有三角戀代碼:#include <stdio.h>#include <string.h>int t,n;//儲存的是節點的入度int in_degree[2010];//儲存的是i,j兩個節點的關係,1:i love j,0:j love ichar adj_mat[2010][2010];int main(){ bool flag;//true表示為有三角戀,false表示為沒有三角戀 scanf("%d",&t); for(int i = 1; i <= t;i++) { scanf("%d",&n); flag = false; //將所有的節點入度初始化為0 memset(in_degree,0,sizeof(in_degree)); for(int j = 0; j < n; j++) { scanf("%s",adj_mat[j]); for(int k=0;k<n;k++) if(adj_mat[j][k]=='1')//如果j喜歡k,則把k的入度加1 in_degree[k]++; } for(int j=0;j<n;j++) { int k; for(k=0;k<n;k++) if(in_degree[k]==0)break;//找出入度為0的節點 if(k==n)//任何一個節點的入度都不為0,說明存在環了,則必有三角戀 { flag = true; break; }else{ //將這個點的入度設為-1,避免再次迴圈時有查到了這個節點, //此時說明這個點已經從集合中除掉了 in_degree[k]--; for(int p=0;p<n;p++) { //把從這個節點出發的引起的節點的入度都減去1 if(adj_mat[k][p]=='1'&&in_degree[p]!=0) in_degree[p]--; } } } if(flag) printf("Case #%d: Yes\n",i); else printf("Case #%d: No\n",i); } return 0;}