abc152F - Tree and Constraints
题意:给定一棵树,要求对每条边染成黑色或者白色,其中有m个限制,第i个限制形如ai,bi,表示ai到bi的路径上至少有一条黑色边,求方案数。
看到数据第一反应是状压,但是好像没办法搞。
于是考虑容斥,能想到容斥的话就差不多做完了,每次标记一下两个点和他们的lca即可,然后从底向上累加标记即可。
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<map>
#include<queue>
#include<bitset>
#include<cmath>
#include<set>
#include<unordered_map>
#define fo(i,a,b) for (ll (i)=(a);(i)<=(b);(i)++)
#define fd(i,b,a) for (ll (i)=(b);(i)>=(a);(i)--)
#define mk(x,y) make_pair((x),(y))
#define lc (o<<1)
#define rc ((o<<1)|1)
//#define A puts("Yes")
//#define B puts("No")
using namespace std;
typedef double db;
typedef long long ll;
//typedef __int128 i128;
const int N=2e5+5;
const int S=1<<15;
const ll inf=1ll<<60;
int to[N*2],nex[N*2],head[N],tot=1,n,x,y;
int a[N*2],b[N*2],m,d[N],f[N],c[N],e[N];
ll p[N],ans;
bool bz[200];
void add(int x,int y){
to[++tot]=y; nex[tot]=head[x]; head[x]=tot;
}
void dg(int x,int y){
for (int i=head[x];i;i=nex[i]) {
int v=to[i];
if (v==y) continue;
f[v]=x;
d[v]=d[x]+1;
dg(v,x);
}
}
int work(int x,int y){
if (d[x]<d[y]) swap(x,y);
while (d[x]>d[y]) x=f[x];
while (x^y) x=f[x], y=f[y];
return x;
}
int calc(int x,int y){
ll s=0,z;
for (int i=head[x];i;i=nex[i]) {
int v=to[i];
if (v==y) continue;
z=calc(v,x);
if (z>0) {
bz[i]=bz[i^1]=1;
}
s+=z;
}
return s+e[x];
}
void dfs(int x,ll f){
if (x>m) {
fo(i,2,tot) bz[i]=0;
calc(1,0);
ll k=0;
for (int i=2;i<=tot;i+=2) {
if (!bz[i]) k++;
}
ans+=p[k]*f;
return;
}
e[a[x]]++;
e[b[x]]++;
e[c[x]]-=2;
dfs(x+1, -f);
e[a[x]]--;
e[b[x]]--;
e[c[x]]+=2;
dfs(x+1, f);
}
int main()
{
// freopen("data.in","r",stdin);
// freopen("data.out","w",stdout);
p[0]=1;
fo(i,1,60) p[i]=p[i-1]*2ll;
scanf("%d",&n);
fo(i,1,n-1) {
scanf("%d %d",&x,&y);
add(x,y);
add(y,x);
}
dg(1,0);
scanf("%d",&m);
fo(i,1,m) {
scanf("%d %d",&a[i],&b[i]);
c[i]=work(a[i],b[i]);
// printf("%d\n",c[i]);
}
dfs(1,1);
printf("%lld",ans);
return 0;
}
标签:abc152F,int,ll,Tree,define,include,Constraints
From: https://www.cnblogs.com/ganking/p/17992498