Advertisement
Josif_tepe

Untitled

Mar 21st, 2025
258
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.25 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <cstring>
  5. #include <queue>
  6. using namespace std;
  7. typedef long long ll;
  8. const int maxn = 2e5 + 100;
  9.  
  10. vector<int> graph[maxn];
  11. int main() {
  12.     int n, m;
  13.     cin >> n >> m;
  14.    
  15.     for(int i = 0; i < m; i++) {
  16.         int a, b;
  17.         cin >> a >> b;
  18.        
  19.         graph[a].push_back(b);
  20.         graph[b].push_back(a);
  21.     }
  22.    
  23.     vector<bool> visited(n);
  24.     ll res = 0;
  25.     for(int i = 0; i < n; i++) {
  26.         if(!visited[i]) {
  27.             visited[i] = true;
  28.             queue<int> q;
  29.             q.push(i);
  30.            
  31.             ll component_size = 0;
  32.             while(!q.empty()) {
  33.                 int node = q.front();
  34.                 q.pop();
  35.                 component_size++;
  36.                 for(int i = 0; i < (int) graph[node].size(); i++) {
  37.                     int neighbour = graph[node][i];
  38.                    
  39.                     if(!visited[neighbour]) {
  40.                         q.push(neighbour);
  41.                         visited[neighbour] = true;
  42.                     }
  43.                 }
  44.             }
  45.            
  46.             res += component_size * (n - component_size);
  47.         }
  48.     }
  49.  
  50.     cout << res / 2 << endl;
  51.     return 0;
  52. }
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement