题目地址:http://poj.org/problem?id=3160
缩点然后找出一条权重最大的路
路当然是越长越好,所以从每个入度为0的点出发,找一条权值最长的
可以假设一个点,从该点出发可以到所有入读为0的,然后以该点为起点SPFA
#include<iostream>
#include<cstdio>
#include<vector>
#include<stack>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=10000+10;
const int INF=1000000000;
typedef pair<int,int> Point;
bool vis[maxn];
int ID[maxn],gift[maxn],ngift[maxn],in[maxn],dist[maxn],inq[maxn]; //点的颜色编号
int index,ncolor;
vector<int> dfn(maxn),low(maxn),st;
vector<vector<int> > color(maxn); //同一种颜色的点
vector<vector<int> > G(maxn),NG(maxn);
void Tarjan(int u)
{dfn[u]=low[u]=++index;vis[u]=true;st.push_back(u);for(int i=0;i<G[u].size();i++){int v=G[u][i];if(!vis[v]){Tarjan(v);low[u]=min(low[u],low[v]);}else if(find(st.begin(),st.end(),v)!=st.end()) //in stacklow[u]=min(low[u],dfn[v]);}if(dfn[u]==low[u]){int v; ncolor++;do{v=st.back(); st.pop_back();color[ncolor].push_back(v);ID[v]=ncolor;}while(v!=u);}
}
int getGraph(int n)
{index=ncolor=0; st.clear();memset(vis,false,sizeof(vis));for(int i=0;i<n;i++)if(!vis[i]) Tarjan(i);vector<int> points;memset(in,0,sizeof(in));memset(ngift,0,sizeof(ngift));for(int i=1;i<=ncolor;i++){points.clear();for(int j=0;j<color[i].size();j++){int u=color[i][j];ngift[i]+=gift[u];for(int k=0;k<G[u].size();k++){int v=G[u][k];if(ID[u]!=ID[v]){if(find(points.begin(),points.end(),ID[v])==points.end()) points.push_back(ID[v]);in[ID[v]]++;}}}for(int j=0;j<points.size();j++)NG[i].push_back(points[j]);}for(int i=1;i<=ncolor;i++)if(in[i]==0) NG[ncolor+1].push_back(i);
}
void Spfa(int s)
{memset(inq,false,sizeof(inq));memset(dist,0,sizeof(dist));queue<int> Q;dist[s]=0;inq[s]=true; Q.push(s);while(!Q.empty()){int u=Q.front(); Q.pop();inq[u]=false;for(int i=0;i<NG[u].size();i++){int v=NG[u][i], w=ngift[v];if(dist[v]<dist[u]+w){dist[v]=dist[u]+w;if(!inq[v]) Q.push(v),inq[v]=true;}}}
}
int main()
{int n,m,u,v;while(cin>>n>>m){for(int i=0;i<n;i++) {G[i].clear(); NG[i].clear(); color[i].clear();cin>>gift[i];if(gift[i]<0) gift[i]=0;}while(m--){cin>>u>>v;G[u].push_back(v);}getGraph(n);Spfa(ncolor+1);cout<<*max_element(dist+1,dist+ncolor+2)<<endl;}return 0;
}