题目链接:Triangle LOVE (http://acm.hdu.edu.cn/showproblem.php?pid=4324)
题目描述:
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.
大意:最近,科学家发现两个人之间有爱。例如,在A和B之间,如果A不爱B,那么B必须爱A,反之亦然。两个人相爱是不可能的,这是一个多么疯狂的世界!
现在,科学家们想知道N人之间是否存在“三角恋”。三角恋爱是指任何三个人(A,B和C),A爱B,B爱C和C爱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
一道英文题,题目意思还算好理解,就是判断给定的图有没有形成环,若形成环则为三角恋(多角恋也是,不过题目应该不会给出多角恋的情况),正好刚复习了拓扑排序,进行拓扑排序,若可以完成排序,则证明是无环的,即没有三角恋。
若是有环,则为三角恋。
但是这道题却坑了我好久,能有一个多小时了吧....在后面归纳下进去的那些坑。
先贴上交了不下10遍终于AC的代码:
#include <stdio.h>
#include <memory.h>
#include<stdbool.h>
#define MAXV 2010
char map[MAXV][MAXV];
int indegree[MAXV];
int cnt=0;
void topo_sort(int n)
{
int i,j,k;
for(i=0; i<n; i++)
{
for(j=0; j<n; j++)
{
if(indegree[j]==0)
{
break;
}
}
if(j==n)
{
return;
}
else
{
indegree[j]--;
cnt++;
for(k=0; k<n; k++)
{
if(map[j][k]=='1'&&indegree[k]!=0)
indegree[k]--;
}
}
}
}
int main()
{
int t;
scanf("%d",&t);
int q;
for(q=1;q<=t;q++)
{
cnt=0;
memset(map,0,sizeof(map));
memset(indegree,0,sizeof(indegree));
int n;
scanf("%d",&n);
int i,j;
for(i=0; i<n; i++)
{
scanf("%s",map[i]);
for(j=0; j<n; j++)
if(map[i][j]=='1')
indegree[j]++;
}
topo_sort(n);
if(cnt!=n)
printf("Case #%d: Yes\n",q);
else
printf("Case #%d: No\n",q);
}
return 0;
}
一开始用数组储存的邻接矩阵,但总是
Time Limit Exceeded。
于是换成char型数组进行存储,可还是存在着一些问题。
for(j=0; j<n; j++)
{
if(indegree[j]==0)
{
break;
}
}
if(j==n)
{
return;
}
这里,当当前顶点入度等于0时,先直接break,而不是继续减小它指向点的入度。
还有最坑最坑的一点就是输出格式了,Case # 后面的数字竟然代表的是当前的组数(其实很容易就可以看出来),但我却把它当成了常量1和2,,,殊不知后面可能还有34567.......
其实人家最后一句英文也有些提示Take the sample output for more details,可完全被忽略了。
正逢四级考试将至,还是抓紧学英语吧!!!