A. Hongcow Builds A Nation
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries.
The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the kcountries that make up the world.
There is at most one edge connecting any two nodes and no edge connects a node to itself. Furthermore, for any two nodes corresponding to governments, there is no path between those two nodes. Any graph that satisfies all of these conditions is stable.
Hongcow wants to add as many edges as possible to the graph while keeping it stable. Determine the maximum number of edges Hongcow can add.
Input
The first line of input will contain three integers n, m and k (1 ≤ n ≤ 1 000, 0 ≤ m ≤ 100 000, 1 ≤ k ≤ n) — the number of vertices and edges in the graph, and the number of vertices that are homes of the government.
The next line of input will contain k integers c1, c2, ..., ck (1 ≤ ci ≤ n). These integers will be pairwise distinct and denote the nodes that are home to the governments in this world.
The following m lines of input will contain two integers ui and vi (1 ≤ ui, vi ≤ n). This denotes an undirected edge between nodes ui and vi.
It is guaranteed that the graph described by the input is stable.
Output
Output a single integer, the maximum number of edges Hongcow can add to the graph while keeping it stable.
Simple Input
4 1 2
1 3
1 2
Simple Output
2
题目大意:有n个城市,m个边,K个国家。每个国家的首都之间没有通路,问最多能在原图中添加多少路径。
分析:K个国家之间没有任何路径相连,即有K个无并集的集合。要使得可添加的路径最多,即只要在K个点集合的基础上做出一个完全图,就能使得路径数量最多。所求结果,添加的路径数量就是最多的路径减去原有的路径。
则,建立一个并查集,每次输入都将集合更新。那么最后就有3部分,一是城市最多的国家,二是其他的国家,三是没有与任何首都相连的国家。推理可得,把独立城市与最大的国家相连,如此得到的无向完全图边数最多。
Code:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <vector>
#include <cmath>
#include <algorithm>
#include <queue>
#include <set>
#include <string>
#include <cstring>
using namespace std;
const int maxn = 1e5+10;
typedef long long ll;
int num[maxn];
int F[1010];
int fnd(int t){
if(F[t] == t) return t;
return F[t] = fnd(F[t]);
}
void join(int a,int b){
int t1 = fnd(a);
int t2 = fnd(b);
if(t1!=t2) F[t1] = t2;
}
int main()
{
int n,m,k;
int cap[maxn];
cin >> n >> m >> k;
memset(num,0,sizeof(num));
memset(F,0,sizeof(F));
for(int i=1; i<=n; ++i)
F[i] = i; //initialize F
for(int i=1; i<=k ;++i)
cin >> cap[i];
for(int i=1,a,b; i<=m; ++i){
cin >> a >> b;
join(a,b);
}
for(int i=1; i<=n; ++i)
num[fnd(i)]++;
int maxn = 0,lef = n;
int ans = 0;
for(int i=1; i<=k; ++i){
num[cap[i]] = num[fnd(cap[i])];
maxn = max(maxn,num[cap[i]]);
lef -= num[cap[i]];
ans += (num[cap[i]] - 1) * (num[cap[i]])/2;
}
ans += (lef+maxn) * (lef+maxn-1)/2;
ans -= maxn*(maxn-1)/2 + m;
cout << ans ;
return 0;
}