CF - 1108 F MST Unification
题意:
在一幅图中, 问需要使得多少条边加一,使得最小生成树只有一种方案。
题解:
Kruskal,
sort完之后,
对于相通的一个边权w,我们可以分析出来有多少边是可以被放到图里面的,
然后我们再开始加边,
最后 多余的边就是 可以被放进去的 - 加进去的边。
代码:
/* code by: zstu wxk time: 2019/01/28 */ #include<bits/stdc++.h> using namespace std; #define Fopen freopen("_in.txt","r",stdin); freopen("_out.txt","w",stdout); #define LL long long #define ULL unsigned LL #define fi first #define se second #define pb push_back #define lson l,m,rt<<1 #define rson m+1,r,rt<<1|1 #define lch(x) tr[x].son[0] #define rch(x) tr[x].son[1] #define max3(a,b,c) max(a,max(b,c)) #define min3(a,b,c) min(a,min(b,c)) typedef pair<int,int> pll; const int inf = 0x3f3f3f3f; const int _inf = 0xc0c0c0c0; const LL INF = 0x3f3f3f3f3f3f3f3f; const LL _INF = 0xc0c0c0c0c0c0c0c0; const LL mod = (int)1e9+7; const int N = 2e5 + 100; int Wa(){return rand()%2;} void Hack(int n){srand(time(0));int hack = 0;for(int j = 1; j <= n; ++j)hack += Wa();if(hack == n)puts("OH No!");} int n, m; struct Node{ int u, v, w; bool operator < (const Node & x) const{ return w < x.w; } }e[N]; int pre[N]; void init(){ for(int i = 1; i <= n; ++i) pre[i] = i; } int Find(int x){ if(x == pre[x]) return x; return pre[x] = Find(pre[x]); } void Ac(){ int u, v, w; for(int i = 1; i <= m; ++i) scanf("%d%d%d", &e[i].u, &e[i].v, &e[i].w); sort(e+1, e+1+m); int ans = 0; for(int i = 1; i <= m; ){ int j = i+1; while(e[i].w == e[j].w) ++j; for(int k = i; k < j; ++k) if(Find(e[k].u) != Find(e[k].v)) ++ans; for(int k = i; k < j; ++k){ if(Find(e[k].u) != Find(e[k].v)){ pre[Find(e[k].u)] = Find(e[k].v); --ans; } } i = j; } printf("%d\n", ans); } int main(){ while(~scanf("%d%d", &n, &m)){ init(); Ac(); } return 0; }