【BZOJ 1040】[ZJOI2008]骑士
【题目链接】:http://www.lydsy.com/JudgeOnline/problem.php?id=1040
【题意】
【题解】
题目相当于给你了若干个环(基本环->简单环);
然后每个环里面选一些点;相邻的点不能同时选;
先考虑只有一个环的情况
这样,
我们可以任意删掉一条边,它的两个端点为u和v;
它就变成一条链了;
然后因为一条边的两个端点不能同时选;
所以
先假设u不选,v任意,然后以u为根做一下DP,
再假设v不选,u任意,然后以v为根做一下DP,
取两个不选的最大值;
累加到答案里面就好;
【完整代码】
#include <bits/stdc++.h>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define rei(x) scanf("%d",&x)
#define rel(x) scanf("%lld",&x)
#define ref(x) scanf("%lf",&x)
typedef pair<int, int> pii;
typedef pair<LL, LL> pll;
const int dx[9] = { 0,1,-1,0,0,-1,-1,1,1 };
const int dy[9] = { 0,0,0,-1,1,-1,1,-1,1 };
const double pi = acos(-1.0);
const int N = 1e6+100;
struct abc
{
int en, nex;
};
int n,fir[N],tot = 1,u,v,db;
LL f[N], g[N],ans = 0,val[N];
abc bian[N*2];
bool vis[N];
void add(int x,int y)
{
bian[++tot].nex = fir[x];
fir[x] = tot;
bian[tot].en = y;
}
void in()
{
rei(n);
int y;
rep1(i, 1, n)
{
rel(val[i]),rei(y);
add(i, y), add(y, i);
}
}
void dfs(int x, int prem)
{
vis[x] = true;
for (int i = fir[x]; i; i = bian[i].nex)
{
if ((i ^ 1) == prem) continue;//往回走了重复边,因为建边的时候是在正、反向一起建的,
//所以这个数i^1对应的奇数/偶数就是反向边的边的编号
int y = bian[i].en;
if (vis[y])//找到环了,记录这条边,等下用于删除
{
u = x, v = y, db = i;
continue;
}
dfs(y, i);
}
}
void tree_dp(int x, int pre)
{
f[x] = val[x], g[x] = 0;
for (int i = fir[x]; i; i = bian[i].nex)
{
if ((i == db) || ((i ^ 1) == db)) continue;
if ((i ^ 1) == pre) continue;
int y = bian[i].en;
tree_dp(y, i);
f[x] += g[y];
g[x] += max(f[y], g[y]);
}
}
void get_ans()
{
rep1(i,1,n)
if (!vis[i])
{
LL temp = 0;
dfs(i, -1);
tree_dp(u, -1);
temp = max(temp, g[u]);
tree_dp(v, -1);
temp = max(temp, g[v]);
ans += temp;
}
}
void o()
{
printf("%lld\n", ans);
}
int main()
{
//freopen("F:\\rush.txt", "r", stdin);
in();
get_ans();
o();
//printf("\n%.2lf sec \n", (double)clock() / CLOCKS_PER_SEC);
return 0;
}