题目:http://www.lydsy.com:808/JudgeOnline/problem.php?id=1179
首先,这是一个有向有环图,而且每个节点可以经过多次,那么很明显就想到用Tarjan算法先把强连通分量进行缩点,然后再在DAG上DP或者SPFA一次求最长路即可。
复杂度:O(n + m + km)
代码(linux的栈空间真是大得惊人,直接递归都不会爆):
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <stack>
#include <cstdlib>
#include <queue>
using namespace std;
#define MAXN 1000010
struct edge{
int t;
edge *next;
edge (){
next=NULL;
}
}*head[MAXN];
void AddEdge(int s,int t){
edge *p=new(edge);
p->t=t,p->next=head[s];
head[s]=p;
}
int w[MAXN],n,m,S,P;
int bar[MAXN];
int dfn[MAXN],low[MAXN],scc[MAXN],Index=0;
bool f[MAXN];
stack<int>Ss;
void Tarjan(int v){
Ss.push(v),f[v]=true;
dfn[v]=low[v]=++Index;
for(edge *p=head[v];p;p=p->next){
if(!dfn[p->t]){
Tarjan(p->t),
low[v]=min(low[v],low[p->t]);
}else if(f[p->t]) low[v]=min(low[v],low[p->t]);
}
if(dfn[v]==low[v]){
int u;
do{
u=Ss.top();
Ss.pop();
f[u]=false;
scc[u]=v;
}while(u!=v);
}
}
int ans[MAXN];
queue<int>Q;
void spfa(int v){
while(!Q.empty()) Q.pop();
Q.push(v);
memset(f,true,sizeof(f));
while(!Q.empty()){
int u=Q.front();
Q.pop();
if(!f[u])continue;
f[u]=false;
for(edge *p=head[u];p;p=p->next){
if(p->t!=u&&scc[p->t]==p->t){
if(ans[p->t]<ans[u]+w[p->t]){
ans[p->t]=ans[u]+w[p->t];
Q.push(p->t);
f[p->t]=true;
}
}
}
}
}
int main(){
memset(head,0,sizeof(head));
scanf("%d%d",&n,&m);
while(m--){
int s,t;
scanf("%d%d",&s,&t);
AddEdge(s,t);
}
for(int i=0;i++<n;) scanf("%d",&w[i]);
scanf("%d%d",&S,&P);
for(int i=0;i++<P;) scanf("%d",&bar[i]);
memset(dfn,0,sizeof(dfn));
memset(f,false,sizeof(f));
for(int i=0;i++<n;)if(!dfn[i]) Tarjan(i);
for(int i=0;i++<n;)if(scc[i]!=i) w[scc[i]]+=w[i];
for(int i=0;i++<n;){
for(edge *p=head[i];p;p=p->next){
if(scc[i]!=i&&scc[p->t]!=p->t){
AddEdge(scc[i],scc[p->t]);
}else{
if(scc[i]!=i) AddEdge(scc[i],p->t)
; else if(scc[p->t]!=p->t) AddEdge(i,scc[p->t]);
}
}
}
memset(ans,0,sizeof(ans));
ans[scc[S]]=w[scc[S]];
spfa(scc[S]);
int Ans=0;
for(int i=0;i++<P;) Ans=max(Ans,ans[scc[bar[i]]]);
printf("%d\n",Ans);
return 0;
}