码迷,mamicode.com
首页 > 其他好文 > 详细

POJ - 2377 - Bad Cowtractors (最小生成树)

时间:2020-02-29 20:49:19      阅读:74      评论:0      收藏:0      [点我收藏+]

标签:mit   mes   else   print   ==   namespace   dig   typename   limits   

题目链接:https://vjudge.net/problem/POJ-2377#author=tsacm123

题目大意:就是让你算出n个谷仓之间的最大生成树,然后把各条边的值累加起来

#include<set>
#include<map>
#include<stack>
#include<queue>
#include<cmath>
#include<cstdio>
#include<cctype>
#include<string>
#include<vector>
#include<climits>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#define endl ‘\n‘
#define max(a, b) (a > b ? a : b)
#define min(a, b) (a < b ? a : b)
#define zero(a) memset(a, 0, sizeof(a))
#define INF(a) fill(a, a+maxn, INF);
#define IOS ios::sync_with_stdio(false)
#define _test printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n")
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
typedef pair<double, int> P2;
const double pi = acos(-1.0);
const double eps = 1e-7;
const ll MOD =  1000000007LL;
const int INF = 0x3f3f3f3f;
const int _NAN = -0x3f3f3f3f;
const double EULC = 0.5772156649015328;
const int NIL = -1;
template<typename T> void read(T &x){
    x = 0;char ch = getchar();ll f = 1;
    while(!isdigit(ch)){if(ch == -)f*=-1;ch=getchar();}
    while(isdigit(ch)){x = x*10+ch-48;ch=getchar();}x*=f;
}
const int maxn = 1e3+10;
int vis[maxn];
vector<P> dis[maxn];
void prim(int n) {
    priority_queue<P> pq;
    zero(vis);
    int sum = 0, s = 0;
    pq.push(make_pair(0, 1));
    while(!pq.empty()) {
        P t = pq.top();
        pq.pop();
        if (vis[t.second])
            continue;
        vis[t.second] = true;
        sum += t.first;
        ++s;
        for (int i = 0; i<(int)dis[t.second].size(); ++i) 
            if (!vis[dis[t.second][i].second]) 
                pq.push(make_pair(dis[t.second][i].first, dis[t.second][i].second));
    }
    if (s != n)
        printf("-1\n");
    else 
        printf("%d\n", sum);
}
int main(void) {
    int n, m;
    scanf("%d%d", &n, &m);
    for (int i = 0, a, b, d; i<m; ++i) {
        scanf("%d%d%d", &a, &b, &d);
        dis[a].push_back(make_pair(d, b));
        dis[b].push_back(make_pair(d, a));
    }
    prim(n);
    return 0;
}

 

POJ - 2377 - Bad Cowtractors (最小生成树)

标签:mit   mes   else   print   ==   namespace   dig   typename   limits   

原文地址:https://www.cnblogs.com/shuitiangong/p/12384759.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!