https://www.luogu.org/problemnew/show/P1262
#include <bits/stdc++.h>
using namespace std;
const int maxN=3005;
const int maxM=8005;
const int INF=(1<<30);
int head[maxN],tot,cs[maxN];
struct graph
{
int to,next;
} G[maxM];
void addedge(int u,int v)
{
G[tot]= {v,head[u]};
head[u]=tot++;
}
int dfn[maxN],low[maxN],tim,insta[maxN];
int scc[maxN],cost[maxN],cnt,in[maxN];
stack<int>sta;
void targan(int u,int fa)
{
dfn[u]=low[u]=++tim;
sta.push(u);
insta[u]=1;
for(int i=head[u]; i+1; i=G[i].next)
{
int v=G[i].to;
if(!dfn[v])
{
targan(v,u);
low[u]=min(low[u],low[v]);
}
else if(insta[v])
low[u]=min(low[u],dfn[v]);
}
if(low[u]==dfn[u])
{
cnt++;
while(1)
{
int v=sta.top();
sta.pop();
insta[v]=0;
scc[v]=cnt;
cost[cnt]=min(cost[cnt],cs[v]);
if(v==u)break;
}
}
}
int main()
{
int N,P,R,u,v,co;
cin>>N>>P;
for(int i=1; i<=N; i++)cs[i]=cost[i]=INF;
for(int i=1; i<=P; i++)
{
cin>>u>>co;
cs[u]=co;
}
cin>>R;
memset(head,-1,sizeof(head));
while(R--)
{
cin>>u>>v;
addedge(u,v);
}
for(int i=1; i<=N; i++)
if(!dfn[i])targan(i,i);
for(int i=1;i<=N;i++)
for(int j=head[i];j+1;j=G[j].next)
if(scc[i]!=scc[G[j].to])
in[scc[G[j].to]]++;
int ans,flag=0;
for(int i=1;i<=cnt;i++)
if(!in[i]&&cost[i]==INF)
{
printf("NO\n");
flag=1;
break;
}
if(flag)
{
ans=INF;
for(int i=1;i<=cnt;i++)
if(!in[i]&&cost[i]==INF)
{
for(int j=1;j<ans;j++)
if(scc[j]==i)ans=j;
}
cout<<ans<<endl;
}
else
{
ans=0;
printf("YES\n");
for(int i=1;i<=cnt;i++)
if(!in[i])ans+=cost[i];
cout<<ans<<endl;
}
return 0;
}