D_L3

Leafs

Jan 26th, 2024
778
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.92 KB | None | 0 0
  1. #include <cmath>
  2. #include <cstdio>
  3. #include <vector>
  4. #include <iostream>
  5. #include <algorithm>
  6. #include <unordered_map>
  7.  
  8. using namespace std;
  9.  
  10. unordered_map<int, vector<int>> graph;
  11.  
  12. int getValue(int a, vector<bool>& visited, vector<int>& result) {
  13.     result[a] = 0;
  14.     for (int neightbour : graph[a]) {
  15.         result[a] += (getValue(neightbour, visited, result) + neightbour);
  16.     }
  17.     visited[a] = true;
  18.     return result[a];
  19. }
  20.  
  21. int main() {
  22.     int m, t, a, b;
  23.     cin >> m >> t;
  24.     int max = 0;
  25.     for (int i = 0; i < m; i++) {
  26.         cin >> a >> b;
  27.         graph[a].push_back(b);
  28.         max = std::max(a, std::max(b, max));
  29.     }
  30.    
  31.     vector<bool> visited(max+1, false);
  32.     vector<int> result(max + 1);
  33.  
  34.  
  35.     for (int i = 0; i < t; i++) {
  36.         cin >> a;
  37.         if (!visited[a])
  38.             getValue(a, visited, result);
  39.         cout << result[a] << endl;
  40.     }
  41.     return 0;
  42. }
  43.  
Advertisement
Add Comment
Please, Sign In to add comment