HDU 5154 Harry and Magical Computer(找环)

Harry and Magical Computer

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1743    Accepted Submission(s): 684


Problem Description
In reward of being yearly outstanding magic student, Harry gets a magical computer. When the computer begins to deal with a process, it will work until the ending of the processes. One day the computer got n processes to deal with. We number the processes from 1 to n. However there are some dependencies between some processes. When there exists a dependencies (a, b), it means process b must be finished before process a. By knowing all the m dependencies, Harry wants to know if the computer can finish all the n processes.
 

Input
There are several test cases, you should process to the end of file.
For each test case, there are two numbers n m on the first line, indicates the number processes and the number of dependencies.  1n100,1m10000
The next following m lines, each line contains two numbers a b, indicates a dependencies (a, b).  1a,bn
 

Output
Output one line for each test case. 
If the computer can finish all the process print "YES" (Without quotes).
Else print "NO" (Without quotes).
 

Sample Input
 
   
3 2 3 1 2 1 3 3 3 2 2 1 1 3
 

Sample Output
 
   
YES NO
 

Source
BestCoder Round #25
 

问题描述
作为年度优秀魔法学员的奖赏,哈利得到了一台具有魔力的计算机。这台计算机一旦开始处理某个任务,就会一直处理到这个任务结束为止(所以你可以认为它是单线程的)。有一天,这台计算机得到了n个任务要处理,分别标号1到n。这n个任务之间又有一些依赖关系,假如存在依赖关系(a, b),那么要处理a任务,必须先将b任务完成。现在哈利得到了所有的这些依赖关系,一共m个。他想知道,这台计算机能否完成所有的任务。
输入描述
多组输入数据
每组数据第一行由n m组成,分别代表任务数和依赖关系数。1 \leq n \leq 100, 1 \leq m \leq 100001n100,1m10000
接下来m行,每行两个数a b,表示一组依赖关系。1 \leq a, b \leq n1a,bn
输出描述
每组输出一行,"YES"(没有引号)表示能完成所有任务。
"NO"(没有引号)表示不能。
输入样例
3 2
3 1
2 1
3 3
3 2
2 1
1 3
输出样例
YES
NO

解题思路:如果存在任务不能完成,那么说明该任务既出现在某任务的前面又出现在某任务的后面,换句话说就是某些任务与该任务一起组成了一个环。用弗洛伊德算法,判断最后的邻接矩阵的对角线是否有1存在,如果有,说明存在环,否则没有。


代码如下:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define debug "output for debug\n"
#define pi (acos(-1.0))
#define eps (1e-6)
#define inf (1<<28)
#define sqr(x) (x) * (x)
#define mod 1000000007
using namespace std;
typedef long long ll;
typedef unsigned long long ULL;
int a[105][105];
int main()
{
    int i,j,k,n,m,x,y,t;
    while(~scanf("%d%d",&n,&m))
    {
        memset(a,0,sizeof(a));
        for(i=1;i<=m;i++)
        {
            scanf("%d%d",&x,&y);
            a[y][x]=1;
        }
        for(i=1;i<=n;i++)
        {
            for(j=1;j<=n;j++)
            {
                for(k=1;k<=n;k++)
                {
                    if(a[i][j]






你可能感兴趣的:(HDU,BC)