BZOJ 1509: [NOI2003]逃学的小孩

傻逼树形DP,WA了半天QAQ。

一直在写脑残的讨论方法,后来想通了直接枚举三条连线的交点,然后求出从以一个点为根的树中距根前三长的路径,最长+2*次长+第三长就是这个点为分叉点的答案,同时这些路径仅在根处相交,这个很好维护的,不过由于我比较脑残(T_T),就直接排序了,于是变成了nlogn,其实可以O(n)的。

#include
#include
#include
#include
#include
#include
using namespace std;
typedef long long ll;
const int N=200000+5;
const ll inf=1LL<<60;
struct Edge{int to,next;ll v;}e[N<<1];
int head[N],cnt;
void ins(int u,int v,ll w){
	e[++cnt]=(Edge){v,head[u],w};head[u]=cnt;
}
ll f[N];
void dp(int u,int fa){
	for(int i=head[u];i;i=e[i].next){
		int v=e[i].to;if(v==fa)continue;
		dp(v,u);
		f[u]=max(f[u],f[v]+e[i].v);
	}
}
ll ans;
bool cmp(ll i,ll j){
	return i>j;
}
void dp(int u,int fa,ll x){
	vectorg;
	for(int i=head[u];i;i=e[i].next){
		int v=e[i].to;if(v==fa)continue;
		g.push_back(f[v]+e[i].v);
	}
	g.push_back(0);
	g.push_back(x);
	sort(g.begin(),g.end(),cmp);
	if(g.size()>=3)
	ans=max(ans,g[0]+g[1]*2+g[2]);
	for(int i=head[u];i;i=e[i].next){
		int v=e[i].to;if(v==fa)continue;
		ll t=g[0];
		if(t==e[i].v+f[v])t=g[1];
		dp(v,u,t+e[i].v);
	}
}
int main(){
	//freopen("a.in","r",stdin);
	//freopen("a.out","w",stdout);
	int n,m;scanf("%d%d",&n,&m);
	int u,v,w;
	while(m--){
		scanf("%d%d%d",&u,&v,&w);
		ins(u,v,w);ins(v,u,w);
	}
	ans=0;
	dp(1,-1);dp(1,-1,0);
	printf("%lld\n",ans);
	return 0;
}


你可能感兴趣的:(动态规划)