L2-010 排座位 (并查集

题目链接

解题思路:

并查集的应用

代码如下:

#include<iostream>
using namespace std;
const int maxn=500;
int f[maxn];
int a[maxn][maxn];
int find(int x)
{
	if(f[x]==x)
	  return x;
	else
	{
		f[x]=find(f[x]);
		return f[x];
	}
}
int hebing(int x,int y)
{
	x=find(x);
	y=find(y);
	if(x!=y)
	{
		f[y]=x;
	}
}
int main()
{
	int n,m,k,p;
	int xx,yy;
	int i;
	int x,y;
	cin>>n>>m>>k;
	for(i=1;i<=n;i++)
	  f[i]=i;
	for(i=0;i<m;i++)
	{
		cin>>x>>y>>p;
		a[x][y]=p;
		a[y][x]=p;
	    if(p==1)
	      hebing(x,y);
	}
	for(i=0;i<k;i++)
	{
		cin>>x>>y;
		xx=find(x);
		yy=find(y);//不加这两个不行 
		if(f[x]==f[y]&&a[x][y]!=-1)
		   cout<<"No problem"<<endl;
		if(f[x]!=f[y]&&a[x][y]!=-1)
		   cout<<"OK"<<endl;
		if(f[x]==f[y]&&a[x][y]==-1)
		   cout<<"OK but..."<<endl;
		if(f[x]!=f[y]&&a[x][y]==-1)
		   cout<<"No way"<<endl;
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值