湘潭大學程序設計實踐 1195

xtuoj 1195 Large Population

Large Population


 

Description

題目描述

很多城市人口衆多,政府決定在不同城市之間修建高速公路提高相互之間的交通條件。 但是由於修建費用昂貴,所以政府只要能保證所有城市都可以通過高速公路互聯就可以了。 但是政府又想這些公路的容量之和儘可能的大。請你設計一下線路,看最大容量和是多少?

輸入

第一行是一個整數K,表示樣例數。 每個樣例的第一行是兩個整數N和M(2≤N≤1000;N-1≤M≤10000), N表示N個城市,其中城市代號用1到N表示;M表示可以修建的高速公路條數。 以後的M行爲每條高速公路的容量情況。 每行爲三個整數X,Y,C,其中1≤X,Y ≤N, 0≤C≤1000000;

輸出

每行輸出一個樣例的結果,爲一個整數。

樣例輸入

2 
2 1 
1 2 1 
3 3 
1 2 1 
1 3 2 
2 3 3

樣例輸出

1 
5
這是一個簡單的求權重最大的生成樹的模板題!之前的那個代碼是前面一個題的,(當時興奮過頭了!十分抱歉!) 

<pre name="code" class="cpp">#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 1001;

typedef struct{
    int x, y, c;
} edge;
edge Edge[10001];

int father[N];

bool cmp(edge a, edge b) {return a.c > b.c;}

int find_father(int n)
{
    return n != father[n] ?<span style="font-family: Arial, Helvetica, sans-serif;"> father[n] = </span><span style="font-family: Arial, Helvetica, sans-serif;">find_father(father[n]) : n;</span>
}

int main()
{
    int cas, n, m;
    scanf("%d", &cas);
    while(cas --)
    {
        scanf("%d%d", &n, &m);
        for(int i = 0; i <= n; i ++)
            father[i] = i;
        for(int i = 0; i < m; i ++)
           scanf("%d%d%d", &Edge[i].x, &Edge[i].y, &Edge[i].c);
        sort(Edge, Edge + m, cmp);
        int sum = 0;      
        for(int i = 0; i < m; i ++)
        {
            if(find_father(Edge[i].x) != find_father(Edge[i].y))
                father[father[Edge[i].x]] = father[Edge[i].y], sum += Edge[i].c;
        }
        printf("%d\n", sum);
    }
    return 0;
}







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章