1013. Battle Over Cities
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
ac代码:
//9:20start
#include<stdio.h>
#include<string.h>
int map[1010][1010],mapc[1010][1010];//mapc为map备份,用地恢复;
int i,j,k,m,n,p,q,a,b,father[1010],t,count=0;
void wipe(int p)
{
int pp;
for(pp=1;pp<=m;pp++)
{
map[p][pp]=0;
map[pp][p]=0;
}
}
int findfather(int af)
{
if(father[af]==af) return af;
else
{
father[af]=findfather(father[af]);
return father[af];
}
}
void un(int ai,int bi)
{
int fa=findfather(ai);
int fb=findfather(bi);
if(fa!=fb)
father[fa]=fb;
}
int main()
{
freopen("data.in","r",stdin);
memset(map,0,sizeof(map));
scanf("%d%d%d",&m,&n,&k);
for(i=1;i<=n;i++)//m为城市个数,n为高速数
{
scanf("%d%d",&p,&q);
map[p][q]=1;
map[q][p]=1;
// un(p,q);
}
/* for(j=1;j<=m;j++)
{
for(int jint=1;jint<=m;jint++)
printf("%d ",map[j][jint]);
printf("\n");
}*/
memcpy(mapc,map,sizeof(map));
for(i=0;i<k;i++)
{
scanf("%d",&p);
/* for(j=1;j<=m;j++)
{
for(int jint=1;jint<=m;jint++)
printf("*%d ",map[j][jint]);
printf("\n");
}*/
wipe(p);//wipe(i)是为了求假设城市i被占领,之后的MAP;
/* for(j=1;j<=m;j++)
{
for(int jint=1;jint<=m;jint++)
printf("%d ",map[j][jint]);
printf("\n");
}
*/
int jj;
for(t=1;t<=m;t++)
father[t]=t;
for(j=1;j<=m;j++)
{
for(jj=1;jj<=m;jj++)
{
if(map[j][jj]==1)//对所有有路相连的点进行合并到一个集合;
{
un(j,jj);
// printf("\n%d %d\n",j,jj);
}
}
}
for(t=1;t<=m;t++)
{
if(father[t]==t)
count++;
}
printf("%d\n",count-2);//统计集合的个数。因为被占领的集全不算,故应该减2;
count=0; //注意带有循环的时候每次做完要恢复原值,包括count和map;
memcpy(map,mapc,sizeof(map));//用于恢复map的原值
}
return 0;
}
浙公网安备 33010602011771号