【YBTOJ进阶训练指导】删点次数【Tarjan】

11 篇文章 0 订阅
4 篇文章 0 订阅

在这里插入图片描述

思路:

我们分析
1.一条链上的点不能同时轰炸,所以答案绝对大于等于最长的链。
2.我们有多条互不相交的链,每次把每条链上取一点,可以得到一个答案为最长链的取法。
综上所述,答案为最长链长度
加个Tarjan缩点就OK了

c o d e code code

#include<iostream>
#include<cstdio>
#include<queue>

using namespace std;

int n, m, tot, cnt, tmp, tot1;
int stack[1000010], top, ru[1000010];
int a[1000010], head[1000010], head1[1000010];
int dfn[1000010], low[1000010];
int d[1000010], c[1000010];
int ans[1000010];
bool v[1000010];
struct node
{
	int from, to, next;
}b[1000100], e[1000100];

void add(int x, int y)
{
	b[++tot]=(node){x, y, head[x]};
	head[x]=tot;
}

void add1(int x, int y)
{
	e[++tot1]=(node){x, y, head1[x]};
	head1[x]=tot1;
}

void tarjan(int x)
{
	dfn[x]=low[x]=++cnt;
	v[x]=1;
	stack[++top]=x;
	for(int i=head[x]; i; i=b[i].next)
	{
		int y=b[i].to;
		if(!dfn[y])
		{
			tarjan(y);
			low[x]=min(low[x], low[y]);
		}
		else if(v[y])
			low[x]=min(low[x], dfn[y]);
	}
	if(dfn[x]==low[x])
	{
		tmp++;
		do
		{
			c[stack[top]]=tmp;
			d[tmp]+=a[stack[top]];
			v[stack[top]]=0;
			top--;
		}
		while(x!=stack[top+1]);
	}
	return;
}

void dp()
{
	queue<int> q;
	for(int i=1; i<=tmp; i++)
		if(!ru[i])
			q.push(i), ans[i]=d[i];
	while(!q.empty())
	{
		int x=q.front();
		q.pop();
		for(int i=head1[x]; i; i=e[i].next)
		{
			int y=e[i].to;
			ru[y]--;
			ans[y]=max(ans[y], ans[x]+d[y]);
			if(!ru[y])
				q.push(y);
		}
	}
}

int main()
{
	scanf("%d%d", &n, &m);
	for(int i=1; i<=n; i++)
		a[i]=1;
	for(int i=1; i<=m; i++)
	{
		int x, y;
		scanf("%d%d", &x, &y);
		add(x, y);
	}
	for(int i=1; i<=n; i++)
	{
		if(!dfn[i])
			tarjan(i);
	}
	for(int i=1; i<=tot; i++)
	{
		int x=b[i].from, y=b[i].to;
		if(c[x]!=c[y])
			add1(c[x], c[y]), ru[c[y]]++;
	}
	dp();
	int maxx=0;
	for(int i=1; i<=tmp; i++)
		maxx=max(maxx, ans[i]);
	printf("%d", maxx);
	return 0; 
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值