HDOJ 1879 继续畅通工程 (Prim 最小生成树)

来源:互联网 发布:网络零售平台有哪些 编辑:程序博客网 时间:2024/04/28 07:41

继续畅通工程

                                                                      Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
                                                                                               Total Submission(s): 25337    Accepted Submission(s): 10802


Problem Description
省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。现得到城镇道路统计表,表中列出了任意两城镇间修建道路的费用,以及该道路是否已经修通的状态。现请你编写程序,计算出全省畅通需要的最低成本。
 

Input
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( 1< N < 100 );随后的 N(N-1)/2 行对应村庄间道路的成本及修建状态,每行给4个正整数,分别是两个村庄的编号(从1编号到N),此两村庄间道路的成本,以及修建状态:1表示已建,0表示未建。

当N为0时输入结束。
 

Output
每个测试用例的输出占一行,输出全省畅通需要的最低成本。
 

Sample Input
31 2 1 01 3 2 02 3 4 031 2 1 01 3 2 02 3 4 131 2 1 01 3 2 12 3 4 10
 

Sample Output
310
 

Author
ZJU
 

Source
浙大计算机研究生复试上机考试-2008年
 

Recommend
We have carefully selected several similar problems for you:  1875 1863 1856 1301 1162 
 
知识点: 最小生成树, 参考 http://blog.csdn.net/yeruby/article/details/38615045

模板题直接上AC代码:

#include <iostream>#include <sstream>#include <cstring>#include <cstdio>#include <cctype>#include <cmath>#include <map>#include <set>#include <list>#include <queue>#include <deque>#include <stack>#include <vector>#include <algorithm>#define inf 0x3f3f3f3f#define PI 3.14159265358979323#define SCD(a) scanf("%d",&a)#define SCDD(a,b) scanf("%d%d",&a,&b)#define SCF(a) scanf("%lf",&a)#define PTD(a) printf("%d\n",a)#define PTS(a) printf("%s\n",a)#define MST(a) memset(a, 0, sizeof(a))using namespace std;//                      HDOJ 1879const int L = 101;int n, m;int maz[L][L], dis[L];bool vis[L];int ans;void init(){    int i, j;    ans = 0;    for(i=1;i<=n;i++){        vis[i] = false;        for(j=1;j<=n;j++){            maz[i][j] = inf;        }    }}void Prim(){    int i, j, pos, t;    for(i=1;i<=n;i++)        dis[i] = maz[1][i];    vis[1] = true;    dis[1] = 0;    for(i=2;i<=n;i++){        t = inf;        for(j=2;j<=n;j++){            if(!vis[j] && dis[j] < t){                t = dis[j];                pos = j;            }        }        ans += t;        vis[pos]  = true;        for(j=2;j<=n;j++){            if(!vis[j] && dis[j] > maz[pos][j]){                dis[j] = maz[pos][j];            }        }    }}int main(){    int i ,j ,a ,b ,t, com;    while(SCD(n)!=EOF&&(n)){        init();        for(i=0;i<n*(n-1)/2;i++){            SCDD(a, b);            SCDD(t, com);            if(com){                maz[a][b] = maz[b][a] = 0;            }else{                maz[a][b] = maz[b][a] = t;            }        }        Prim();        PTD(ans);    }    return 0;}/*Sample Input31 2 1 01 3 2 02 3 4 031 2 1 01 3 2 02 3 4 131 2 1 01 3 2 12 3 4 10 Sample Output310*/




阅读全文
1 0