九度[1028]-繼續暢通工程

九度[1028]-繼續暢通工程

題目描述:
省政府“暢通工程”的目標是使全省任何兩個村莊間都可以實現公路交通(但不一定有直接的公路相連,只要能間接通過公路可達即可)。現得到城鎮道路統計表,表中列出了任意兩城鎮間修建道路的費用,以及該道路是否已經修通的狀態。現請你編寫程序,計算出全省暢通需要的最低成本。
輸入
測試輸入包含若干測試用例。每個測試用例的第1行給出村莊數目N ( 1< N < 100 );隨後的 N(N-1)/2 行對應村莊間道路的成本及修建狀態,每行給4個正整數,分別是兩個村莊的編號(從1編號到N),此兩村莊間道路的成本,以及修建狀態:1表示已建,0表示未建。
當N爲0時輸入結束。
輸出
每個測試用例的輸出佔一行,輸出全省暢通需要的最低成本。
樣例輸入
3
1 2 1 0
1 3 2 0
2 3 4 0
3
1 2 1 0
1 3 2 0
2 3 4 1
3
1 2 1 0
1 3 2 1
2 3 4 1
0
樣例輸出
3
1
0

解題思路:
本質上還是最小生成樹

AC代碼:

#include <cstdio>
const int maxn = 110;
int N;
bool vis[maxn];
int father[maxn];

struct road{
    int A;
    int B;
    int cost;
    int connect;
}roads[maxn*maxn];

int findFather(int n){
    if(n == father[n]) return n;
    else return findFather(father[n]);
}

void quickSort(road roads[], int l, int r){
    if(l >= r) return;
    int low = l, high = r;
    road key = roads[low];
    while(low < high){
        while(low < high && roads[high].cost >= key.cost) high--;
        if(low < high) roads[low] = roads[high];
        while(low < high && roads[low].cost < key.cost) low++;
        if(low < high) roads[high] = roads[low];
    }
    roads[low] = key;
    quickSort(roads, l, low-1);
    quickSort(roads, high+1, r);
}

int kruskal(road roads[], int eNum){
    int ans = 0;
    //for(int i = 0; i < eNum && cnt <= pNum; i++) is wrong?
    for(int i = 0; i < eNum; i++){
        int faA = findFather(roads[i].A);
        int faB = findFather(roads[i].B);
        if(faA != faB) {
            father[faA] = faB;
            if(!vis[roads[i].A]){
                vis[roads[i].A] = true;
            }
            if(!vis[roads[i].B]){
                vis[roads[i].B] = true;
            }
            ans += roads[i].cost;
        }
    }
    return ans;
}

int main(){
    freopen("C:\\Users\\Administrator\\Desktop\\test.txt", "r", stdin);
    while(scanf("%d", &N) != EOF){
        if(N == 0) break;
        for(int i = 0; i < maxn; i++){
            father[i] = i;
            vis[i] = false;
        }
        int num = N*(N-1)/2;
        for(int i = 0; i < num; i++){
            scanf("%d%d%d%d", &roads[i].A, &roads[i].B, &roads[i].cost, &roads[i].connect);
            if(roads[i].connect == 1) roads[i].cost = 0;
        }
        quickSort(roads, 0, num-1);
        printf("%d\n", kruskal(roads, num));
    }
    fclose(stdin);
    return 0;
} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章