Algoogle

Algorithm for Programming Contest

ACM-ICPC Tokyo Regional 2014 F There is No Alternative

Category: ICPC Tag: spanning-tree

There is No Alternative

問題概要


最小全域木を作るのに必ず必要になる辺の数とそのコストの和を求めよ

解法


最小全域木を作ってみる.
必ず必要な辺はそれに含まれる.
あとはその辺それぞれを使わないで最小全域木を作り, 非連結か重さが増える場合必要.

コード


(F.cpp) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <bits/stdc++.h>
using namespace std;


struct edge
{
        int from, to, cst;
        edge(int from, int to, int cst):from(from),to(to),cst(cst){}
        bool operator==(const edge &e)const{return from==e.from and to==e.to and cst == e.cst;}
        bool operator<(const edge &e)const{return cst < e.cst;}
};

const int MAX = 512;
struct union_find
{
        int rnk[MAX], par[MAX];

        union_find(int n){ for(int i = 0; i < n; i++) rnk[i] = 1, par[i] = i;}

        int find(int x){
                if(x == par[x]) return x;
                else return par[x] = find(par[x]);
        }
        void unite(int x, int y){
                x = find(x); y = find(y);
                if(x == y) return;
                if(rnk[x] > rnk[y]) par[y] = x;
                else{
                        par[x] = y;
                        if(rnk[x] == rnk[y]) rnk[y]++;
                }
        }
        bool same(int x, int y){
                x = find(x); y = find(y);
                return x == y;
        }
};

int n, m;

int kruskal(vector<edge> &es, vector<edge> &tree, edge rm)
{
        sort(begin(es), end(es));
        tree.clear();
        union_find uf(n) ;
        int w = 0;
        for(auto &e: es) {
                if(e==rm or uf.same(e.from, e.to)) continue;
                uf.unite(e.from, e.to);
                w += e.cst;
                tree.push_back(e);
        }
        for (int i = 0; i < n; i++)
                if(!uf.same(0,i)) return 1e9;
        return w;
}

vector<edge> es, used, tmp;

void solve()
{
        int w = kruskal(es,used,edge(-1,-1,-1));
        int ans = 0, cnt = 0;
        for(auto &e: used) {
                if(w < kruskal(es,tmp,e)) {
                        cnt++;
                        ans += e.cst;
                }
        }
        cout << cnt << " " << ans << endl;
}

void input()
{
        cin >> n >> m;
        int a, b, c;
        for (int i = 0; i < m; i++) {
                cin >> a >> b >> c;
                es.push_back(edge(a-1,b-1,c));
        }
}

int main()
{
        cin.tie(0);
        cin.sync_with_stdio(0);
        input();
        solve();
        return 0;
}

Comments