閱讀136 返回首頁    go 阿裏雲 go 技術社區[雲棲]


九度題目1325:Battle Over Cities

題目1325:Battle Over Cities
時間限製:1 秒
內存限製:32 兆
特殊判題:否
提交:331
解決:104
題目描述:
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.

輸入:
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.

輸出:
For each of the K cities, output in a line the number of highways need to be repaired if that city is lost.

樣例輸入:
3 2 3
1 2
1 3
1 2 3樣例輸出:
1
0
0

 


/*
題意:給你若幹個點和這鏈接這幾個點的路,讓你求刪除一個點之後,讓剩下的所有點重新組成通路所需要最少的路徑。
思路:采用劃分集合的思想,隻要是和刪除的點有關的(與其有鏈接的)點都不用管,和刪除點無關的隻要存在通路就放在一個集合內,
最後看看有幾個集合(sum),就需要有幾條路(sum-1)。
劃分集合可以采用DFS(深入優先搜索)方法,將與一個節點有關的所有節點都劃分到集合中去(說白了就是標記掉)
每次DFS之後都記錄一次,下次再碰到沒有劃分到集合的節點(即沒有被標記),繼續對其DFS,以此推類
*/
AC代碼:

#include<stdio.h>
#include<string.h>
int a[1500][1500],f[1500],n;
void DFS(int p)
{
 f[p]=1;//該點當成已經劃入集合的點
 for(int i=1;i<=n;i++)
 {
        if(f[i]==0&&a[i][p]==1)//找出與p點相接的點i,把i以及i所連接的路徑都劃入集合
   DFS(i);
 }
}
int main()
{
 int i,m,k,p,x,y,sum;
    while(scanf("%d %d %d",&n,&m,&k)!=EOF)
 {
   memset(a,0,sizeof(a));
         for(i=0;i<m;i++)
         {
    scanf("%d %d",&x,&y);
    a[x][y]=1;
    a[y][x]=1;
   }
   while(k--)
   {
    scanf("%d",&p);
    memset(f,0,sizeof(f));
    sum=0;
    f[p]=1;//將被敵人占據的點當成一個單獨的集合
    for(i=1;i<=n;i++)
    {
     if(f[i]==0)//開始劃分集合
     {
      DFS(i);
      sum++;//將i以及i所連接的所有節點歸為一個集合
     }
    }
    printf("%d\n",sum-1);//找出有幾個單獨集合,集合總數減一(sum-1)就是最小鏈接路徑
   }
 }
 return 0;
}

最後更新:2017-04-03 05:38:56

  上一篇:go nginx.conf 配置文件中文說明
  下一篇:go 初識ASP.NET---ASP.NET中驗證控件的用法