745C - Hongcow Builds A Nation - CodeForces Solution


constructive algorithms dfs and similar graphs *1500

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;
#define ll long long
vector<int>adj[1005];
bool vis[1005];
int nodes=1, edges=0;
void dfs(int n) {
    vis[n]=1;
    for(auto it:adj[n])
        if(!vis[it]) {
            nodes++;
            edges+=adj[it].size();
            dfs(it);
        }
}
int main() {
    std::ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    int n, m, k, u, v;
    cin>>n>>m>>k;
    int a[k];
    for(int i=0; i<k; i++)
        cin>>a[i];
    for(int i=0; i<m; i++) {
        cin>>u>>v;
        adj[u].push_back(v);
        adj[v].push_back(u);
    }
    priority_queue<int>pq;
    ll ans=0;
    for(int i=0; i<k; i++) {
        nodes=1, edges=adj[a[i]].size();
        dfs(a[i]);
        edges/=2;
        ans+=((nodes*(nodes-1)/2)-edges);
        pq.push(nodes);
    }
    ll mx=pq.top();
    for(int i=1; i<=n; i++)
        if(!vis[i]) {
            nodes=1, edges=adj[i].size();
            dfs(i);
            edges/=2;
            ans+=((nodes*(nodes-1)/2)-edges);
            ans+=mx*nodes;
            mx+=nodes;
        }
    cout<<ans;
    return 0;
}


Comments

Submit
0 Comments
More Questions

1075B - Taxi drivers and Lyft
1562A - The Miracle and the Sleeper
1216A - Prefixes
1490C - Sum of Cubes
868A - Bark to Unlock
873B - Balanced Substring
1401D - Maximum Distributed Tree
1716C - Robot in a Hallway
1688B - Patchouli's Magical Talisman
99A - Help Far Away Kingdom
622B - The Time
1688C - Manipulating History
1169D - Good Triple
1675B - Make It Increasing
588A - Duff and Meat
1541B - Pleasant Pairs
1626B - Minor Reduction
1680A - Minimums and Maximums
1713A - Traveling Salesman Problem
1713B - Optimal Reduction
1710A - Color the Picture
1686B - Odd Subarrays
251A - Points on Line
427C - Checkposts
1159A - A pile of stones
508A - Pasha and Pixels
912A - Tricky Alchemy
1249A - Yet Another Dividing into Teams
1713C - Build Permutation
1699A - The Third Three Number Problem