HDU 4324 Triangle LOVE 拓扑排序

来源:互联网 发布:淘宝强行退款 编辑:程序博客网 时间:2024/05/19 16:02
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题意: 有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;}


0 0
原创粉丝点击