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
遇到的问题和思路:
和前几道最小生成树差不多。因为书上说kruskal算法好,我现在就一直用kruskal算法写了。不过prim算法的复杂度和kruskal是一样的。
给出AC代码:
#include<cstdio> #include<algorithm> #include<cstring> #include<cmath> using namespace std; typedef long long ll; const ll MAX_N = 100 + 10; struct edge{ ll from, to, cost; }; edge ed[MAX_N * MAX_N]; ll n, f, tally; ll par[MAX_N], degree[MAX_N]; void init(){ for(int i = 1; i <= n; i++){ par[i] = i; degree[i] = 0; } } int find(int x){ if(par[x] == x) return x; return par[x] = find(par[x]); } void unite(int x, int y){ x = find(x); y = find(y); if(x == y) return ; if(degree[x] > degree[y]){ par[y] = x; } else { par[x] = y; if(degree[x] == degree[y])degree[y]++; } } bool same(int x, int y){ return find(x) == find(y); } bool cmp(const edge &e1, const edge &e2){ return e1.cost < e2.cost; } void kruskal(){ sort(ed + 1, ed + 1 + f, cmp); ll res = 0; for(int i = 1; i <= f; i++){ if(!same(ed[i].from, ed[i].to)){ res += ed[i].cost; unite(ed[i].from, ed[i].to); //tally++; } } printf("%d\n", res); } int main(){ while(scanf("%d", &n) && n){ f = n * (n - 1) / 2; init(); for(int i = 1; i <= f; i++){ scanf("%I64d%I64d%I64d", &ed[i].from, &ed[i].to, &ed[i].cost); int lamp; scanf("%d", &lamp); if(lamp == 1){ if(!same(ed[i].from, ed[i].to)) unite(ed[i].from, ed[i].to); //tally++; } } kruskal(); } return 0; }