Advertisement
Josif_tepe

Untitled

Oct 29th, 2023
853
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.71 KB | None | 0 0
  1. #include <iostream>
  2. #include <queue>
  3. #include <vector>
  4. #include <fstream>
  5. using namespace std;
  6. const int maxn = 1e5 + 10;
  7.  
  8. vector<int> graph[maxn];
  9. int main() {
  10.     ifstream cin("milkvisits.in");
  11.     ofstream cout("milkvisits.out");
  12.     int n, m;
  13.     cin >> n >> m;
  14.     string s;
  15.     cin >> s;
  16.    
  17.     for(int i = 1; i < n; i++) {
  18.         int a, b;
  19.         cin >> a >> b;
  20.         a--;
  21.         b--;
  22.         graph[a].push_back(b);
  23.         graph[b].push_back(a);
  24.     }
  25.     vector<pair<pair<int, int>, char>> queries;
  26.     for(int i = 0; i < m; i++) {
  27.         int a, b;
  28.         cin >> a >> b;
  29.         a--; b--;
  30.         char c;
  31.         cin >> c;
  32.         queries.push_back(make_pair(make_pair(a, b), c));
  33.     }
  34.    
  35.     vector<int> id(n, -1);
  36.    
  37.     for(int i = 0; i < n; i++) {
  38.         if(id[i] == -1) {
  39.             queue<int> q;
  40.             q.push(i);
  41.            
  42.             while(!q.empty()) {
  43.                 int node = q.front();
  44.                 q.pop();
  45.                 id[node] = i;
  46.                 for(int neighbour : graph[node]) {
  47.                     if(id[neighbour] == -1 and s[neighbour] == s[i]) {
  48.                         q.push(neighbour);
  49.                     }
  50.                 }
  51.             }
  52.         }
  53.     }
  54.     string res = "";
  55.     for(int i = 0; i < m; i++) {
  56.         int a = queries[i].first.first;
  57.         int b = queries[i].first.second;
  58.         char c = queries[i].second;
  59.        
  60.         if(id[a] == id[b]) {
  61.             if(s[a] == c) {
  62.                 res += "1";
  63.             }
  64.             else {
  65.                 res += "0";
  66.             }
  67.         }
  68.         else {
  69.             res += "1";
  70.         }
  71.     }
  72.    
  73.     cout << res << endl;
  74.     return 0;
  75. }
  76.  
  77.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement