D_L3

test 6 - 2022-2023 - Преброяване на области

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