值得注意的是需要反向建图(首先这道题后续节点的奖金数决定了前续节点,所以我们需要反向建图)、取最大值(有点dp的味道)
题目:https://vjudge.net/contest/240486#problem/B
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAX=1e4+7;
vector<int>v[MAX];
int degree[MAX],d[MAX];
int n,m;
ll ans;
bool topological_sort()
{
int cnt=0;
queue<int>q;
for(int i=1; i<=n; i++)
if(degree[i]==0)
q.push(i);
while(!q.empty())
{
int u=q.front();
q.pop();
cnt++;
for(int i=0; i<v[u].size(); i++)
{
int t=v[u][i];
degree[t]--;
d[t]=max(d[t],d[u]+1);
if(degree[t]==0)
q.push(t);
}
}
if(cnt!=n)
return 0;
else
return 1;
}
int main()
{
while(~scanf("%d%d",&n,&m)){
ans=0;
while(m--){
int x,y;
scanf("%d%d",&x,&y);
degree[x]++;
v[y].push_back(x);
}
if(topological_sort()){
for(int i=1; i<=n; i++)
ans+=888+d[i];
printf("%lld\n",ans);
}
else
printf("-1\n");
for(int i=0; i<=n; i++) {
v[i].clear();
d[i]=degree[i]=0;
}
}
return 0;
}