比赛 EYOI与SBOI开学欢乐赛11th 评测结果 EWWEEETTTT
题目名称 骑士 最终得分 0
用户昵称 该账号已注销 运行时间 9.948 s
代码语言 C++ 内存使用 35.47 MiB
提交时间 2022-10-14 22:06:55
显示代码纯文本
#include <bits/stdc++.h>
using namespace std;

struct eg {
	int t, n;
} e[2001000];
int n, cnt = 0;
int a[1001000], b[1001000], hd[1001000];
int rt = 0;
long long ans = 0;
bool q = 0;

int f[1001000][2] = {0};

bool in[1001000] = {0};

void add(int x, int y) {
	e[++cnt].t = y;
	e[cnt].n = hd[x];
	hd[x] = cnt;
}
int dp(int x, int fa) {
	long long sum = 0;
	for (int i = hd[x]; i; i = e[i].n) {
		int ver = e[i].t;
		if (ver == fa)
			continue;
		if (ver == rt) {
			long long p = max(f[ver][1], f[ver][0]);
			sum = max(sum, p);
			continue;
		}
		f[ver][1] = f[x][0] + a[ver];
		f[ver][0] = max(f[x][1], f[x][0]);
		dp(ver, x);
		long long p = max(f[ver][1], f[ver][0]);
		sum = max(sum, p);
	}
	return sum;
}

int dfs(int x, int fa) {
	in[x] = 1;
	for (int i = hd[x]; i; i = e[i].n) {
		int ver = e[i].t;
		if (ver == fa)
			continue;
		if (q == 1)
			break;
		if (in[ver] == 1) {
			rt = ver;
			long long p1 = dp(rt, -1);
			rt = x;
			long long p2 = dp(rt, -1);
			ans += max(p1, p2);
			q = 1;
			return 0;
		} else {
			dfs(ver, x);
		}
	}
	return 0;
}

int main() {
	freopen("bzoj_1040.in", "r", stdin);
	freopen("bzoj_1040.out", "w", stdout);
	cin >> n;
	for (int i = 1; i <= n; i++) {
		cin >> a[i] >> b[i];
		add(i, b[i]);
		add(b[i], i);
	}
	for (int i = 1; i <= n; i++) {
		q = 0;
		if (in[i] == 0) {
			dfs(i, -1);
		}
	}
	cout << ans << endl;
	return 0;
}