CF1970C3 Game on Tree (Hard) 题解

· · 题解

先不考虑往父节点走,只考虑子树内先手输赢。

那么有叶节点先手必输,其它节点如果有先手必输的子节点就先手必赢,否则必输。

现在考虑往父节点走,发现如果子树内先手必赢,先手肯定直接走子树内了,也就是说子树内先手必输才会往父节点走。

然后先手转换成赫敏,也是同理,但是子节点信息要去掉刚才走上来的那一边。

最后看到先手必赢的节点时,先手是谁即可,注意特判到根节点后不能再往上走。

#include <bits/stdc++.h>
#define lowbit(o) o & -o
#define pb push_back
#define x first
#define y second
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
const int N = 500005;
const int mod = 998244353;
const int inf = 0x3f3f3f3f;
const LL INF = 2e18;
vector<int> g[N];
int f[N], dep[N], cnt[N], n, m;
bool st[N];
int w;
void dfs(int u,int fa)
{
    f[u] = 1;
    dep[u] = dep[fa] + 1;
    for (int i : g[u])
    {
        if (i == fa)
            continue;
        dfs(i, u);
        if (f[i] == 1)
            f[u] = 0, cnt[u] ++;
    }
}
void dfs2(int u,int fa,int last)
{
    if (u != 1)
    {
        if (last && (dep[u] - dep[last]) % 2 == 0)
            st[u] = true;
        if (!last && !w && (dep[u] - dep[1]) % 2 == 1)
            st[u] = true;
    }
    if (u == 1)
        w = cnt[u];
    for (int i : g[u])
    {
        if (i == fa)
            continue;
        int v = cnt[u];
        if (f[i] == 1)
            v --;
        if (u == 1 && f[i] == 1)
            w --;
        if (v)
            dfs2(i, u, u);
        else
            dfs2(i, u, last);
    }
}
void work()
{
    cin >> n >> m;
    for (int i=1;i<n;i++)
    {
        int a, b;
        cin >> a >> b;
        g[a].pb(b);
        g[b].pb(a);
    }
    dfs(1, 1);
    dfs2(1, 1, 0);
    while (m--)
    {
        int x;
        cin >> x;
        if (f[x] == 0 || st[x])
            cout << "Ron\n";
        else
            cout << "Hermione\n";       
    }
}
signed main()
{
    ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
    int _T = 1;
    //cin >> _T;
    while (_T--)
        work();
    return 0;
}