(MST) HDOJ 1102 Constructing Roads

怎么说呢

这题就是个模板题

但是

hud你妹夫啊说好的只有一组数据呢???

嗯???

wa到家都不认识了好吗

#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>
#define INF 0x3f3f3f3f
using namespace std;

typedef pair<int, int> pii;
struct cmp{
    bool operator() (const pii a, const pii b){
        return a.first > b.first;
    }
};

int n, q, val[110][110], dist[110];
bool vis[110];

int prim(int s)
{
    priority_queue<pii, vector<pii>, cmp> q;
    memset(vis, false, sizeof vis);
    for(int i = 1; i <= n; i++){
        dist[i] = val[s][i];
        q.push(make_pair(dist[i], i));
    }
    vis[s] = true;
    int res = 0;
    while(!q.empty()){
        pii u = q.top();
        q.pop();
        if(vis[u.second]) continue;
        vis[u.second] = true;
        res += u.first;
        for(int i = 1; i <= n; i++){
            if(!vis[i] && i != u.second && val[u.second][i] < dist[i]){
                dist[i] = val[u.second][i];
                q.push(make_pair(dist[i], i));
            }
        }
    }
    return res;
}

int main()
{
    while(~scanf("%d", &n)){
        for(int i = 1; i <= n; i++){
            for(int j = 1 ; j <= n; j++){
                scanf("%d", &val[i][j]);
            }
        }
        scanf("%d", &q);
        while(q--){
            int u, v;
            scanf("%d%d", &u, &v);
            val[u][v] = val[v][u] = 0;
        }
        printf("%d\n", prim(1));
    }
    return 0;
}

 

你可能感兴趣的:((MST) HDOJ 1102 Constructing Roads)