算法:模板题,仅作为补档博客。
Code:
#include<bits/stdc++.h>
#define rep(i,j,k) for(int i=j;i<=k;i++)
using namespace std;
template<typename T> void read(T &x){scanf("%d",&x);}
template<typename T> void write(T x){printf("%d\n",x);}
template<typename T> void chkmin(T &x,T y){x=min(x,y);}
template<typename T> void chkmax(T &x,T y){x=max(x,y);}
int w[10010];int u[100010];int v[100010];
struct wzy{
int nxt,vertice;
}edge[100010];
int head[10010];int len=0;
inline void add_edge(int x,int y){
edge[++len].nxt=head[x];edge[len].vertice=y;head[x]=len;
return;
}
int dfn[10010];int low[10010];bool in[10010];
int color[10010];int sum[10010];
stack<int>vq;int siz=0;int tot=0;
inline void tarjan(int x){
dfn[x]=low[x]=++siz;
vq.push(x);in[x]=1;
for(int i=head[x];i;i=edge[i].nxt){
int nop=edge[i].vertice;
if(!dfn[nop]){
tarjan(nop);
chkmin(low[x],low[nop]);
}else if(in[nop]){
chkmin(low[x],dfn[nop]);
}
}
if(dfn[x]==low[x]){
tot++;
while(vq.top()!=x){
color[vq.top()]=tot;sum[tot]+=w[vq.top()];
in[vq.top()]=0;vq.pop();
}
color[x]=tot;sum[tot]+=w[x];in[x]=0;vq.pop();
}
return;
}
int dp[10010];
int ans=0;
inline void solve(int x){
if(dp[x])return;
dp[x]=sum[x];
int re_value=0;
for(int i=head[x];i;i=edge[i].nxt){
int nop=edge[i].vertice;
if(!dp[nop])solve(nop);
chkmax(re_value,dp[nop]);
}
dp[x]+=re_value;return;
}
int main(){
int n,m;read(n);read(m);
rep(i,1,n){read(w[i]);}
rep(i,1,m){read(u[i]);read(v[i]);add_edge(u[i],v[i]);}
rep(i,1,n){if(!dfn[i]){tarjan(i);}}
memset(head,0,sizeof(head));
rep(i,1,m){edge[i].nxt=edge[i].vertice=0;}
len=0;
rep(i,1,m){
if(color[u[i]]!=color[v[i]]){
add_edge(color[u[i]],color[v[i]]);
}
}
int ans=0;
rep(i,1,tot){solve(i);}
rep(i,1,tot){chkmax(ans,dp[i]);}
write(ans);
return 0;
}