您的位置:首页 > 其它

BZOJ 2427: [HAOI2010]软件安装|树形动规|tarjan

2016-01-09 08:29 423 查看
若是有换要么全选要么全不选

然后缩点

建立一个虚根连上所有入度为0的点

然后裸的树形dp

(变量开得有点凌乱)

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<algorithm>
#include<iostream>
#define T 122
using namespace std;
int sc()
{
	int i=0; char c=getchar();
	while(c>'9'||c<'0')c=getchar();
	while(c>='0'&&c<='9')i=i*10+c-'0',c=getchar();
	return i;
}
int f[T][505],ww[T],vv[T],bl[T],D[T];
int Head[T],Lst[T],Nxt[T];
int dfn[T],low[T],st[T],vis[T];
int head[T],nxt[T],lst[T];
int Root[T],w[T],v[T];
int n,m,tot,cnt,root,sm,top,total,scc=1,Tot;
void insert(int x,int y)
{
	lst[++tot]=y;
	nxt[tot]=head[x];
	head[x]=tot;
}
void dfs(int x)
{
	int s[505]; vis[x]=1;
	memset(s,0,sizeof(s));
	for(int e=Head[x]; e; e=Nxt[e]) if(!vis[Lst[e]])
	{
		int k=Lst[e]; dfs(k);
		for(int i=m; i; i--)
			for(int j=0; j<=i; j++)
			    s[i]=max(s[i],s[j]+f[k][i-j]);
			//cout << x <<" "<<i <<": "<<s[i]<<endl;;
	}
	for(int i=0;i+ww[x]<=m;i++)
	    f[x][i+ww[x]]=s[i]+vv[x];
}
void tarjan(int x)
{
	vis[x]=1;st[++top]=x;
	dfn[x]=low[x]=++total;
	for(int i=head[x]; i; i=nxt[i])
	{
		if(vis[lst[i]])low[x]=min(low[x],dfn[lst[i]]);
		else if(!dfn[lst[i]])
		{
			tarjan(lst[i]);
			low[x]=min(low[x],low[lst[i]]);
		}
	}
	if(low[x]==dfn[x])
	{
		int k=0; scc++;
		while(k!=x)
		{
			k=st[top--];
			bl[k]=scc;
			vis[k]=0;
			ww[scc]+=w[k];
			vv[scc]+=v[k];
		}
	}
}
void Insert(int x,int y)		
{
	D[y]++;
	Lst[++Tot]=y;
	Nxt[Tot]=Head[x];
	Head[x]=Tot;
}
int main()
{
	sm=n=sc(),m=sc();
	for(int i=1; i<=n; i++) w[i]=sc();
	for(int i=1; i<=n; i++) v[i]=sc();
	for(int i=1; i<=n; i++)
	{
		int x=sc();
		if(x)insert(x,i);
	}
	for(int i=1; i<=n; i++)
	    if(!dfn[i]) tarjan(i);
	for(int i=1; i<=n; i++)
	    for(int j=head[i]; j; j=nxt[j])
	        if(bl[i]!=bl[lst[j]]) Insert(bl[i],bl[lst[j]]);
	for(int i=2; i<=scc; i++) if(!D[i])Insert(1,i);
	dfs(1);
	cout << f[1][m];
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: