1013. Battle Over Cities (25)
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
在并查集union函数中,City[xx]=yy; 结果弄错为City[x]=yy;
评测结果
时间 | 结果 | 得分 | 题目 | 语言 | 用时(ms) | 内存(kB) | 用户 |
---|---|---|---|---|---|---|---|
7月16日 16:17 | 答案正确 | 25 | 1013 | C++ (g++ 4.7.2) | 227 | 4276 | datrilla |
#include<iostream> using namespace std; struct Roads { int c1,c2; }; void InprintRoads(long int M,Roads*Linkc) { for(int i=0;i<M;i++) { cin>>Linkc[i].c1>>Linkc[i].c2; } } int Find_set(int*City,int C) { if(C!=City[C]) City[C]=Find_set(City,City[C]); return City[C]; } void Union(Roads*Linkc,int*City,long int M,int Od) { long int i; int x,y,xx,yy; for(i=0;i<M;i++) { x=Linkc[i].c1; y=Linkc[i].c2; if(x!=Od&&y!=Od) { xx=Find_set(City,x); yy=Find_set(City,y); if(xx!=yy) { City[xx]=yy; } } } } void StarClear(int * City,int N) { while(N) City[N]=N--; City[N]=N; } int judge(int*City,int N) { int count=0; while(N) { if(City[N]==N--)count++; } if(count>2)return count-2; return 0; } int main() { int N,K,i; long int M; int *Occupied; Roads *Linkc; int *City; cin>>N>>M>>K; City=(int*)malloc((N+1)*sizeof(int)); Linkc=(Roads *)malloc(M*sizeof(Roads)); Occupied=(int*)malloc(K*sizeof(int)); InprintRoads(M,Linkc); for(i=0;i<K;i++) cin>>Occupied[i]; for(i=0;i<K;i++) { StarClear(City,N); Union(Linkc,City,M,Occupied[i]); cout<<judge(City,N)<<endl; } free(Linkc); free(City); free(Occupied); return 0; }