P3074 [USACO13FEB] Milk Scheduling S(拓扑排序)

思路:

核心:拓扑排序+

复制代码
ans[x]=max(ans[x],ans[t]+f[x]);

注意比当前大才更新!!!

接下来几乎就是拓扑排序模板啦~

ACcode:

复制代码
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N=5e4+10;
int f[N],n,m,ru[N],ans[N];
vector<int>v[N];
void topsort() {
	queue<int>q;
	for(int i=1; i<=n; i++) {
		if(ru[i]==0) {
			ans[i]=f[i];
			q.push(i);
		}
	}
	while(!q.empty()) {
		int t=q.front();
		q.pop();
		for(auto x:v[t]) {
			 ans[x]=max(ans[x],ans[t]+f[x]);
			ru[x]--;
			if(ru[x]==0)q.push(x);
		}
	}
}
void solve() {
	cin>>n>>m;
	for(int i=1; i<=n; i++) cin>>f[i];
	for(int i=1; i<=m; i++) {
		int x,y;
		cin>>x>>y;
		v[x].push_back(y);
		ru[y]++;
	}
	topsort();
	int mmax=-1;
	for(int i=1;i<=n;i++){
		mmax=max(mmax,ans[i]);
	}
	cout<<mmax<<"\n";
}
signed main() {

	ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
	int tt=1;
	//cin>>tt;
	while(tt--) solve();
	return 0;
}
//3

over~

相关推荐
陈增林2 分钟前
基于 PyQt5 的多算法视频关键帧提取工具
开发语言·qt·算法
C嘎嘎嵌入式开发2 小时前
【机器学习算法篇】K-近邻算法
算法·机器学习·近邻算法
小L~~~2 小时前
2025吉比特-游戏引擎开发-一面复盘
数据结构·算法·游戏引擎
程序猿Eason2 小时前
U587038 背包 题解
c++·算法·动态规划
potato_may3 小时前
第18讲:C语言内存函数
c语言·数据结构·算法
dingzd953 小时前
TikTok推荐算法快速解析
算法·机器学习·web3·facebook·推荐算法·tiktok·instagram
仰泳的熊猫3 小时前
LeetCode:95. 不同的二叉搜索树 II
数据结构·c++·算法·leetcode
Nix Lockhart3 小时前
《算法与数据结构》第七章[算法4]:最短路径
c语言·数据结构·学习·算法·图论
用户6605307619624 小时前
UFlow:像素级工业零件异常检测 Normalized Flow 方法
算法