这个做过的经典而且难忘的题目 本来是劲点决赛的倒数第二道题。
dp[t]=dp[pos]+profit[t];
题意就是给一个有向图 每个节点有权值。
找到 入度为0的点 到出度为0的点。 更新权值。 要求权值尽量大
就是拓扑排序加一个
if(dp[pos]+profit[t]>dp[t])
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
const int maxn=100005;
const int inf=1<<29;
vector<int> Graph[maxn];
int Indegree[maxn];
int Outdegree[maxn];
int profit[maxn];
int dp[maxn];
int n,m,i,j,k,f,t;
void Solve()
{
for(i=1; i<=n; ++i) //初始化,清空图,清零数组
Graph[i].clear();
memset(Indegree,0,sizeof(Indegree));
memset(Outdegree,0,sizeof(Outdegree));
for(i=1; i<=n; ++i)
scanf("%d",&profit[i]);//输入节点权值
for(i=1; i<=m; ++i) //输入边并且修改入度出度数组
{
scanf("%d%d",&f,&t);
Graph[f].push_back(t);
Indegree[t]++;
Outdegree[f]++;
}
queue<int> q;
for(i=1; i<=n; ++i)
{
if(Indegree[i]==0)
{
dp[i]=profit[i];
q.push(i);
}
else
dp[i]=-inf;
}
while(!q.empty())
{
int pos=q.front();
q.pop();
for(i=0; i<Graph[pos].size(); ++i)
{
t=Graph[pos][i];
Indegree[t]--;
if(dp[pos]+profit[t]>dp[t])
dp[t]=dp[pos]+profit[t];
if(Indegree[t]==0)
q.push(t);
}
}
int max=-inf;
for(i=1; i<=n; ++i)
{
if(Outdegree[i]==0 && dp[i]>max)
max=dp[i];
}
printf("%d\n",max);
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
Solve();
}
return 0;
}