Description
Once upon a time there was an undirected graph with n points, m edges, no self rings and double edges.
For two points u;v that do not have a direct edge, you can combine them. Specifically, you can delete u;v and all the edges that end with them, and then add a new point x to connect it with all the points that have direct connection with u or v in the original image.
You need to decide whether you can make the original image a chain through several merging operations. If you can, you need to find out the maximum length of the chain
Title Solution
First, judge the situation without solution,
It is obvious that a ternary ring has no solution,
To generalize, as long as there are odd rings, there is no solution.
Consider constructing a legal solution,
Enumerate a point as the top of the chain,
Then you can reduce all the points that are the same distance to it to one point.
So the last one that comes out must be a chain,
How is the longest chain? That's obviously the diameter of the graph.
For different connection blocks, add their answers together.
code
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string.h>
#include <cmath>
#define ll long long
#define N 100003
#define M 103
#define db double
#define P putchar
#define G getchar
using namespace std;
char ch;
void read(int &n)
{
n=0;
ch=G();
while((ch<'0' || ch>'9') && ch!='-')ch=G();
ll w=1;
if(ch=='-')w=-1,ch=G();
while('0'<=ch && ch<='9')n=(n<<3)+(n<<1)+ch-'0',ch=G();
n*=w;
}
int max(int a,int b){return a>b?a:b;}
int min(int a,int b){return a<b?a:b;}
void write(ll x){if(x>9) write(x/10);P(x%10+'0');}
int n,m,nxt[N*2],lst[N],to[N*2],tot,x,y;
int ans,mx[N],cnt,col[N],dis[N],w[N];
int head,tail,q[N];
bool bz[N];
void ins(int x,int y)
{
nxt[++tot]=lst[x];
to[tot]=y;
lst[x]=tot;
}
void dfs(int x,int fa,int dep)
{
col[x]=cnt;w[x]=dep;
for(int i=lst[x];i;i=nxt[i])
{
if(to[i]==fa)continue;
if(!col[to[i]])dfs(to[i],x,dep^1);else
if(w[x]==w[to[i]])ans=-1;
}
}
void work(int st)
{
memset(dis,128,sizeof(dis));
memset(bz,1,sizeof(bz));
for(dis[st]=head=bz[q[tail=1]=st]=0;head<tail;)
{
x=q[++head];
for(int i=lst[x];i;i=nxt[i])
if(dis[to[i]]<dis[x]+1 && bz[to[i]])
{
dis[to[i]]=dis[x]+1;
bz[q[++tail]=to[i]]=0;
}
}
}
int main()
{
freopen("merge.in","r",stdin);
freopen("merge.out","w",stdout);
read(n);read(m);
for(int i=1;i<=m;i++)
read(x),read(y),ins(x,y),ins(y,x);
for(int i=1;i<=n;i++)
if(!col[i])cnt++,dfs(i,0,0);
if(ans==-1)
{
printf("%d",ans);
return 0;
}
for(int i=1;i<=n;i++)
{
work(i);
for(int i=1;i<=n;i++)
mx[col[i]]=max(mx[col[i]],dis[i]);
}
for(int i=1;i<=cnt;i++)
ans=ans+mx[i];
printf("%d\n",ans);
return 0;
}