P3387 【模板】缩点
可以重复走的图,求一条走过权值和最大的路径
先对这个图跑tarjan,对于每个强联通点,有sum[i],然后把原来的边都删了。
若两个强联通分量内的点有一条边,就对这两个分量连一条边。
记忆化搜索出最大值。
代码语言:javascript复制#include<bits/stdc .h>
#define ll long long
using namespace std;
const int N = 10005;
const int M = 300005;
int dfn[N],low[N],cnt,belong[N],book[N],sum[N];
int n,m,dfnum,val[N],a[M],b[M],cnt2,head[M];
int f[N];
stack<int> s;
struct E{
int u,v,nxt;
};
E edge[M];
void add(int u,int v){
cnt2;
edge[cnt2].v = v;
edge[cnt2].nxt = head[u];
head[u] = cnt2;
}
void tarjan(int u){
dfn[u] = low[u] = dfnum;
s.push(u); book[u]=1;
for(int v,i = head[u];i;i=edge[i].nxt){
v = edge[i].v;
if(!dfn[v]){
tarjan(v);
low[u] = min(low[v],low[u]);
}else if(book[v])low[u] = min(dfn[v],low[u]);
//v在栈内 u能到达的边是v的序号和u能到达最小的序号中较小的
}
if(dfn[u]==low[u]){
belong[u] = cnt;
int v;
do{
v = s.top();
book[v]=0;
s.pop();
belong[v]=cnt;
sum[cnt] =val[v];
}while(u!=v);
}
}
void dfs(int u){
int ans=0;
f[u] = sum[u];
for(int v,i=head[u];i;i=edge[i].nxt){
v = edge[i].v;
if(!f[v])dfs(v);
ans=max(ans,f[v]);
}
f[u] =ans;
}
int main()
{
scanf("%d %d",&n,&m);
for(int i=1;i<=n;i )scanf("%d",&val[i]);
for(int i=1;i<=m;i ){
int u,v;
scanf("%d %d",&a[i],&b[i]);
u = a[i]; v = b[i];
edge[i].v = v; edge[i].nxt = head[u]; head[u]=i;
}
for(int i=1;i<=n;i ){
if(!dfn[i]){
tarjan(i);
}
}
memset(head,0,sizeof(head));
for(int i=1;i<=m;i ){
if(belong[a[i]]!=belong[b[i]]){
add(belong[a[i]],belong[b[i]]);
}
}
int ans=0;
for(int i=1;i<=cnt;i ){
if(!f[i]){
dfs(i);ans = max(ans,f[i]);
}
}
printf("%dn",ans);
return 0;
}