2815: [ZJOI2012]灾难

bz没有题面,,就不贴了= =


实际上有一种叫支配树的东西可以构造出答案,这题是支配树中最简单的= =因为原图是个DAG

blog传送门。。。。。。。。

大概是首先求个拓扑序,由拓扑序建树,每个点在它所有食物中找LCA,然后把这个点放在LCA下就行了

#include
#include
#include
#include
#include
#include
#include
using namespace std;

const int maxn = 1E5 + 10;

int n,m,ans[maxn],du[maxn],L[maxn],fa[maxn][17];
bool vis[maxn];

vector  v[maxn],v2[maxn],G[maxn];
queue  Q;

void Dfs(int x)
{
	ans[x] = 1;
	for (int i = 0; i < G[x].size(); i++)
	{
		int to = G[x][i];
		Dfs(to); ans[x] += ans[to];
	}
}

int LCA(int p,int q)
{
	if (L[p] < L[q]) swap(p,q);
	for (int j = 16; j >= 0; j--)
		if (L[p] - (1<= L[q])
			p = fa[p][j];
	if (p == q) return p;
	for (int j = 16; j >= 0; j--)
		if (fa[p][j] != fa[q][j])
			p = fa[p][j],q = fa[q][j];
	return fa[p][0];
}

void Add(int k,int F)
{
	fa[k][0] = F; L[k] = L[F] + 1; G[F].push_back(k);
	for (int i = 1; i < 16; i++)
		if (fa[k][i-1] == -1) return;
		else fa[k][i] = fa[fa[k][i-1]][i-1];
}

int main()
{
	#ifdef DMC
		freopen("DMC.txt","r",stdin);
	#endif
	
	cin >> n;
	for (int i = 1; i <= n; i++)
	{
		int x; scanf("%d",&x);
		while (x)
		{
			v[x].push_back(i);
			v2[i].push_back(x);
			++du[i]; scanf("%d",&x);
		}
	}
	memset(fa,-1,sizeof(fa)); L[0] = 1;
	for (int i = 1; i <= n; i++)
		if (!du[i]) Q.push(i);
	while (!Q.empty())
	{
		int k = Q.front(),lca = k; Q.pop();
		for (int i = 0; i < v2[k].size(); i++)
		{
			int fd = v2[k][i];
			if (!i) lca = fd;
			lca = LCA(lca,fd);
		}
		for (int i = 0; i < v[k].size(); i++)
		{
			int to = v[k][i]; --du[to];
			if (!du[to]) Q.push(to);
		}
		if (lca == k) Add(k,0); else Add(k,lca);
	}
	Dfs(0);
	for (int i = 1; i <= n; i++) printf("%d\n",--ans[i]);
	return 0;
}

你可能感兴趣的:(支配树)