A 多彩的树

题目地址:

https://ac.nowcoder.com/acm/contest/5556/A

基本思路:

我们看这个K只有10,所以很容易想到状压,那么我们状压颜色,然后对于每种情况我们去找图中只包含这几种颜色的连通块,对于每个联通块,假如包含n个顶点,那么路径就有条,也就是条,综上我们得到了每种颜色状态的路径条数。但是由于存在更多颜色数的状态里包含更少颜色数状态的情况,所以我们要对上面得到的答案再进行一个容斥,就能得到真正的答案了。

参考代码:

#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>
using namespace std;
#define IO std::ios::sync_with_stdio(false)
#define int long long
#define rep(i, l, r) for (int i = l; i <= r; i++)
#define per(i, l, r) for (int i = l; i >= r; i--)
#define mset(s, _) memset(s, _, sizeof(s))
#define pb push_back
#define pii pair <int, int>
#define mp(a, b) make_pair(a, b)
#define INF 0x3f3f3f3f

inline int read() {
  int x = 0, neg = 1; char op = getchar();
  while (!isdigit(op)) { if (op == '-') neg = -1; op = getchar(); }
  while (isdigit(op)) { x = 10 * x + op - '0'; op = getchar(); }
  return neg * x;
}
inline void print(int x) {
  if (x < 0) { putchar('-'); x = -x; }
  if (x >= 10) print(x / 10);
  putchar(x % 10 + '0');
}
const int maxn = 5e4 + 10;
struct Edge{
  int to,next;
}edge[maxn << 1];
int cnt = 0 ,head[maxn];
void add_edge(int u,int v){
  edge[++cnt].next = head[u];
  edge[cnt].to = v;
  head[u] = cnt; 
}
int n,k,a[maxn],fac[maxn];
int res = 0;
bool vis[maxn];
void dfs(int u,int par,int S){//dfs找连通块;
  if((a[u]|S) != S || vis[u]) return;
  vis[u] = true; res++;
  for(int i = head[u] ; i!= -1 ; i = edge[i].next){
    int to = edge[i].to;
    if(to == par) continue;
    dfs(to,u,S);
  }
}
int dp[1 << 11];
const int mod = 1e9 + 7;
signed main() {
  fac[0] = 1;
  rep(i,1,maxn-1) fac[i] = fac[i-1] * 131 % mod;//预处理下这个131^i;
  n = read(),k = read();
  rep(i,1,n) a[i] = 1 << (read() - 1);//这里处理一下颜色;
  cnt = 0;mset(head,-1);
  rep(i,1,n-1){
    int u = read(),v = read();
    add_edge(u,v);
    add_edge(v,u);
  }
  for(int i = 0 ; i < (1 << k) ; i++){
    mset(vis,false);
    rep(j,1,n) if(!vis[j]){
      res = 0 ; dfs(j,0,i);
      int k1 = res,k2 = res - 1;
      if(k1 % 2 == 0) k1 /= 2;
      else k2 /= 2; 
      //加每个联通块中的路径条数;
      dp[i] = (dp[i] + k1 * k2 % mod + res) % mod;
    }
  }
  int ans = 0;
  for(int i = 0 ; i < (1 << k) ; i++){
    for(int j = (i-1) & i ; j ; j = (j-1) & i) dp[i] -= dp[j];//容斥一下;
    ans = (ans + fac[__builtin_popcount(i)] * dp[i] % mod) % mod;
  }
  while(ans < 0) ans += mod;
  ans %= mod;
  cout << ans << '\n';
  return 0;
}