欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

3 Steps

程序员文章站 2024-01-15 08:28:04
...

C - 3 Steps
Time limit : 2sec / Memory limit : 256MB

Score : 500 points

Problem Statement
Rng has a connected undirected graph with N vertices. Currently, there are M edges in the graph, and the i-th edge connects Vertices Ai and Bi.

Rng will add new edges to the graph by repeating the following operation:

Operation: Choose u and v (u≠v) such that Vertex v can be reached by traversing exactly three edges from Vertex u, and add an edge connecting Vertices u and v. It is not allowed to add an edge if there is already an edge connecting Vertices u and v.
Find the maximum possible number of edges that can be added.

Constraints
2≤N≤105
1≤M≤105
1≤Ai,Bi≤N
The graph has no self-loops or multiple edges.
The graph is connected.
Input
Input is given from Standard Input in the following format:

N M
A1 B1
A2 B2
:
AM BM
Output
Find the maximum possible number of edges that can be added.

Sample Input 1
Copy
6 5
1 2
2 3
3 4
4 5
5 6
Sample Output 1
Copy
4
If we add edges as shown below, four edges can be added, and no more.

Sample Input 2
Copy
5 5
1 2
2 3
3 1
5 4
5 1
Sample Output 2
Copy
5
Five edges can be added, for example, as follows:

Add an edge connecting Vertex 5 and Vertex 3.
Add an edge connecting Vertex 5 and Vertex 2.
Add an edge connecting Vertex 4 and Vertex 1.
Add an edge connecting Vertex 4 and Vertex 2.
Add an edge connecting Vertex 4 and Vertex 3.

解析:判断是否是二分图,用深搜遍历,二分图的判断是用染色法,从而得出相应的答案;
代码:

#include<iostream>
#include<cstdio>
#include<vector> 
#include<cstring>
using namespace std;
const int maxn = 1e5 + 5;
vector<int> list[maxn];
int vis[maxn];
int lose=0;
void bfs(int ne,int be,int re)
{
    if(!lose)
    {
        if(vis[ne]==-1)
            vis[ne]=re;
        else
            if(vis[ne]!=re)
            {
                lose=1;
                return;
            }
            else
                return;
        for(int i=0;i<list[ne].size();i++)
        {
            if(list[ne][i]!=be)
                bfs(list[ne][i],ne,!re);    
        }

    }

}
int main()
{
    long long m,n;
    scanf("%lld%lld",&m,&n);
    for(int i=0;i<n;i++)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        list[x].push_back(y);
        list[y].push_back(x);
    }
    memset(vis,-1,sizeof(vis));
    bfs(1,0,1);
    long long q=0,p=0;
    for(int i=1;i<=m;i++)
    {
        if(vis[i]==1)
            q++;
        else
            p++;
    }
    if(lose)
        printf("%lld\n",m*(m-1)/2-n);
    else
        printf("%lld\n",q*p-n);

    return 0;
}