拓扑排序 + DP
A-来自wzc的简单拓扑dp_浙江农林大学第二十届程序设计竞赛暨团体程序设计天梯赛选拔赛(同步赛) (nowcoder.com)
拓扑DP模板题
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
const int N = 100010;
int n, m;
int res, w[N];
int in[N], f[N];
vector<int> g[N];
bool st[N];
void dfs(int u, int v)
{
if(u == n)
{
res = max(res, v);
return ;
}
for(int i = 0; i < g[u].size(); i ++ )
{
int t = g[u][i];
st[t] = true;
dfs(t, v + w[t]);
st[t] = false;
}
}
void topsort()
{
queue<int> q;
q.push(0);
while(q.size())
{
auto t = q.front();
q.pop();
for(auto x : g[t])
{
f[x] = max(f[x], f[t] + w[x]);
if(! --in[x]) q.push(x);
}
}
}
int main()
{
memset(f, -1, sizeof f);
f[0] = 0;
cin >> n >> m;
for(int i = 1; i <= n; i ++ ) cin >> w[i];
while(m -- )
{
int a, b;
cin >> a >> b;
g[a].push_back(b);
in[b] ++ ;
topsort();
// for(int i = 1; i <= n; i ++ )
// cout << f[i] << endl;
cout << f[n] << endl;
return 0;
}