BZOJ 1509 逃学的小孩(树的直径)
题意:从树上任找三点u,v,w。使得dis(u,v)+min(dis(u,w),dis(v,w))最大。
有一个结论u,v必是树上直径的两端点。 剩下的枚举w就行了。
具体不会证。。。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# include <cstdio> # include <cstring> # include <cstdlib> # include <iostream> # include <vector> # include <queue> # include <stack> # include <map> # include <set> # include <cmath> # include <algorithm> using namespace std; # define lowbit(x) ((x)&(-x)) # define pi 3.1415926535 # define eps 1e-9 # define MOD 100000007 # define INF 1000000000 # define mem(a,b) memset(a,b,sizeof(a)) # define FOR(i,a,n) for(int i=a; i<=n; ++i) # define FO(i,a,n) for(int i=a; i<n; ++i) # define bug puts("H"); # define lch p<<1,l,mid # define rch p<<1|1,mid+1,r # define mp make_pair # define pb push_back typedef pair<int,int> PII; typedef vector<int> VI; # pragma comment(linker, "/STACK:1024000000,1024000000") typedef long long LL; int Scan() { int res=0, flag=0; char ch; if((ch=getchar())=='-') flag=1; else if(ch>='0'&&ch<='9') res=ch-'0'; while((ch=getchar())>='0'&&ch<='9') res=res*10+(ch-'0'); return flag?-res:res; } void Out(int a) { if(a<0) {putchar('-'); a=-a;} if(a>=10) Out(a/10); putchar(a%10+'0'); } const int N=200005; //Code begin... struct Edge{int p, next, w;}edge[N<<1]; int head[N], cnt=1; LL dis[N], dist[N]; void add_edge(int u, int v, int w){ edge[cnt].p=v; edge[cnt].w=w; edge[cnt].next=head[u]; head[u]=cnt++; } void dfs(int x, int fa){ for (int i=head[x]; i; i=edge[i].next) { int v=edge[i].p; if (v==fa) continue; dis[v]=dis[x]+edge[i].w; dfs(v,x); } } int main () { int n, m, u, v, w; LL ans=0; scanf("%d%d",&n,&m); while (m--) scanf("%d%d%d",&u,&v,&w), add_edge(u,v,w), add_edge(v,u,w); dfs(1,0); int ma=0; FOR(i,1,n) if(dis[ma]<dis[i]) ma=i; mem(dis,0); dfs(ma,0); ma=0; FOR(i,1,n) { dist[i]=dis[i]; if (dis[ma]<dis[i]) ma=i; } mem(dis,0); dfs(ma,0); FOR(i,1,n) ans=max(ans,dist[ma]+min(dis[i],dist[i])); printf("%lld\n",ans); return 0; }