Blog of RuSun

\begin {array}{c} \mathfrak {One Problem Is Difficult} \\\\ \mathfrak {Because You Don't Know} \\\\ \mathfrak {Why It Is Diffucult} \end {array}

P2607 [ZJOI2008] 骑士

P2607 [ZJOI2008] 骑士

基环树森林最大独立集,当作仙人掌做。

查看代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <cstdio>
#include <list>
#include <vector>
#define pb push_back
using namespace std;
template <class Type>
void read (Type &x)
{
char c;
bool flag = false;
while ((c = getchar()) < '0' || c > '9')
c == '-' && (flag = true);
x = c - '0';
while ((c = getchar()) >= '0' && c <= '9')
x = (x << 1) + (x << 3) + c - '0';
flag && (x = ~x + 1);
}
template <class Type, class ...rest>
void read (Type &x, rest &...y) { read(x), read(y...); }
template <class Type>
void write (Type x)
{
x < 0 && (putchar('-'), x = ~x + 1);
x > 9 && (write(x / 10), 0);
putchar('0' + x % 10);
}
typedef long long LL;
const int N = 1e6 + 10;
LL f[N][2];
int n, w[N], p[N];
vector <int> g[N];
int stmp, dfn[N], low[N];
LL calc (list <LL> &h)
{
LL k[2] = { 0, 0 };
for (LL i : h)
{
LL tk[2] = { k[0], k[1] };
k[0] = max(tk[0], tk[1]) + f[i][0];
k[1] = tk[0] + f[i][1];
}
return max(k[0], k[1]);
}
void tarjan (int u)
{
dfn[u] = low[u] = ++stmp;
f[u][0] = 0, f[u][1] = w[u];
for (int v : g[u]) if (v ^ p[u])
if (!dfn[v])
{
p[v] = u;
tarjan(v);
low[u] = min(low[u], low[v]);
if (low[v] > dfn[u])
{
f[u][0] += max(f[v][0], f[v][1]);
f[u][1] += f[v][0];
}
}
else low[u] = min(low[u], dfn[v]);
for (int v : g[u]) if (dfn[v] > dfn[u] && p[v] ^ u)
{
list <LL> h;
for (int t = v; t ^ u; t = p[t]) h.pb(t);
f[u][0] += calc(h);
f[u][1] += f[h.front()][0] + f[h.back()][0];
h.pop_front(), h.pop_back();
f[u][1] += calc(h);
}
}
int main ()
{
read(n);
for (int i = 1, a; i <= n; ++i)
{
read(w[i], a);
g[i].pb(a), g[a].pb(i);
}
LL res = 0;
for (int i = 1; i <= n; ++i) if (!dfn[i])
{
tarjan(i);
res += max(f[i][0], f[i][1]);
}
write(res);
return 0;
}