AT_arc143_e [ARC143E] Reversi 题解

· · 题解

:::::success[Hint 1] 考虑对叶子节点进行观察,然后扩展到整棵树。 :::::

对应 Hint 1:

我们直接对任意节点进行讨论过于麻烦,所以我们考虑对叶子节点这样较为简单的节点进行讨论。

我们发现:

然后我们发现,我们对于任意节点,我们只需要先讨论完它的儿子就可以将其当作叶子节点来考虑了,这样我们可以对所有树边进行定向。

当讨论完所有点后发现最终根节点变成了黑色那么就无解,否则我们可以使用拓扑排序来得到答案。

这样我们就做完了这道题。
时间复杂度为 \Theta(n\log n),空间复杂度为 \Theta(n)。

:::::success[code]

#include<bits/stdc++.h>
#define inl inline
#define int long long 
#define lll __int128
#define fst ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define rep(i,x,y) for(int i=x;i<=(y);++i) 
#define per(i,x,y) for(int i=x;i>=(y);--i)
#define rpr(i,x,y,z) for(int i=x;i<=(y);i+=z)
#define epe(i,x,y,z) for(int i=x;i>=(y);i-=z)
#define repe(i,x,y) for(i=x;i<=(y);++i) 
#define endl '\n'
#define INF 1e18
#define pb push_back
#define pob pop_back
#define pf push_front
#define pof pop_front 
#define fi first
#define se second
#define lcm(x,y) x/__gcd(x,y)*y
#define ull unsigned long long
#define prr make_pair
#define pii pair<int,int> 
#define gt(s) getline(cin,s)
#define at(x,y) for(const auto &x:y)
#define ff fflush(stdout)
#define mt(x,y) memset(x,y,sizeof(x))
#define idg isdigit
#define fp(s) string ssss=s;freopen((ssss+".in").c_str(),"r",stdin);freopen((ssss+\
".out").c_str(),"w",stdout);
#define sstr stringstream 
#define all(x) x.begin(),x.end()
#define mcy(a,b) memcpy(a,b,sizeof(b))
#define ui unsigned
#define si signed
#define eb emplace_back
#define pff(x) ((x)*(x))
#define eush emplace
#define double long double
#define pdi pair<double,int>
#ifdef __unix__
#define gc getchar_unlocked
#else
#define gc _getchar_nolock
#endif
#ifdef __unix__
#define pc putchar_unlocked
#else
#define pc _putchar_nolock
#endif
using namespace std;
const int N=2e5+5;
vector<int>g[N],gx[N],ans;
int a[N],n,ind[N];
inl void dfs(int u,int ft){
    at(v,g[u])
        if(v!=ft){
            dfs(v,u);
            a[u]^=!a[v];
            if(a[v]){
                gx[u].pb(v);
                ++ind[v];
            }else{
                gx[v].pb(u);
                ++ind[u];
            }
        }
}
inl void topsort(){
    priority_queue<int,vector<int>,greater<int> >pq;
    rep(i,1,n)
        if(!ind[i]) pq.eush(i);
    while(!pq.empty()){
        int u=pq.top();
        pq.pop();
        ans.pb(u);
        at(v,gx[u]){
            --ind[v];
            if(!ind[v]) pq.eush(v);
        }
    }
}
si main(){
    fst;
    string s;
    cin>>n;
    rep(i,2,n){
        int u,v;
        cin>>u>>v;
        g[u].pb(v);
        g[v].pb(u);
    }
    cin>>s;
    s=' '+s;
    rep(i,1,n)
        if(s[i]=='B') a[i]=1;
        else a[i]=0;
    dfs(1,0);
    if(a[1]){
        cout<<-1<<endl;
        return 0;
    }
    topsort();
    at(x,ans) cout<<x<<' ';
    return 0;
} 

:::::