题解 「JOISC 2016 Day 3」电报
题目大意
给出一个\(n\)个点\(n\)条边的图,每个点有且仅有一个出边,改变每条边都会有对应的花费。求最小的花费使得整个图强连通。
思路
很显然,最后的图就是一个环。那我们要求的答案实际上就是链的最大权值之和。
我们再次将问题转换,发现就是每个点只保留一条边,而保留的边就是连向它的边权最大的边。但是我们发现这实际上还有问题,因为这样仍可以构成一个环,那我们就选环上一个点断开再选一条不在环上且边权最大的边即可。
\(\texttt{Code}\)
#include <bits/stdc++.h>
using namespace std;
#define Int register int
#define ll long long
#define MAXN 100005
template <typename T> inline void read (T &t){t = 0;char c = getchar();int f = 1;while (c < '0' || c > '9'){if (c == '-') f = -f;c = getchar();}while (c >= '0' && c <= '9'){t = (t << 3) + (t << 1) + c - '0';c = getchar();} t *= f;}
template <typename T,typename ... Args> inline void read (T &t,Args&... args){read (t);read (args...);}
template <typename T> inline void write (T x){if (x < 0){x = -x;putchar ('-');}if (x > 9) write (x / 10);putchar (x % 10 + '0');}
ll ans;
int n,a[MAXN],c[MAXN],cm[MAXN],ncm[MAXN],vis[MAXN];
signed main(){
read (n);
for (Int i = 1;i <= n;++ i) read (a[i],c[i]),ans += c[i];
for (Int i = 1;i <= n;++ i) if (!vis[i]){
int x = i;for (;!vis[x];x = a[x]) vis[x] = i;
if (vis[x] == i){int siz = 0;for (;~vis[x];x = a[x]) siz ++,vis[x] = -1;if (siz == n) return puts ("0"),0;}
}
for (Int i = 1;i <= n;++ i){
cm[a[i]] = max (cm[a[i]],c[i]);
if (~vis[i]) ncm[a[i]] = max (ncm[a[i]],c[i]);
}
for (Int i = 1;i <= n;++ i) ans -= cm[i];
for (Int i = 1;i <= n;++ i) if (vis[i] == -1){
int minn = 2e9;
for (Int x = i;vis[x] == -1;x = a[x]) minn = min (minn,cm[x] - ncm[x]),vis[x] = 0;
ans += minn;
}
write (ans),putchar ('\n');
return 0;
}