人类正在经历一场生化危机,许多城市已经被病毒侵袭,这些城市中的人们为了避免感染病毒,计划开车逃往其他没有被病毒入侵的城市(安全城市)。有些城市之间有公路直达,有些没有。虽然他们知道哪些城市是安全的,但是不知道有没有一条安全路径能够到达安全城市(只有该路径上经过的所有城市都是安全的,该路径才是安全路径)。请你编写一个程序帮助他们判断。
输入格式:
输入第一行为三个正整数,分别表示所有城市个数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!
结尾无空行
目录
package M1;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
MatGraphClass G = new MatGraphClass();
System.out.println("输入城市的个数、安全城市的个数、路的个数");
int city = sc.nextInt();//城市个数
int n = sc.nextInt();//n个安全城市
int road = sc.nextInt();//路的个数
int safecity [] = new int[100];
for(int i =0;i<n;i++)
{
safecity [i] = sc.nextInt();
}
for(int i =0;i<city;i++)
{
for(int j =0;j < city;j++)
{
G.edges[i][j]=0;
}
}
for(int i =0;i<road;i++)
{
int x,y;
x = sc.nextInt();
y = sc.nextInt();
G.edges[x][y] = 1;//将有路的城市之间的值赋予1
G.edges[y][x] = 1;
}
int nowcity,des,flag =0;//现在所在的城市和目的地
nowcity = sc.nextInt();
des = sc.nextInt();
for(int i =0;i<n;i++)
{
if(des==safecity[i])//查询目的地是否为安全点,则做上标记
{
flag =1;
break;
}
}
if(G.edges[nowcity][des]==1)
{
if(flag==1)//是安全城市并且有通路
System.out.printf("The city %d can arrive safely!\n",des);
else //有通路但是不是安全城市
{
System.out.printf("The city %d is not safe!\n",des);
}
}
else
{
if(flag==1)
{
System.out.printf("The city %d can not arrive safely!\n",des);
}
else
System.out.printf("The city %d is not safe!\n",des);//不是安全城市也没有通路
}
}
}
package M1;
import java.util.*;
public class MatGraphClass
{
final int MAVX = 100;
final int INF = 0x3f3f3f3f;
int [] [] edges;
int n,e;//顶点数,边数
String [] vexs;
public MatGraphClass()
{
edges = new int[MAVX][MAVX];
vexs = new String [MAVX];
}
public void CreatMatGraph(int[][] a,int n,int e)
{
this.n =n;
this.e =e;
for(int i = 0;i < n; i++)
{
edges[i] = new int[n];
for(int j =0; j<n ; j++)
{
edges[i][j] = a[i][j];
}
}
}
}