Advertisement
Guest User

Untitled

a guest
Dec 6th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. typedef long long ll;
  6.  
  7. const int ms = 1e5 + 20;
  8. const int mx = 5;
  9. const ll mod = 1e9 + 7;
  10.  
  11. vector<pair<int, int>> adj[ms];
  12. ll dp[ms][mx];
  13.  
  14. ll dfs(int u, int p, int ci) {
  15.   ll &ans = dp[u][ci];
  16.   if (ans != -1) return ans;
  17.   bool mk[mx] = {0};
  18.   if (u != 0) mk[ci] = 1;
  19.  
  20.   ans = 1;
  21.  
  22.   vector<int> vs, cs;
  23.  
  24.   for (auto e : adj[u]) {
  25.     int v, c;
  26.     tie(v, c) = e;
  27.     if (v == p) continue;
  28.     if (c == -1) {
  29.       vs.push_back(v);
  30.     } else {
  31.       if (mk[c]) {
  32.         return ans = 0;
  33.       }
  34.       mk[c] = 1;
  35.       ans = ans * dfs(v, u, c) % mod;
  36.     }
  37.   }
  38.  
  39.   for (int i = 0; i < mx; i++) {
  40.     if (!mk[i]) cs.push_back(i);
  41.   }
  42.  
  43.   if (cs.size() < vs.size()) return ans = 0;
  44.   ll lsc = -1, tt = 0;
  45.   do {
  46.     ll cur = 1, cur_c = 0;
  47.     for (int i = 0; i < vs.size(); i++) {
  48.       cur = cur * dfs(vs[i], u, cs[i]) % mod;
  49.       cur_c *= mx;
  50.       cur_c += cs[i];
  51.     }
  52.     if (cur_c != lsc) {
  53.       tt += cur;
  54.       if (tt >= mod) tt -= mod;
  55.     }
  56.     lsc = cur_c;
  57.   } while(next_permutation(cs.begin(), cs.end()));
  58.   ans = ans * tt % mod;
  59.   return ans;
  60. }
  61.  
  62. int main() {
  63.   int n;
  64.   cin >> n;
  65.   for (int i = 1; i < n; i++) {
  66.     int u, v, c;
  67.     scanf("%d %d %d", &u, &v, &c);
  68.     u--;
  69.     v--;
  70.     c--;
  71.     adj[u].emplace_back(v, c);
  72.     adj[v].emplace_back(u, c);
  73.   }
  74.   memset(dp, -1, sizeof dp);
  75.   cout << dfs(0, 0, 0) << endl;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement