[AGC 018F] Two Trees

题目

传送门

解法

首先由于每个子树贡献均为奇,通过统计子树个数我们可以算出每个点权值的奇偶性,令权值为偶的点为偶点,反之奇点。如果某点在 (A,B) 树的奇偶性不同则不合法。

我们将 (A,B) 的根连一条边。这样每个点度数的奇偶性就是权值的奇偶性了。

然后将奇点在 (A,B) 中的对应点连边(称这种边为横叉边)。这样每个点度数为偶,且图联通,我们可以在这张图上跑欧拉回路。

偶点设定权值为 (0),奇点在欧拉回路上若有 (A ightarrow B),就令权值为 (1),反之为 (-1)

现在证明正确性。将欧拉回路拆成简单环,分别计算对一个点的贡献。

  1. 点,横叉边,子树。改值操作均在子树(包含自己)内,(1-1=0)
  2. 点走到子树/父亲,从父亲/子树回来。只有子树中横叉边有影响,贡献为 (1/-1)
  3. 点走到横叉边/父亲,从父亲/横叉边回来。贡献为 (1/-1)

由于是欧拉回路,(2,3) 情况对于每个点只有一次,故此构造正确。

代码

#include <cstdio>

#define rep(i,_l,_r) for(register signed i=(_l),_end=(_r);i<=_end;++i)
#define fep(i,_l,_r) for(register signed i=(_l),_end=(_r);i>=_end;--i)
#define erep(i,u) for(signed i=head[u],v=to[i];i;i=nxt[i],v=to[i])
#define efep(i,u) for(signed i=Head[u],v=to[i];i;i=nxt[i],v=to[i])
#define print(x,y) write(x),putchar(y)

template <class T> inline T read(const T sample) {
    T x=0; int f=1; char s;
    while((s=getchar())>'9'||s<'0') if(s=='-') f=-1;
    while(s>='0'&&s<='9') x=(x<<1)+(x<<3)+(s^48),s=getchar();
    return x*f;
}
template <class T> inline void write(const T x) {
    if(x<0) return (void) (putchar('-'),write(-x));
    if(x>9) write(x/10);
    putchar(x%10^48);
}
template <class T> inline T Max(const T x,const T y) {if(x>y) return x; return y;}
template <class T> inline T Min(const T x,const T y) {if(x<y) return x; return y;}
template <class T> inline T fab(const T x) {return x>0?x:-x;}
template <class T> inline T gcd(const T x,const T y) {return y?gcd(y,x%y):x;}
template <class T> inline T lcm(const T x,const T y) {return x/gcd(x,y)*y;}

#include <cmath>

const int maxn=3e5+5;

int tot,n,cnt=1,son[maxn<<1],head[maxn<<1],nxt[maxn*6],to[maxn*6],Euler[maxn<<1],RootA,RootB,ans[maxn];
bool vis[maxn*3];

void addEdge(int u,int v) {
	nxt[++cnt]=head[u],to[cnt]=v,head[u]=cnt;
	nxt[++cnt]=head[v],to[cnt]=u,head[v]=cnt;
}

void dfs(int u) {
	for(int &i=head[u];i;i=nxt[i]) {
		int v=to[i];
		if(vis[i>>1]) continue;
		vis[i>>1]=1;
		dfs(v);
	}
	Euler[++tot]=u;
}

int main() {
	int x;
	n=read(9);
	rep(i,1,n) {
		x=read(9);
		if(~x) addEdge(x,i),++son[x];
		else RootA=i;
	}
	rep(i,1,n) {
		x=read(9)+n;
		if(x>n) addEdge(x,i+n),++son[x];
		else RootB=i+n;
	}
	rep(i,1,n) if((son[i]&1)^(son[i+n]&1)) return puts("IMPOSSIBLE"),0;
	puts("POSSIBLE");
	addEdge(RootA,RootB);
	rep(i,1,n) if(!(son[i]&1)) addEdge(i,i+n);
	dfs(1);
	rep(i,2,tot) if(fabs(Euler[i]-Euler[i-1])==n) {
		x=Min(Euler[i],Euler[i-1]);
		if(son[x]&1) continue;
		if(Euler[i-1]<=n) ans[x]=1;
		else ans[x]=-1;
	}
	rep(i,1,n) print(ans[i],' '); puts("");
	return 0;
}
原文地址:https://www.cnblogs.com/AWhiteWall/p/14409682.html