题目要求
翻译
在战争中,所有的城市都通过高速公路连接在一起,这一点是至关重要的。如果一个城市被敌人占领了,那么所有连接这个城市的高速公路都会被封闭。我们必须马上知道为了使得余下的城市保持连接状态,我们是否需要修建其他的高速公路。给你一张城市地图,上面标识出了所有余下的高速公路,你需要快速说出需要修建的高速公路的数量。
举个例子,如果我们有3座城市,2条高速公路分别连接city1-city2、city1-city3。如果city1被敌人占领了,我们就需要修建一条高速公路,那就是city2-city3。
输入格式:
每个输入文件包含一个测试用例。对每个测试用例,第一行包含3个数字:N(<= 1000)表示城市总数量,M表示高速公路数量,K表示需要检查的城市数量。接下来的M行,每行用2个整数描述一条高速公路,这2个整数分别代表这条高速公路所连接的两个城市的编号。城市编号从1到N。最后一行有K个数字,代表了我们关注的城市。
输出格式:
对K个城市中的每一个城市,分别在1行中输出如果该城市被敌人占领所需要修建的高速公路的数量。
输入样例:
3 2 3
1 2
1 3
1 2 3
输出样例:
1
0
0
代码
// https://blog.csdn.net/qq_41231926/article/details/83511340
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int city1,city2;
vector<int> graph[1001];
bool visited[1001];
int count,lost_city;
void dfs(int now);
int main()
{
int N,M,K;
int count;
cin>>N>>M>>K;
for(int i=0;i<M;i++)
{
scanf("%d %d",&city1,&city2);
graph[city1].push_back(city2);
graph[city2].push_back(city1);
}
for(int i=0;i<K;i++)
{
fill(visited+1,visited+N+1,false);
count=0;
scanf("%d",&lost_city);
for(int j=1;j<=N;j++)
{
if(j==lost_city) continue;
if(!visited[j])
{
dfs(j);
count++;
}
}
cout<<count-1<<endl;
}
system("pause");
}
void dfs(int now)
{
visited[now]=true;
for(int i=0;i<graph[now].size();i++)
{
int v=graph[now][i];
if(!visited[v]&&v!=lost_city)
{
dfs(v);
}
}
}
思路
使用图的深度优先遍历,主要避开被占领的城市即可。