Problem Description
Soda has a bipartite graph with m undirected edges. Now he wants to make the graph become a complete bipartite graph with most edges by adding some extra edges. Soda needs you to tell him the maximum number of edges he can add.

Note: There must be at most one edge between any pair of vertices both in the new graph and old graph.
 

 

Input
There are multiple test cases. The first line of input contains an integer v.

There's at most one edge between any pair of vertices. Most test cases are small.
 

 

Output
For each test case, output the maximum number of edges Soda can add.
 

 

Sample Input
2 4 2 1 2 2 3 4 4 1 2 1 4 2 3 3 4
 

 

Sample Output
2 0
 

 

Source

 题意:给定一个二分图,要求添加最多的边将原来的二分图变成完全二分图。

解法一:dfs染色:

ans[0]表示左边的图的点个数, ans[1]表示右边的点个数,跑一个dfs,将给定二分图分成两种颜色(color数组用来记录是否染色到),然后没有染色到的就加入左右两边,使得左右两边尽可能接近,相乘 再减掉原来给定边的数量就是能加得最多的边数了。

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<vector>
 5 #include<set>
 6 #include<map>
 7 using namespace std;
 8 #define N 10006
 9 int n,m;
10 vector<int>G[N];
11 int color[N];
12 int ans[2];
13 void init()
14 {
15     for(int i=0;i<=n;i++)
16     {
17         G[i].clear();
18         color[i]=-1;
19     } 
20     ans[0]=ans[1]=0;
21 
22 }
23 void dfs(int cur,int cnt)
24 {
25     for(int i=0;i<G[cur].size();i++)
26     {
27         int u=G[cur][i];
28         if(color[u]==-1)
29         {
30             color[u]=0;
31             ans[cnt]++;
32             dfs(u,cnt^1);
33         }
34     }
35 }
36 int main()
37 {
38     int t;
39     scanf("%d",&t);
40     while(t--)
41     {
42         scanf("%d%d",&n,&m);
43         init();
44         for(int i=0;i<m;i++)
45         {
46             int x,y;
47             scanf("%d%d",&x,&y);
48             G[x].push_back(y);
49             G[y].push_back(x);
50         }
51         for(int i=1;i<=n;i++)
52         {
53             if(color[i]==-1 && G[i].size()!=0)
54             {
55                 color[i]=0;
56                 ans[0]++;
57                 dfs(i,1);
58             }
59         }
60         
61         int res=0;
62         
63         for(int i=1;i<=n;i++)
64         {
65             if(color[i]==-1)
66               res++;
67         }
68         
69         while(res--)
70         {
71             if(ans[0]<ans[1])
72               ans[0]++;
73              else 
74                ans[1]++;
75         }
76         printf("%d\n",ans[0]*ans[1]-m);
77     }
78     
79     return 0;
80 }
View Code

相关文章: