YBTOJ G. 3.删点次数

本文探讨了在图中找到最大链的高效算法,通过先将图转换为有向无环图(DAG),然后利用拓扑排序的动态规划方法求解。代码展示了如何使用C++实现这一过程,适用于网络流问题中的关键路径分析。

思路:很显然找最大链

方法:先缩点形成一张DAG,再跑一遍拓扑dp找链的最大值(感觉思路很清晰~

Code

#include<bits/stdc++.h>
#define re register
#define ll long long
#define inl inline
using namespace std;
const int N=2e6+10;
int read(){
	int sum=0,f=1;char c=getchar();
	while(!isdigit(c)){if(c=='-') f=-1;c=getchar();}
	while(isdigit(c)){sum=(sum<<3)+(sum<<1)+(c^48);c=getchar();}
	return sum*f;
}
int n,m,cnt,head[N],dfn[N],low[N],top,color,dep,col[N],g[N],stk[N],ans,cnt2,dis[N],head2[N];
int scc[N];
struct node{
	int to,nxt;
}e[N],r[N];
void add(int u,int v){
	e[++cnt].to=v;
	e[cnt].nxt=head[u];
	head[u]=cnt;
}
void add2(int u,int v){
	r[++cnt2].to=v;
	r[cnt2].nxt=head2[u];
	head2[u]=cnt2;
}
inl void tarjan(int u){
	dfn[u]=low[u]=++dep,stk[++top]=u;
	for(int i=head[u];i;i=e[i].nxt){
		int v=e[i].to;
		if(!dfn[v]){
			tarjan(v);
			low[u]=min(low[u],low[v]);
		}
		else if(!col[v]) low[u]=min(low[u],dfn[v]);
	}
	if(dfn[u]==low[u]){
		color++;
		col[u]=color;
		scc[color]++;
		while(stk[top]!=u){
			col[stk[top--]]=color;
			scc[color]++;
		} 
		top--;
	}
}
int u[N],y[N],ind[N];
queue<int> q;
int main(){
	n=read(),m=read();
	for(int i=1;i<=m;i++){
		u[i]=read(),y[i]=read();
		add(u[i],y[i]);
	}
	for(int i=1;i<=n;i++){if(!dfn[i]) tarjan(i);}
	for(re int i=1;i<=m;i++){
		if(col[u[i]]!=col[y[i]]){
			add2(col[u[i]],col[y[i]]);
			ind[col[y[i]]]++;
		}
	}
	for(re int i=1;i<=color;i++){
		if(!ind[i]) q.push(i),dis[i]=scc[i],ans=max(dis[i],ans);
	}
	while(q.size()){
		int tmp=q.front();q.pop();
		for(re int i=head2[tmp];i;i=r[i].nxt){
			int w=r[i].to;
			dis[w]=max(dis[w],dis[tmp]+scc[w]);
			ans=max(ans,dis[w]);
			ind[w]--;
			if(!ind[w]) q.push(w);
		}
	} 
	printf("%d\n",ans);
	return 0;
}

### ybtoj 平台问题21276题目详情 ybtoj平台上的编号为21276的问题涉及一种基于区间的动态规划算法,即区间DP。这类问题通常围绕特定的操作序列展开,在这个问题中是以消除木块为核心[^1]。 #### 动态规划定义与思路 对于该类问题的核心在于如何定义状态以及转移方程的设计。在此案例里,`dp[i][j]`表示从第i个位置到第j个位置之间完成目标所需的最小代价或最优解路径数。通过这种方式可以有效地减少重复计算并优化整体性能表现。 #### 解决方案概述 解决方案采用了递归的方式来进行动态规划求解而不是传统的迭代方法。这种方法不仅简化了逻辑实现还保持了较低的时间复杂度。具体来说,当面对一系列待处理的数据时(比如一排不同颜色的木块),程序会尝试找到能够一次性清除最多相同类型的连续子串,并将其作为基础情况来构建更复杂的场景解答。 ```python def solve(dp, i, j): if i > j: return 0 while (i < j) and (blocks[j] != blocks[i]): j -= 1 if i == j: return scores[1] # Case where we merge the same color at both ends. res = solve(dp, i + 1, j - 1) + scores[2] # Try merging with any other matching block before &#39;i&#39;. for k in range(i + 1, j): if blocks[k] == blocks[i]: res = max(res, solve(dp, i + 1, k - 1) + solve(dp, k, j)) dp[i][j] = res return res ``` 此代码片段展示了如何利用Python语言编写解决此类问题的方法之一。注意这里假设存在两个全局变量`blocks[]`存储每一块的颜色信息和`scores[]`记录对应数量得分表;同时为了防止多次访问相同的索引组合而引入了一个二维数组`dp[][]`用于缓存中间结果以提高效率。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值