pta 生化危机

人类正在经历一场生化危机,许多城市已经被病毒侵袭,这些城市中的人们为了避免感染病毒,计划开车逃往其他没有被病毒入侵的城市(安全城市)。有些城市之间有公路直达,有些没有。虽然他们知道哪些城市是安全的,但是不知道有没有一条安全路径能够到达安全城市(只有该路径上经过的所有城市都是安全的,该路径才是安全路径)。请你编写一个程序帮助他们判断。

输入格式:
输入第一行为三个正整数,分别表示所有城市个数m(m<=100)、安全城市个数n(m<=50)、公路个数k(k<=100)。随后一行给出n个安全城市的编号。随后k行,每一行给出两个整数,表示连接一条公路的两个城市编号。最后一行输入两个整数,分别表示当前所在城市s、目标城市d。每行整数之间都用空格分隔。

输出格式:
若目标城市已被病毒入侵(非安全城市),输出"The City i is not safe!";若目标城市为安全城市且从当前所在城市能够经过一条安全路径到达目标城市,输出"The city can arrive safely!";若目标城市为安全城市但是从当前所在城市没有一条安全路径到达目标城市,输出"The city can not arrive safely!",i为目标城市编号。

输入样例1:
5 2 5
3 4
0 1
0 2
0 4
1 2
2 4
0 4
输出样例1:
The city 4 can arrive safely!
输入样例2:
5 2 5
3 4
0 1
0 2
0 4
1 2
2 4
0 3
输出样例2:
The city 3 can not arrive safely!
输入样例3:
5 2 5
3 4
0 1
0 2
0 4
1 2
2 4
0 1
输出样例3:
The city 1 is not safe!

并查集无疑,开始纠结总是错。 正确思路:只把安全的路连在一起,特判一下初始和目的两个城市。

#include<stdio.h>
int pre[500];//根节点全为自己
int mark[500];
int find(int root)
{
	int son,tep;
	son=root;
	while(root!=pre[root]) root=pre[root];
	while(son!=root)
	{
		tep=pre[son];
		pre[son]=root;
		son=tep;
	}
	return root;
}
int main(void)
{
	int m,n,k;
	int safe_ci;
	int pos,dic;
	scanf("%d%d%d",&m,&n,&k);
	for(int i=0; i<=100; i++)
	{
		pre[i]=i;
	}
	for(int i=0; i<n; i++)
	{
		scanf("%d",&safe_ci);
		mark[safe_ci]=1;
	}
	int r1,r2;
	int city[102][3]={0}; 
	for(int i=1; i<=k; i++)
	{
		scanf("%d%d",&r1,&r2);
		city[i][1]=r1;
		city[i][2]=r2;
		if(mark[r1]&&mark[r2])
		{
			int roo1,roo2;
			roo1=find(r1);
			roo2=find(r2);
			if(roo1!=roo2)
			{
				pre[roo1]=roo2;
			}
		}
	}
	scanf("%d%d",&pos,&dic);
	int flag=0;
	if(mark[dic]) flag=1;
	if(flag==0) printf("The city %d is not safe!\n",dic);
	else
	{
		int flag1=0;
		for(int i=1;i<=k;i++)
		{
			if(city[i][1]==pos&&city[i][2]==dic||city[i][1]==dic&&city[i][2]==pos)
			{
				flag1=1;
				break;				
			}
		}
		if(flag1) printf("The city %d can arrive safely!\n",dic);
		else
		{
			int roo1,roo2;
			roo1=find(pos);
			roo2=find(dic);
			if(roo1==roo2)
			{
				printf("The city %d can arrive safely!\n",dic);
			}
			else printf("The city %d can not arrive safely!\n",dic);
		}
	}
	return 0;
}
  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值