YBT高效进阶3.4.1 洛谷P3387有向图缩点
Title
思路
建图
Tanjan缩点
拓扑DP
设f[i]为以i为终点的值
f[v]=max(f[u]+s[v],f[v])
ans=max(f[i])
CODE
#include<iostream>
#include<cstdio>
#include<stack>
#include<queue>
using namespace std;
const long long maxn=200010;
struct jgt
{
long long u,v,nxt;
} efirst[maxn],esd[maxn],edz[maxn];
long long a[maxn],dfn[maxn],low[maxn],col[maxn],s[maxn],ins[maxn],f[maxn],cnt,len;
long long headfirst[maxn],totfirst;
long long headsd[maxn],totsd;
long long headdz[maxn],totdz;
stack<long long>stck;
queue<long long>que;
void Tanjan(long long x)
{
dfn[x]=low[x]=++cnt;
stck.push(x);
for(long long i=headfirst[x]; i; i=efirst[i].nxt)
if(!dfn[efirst[i].v])Tanjan(efirst[i].v),low[x]=min(low[x],low[efirst[i].v]);
else if(!col[efirst[i].v])low[x]=min(low[x],dfn[efirst[i].v]);
if(dfn[x]==low[x])
{
for(col[x]=++len,s[len]=a[x]; stck.top()!=x; stck.top(),stck.pop())col[stck.top()]=len,s[len]+=a[stck.top()];
stck.pop();
}
return;
}
int main()
{
long long n,m,i,ans=0,j,w,x,y;
ios::sync_with_stdio(false);
for(cin>>n>>m,i=1; i<=n; i++)cin>>a[i];
for(i=1; i<=m; i++)cin>>efirst[i].u>>efirst[i].v,efirst[i].nxt=headfirst[efirst[i].u],headfirst[efirst[i].u]=i;
for(i=1; i<=n; i++)if(!dfn[i])Tanjan(i);
for(i=1; i<=m; i++)
{
x=col[efirst[i].u],y=col[efirst[i].v];
if(x!=y)
{
esd[++totsd].u=x,esd[totsd].v=y,esd[totsd].nxt=headsd[x],headsd[x]=totsd,ins[y]++;
edz[++totdz].u=y,edz[totdz].v=x,edz[totdz].nxt=headdz[y],headdz[y]=totdz;
}
}
for(j=1; j<=len; j++)
if(!ins[j])
que.push(j);
for(; que.size(); que.pop())
{
for(w=que.front(),f[w]=s[w],j=headdz[w]; j; j=edz[j].nxt)
f[w]=max(f[w],f[edz[j].v]+s[w]);
for(j=headsd[w]; j; j=esd[j].nxt)
if(!(--ins[esd[j].v]))que.push(esd[j].v);
ans=max(ans,f[w]);
}
cout<<ans;
return 0;
}