拓补排序

来源:互联网 发布:腾讯抄袭知乎 编辑:程序博客网 时间:2024/04/29 01:32

                                               Triangle LOVE

                                                     Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
                                                                         Total Submission(s): 3922    Accepted Submission(s): 1547


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
 

题目大意:给出你全部人的关系,让你判断一下是否存在三角恋。T组测试数据,每组数据一个n,表示n个人。接下来n*n的矩阵表示这些人之间的关系,输入一定满足若A喜欢B则B一定不喜欢A,且不会出现A,B互相喜欢的情况,问你这些人中是否存在三角恋,若存在输出“Yes“,否则输出”No“。

 

题目解析:此题运用拓扑排序很容易就做出来,就是找入度为零的点,放入队列用队列来实现。可以用一遍拓扑排序判环求解,即只需找到一个环就必定存在三元环。


AC代码:#include<cstdio>#include<cstring>#include<cstdlib>char map[2010][2010]; //存储A和B的关系 int indegree[2010]; //记录节点入度数 int T,n;int main(){bool flage; //true表示有三角恋,false表示没有三角恋 scanf("%d",&T);for(int k=1;k<=T;k++){    scanf("%d",&n);flage=false; memset(indegree,0,sizeof(indegree)); //将所有节点的入度初始化为0 for(int i=0;i<n;i++){scanf("%s",map[i]);    for(int j=0;j<n;j++)    if(map[i][j]=='1') //如果i喜欢j则把j的入度加1     indegree[j]++;}    for(int j=0;j<n;j++)    {        int d;        for(d=0;d<n;d++)        if(indegree[d]==0) //找出入度为0的点并跳出循环    break;            if(d==n) //任何一个节点的入度都不为零,说明存在环则必有三角恋          {    flage=true;     break;       }    else     {    indegree[d]--;//将这个点的入度设为-1,避免再次循环时又查到这个点    for(int m=0;m<n;m++)            {              if(map[d][m]=='1')               indegree[m]--;//把从这个节点出发的引起的节点的入度都减去1            }            }        }    if(flage)      printf("Case #%d: Yes\n",k);        else          printf("Case #%d: No\n",k); }return 0;}



0 0
原创粉丝点击