跳到正文

个人记录

P6145 [USACO20FEB] Timeline G

sixwl约 2 分钟
原文
文章信息与版本

文章信息

收录
2026年5月5日
更新
2026年5月5日
篇幅
约 2 分钟

版本

  1. v1当前

思路: 用拓扑排序处理图上的约束更新,初始读取节点值和约束关系,将入度为 0 的节点加入队列,依次取出节点更新其邻接节点的最大值并减少入度,入度为 0 时入队,最后输出所有节点更新后的结果

代码:

C++
#include<bits/stdc++.h>
using namespace std;
#define int long long

queue<int> q;
int s[100010],cnt[100010],vis[100010];
vector<pair<int,int>> v[1000010];
signed main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int n,m,c;
	cin>>n>>m>>c;
	for(int i=1; i<=n; i++){
        cin>>s[i];
	}
	for(int i=1; i<=c; i++){
        int a,b,x;
        cin>>a>>b>>x;
        v[a].push_back({b,x});
        cnt[b]++;
    }
    for(int i=1; i<=n; i++){
        if(cnt[i]==0){
            q.push(i);
        }
    }
    while(q.size()){
        int t=q.front();
        q.pop();
        if(vis[t]==1){
            continue;
        }
        vis[t]=1;
        for(auto i : v[t]){
			s[i.first]=max(s[i.first],s[t]+i.second);
			cnt[i.first]--;
			if(cnt[i.first]==0)
			 q.push(i.first);
        }
    }
    for(int i=1; i<=n; i++){
        cout<<s[i]<<"\n";
    }
	return 0;
}
原文