1 solutions
-
1
缩点之后在DAG上DP即可
# include<iostream> # include<vector> # include<algorithm> # include<queue> using namespace std; # define ll long long const int N=1e4+5,M=1e5+5; struct edge{ int v,next; }e[M]; int n,m,x,y; int head[N],cnt=0; int dfn[N],low[N],num=0; int top=0,st[N]; int co[N],col=0; ll a[N],s[N],dp[N],ans; int p[N],d[N],k=0; queue<int> q; vector<int> e1[N]; void add(int x,int y){ e[++cnt].next=head[x]; head[x]=cnt; e[cnt].v=y; } void tarjan(int u){ dfn[u]=low[u]=++num; st[++top]=u; for(int i=head[u];i;i=e[i].next){ int v=e[i].v; if(!dfn[v]){ tarjan(v); low[u]=min(low[u],low[v]); } else if(!co[v]) low[u]=min(low[u],dfn[v]); } if(dfn[u]==low[u]){ co[u]=++col; while(st[top]!=u) co[st[top--]]=col; --top; } } void toposort(){ for(int i=1;i<=col;++i){ dp[i]=s[i]; if(!d[i]) q.push(i); } while(!q.empty()){ int u=q.front(); q.pop(); p[++k]=u; for(int i=0;i<e1[u].size();++i){ int v=e1[u][i]; d[v]--; if(!d[v]) q.push(v); } } } int main(){ cin>>n>>m; for(int i=1;i<=n;++i) cin>>a[i]; for(int i=1;i<=m;++i){ cin>>x>>y; if(x!=y) add(x,y); } for(int i=1;i<=n;++i) if(!dfn[i]) tarjan(i); for(int i=1;i<=n;++i){ s[co[i]]+=a[i]; for(int j=head[i];j;j=e[j].next){ int u=co[i],v=co[e[j].v]; if(u!=v){ e1[u].push_back(v); d[v]++; } } } toposort(); for(int i=1;i<=k;++i){ int u=p[i]; ans=max(ans,dp[u]); for(int j=0;j<e1[u].size();++j){ int v=e1[u][j]; dp[v]=max(dp[v],dp[u]+s[v]); } } cout<<ans; return 0; }
- 1
Information
- ID
- 1692
- Time
- 1000ms
- Memory
- 512MiB
- Difficulty
- 4
- Tags
- # Submissions
- 50
- Accepted
- 8
- Uploaded By