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 Specification:
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 Specification:
For each of the K cities, output in a line the number of highways need to be repaired if that city is lost.
Sample Input:
3 2 3
1 2
1 3
1 2 3
Sample Output:
1
0
0
-------------------------------------这是题目和解题的分割线 -------------------------------------
求删除顶点后需要增加几条边,才能使图变为连通的。 也就是删除顶点后,连通块-1。(当然这不是我想出来的是书上的= =
#include<cstdio>
#include<cstring>
using namespace std;
#define maxN 1010
int n,m,k,nowCut;
int G[maxN][maxN] = {},vis[maxN] = {};
//连通块的遍历
void dfs(int index)
{
if(index==nowCut) return; //碰到要删除的点,return
vis[index] = 1; //访问
for(int i=1;i<=n;i++)
{
if(G[index][i]&&!vis[i])
dfs(i);
}
}
//图的遍历
int DFSTravel()
{
int i,cnt = 0;
//from 1 to N
for(i=1;i<=n;i++)
{
//如果没访问过该点,且不是要删除的点
if(!vis[i]&&i!=nowCut)
{
dfs(i); //遍历该连通块
cnt++; //连通块+1
}
}
return cnt;
}
int main()
{
int i,a,b;
scanf("%d%d%d",&n,&m,&k);
for(i=0;i<m;i++)
{
scanf("%d%d",&a,&b);
G[a][b] = 1;
G[b][a] = 1;
}
int qy;
for(i=0;i<k;i++)
{
memset(vis,0,sizeof(vis)); //清除上一次的访问痕迹
scanf("%d",&qy);
nowCut = qy; //全局变量nowCut记录当前删除的顶点
int out = DFSTravel();
printf("%d\n",out-1); //连通块-1
}
return 0;
}