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~

相关推荐
Nil2082 分钟前
golang解决单词转换
算法
imaol132 分钟前
文件编程--标准IO
linux·运维·算法
青 春 记 忆35 分钟前
LeetCode 121. 买卖股票的最佳时机|Python 解法详解
python·算法·leetcode
stolentime1 小时前
AT_agc066_a [AGC066A] Adjacent Difference题解
c++·算法·贪心算法·构造
渣波1 小时前
深度解析:LeetCode 51. N 皇后 —— 回溯算法的巅峰之作
算法
咪饭只吃一小碗1 小时前
# C++ STL 常用容器方法全面总结vector / map / set / unordered_map / unordered_set
算法
daad7771 小时前
802.11 前导码与 STF 深度解析(含检测算法与 5G 对比
人工智能·算法·5g·wifi·802.11·前导码
Navigator_Z2 小时前
LeetCode //C - 1203. Sort Items by Groups Respecting Dependencies
c语言·算法·leetcode
我变成萤火虫3 小时前
2026 ICPC沈阳邀请赛Vp补题
数据结构·c++·算法·贪心算法·stl·排序算法·动态规划