Guest User

Untitled

a guest
Jan 18th, 2020
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.06 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define fastio ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
  4. typedef long long int ll;
  5. #define INF LLONG_MAX
  6.  
  7. vector<bool> visited(100005);
  8. vector<ll> adj[100005];
  9. vector<ll> dist(100005);
  10. ll n,m,u,v;
  11. ll c = 0;
  12. ll big = -INF;
  13. ll sum;
  14.  
  15. void dfs(ll s){
  16.  
  17.     if(visited[s] == true) return;
  18.     visited[s] = true;
  19.     c++;
  20.     big = max(big , s);
  21.     for(auto u : adj[s]) if(visited[u] == false ) dfs(u);
  22. }
  23.  
  24. void bfs(ll s){
  25.  
  26.     queue<ll> q;
  27.     for(ll i = 0; i < n; i++) {
  28.         dist[i] = 0;
  29.         visited[i] = false;
  30.     }
  31.     q.push(s);
  32.     dist[s]  = 1;
  33.     sum = 1;
  34.     while(!q.empty()){
  35.         ll a = q.front();
  36.         q.pop();
  37.         if(visited[a] == true) continue;
  38.         visited[a] = true;
  39.  
  40.         for(auto x : adj[a]){
  41.             if(visited[x] == true) continue;
  42.             q.push(x);
  43.             dist[x] = dist[a] + 1;
  44.             sum += dist[x];
  45.         }
  46.     }
  47. }
  48.  
  49.  
  50. int main() {
  51.  
  52.     fastio;
  53.  
  54.     ll test;
  55.     cin >> test;
  56.  
  57.     while(test--){
  58.  
  59.         queue<ll> o;
  60.         queue<ll> e;
  61.         ll powerodd = 0 , powereven = 0;
  62.  
  63.         cin >> n >> m;
  64.         for(ll i = 0; i < m; i++){
  65.             cin >> u >> v;
  66.             adj[u-1].push_back(v-1);
  67.             adj[v-1].push_back(u-1);
  68.         }
  69.         for(ll i = 0; i < n; i++){
  70.             if(visited[i] == true) continue;
  71.             c = 0;
  72.             big = -INF;
  73.             dfs(i);
  74.             if(c%2 == 0) e.push(i);
  75.             else o.push(big);
  76.         }
  77.  
  78.         while(!e.empty()){
  79.  
  80.             ll a = e.front();
  81.             e.pop();
  82.            sum = 0;
  83.  
  84.             bfs(a);
  85.             powereven += sum;
  86.  
  87.         }
  88.  
  89.         while(!o.empty()){
  90.  
  91.             ll b = o.front();
  92.             o.pop();
  93.             sum  = 0;
  94.             bfs(b);
  95.             powerodd += sum;
  96.         }
  97.  
  98.         cout << powereven << " " << powerodd << "\n";
  99.  
  100.         for(ll i = 0; i < n; i++) {
  101.             adj[i].clear();
  102.             visited[i] = false;
  103.         }
  104.     }
  105.     return 0;
  106. }
Add Comment
Please, Sign In to add comment