[环套树 单调队列DP] BZOJ 1791 [Ioi2008]Island 岛屿

先找环 用环上每个点的子树的直径更新答案

然后跨环 把环展开倍增 做一遍单调队列DP max{f[i]+sum[i]+f[j]-sum[j]}

似乎可以直接套仙人掌模板啊

注意 long long 

会爆栈 懒得手写栈 先让它RE好了


#include
#include
#include
using namespace std;
typedef long long ll;

inline char nc()
{
	static char buf[100000],*p1=buf,*p2=buf;
	if (p1==p2) { p2=(p1=buf)+fread(buf,1,100000,stdin); if (p1==p2) return EOF; }
	return *p1++;
}

inline void read(int &x)
{
	char c=nc(),b=1;
	for (;!(c>='0' && c<='9');c=nc()) if (c=='-') b=-1;
	for (x=0;c>='0' && c<='9';x=x*10+c-'0',c=nc()); x*=b;
}

const int N=40005;

struct edge{
	int u,v,w,next;
};

edge G[N<<1];
int head[N],inum=1;

inline void add(int u,int v,int w,int p){
	G[p].u=u; G[p].v=v; G[p].w=w; G[p].next=head[u]; head[u]=p;
}

int n; ll Ans,ans;
int vst[N];
int pnt,cir[N],dis[N<<1],val[N<<1];

#define V G[p].v
inline int dfs(int u,int fa)
{
	vst[u]=1;
	int ret=0,d;
	for (int p=head[u];p;p=G[p].next)
		if (p!=(fa^1) && vst[V]!=2)
		{
			if (vst[V]==1) 
			{
				vst[u]=2; cir[++pnt]=u,dis[pnt]=G[p].w;
				ret=V; continue;
			}
			d=dfs(V,p);
			if (d)
			{
				vst[u]=2; cir[++pnt]=u,dis[pnt]=G[p].w;
				if (d!=u) ret=d; else ret=0;
			}
		}
	return ret;
}

ll g[N];

inline void dfs2(int u,int fa){
	for (int p=head[u];p;p=G[p].next)
		if (V!=fa && vst[V]!=2)
		{
			dfs2(V,u);
			ans=max(ans,g[u]+G[p].w+g[V]);
			g[u]=max(g[u],G[p].w+g[V]);
		}
}

int Q[N<<1],l,r;
ll f[N<<1],sum[N<<1];

inline ll dist(int u,int v){
	return sum[v-1]-sum[u-1];
}

inline ll DP()
{
	ll ret=0;
	reverse(val+1,val+pnt+1);
	reverse(dis+1,dis+pnt+1);
	for (int i=1;i<=pnt;i++)
		val[i+pnt]=val[i],dis[i+pnt]=dis[i];
	for (int i=1;i<=pnt+pnt;i++)
		sum[i]=sum[i-1]+dis[i];
	l=1,r=0;
	for (int i=1;i<=pnt+pnt;i++)
	{
		while (l<=r && i-Q[l]>=pnt) Q[l++]=0;
		if (l<=r) 
			ret=max(ret,val[i]+val[Q[l]]+dist(Q[l],i));
		int v=val[i]-sum[i-1];
		while (l<=r && v>f[r]) Q[r--]=0;
		Q[++r]=i; f[r]=v;
	}
	return ret;
}

int main()
{
	int iu,iw;
	freopen("t.in","r",stdin);
	freopen("t.out","w",stdout);
	read(n);
	for (int i=1;i<=n;i++)
		read(iu),read(iw),add(i,iu,iw,++inum),add(iu,i,iw,++inum);
	for (int i=1;i<=n;i++)
		if (!vst[i])
		{
			pnt=0; ans=0;
			dfs(i,0);
			for (int j=1;j<=pnt;j++) dfs2(cir[j],0),val[j]=g[cir[j]];
			ans=max(ans,DP());
			Ans+=ans;
		}
	printf("%lld\n",Ans);
	return 0;
}



你可能感兴趣的:(DP,环套树,单调队列)