题目要求:
It is vitally important to have all the cities connected by highways in a war. If a city is occupied by the enemy, all the highways from/toward that city are closed. We must know immediately if we need to repair any other highways to keep the rest of the cities connected. Given the map of cities which have all the remaining highways marked, you are supposed to tell the number of highways need to be repaired, quickly.
For example, if we have 3 cities and 2 highways connecting city1-city2 and city1-city3. Then if city1 is occupied by the enemy, we must have 1 highway repaired, that is the highway city2-city3.
Input
Each input file contains one test case. Each case starts with a line containing 3 numbers N (<1000), M and K, which are the total number of cities, the number of remaining highways, and the number of cities to be checked, respectively. Then M lines follow, each describes a highway by 2 integers, which are the numbers of the cities the highway connects. The cities are numbered from 1 to N. Finally there is a line containing K numbers, which represent the cities we concern.
Output
For each of the K cities, output in a line the number of highways need to be repaired if that city is lost.
Sample Input3 2 3 1 2 1 3 1 2 3Sample Output
1 0 0分析:
其实这一题看起来很繁琐,其实不难,一个深搜就可以了。如有有不连通的区域,那么有几个不连通区域就需要几条新的highway。注意到第一次进行搜索的时候不连通区域不要多算了一个。
代码如下:
#include <stdio.h>
int city[1000][1000];
int visit[1000];
int check(int c,int n);
void init_v(int *v,int n);
int dfs(int r,int c,int n);
int main(int argc,char* argv[])
{
int i,j,n,m,k;
int c1,c2,count,c;
scanf("%d%d%d",&n,&m,&k);
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
city[i][j] = 0;
for(i=0;i<m;i++)
{
scanf("%d%d",&c1,&c2);
city[c1][c2] = 1;
city[c2][c1] = 1;
}
/*for(i=1;i<=n;i++)
printf("%d ",visit[i]);
printf("\n");*/
for(i=0;i<k;i++)
{
scanf("%d",&c);
count = check(c,n);
printf("%d\n",count);
}
return 0;
}
int check(int c,int n)
{
int i,count;
count = -1;
init_v(visit,n);
for(i=1;i<=n;i++)
{
if(i!=c && visit[i]==0)
{
count += 1;
visit[i] = 1;
dfs(i,c,n);
}
}
return count;
}
void init_v(int *v,int n)
{
int i;
for(i=1;i<=n;i++)
v[i] = 0;
}
int dfs(int r,int c,int n)
{
int i;
for(i=1;i<=n;i++)
{
if(city[i][r]!=0 && i!=c && !visit[i])
{
visit[i] = 1;
dfs(i,c,n);
}
}
}