其他分享
首页 > 其他分享> > Atcoder256 E

Atcoder256 E

作者:互联网

#include <bits/stdc++.h>

using i64 = long long;

int main() {
	std::cin.tie(nullptr)->sync_with_stdio(false);

	int n; std::cin >> n;

	std::vector<int> a(n + 1), f(n + 1), c(n + 1);
	std::iota(f.begin(), f.end(), 0);

	for (int i = 1; i <= n; i ++ ) std::cin >> a[i];
	for (int i = 1; i <= n; i ++ ) std::cin >> c[i];

	std::function<int(int)> find = [&] (int x) -> int {
		return x == f[x] ? f[x] : f[x] = find(f[x]);
	};

	auto same = [&] (int u, int v) -> bool {
		return find(u) == find(v);
	};

	auto merge = [&] (int u, int v) -> void {
		int fu = find(u), fv = find(v);
		if (fu == fv) return ;
		f[fv] = fu;
	};

	i64 ans = 0;
	for (int i = 1; i <= n; i ++ ) {
		if (!same(i, a[i])) {
			merge(i, a[i]);
			continue;
		}
		int cur = c[i], v = i;
		do {
			v = a[v];
			cur = std::min(cur, c[v]);
		}while(v != i);
		ans += cur;
	}
	std::cout << ans << "\n";
	return 0;
}

标签:std,Atcoder256,return,fu,fv,int,find
来源: https://www.cnblogs.com/Haven-/p/16417589.html