【模板】缩点 / 强连通分量
题目跳转
代码
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
uint8_t buf[1<<20],*p1,*p2;
#define gc() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<20,stdin),p1==p2)?EOF:*p1++)
ll rd(){
ll x=0,f=1,ch=gc();
while(ch<'0'||ch>'9'){
if(ch=='-'){
f=-1;
}
ch=gc();
}
while(ch>='0'&&ch<='9'){
x=(x<<1)+(x<<3)+(ch-'0');
ch=gc();
}
return x*f;
}
void write(ll x){
if(x<0){
x*=-1;
putchar('-');
}
if(x>9){
write(x/10);
}
putchar(x%10+'0');
}
const ll maxn=1e4+5;
ll n,m,cnt,scc,a[maxn],dfn[maxn],low[maxn],belong[maxn],val[maxn],ru[maxn],ans,dp[maxn];
vector<ll> e[maxn],g[maxn];
bool isin[maxn];
stack<ll> stk;
queue<ll> q;
void tarjan(ll x){
dfn[x]=low[x]=++cnt;
isin[x]=true;
stk.push(x);
for(auto y:e[x]){
if(!dfn[y]){
tarjan(y);
low[x]=min(low[x],low[y]);
}else if(isin[y]){
low[x]=min(low[x],dfn[y]);
}
}
if(dfn[x]==low[x]){
ll y;
scc++;
do{
y=stk.top();
stk.pop();
isin[y]=false;
belong[y]=scc;
val[scc]+=a[y];
}while(y!=x);
}
}
int main(){
n=rd();
m=rd();
for(ll i=1;i<=n;i++){
a[i]=rd();
}
for(ll i=1;i<=m;i++){
ll u=rd(),v=rd();
e[u].push_back(v);
}
for(ll i=1;i<=n;i++){
if(!dfn[i]){
tarjan(i);
}
}
for(ll x=1;x<=n;x++){
for(auto y:e[x]){
if(belong[x]!=belong[y]){
g[belong[x]].push_back(belong[y]);
ru[belong[y]]++;
}
}
}
for(ll i=1;i<=scc;i++){
if(ru[i]==0){
q.push(i);
dp[i]=val[i];
}
}
while(!q.empty()){
ll x=q.front();
q.pop();
for(auto y:g[x]){
dp[y]=max(dp[y],dp[x]+val[y]);
ru[y]--;
if(ru[y]==0){
q.push(y);
}
}
}
for(ll i=1;i<=scc;i++){
ans=max(ans,dp[i]);
}
write(ans);
return 0;
}
Goodbye!

浙公网安备 33010602011771号