leoanjos

Jingle Bells

Oct 26th, 2021
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. #define long long long int
  6.  
  7. const int MOD = 1e9 + 7;
  8.  
  9. vector<vector<pair<int, int>>> tree;
  10. vector<vector<long>> memo;
  11.  
  12. long ways(int parent_color = 6, int v = 0, int p = -1) {
  13.     int children = (int) tree[v].size();
  14.     if (children <= 1 && ~p) return 1LL;
  15.  
  16.     long &ans = memo[parent_color][v];
  17.     if (~ans) return ans;
  18.  
  19.     ans = 0LL;
  20.     for (int i = 1; i < (1 << 5); i++) {
  21.         if (__builtin_popcount(i) != children) continue;
  22.  
  23.         vector<int> colors;
  24.         for (int j = 0; j < 5; j++)
  25.             if (i & (1 << j))
  26.                 colors.push_back(j + 1);
  27.  
  28.         do {
  29.             long cnt = 1LL;
  30.             bool possible = true;
  31.  
  32.             for (int j = 0; j < children && possible; j++) {
  33.                 auto [u, c] = tree[v][j];
  34.                 if (u == p && colors[j] != parent_color) possible = false;
  35.                 else if (u != p) {
  36.                     if (c && c != colors[j]) possible = false;
  37.                     else cnt = (cnt * ways(colors[j], u, v)) % MOD;
  38.                 }
  39.             }
  40.  
  41.             if (!possible) continue;
  42.             ans = (ans + cnt) % MOD;
  43.         } while (next_permutation(colors.begin(), colors.end()));
  44.     }
  45.  
  46.     return ans;
  47. }
  48.  
  49. int main() {
  50.     ios_base::sync_with_stdio(false);
  51.     cin.tie(NULL);
  52.  
  53.     int N; cin >> N;
  54.  
  55.     tree.assign(N, vector<pair<int, int>>());
  56.     for (int i = 1; i < N; i++) {
  57.         int u, v, c;
  58.         cin >> u >> v >> c;
  59.  
  60.         tree[u - 1].emplace_back(v - 1, c);
  61.         tree[v - 1].emplace_back(u - 1, c);
  62.     }
  63.  
  64.     memo.assign(10, vector<long>(N + 5, -1LL));
  65.  
  66.     if (N == 1) cout << "1\n";
  67.     else {
  68.         long ans = ways();
  69.         cout << ans << "\n";
  70.     }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment