删点博弈
ben_ben_ta_ge · · 个人记录
思路
不难发现,每次操作改变了连通块数量,且最后结束的条件也与连通块数有关,所以我们考虑连通块数(
其中
由于剩下的点数是
所以先手肯定是想每次删度大于等于 3 的点。
再看一下后手,他每次肯定是要在两个读书都小于等于 1 的点间连边,不然就会有一个点的度大于 2,先手删去后会带来收益。
那现在先手的策略就很明显了,选定一些度数大于等于 3 (被删时)的点,并指定一个删除顺序,然后计算收益。我们需要区分一个点被删时他的父节点有没有被删,很容易想到树上 DP。
DP
状态设计:
对于每个点,我们关心的有两件事:1.它有没有被删。2.如果它被删了,删它时它的父节点有没有被删(也就是说它的三条边来自哪里)。于是可以想到一下定义:
初值:
全部为 0。
转移:
对于当前点
接下来开始转移:
- 需注意:若在后两种转移中
x 的子节点不足 2/3 个,那么f[x][2/3] 的值为-\inf 。
答案:
由于根结点处没有父节点,所以忽略
最终输出
代码:
::::success[代码]
#include<cmath>
#include<stack>
#include<queue>
#include<cstdio>
#include<vector>
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 1e6 + 10;
int vis[N];
int f[N][3];
vector<int> v[N];
stack<pair<int,int>> st;
void bfs(int s)
{
queue<int> q;
q.push(s);
vis[s] = 1;
while(!q.empty())
{
int x = q.front();
q.pop();
st.push({x,vis[x] - 1});
for(int i = 0; i < v[x].size(); i++)
{
int y = v[x][i];
if(vis[y]) continue;
vis[y] = x + 1;
q.push(y);
}
}
}
void work(int x,int fa)
{
f[x][0] = 0;
f[x][1] = -1;
f[x][2] = -1;
priority_queue<int,vector<int>,greater<int> > q;
for(int i = 0; i < v[x].size(); i++)
{
int y = v[x][i];
if(y == fa) continue;
int w1 = max(f[y][0],f[y][1]) + 1;
int w2 = max(f[y][0],max(f[y][1],f[y][2])) + 1;
q.push(w2 - w1);
f[x][0] += max(f[y][0],max(f[y][1],f[y][2]) + 1);
f[x][2] += w2;
}
f[x][1] = f[x][2];
if(!q.empty())
{
f[x][2] -= q.top();
f[x][1] -= q.top();
q.pop();
}
else
{
f[x][2] = -1e9;
f[x][1] = -1e9;
return;
}
if(!q.empty())
{
f[x][2] -= q.top();
f[x][1] -= q.top();
q.pop();
}
else
{
f[x][2] = -1e9;
f[x][1] = -1e9;
return;
}
if(!q.empty())
{
f[x][1] -= q.top();
q.pop();
}
else
{
f[x][1] = -1e9;
return;
}
}
int main()
{
//freopen("treegame.in","r",stdin);
//freopen("treegame.out","w",stdout);
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int T;
cin >> T;
while(T--)
{
int n;
cin >> n;
for(int i = 1; i <= n; i++)
{
vis[i] = 0;
v[i].clear();
}
for(int i = 1; i < n; i++)
{
int x,y;
cin >> x >> y;
v[x].push_back(y);
v[y].push_back(x);
}
bfs(1);
while(!st.empty())
{
auto t = st.top();
st.pop();
work(t.first,t.second);
}
cout << n - max(f[1][0],max(f[1][1],1)) << "\n";
}
return 0;
}
::::