1. 程式人生 > >POJ(1258):Agri-Net(最小生成樹)

POJ(1258):Agri-Net(最小生成樹)

Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 68523 Accepted: 28406

Description

Farmer John has been elected mayor of his town! One of his campaign promises was to bring internet connectivity to all farms in the area. He needs your help, of course. 
Farmer John ordered a high speed connection for his farm and is going to share his connectivity with the other farmers. To minimize cost, he wants to lay the minimum amount of optical fiber to connect his farm to all the other farms. 
Given a list of how much fiber it takes to connect each pair of farms, you must find the minimum amount of fiber needed to connect them all together. Each farm must connect to some other farm such that a packet can flow from any one farm to any other farm. 
The distance between any two farms will not exceed 100,000. 

Input

The input includes several cases. For each case, the first line contains the number of farms, N (3 <= N <= 100). The following lines contain the N x N conectivity matrix, where each element shows the distance from on farm to another. Logically, they are N lines of N space-separated integers. Physically, they are limited in length to 80 characters, so some lines continue onto others. Of course, the diagonal will be 0, since the distance from farm i to itself is not interesting for this problem.

Output

For each case, output a single integer length that is the sum of the minimum length of fiber required to connect the entire set of farms.

Sample Input

4
0 4 9 21
4 0 8 17
9 8 0 16
21 17 16 0

Sample Output

28

Source

圖節點數目為N,正在構造的生成樹為T,
• 維護Dist陣列,Dist[i]表示Vi到T的“距離”
• 開始所有Dist[i] = 無窮大, T 為空集
1) 若|T| = N,最小生成樹完成。否則取Dist[i]最小
的不在T中的點Vi, 將其加入T
2) 更新所有與Vi有邊相連且不在T中的點Vj的Dist值:
Dist[j] = min(Dist[j],W(Vi,Vj))
3) 轉到1)

                            關鍵問題
每次如何從連線T 中和T 外頂點的所有邊中,找到一條最短的
1) 如果用鄰接矩陣存放圖,而且選取最短邊的時候遍歷所有點進行選取,則總時間複雜度為O(V 2 ), V 為頂點個數
2)用鄰接表存放圖,並使用堆來選取最短邊,則總時間複雜度為O(ElogV)不加堆優化的Prim 演算法適用

#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<queue>
const int inf = 1<<30;

using namespace std;

struct edge{
    int v;
    int w;
    edge(int v_ = 0,int w_ = inf):v(v_),w(w_){}
    bool operator<(const edge &e)const{
        return w > e.w;
    }
};
vector<vector<edge> >G(110);

int heap_prime(const vector<vector<edge> >&G,int n){
    edge xDist(0,0);
    priority_queue<edge>pq;//存放頂點及其到在建生成樹的距離
    vector<int>vDist(n);//各定點到已建好的那部分樹的距離
    vector<int>vUsed(n);
    int nDoneNum = 0;
    for(int i = 0;i < n;i++){
        vUsed[i] = 0;
        vDist[i] = inf;
    }
    nDoneNum = 0;
    int nTotalW = 0;
    pq.push(edge(0,0));
    while(nDoneNum < n && !pq.empty()){
        do{
            xDist = pq.top();
            pq.pop();
        }while(vUsed[xDist.v]==1 && !pq.empty());
        if(vUsed[xDist.v] == 0){
            nTotalW += xDist.w;
            vUsed[xDist.v] = 1;
            nDoneNum++;
        }
        for(int i = 0;i < G[xDist.v].size();i++){
            int k = G[xDist.v][i].v;
            if(vUsed[k] ==0 ){
                int w = G[xDist.v][i].w;
//                    cout<<vDist[k]<<" "<<endl;
                    pq.push(edge(k,w));
            }
        }
    }
    if( nDoneNum < n )
    return -1; //圖不連通
    return nTotalW;
}
int main()
{
    int n;
    while(~scanf("%d",&n)){
        for(int i = 0;i < n;i++)
            G[i].clear();
        for(int i = 0;i < n;i++){
            for(int j = 0;j < n;j++){
                int w;
                scanf("%d",&w);
                G[i].push_back(edge(j,w));
            }
        }
        printf("%d\n",heap_prime(G,n));
    }
}

Kruskal:

#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>

using namespace std;

struct edge{
    int s,e,w;
    edge(int ss,int ee,int ww):s(ss),e(ee),w(ww){}
    bool operator<(const edge &e1) const{
        return w < e1.w;
    }
};
vector<edge>edges;
vector<int>parent;

int get_root(int a){
    if(parent[a] == a)
        return a;
    parent[a] = get_root(parent[a]);
        return parent[a];
}

void merge(int a,int b){
    int p1 = get_root(a);
    int p2 = get_root(b);
    if(p1 == p2)
        return;
    else{
        parent[p2] = p1;
    }
}
int main()
{
    int n;
    while(~scanf("%d",&n)){
        parent.clear();
        edges.clear();
        for(int i = 0;i < n;i++){
            parent.push_back(i);
        }
        for(int i = 0;i < n;i++){
            for(int j = 0;j < n;j++){
                int w;
                scanf("%d",&w);
                edges.push_back(edge(i,j,w));
            }
        }
        sort(edges.begin(),edges.end());
        int done = 0;
        int totalLen = 0;
        for( int i = 0;i < edges.size(); ++i) {
            if( get_root(edges[i].s) != get_root(edges[i].e)) {
                merge(edges[i].s,edges[i].e);
                    ++done;
                    totalLen += edges[i].w;
            }
            if( done == n-1)
                break;
        }
        cout << totalLen << endl;
    }

}