[haoi2009]毛毛虫
#include<cstdio> #include<iostream> #include<cmath> #include<algorithm> #include<cstring> #include<cstdlib> #include<cctype> #include<vector> #include<stack> #include<queue> using namespace std; #define enter puts("") #define space putchar(' ') #define Mem(a, x) memset(a, x, sizeof(a)) #define rg register typedef long long ll; typedef double db; const int INF = 0x3f3f3f3f; const db eps = 1e-8; const int maxn = 3e5 + 5; inline ll read() { ll ans = 0; char ch = getchar(), last = ' '; while(!isdigit(ch)) last = ch, ch = getchar(); while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar(); if(last == '-') ans = -ans; return ans; } inline void write(ll x) { if(x < 0) x = -x, putchar('-'); if(x >= 10) write(x / 10); putchar(x % 10 + '0'); } int n, m, w[maxn]; struct Edge { int nxt, to; }e[maxn << 1]; int head[maxn], ecnt = -1; void addEdge(int x, int y) { e[++ecnt] = (Edge){head[x], y}; head[x] = ecnt; } int dp[maxn], ans = 0; void dfs(int now, int _f) { int Max1 = 0, Max2 = 0; dp[now] = 1; for(int i = head[now], v; i != -1; i = e[i].nxt) { v = e[i].to; if(v == _f) continue; dfs(v, now); if(dp[v] > Max1) Max2 = Max1, Max1 = dp[v]; else if(dp[v] > Max2) Max2 = dp[v]; dp[now] = max(dp[now], dp[v] + w[now] - 1); //如果now做为子结点,给其父亲的贡献只为其"最长链" } ans = max(ans, Max1 + Max2 + w[now] - 1); //某个点,其最长链,次长链,加其所有子结点,再减2,再加1,1是它本身 } int main() { Mem(head, -1); n = read(); m = read(); for(int i = 1; i <= m; ++i) { int x = read(), y = read(); w[x]++; w[y]++; addEdge(x, y); addEdge(y, x); } dfs(1, 0); write(ans), enter; return 0; }
#include<bits/stdc++.h> using namespace std; int hea[300010],nxt[600010],to[600010],a[300010],d[300010],mx,tot; void fason(int a,int b) { nxt[++tot]=hea[a]; hea[a]=tot; to[tot]=b; } void dfs(int x,int fa) { d[x]=a[x]; for(int i=hea[x],y;(y=to[i]);i=nxt[i]) { if(y==fa)continue; dfs(y,x); mx=max(d[x]+d[y],mx); d[x]=max(d[x],d[y]+a[x]-1); //a[x]指x有多少子结点,已包含y,现在去掉之 } } int main() { int n,x,y; scanf("%d%*d",&n); for(int i=1;i<n;i++) { scanf("%d%d",&x,&y); fason(x,y); fason(y,x); a[x]++; a[y]++; } dfs(1,0); printf("%d ",mx); return 0; }