做了2h,可见,对图的掌握还是不够。。。。
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 Input
3 2 3
1 2
1 3
1 2 3
Sample Output
1
0
0
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define INF 0x3f3f3f
#define MAXCITIES 2001
bool visited[MAXCITIES];
int map[MAXCITIES][MAXCITIES];
void DFS(int start, int numOfCity);
void DFS(int start, int numOfCity)
{
if(visited[start])
{
return;
}
else
{
//printf("checking %d\n", start);
visited[start] = true;
int i;
for(i=1; i<=numOfCity; i++)
{
if(visited[i]==false && map[start][i]==1)
{
DFS(i, numOfCity);
}
}
}
}
int main()
{
int numOfCity, numOfEdge, numOfChkPt;
int i, j;
scanf("%d %d %d", &numOfCity, &numOfEdge, &numOfChkPt);
/**< 初始化边map[][] */
for(i=1; i<=numOfCity; i++)
{
for(j=0; j<numOfCity; j++)
map[i][j] = -INF;
}
/**< 读入边 */
for(i=0; i<numOfEdge; i++)
{
int a, b;
scanf("%d %d", &a, &b);
map[a][b] = 1;
map[b][a] = 1;
}
/**< 读入要检查的城市,并输出结果 */
for(i=0; i<numOfChkPt; i++)
{
/**< 初始化visited */
for(j=1; j<=numOfCity; j++)
{
visited[j] = false;
}
int checkCity;
int cnt = 0;
scanf("%d", &checkCity);
visited[checkCity] = true;/**< 将要访问的城市标记为已访问,当作被占领 */
/**< 遍历所有城市 */
for(j=1; j<=numOfCity; j++)
{
if(!visited[j])
{/**< 若未访问,则开始DFS,若然所有城市都是通路,理应除开始城市,其他城市都被标记为已访问了,所以cnt==1 */
/**< 但实际上cnt那个1是起点,所以需要在最后减去1 */
//printf("%d isnt visited\n", j);
cnt++;
DFS(j, numOfCity);
}
}
printf("%d\n", cnt-1);
}
system("pause");
}