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

思路:

P3074 [USACO13FEB] Milk Scheduling S(拓扑排序)_第1张图片核心:拓扑排序+

ans[x]=max(ans[x],ans[t]+f[x]);

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

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

ACcode:


#include
using namespace std;
#define int long long
const int N=5e4+10;
int f[N],n,m,ru[N],ans[N];
vectorv[N];
void topsort() {
	queueq;
	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<>tt;
	while(tt--) solve();
	return 0;
}
//3

over~

你可能感兴趣的:(算法,拓扑排序)