找点对数很容易想到点分治,k<10很容易想到状压,那么就维护根为x向下的有对应颜色状态的方案数有多少,可以用树背包DP维护即可。。然后统计的时候可以借用树分治的套路,在边dfs的时候和已统计出来的树链合并就可以了。。
#include<bits/stdc++.h>
using namespace std;
#define inc(i,l,r) for(int i=l;i<=r;i++)
#define dec(i,l,r) for(int i=l;i>=r;i--)
#define link(x) for(edge *j=h[x];j;j=j->next)
#define mem(a) memset(a,0,sizeof(a))
#define eps 1e-8
#define NM 50005
#define nm 100005
#define mid (x+y>>1)
#define succ(x) (1<<(x))
#define ll long long
const ll inf=1e9+7;
ll read(){
ll x=0,f=1;char ch=getchar();
while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();}
while(isdigit(ch))x=x*10+ch-'0',ch=getchar();
return f*x;
}
struct edge{int t;edge*next;}e[nm],*h[NM],*o=e;
void add(int x,int y){o->t=y;o->next=h[x];h[x]=o++;}
int n,m,cnt,a[NM],_x,_y;
ll ans;
unsigned short d[NM][1024];
int size[NM],smin,s,tot,root;
bool v[NM];
void dfs1(int x,int f){size[x]=1;link(x)if(!v[j->t]&&j->t!=f)dfs1(j->t,x),size[x]+=size[j->t];}
void getroot(int x,int f){
int s=tot-size[x];
link(x)if(!v[j->t]&&j->t!=f)getroot(j->t,x),s=max(s,size[j->t]);
if(s<smin)smin=s,root=x;
}
void dfs(int x,int f,int t){
inc(k,0,cnt){if((k|t)==cnt)ans+=d[root][k];d[x][k]=0;}
link(x)if(!v[j->t]&&j->t!=f){
dfs(j->t,x,t|succ(a[j->t]));
inc(k,0,cnt)d[x][succ(a[x])|k]+=d[j->t][k];
}
d[x][succ(a[x])]++;
}
void div(int x){
dfs1(x,0);
tot=size[x];smin=n;
getroot(x,0);
v[root]++;mem(d[root]);d[root][succ(a[root])]=1;
link(root)if(!v[j->t]){
dfs(j->t,root,succ(a[j->t]));
inc(k,0,cnt)d[root][succ(a[root])|k]+=d[j->t][k];
}
link(root)if(!v[j->t])div(j->t);
}
int main(){
while(~scanf("%d%d",&n,&m)){
mem(e);mem(h);o=e;mem(v);ans=0;
cnt=succ(m)-1;
inc(i,1,n)a[i]=read()-1;
inc(i,1,n-1){_x=read();_y=read();add(_x,_y);add(_y,_x);}
div(1);ans*=2;if(m==1)ans+=n;
printf("%lld\n",ans);
}
return 0;
}
Garden of EdenTime Limit: 10000/5000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)Total Submission(s): 2039 Accepted Submission(s): 661 Problem Description When God made the first man, he put him on a beautiful garden, the Garden of Eden. Here Adam lived with all animals. God gave Adam eternal life. But Adam was lonely in the garden, so God made Eve. When Adam was asleep one night, God took a rib from him and made Eve beside him. God said to them, “here in the Garden, you can do everything, but you cannot eat apples from the tree of knowledge.”
Input There are several cases.Process till end of input.
Output For each case output your answer on a single line.
Sample Input 3 2 1 2 2 1 2 1 3
Sample Output 6
Source 2016ACM/ICPC亚洲区大连站-重现赛(感谢大连海事大学)
Recommend wange2014
|