Advertisement
Josif_tepe

Untitled

Jul 8th, 2023
826
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <cstring>
  4. #include <fstream>
  5. using namespace std;
  6. typedef long long ll;
  7. const int maxn = 1e5 + 10;
  8. vector<int> graph[maxn];
  9. const ll MOD = 1e9 + 7;
  10. int painted[maxn];
  11. ll dp[maxn][4];
  12. void dfs(int node, int prev) {
  13.     for(int i = 0; i < (int) graph[node].size(); i++) {
  14.         int neighbour = graph[node][i];
  15.         if(neighbour != prev) {
  16.             dfs(neighbour, node);
  17.         }
  18.     }
  19.     for(int current_color = 1; current_color <= 3; current_color++) {
  20.         if(painted[node] != -1 and painted[node] != current_color) {
  21.             continue;
  22.         }
  23.        
  24.         dp[node][current_color] = 1;
  25.        
  26.         for(int i = 0; i < (int) graph[node].size(); i++) {
  27.             int neighbour = graph[node][i];
  28.             if(neighbour != prev) {
  29.                 ll sum = 0;
  30.                 for(int next_color = 1; next_color <= 3; next_color++) {
  31.                     if(current_color != next_color) {
  32.                         sum += dp[neighbour][next_color];
  33.                     }
  34.                 }
  35.                 dp[node][current_color] *= sum;
  36.                 dp[node][current_color] %= MOD;
  37.                
  38.             }
  39.         }
  40.     }
  41. }
  42. int main(int argc, const char * argv[]) {
  43.     ios_base::sync_with_stdio(false);
  44.     ifstream cin("barnpainting.in");
  45.     ofstream cout("barnpainting.out");
  46.     int n, k;
  47.     cin >> n >> k;
  48.    
  49.     for(int i = 0; i < n - 1; i++) {
  50.         int a, b;
  51.         cin >> a >> b;
  52.         a--; b--;
  53.         graph[a].push_back(b);
  54.         graph[b].push_back(a);
  55.     }
  56.     memset(painted, -1, sizeof painted);
  57.     for(int i = 0; i < k; i++) {
  58.         int a, b;
  59.         cin >> a >> b;
  60.         a--;
  61.         painted[a] = b;
  62.     }
  63.     dfs(0, -1);
  64.     cout << (dp[0][1] + dp[0][2] + dp[0][3]) % MOD  << endl;
  65.     return 0;
  66. }
  67.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement