题解:
我们能用
O(n2|S|)
O
(
n
2
|
S
|
)
的时间统计出所有点都是颜色集合
S
S
中的一个颜色的方案树。
然后枚举 S S 做容斥即可。 时间复杂度。
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int RLEN=1<<18|1;
inline char nc() {
static char ibuf[RLEN],*ib,*ob;
(ib==ob) && (ob=(ib=ibuf)+fread(ibuf,1,RLEN,stdin));
return (ib==ob) ? -1 : *ib++;
}
inline int rd() {
char ch=nc(); int i=0,f=1;
while(!isdigit(ch)) {if(ch=='-')f=-1; ch=nc();}
while(isdigit(ch)) {i=(i<<1)+(i<<3)+ch-'0'; ch=nc();}
return i*f;
}
const int N=20;
int n, m, G[N][N], bin[N], a[N], tot;
LL f[N][N];
vector <int> edge[N];
inline void dfs(int x,int fa,int sta) {
for(int e=edge[x].size()-1;e>=0;e--) {
int v=edge[x][e]; if(v==fa) continue;
dfs(v,x,sta);
}
for(int now=1;now<=tot;++now) {
LL rs=1;
for(int e=edge[x].size()-1;e>=0;e--) {
int v=edge[x][e]; if(v==fa) continue;
LL sum=0;
for(int j=1;j<=tot;j++)
if(G[a[now]][a[j]]) sum+=f[v][a[j]];
rs=rs*sum;
}
f[x][a[now]]=rs;
}
}
inline LL calc(int sta) {
memset(f,0,sizeof(f));
tot=0;
for(int i=0;i<n;i++)
if((sta>>i)&1) a[++tot]=i;
dfs(0,0,sta); LL rs=0;
for(int i=0;i<n;i++) rs+=f[0][i];
return rs;
}
int main() {
n=rd(); m=rd();
for(int i=1;i<=m;i++) {
int x=rd()-1, y=rd()-1;
G[x][y]=G[y][x]=1;
}
for(int i=1;i<n;i++) {
int x=rd()-1, y=rd()-1;
edge[x].push_back(y);
edge[y].push_back(x);
}
for(int i=0;i<=n;i++) bin[i]=1<<i;
long long ans=0;
for(int i=0;i<bin[n];i++)
ans+=calc(i)*((__builtin_popcount(i)&1) ? 1 : -1);
cout<<abs(ans);
}