Description
圖中有N個點,每兩點間只有唯一的路徑,對於這樣一個給定的圖,最大的“毛毛蟲”會有多大。毛毛蟲包含一條主鏈,毛毛蟲中的節點,要不在主鏈上,要麼和主鏈上某節點相鄰,點數越多,毛毛蟲越大。
Input
輸入文件第一行兩個整數N,M(N≤1000000)
接下來M行,每行兩個整數a, b(a, b≤N)
你可以假定沒有一對相同的(a, b)會出現一次以上。
Output
一個整數ans,表示最大的毛毛蟲的大小。
Sample Input
5 4
1 2
1 3
4 1
5 1
Sample Output
5
Data Constraint
Hint
【數據規模】
1. 對於20%的數據,N≤200
2. 對於40%的數據,N≤5000
3. 對於100%的數據,N≤10^6
//written by zzy
題目大意:
找一個最大的毛毛蟲,毛毛蟲的大小爲一條鏈及與鏈相連的點。
題解:
有點像樹上最長鏈,但有區別。
思路差不過,給每個點賦值爲它的入度,
按權跑最長鏈(兩次dfs),但發現鏈上除去頭尾的點會重複,
於是再減去鏈長減2及可。
#include<cmath>
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#define N 2000015
int i,j,n,m,l,Max,p,num,numl,e;
int x[N],y[N],list[N*2],next[N*2];
int a[N];
bool b[N];
int add(int x){
l++;
next[l]=list[x];
list[x]=l;
}
void dfs(int p,int s)
{
if (s>Max) {
Max=s; num=p;
}
for (int t=list[p];t;t=next[t])
if (b[y[t]]) {
b[y[t]]=false;
dfs(y[t],s+a[y[t]]-1);
}
}
int main()
{
scanf("%d%d",&n,&m);
for (i=1;i<=m;i++)
{
scanf("%d%d",&x[i*2-1],&y[i*2-1]);
add(x[i*2-1]);
a[x[i*2-1]]++; a[y[i*2-1]]++;
x[i*2]=y[i*2-1]; y[i*2]=x[i*2-1];
add(x[i*2]);
}
Max=0;
memset(b,true,sizeof(b)); b[1]=false;
dfs(1,a[1]+1);
Max=0;
memset(b,true,sizeof(b)); b[num]=false;
dfs(num,a[num]+1);
printf("%d",Max);
}