P1262 间谍网络 tarjan

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值