ARC143E 题解

· · 题解

Reversi

思路

考虑发生在叶子节点处的翻转,此时有两种情况:叶子是白的、叶子是黑的。讨论父亲和儿子的删除顺序。

那我们可以从 1 开始 dfs(因为字典序要最小),从下往上模拟删除每个叶子。我们就可以根据父亲和儿子的删除顺序建出一个有向图,在有向图上跑拓扑,拓扑序就是操作序列。

dfs 完我们可以得到根节点的颜色,如果是黑色就是无解。

代码

#include <bits/stdc++.h>
using namespace std;
int n,tot,a[200005],head1[200005],head[200005],in[200005];
string s;
priority_queue<int>q;
struct Edge
{
    int next,to;
}e1[400005],e[400005];
void add_edge1(int u,int v)
{
    e1[++tot].next=head1[u];
    e1[tot].to=v;
    head1[u]=tot;
}
void add_edge(int u,int v)
{
    e[++tot].next=head[u];
    e[tot].to=v;
    head[u]=tot;
    in[v]++;
}
void dfs(int u,int fa)
{
    for(int i=head1[u];i;i=e1[i].next)
    {
        int v=e1[i].to;
        if(v==fa)
            continue;
        dfs(v,u);
        a[u]^=a[v];
        if(a[v])
            add_edge(v,u);
        else
            add_edge(u,v);
    }
}
void topo()
{
    for(int i=1;i<=n;i++)
    {
        if(!in[i])
            q.push(-i);
    }
    while(!q.empty())
    {
        int u=-q.top();
        q.pop();
        printf("%d ",u);
        for(int i=head[u];i;i=e[i].next)
        {
            int v=e[i].to;
            in[v]--;
            if(!in[v])
                q.push(-v);
        }
    }
}
int main()
{
    scanf("%d",&n);
    for(int i=1;i<n;i++)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        add_edge1(x,y);
        add_edge1(y,x);
    }
    for(int i=1;i<=n;i++)
    {
        char c;
        cin >> c;
        a[i]=c=='W'?1:0;
    }
    tot=0;
    dfs(1,0);
    if(!a[1])
    {
        printf("-1");
        return 0;
    }
    topo();
}

希望本篇题解能帮到大家!!!