【再思考】1013. Battle Over Cities (25)

来源:互联网 发布:软件他电脑效果器 编辑:程序博客网 时间:2024/06/05 20:22

1013. Battle Over Cities (25)

时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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 31 21 31 2 3
Sample Output
100
这个题的思路是,求删除一个结点后,剩下的结点组成的集合是多少个(假设为n个),道路的数量即为n-1个
“算法其实就是DFS, 在图上去掉一个node, 求剩下的图的连通component, 有多少个连通的component(设有T个connected component), 这个数目减一(T-1)就是需要加的边数. 至于为什么, 其实问一个更简单的问题就能理解了, 比如我们想使得T个孤立的点都连通, 也就是任意两点之间都有路径, 那么用T-1条边把他们连成一颗树是不是就行了? 同样道理, 题目中去掉一个节点(city)之后的每一个连通子图就是我们的孤立的点, 所以需要T-1条边. 找连通component利用dfs就可以了. DFS完所有剩下的node直到每个node都有一个自己的component id即可”
(出自http://tech-wonderland.net/blog/pat-1013-battle-over-cities.html)
这个题的代码,怎么着都不对劲,我也不知道到底是哪里出了问题。
#include<vector>#include <sstream>#include<cmath>#include<iomanip>#include<iostream>#include <ctype.h>#include <stdlib.h>#include <algorithm>#include <map>#include <utility>using namespace std;#define MAX 2000int N, M, K;int Citymap[MAX][MAX];int visit[MAX];void DFS(int strtn){int i;for (i = 1; i <= N; i++){if (i != strtn&&visit[i] == 0 && Citymap[strtn][i] == 1){visit[i] = 1;DFS(i);}}}int main(){int N, M, K;cin >> N >> M >> K;int x, y;memset(Citymap, 0, sizeof(Citymap));for (int i = 0; i < M; i++){cin >> x >> y;Citymap[x][y] = 1;Citymap[y][x] = 1;}int city;for (int i = 0; i < K; i++){cin >> city;memset(visit, 0, sizeof(visit));visit[city] = 1;int cnt = 0;for (int j = 1; j <= N; j++){if (visit[j] == 0){cnt++;DFS(j);}}cout << cnt-1 <<endl;}return 0;}

【参考链接】http://www.cnblogs.com/morgan-yuan/archive/2013/03/04/2943576.html
0 0
原创粉丝点击