http://pat.zju.edu.cn/contests/pat-a-practise/1013
It is vitally important to have all cities connected by highways in a war. If A is occupied by the enemy, all the highways From/toward this city are closed. We must know immediately if we need to repair any other highways to keep the rest of the cities. Given the map of cities which have all 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, which 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 Remaining highways, and the number of cities to is checked, respectively. Then M lines Follow, each describes a highway by 2 integers, which are the numbers the cities the highway. 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 this is lost. Sample Input
3 2 3
1 2 1 3 1 2 3
Sample Output
1
0
0
Use and check the connection graph to process:
#include <cstdio>
int tree[1000];
int findRoot (int x) {
if (tree[x] = = 1) return x;
else{
int tmp = FindRoot (tree[x]);
TREE[X] = tmp;
return tmp;
}
}
struct w{
int x;
int y;
} WAY[500000];
int main () {
int n, m, K;
scanf ("%d%d%d", &n, &m, &k);
for (int i = 0; i < m i++) {
scanf ("%d%d", &way[i].x, &WAY[I].Y);
}
while (k--) {for
(int i = 1; I <= n; i++)
tree[i] =-1;
int C;
scanf ("%d", &c);
for (int i = 0; i < m; i++) {
if (way[i].x!= c && way[i].y!= c) {
Int. rx = FindRoot (way[i].x);
int ry = FindRoot (WAY[I].Y);
if (Rx!= ry) {
Tree[rx] = ry;
}} int group = 0;
for (int i = 1; I <= n; i++) {
if (tree[i] = = 1)
group++;
}
printf ("%d\n", group-2);
}
return 0;
}
DFS solution (also available with BFS):
#include <cstdio>
#include <cstring>
#define MAX 1000
int Edge[max][max];
int Visited[max];
int n, m, K;
void Dfs (int t) {
visited[t] = 1;
for (int i = 1; I <= n; ++i) {
if (!visited[i] && edge[i][t] = = 1)
dfs (i)
;
}
int main () {
scanf ("%d%d%d", &n, &m, &k);
int a, B;
for (int i = 0; i < m ++i) {
scanf ("%d%d", &a, &b);
EDGE[A][B] = 1;
Edge[b][a] = 1;
}
int C;
while (k--) {
int count = 0;
scanf ("%d", &c);
memset (visited, 0, sizeof (visited));
VISITED[C] = 1;
for (int i = 1; I <= n; ++i) {
if (visited[i] = = 0) {
dfs (i);
count++
}
}
printf ("%d\n", count-1);
}
return 0;
}