B - Hongcow Builds A Nation
Codeforces Round #385 (Div. 2)
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 k countries 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.
Example
Input
4 1 2
1 3
1 2
Output
2
Input
3 3 1
2
1 2
1 3
2 3
Output
0
Note
For the first sample test, the graph looks like this:
Vertices 1 and 3 are special. The optimal solution is to connect vertex 4 to vertices 1 and 2. This adds a total of 2 edges. We cannot add any more edges, since vertices 1 and 3 cannot have any path between them.For the second sample test, the graph looks like this:
We cannot add any more edges to this graph. Note that we are not allowed to add self-loops, and the graph must be simple.
題意:已知一個無向圖,圖中一些結點為政府,在圖中添加盡量多的邊,使每一個非政府結點都與政府結點連通,且所有政府結點不相互連通,問最多加幾條邊。
解法:并查集,求出每個有政府的集合有多少個結點,找出有最多結點的集合,把沒有與政府相連的結點都算到這個集合中,求出每個集合最多邊數量,減去起始時邊的數量,即為答案
代碼:
#include<iostream>
using namespace std;
bool g[1005];
int pre[1005],cnt[1005],maxn=1;
int root(int x){
if(x!=pre[x])
pre[x]=root(pre[x]);
return pre[x];
}
int main()
{
int n,m,k,gg,x,y;
cin>>n>>m>>k;
for(int i=1;i<=n;i++){
pre[i]=i;
g[i]=0;
cnt[i]=1;
}
for(int i=0;i<k;i++){
cin>>gg;
g[gg]=1;
}
for(int i=0;i<m;i++){
cin>>x>>y;
int px=root(x);
int py=root(y);
if(px!=py){
if(g[px]==1&&g[py]==0)
swap(px,py);
pre[px]=py;
cnt[py]+=cnt[px];
if(g[pre[py]])
maxn=max(cnt[py],maxn);
}
}
int sum=0,temp,flag=0,num=0;
for(int i=1;i<=n;i++){
if(g[i]==1){
if(cnt[i]==maxn&&flag==0){
temp=i;
flag=1;
}
else
sum=sum+cnt[i]*(cnt[i]-1)/2;
}
else
if(g[root(i)]==0)
num++;
}
sum=sum+(cnt[temp]+num)*(cnt[temp]+num-1)/2;
cout<<sum-m<<endl;
return 0;
}