拓扑排序 2892. Task

本文介绍了一个简单的任务排序算法,用于判断一组任务是否可以按照特定约束条件完成。通过使用邻接矩阵和入度数组来记录任务之间的依赖关系,并采用拓扑排序的方法进行解决。

Peter is very interested in Artificial Intelligence. His teacher leaves him several problems. Since he is not very familiar with the subject, he will read some necessary information to complete the task. But unfortunately there are some constrains between the problems (that one problem must be done after another one). Please write a program to judge whether Peter can complete the task.

Input

There are several test cases in the input data. The first line contains the number of test cases. In each test case, the first line contains two positive integers n (1 ≤ n ≤ 20) and m (0 ≤ m ≤ 20), denoting that there are n problems and m constrains. Then there are m lines to describe the constrains, and each line contains two different integers i and j (1 ≤ i, j ≤ n), denoting that the problem j must be done after the problem i. (The problems' number starts at 1.)

Output

Please write a program to judge whether Peter can complete the task. If he can, please output "1"; otherwise output "0" instead.

Sample Input

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

Sample Output

1

0

#include<iostream>
#include<cstring>
#include<stack>
using namespace std;
int map[21][21],degree[21];
int main(){
	int t,m,n,count,a,b;
	cin>>t;
	while(t--)
	{
		cin>>n>>m;
		memset(map,0,sizeof(map));
		memset(degree,0,sizeof(degree));
		for(int i=1;i<=m;i++)
		{
			cin>>a>>b;
			map[a][b]=1;
			degree[b]++;
		}
		stack<int>s;
		for(int i=1;i<n;i++)
		{
			if(degree[i]==0)
				s.push(i);
		}
		if(s.empty())
		{
			cout<<"0"<<endl;
			continue;
		}
		count=0;
		while(!s.empty())
		{
			int temp=s.top();
			s.pop();
			count++;
			for(int i=1;i<=n;i++)
			{
				if(map[temp][i])
				{
					degree[i]--;
					if(degree[i]==0)
						s.push(i);
				}
			}
		}
		if(count==n)
			cout<<"1"<<endl;
		else
			cout<<"0"<<endl;
	}
	return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值