您的位置:首页 > 其它

hdu 5154 Harry and Magical Computer(拓扑排序,dfs判环)

2015-01-03 22:13 309 查看
[align=left]Problem Description[/align]
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.

[align=left]Input[/align]
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.1≤n≤100,1≤m≤10000

The next following m lines, each line contains two numbers a b, indicates a dependencies (a, b).1≤a,b≤n

[align=left]Output[/align]
Output one line for each test case.

If the computer can finish all the process print "YES" (Without quotes).

Else print "NO" (Without quotes).

[align=left]Sample Input[/align]

3 2
3 1
2 1
3 3
3 2
2 1
1 3


[align=left]Sample Output[/align]

YES
NO

拓扑排序


#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
int n,m;
bool map[101][101];
int degree[110];
bool topsort()
{
int i,j;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(map[i][j])
degree[j]++;
}
}
int k;
for( i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(degree[j]==0)
{
k=j;
break;
}
}
degree[j]=-1;
if(j==n+1)
return false;
for(j=1;j<=n;j++)
{
if(map[k][j])
degree[j]--;
}
}
return true;
}
int main()
{
int i;
while(scanf("%d%d",&n,&m)!=EOF)
{
int a,b;
memset(map,false,sizeof(map));
memset(degree,0,sizeof(degree));
bool flag=true;
for(i=0;i<m;i++)
{
scanf("%d%d",&a,&b);
if(a==b)
{
flag=false;
}
map[a][b]=true;
}
if((flag && topsort() ))
printf("YES\n");
else
printf("NO\n");
}
return 0;
}


dfs 判环

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
bool map[101][101],flag;
int vis[101];  //3种状态,0表示还没有访问,1,表示正在访问,2表示访问结束
int n,m;
void dfs(int now)
{
vis[now]=1;
for (int i=1; i<=n && flag; i++)
{
if(map[now][i] && vis[i]==0)
{
map[now][i]=false;
dfs(i);
}
else if(vis[i]==1 && map[now][i])  //边没有被访问,但是结点正在访问中,则必然有环存在
{
flag=false;
return;
}
else if(vis[i]==2 && map[now][i])
{
map[now][i]=false;
}
}
vis[now]=2;
}
int main()
{
while (scanf("%d%d",&n,&m)!=EOF)
{
flag=true;
memset(map, false, sizeof(map));
memset(vis,0, sizeof(vis));
for (int i=0; i<m; i++)
{
int a,b;
scanf("%d%d",&a,&b);
map[a][b]=true;
}
for (int i=1; i<=n && flag; i++)
{
if(!vis[i])
dfs(i);
}
if (flag)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: