当前位置: 代码迷 >> 综合 >> 【tarjan】P1262 间谍网络
  详细解决方案

【tarjan】P1262 间谍网络

热度:61   发布时间:2024-01-31 05:46:20.0

对能被收买的间谍进行tarjan

tarjan后求入度为0的新点,答案为这些新点中最小的点权之和

如果跑完tarjan后,还有人没被走过,那就意味着无法全部收买,输出NO

#include<bits/stdc++.h>
using namespace std;
const int maxn=3005;
const int inf=0x3f3f3f3f;
const int maxm=8005;
int n,p,m;
int money[maxn],ans,head[maxn],dfn[maxn],low[maxn],que[maxn];
int inin[maxn],top,cnt,tot,times,col[maxn],minnum[maxn];
struct edge
{int to,nxt;
}G[maxm];
void add(int x ,int y)
{G[++cnt].to=y; G[cnt].nxt=head[x]; head[x]=cnt;
}
void tarjan(int x)
{que[++top]=x;inin[x]=1;dfn[x]=low[x]=++times;for(int i=head[x];i;i=G[i].nxt){int to=G[i].to;if(!dfn[to]){tarjan(to);low[x]=min(low[x],low[to]);}else if(inin[to])low[x]=min(low[x],dfn[to]);}if(low[x]==dfn[x]){tot++;while(que[top+1]!=x){col[que[top]]=tot;minnum[tot]=min(minnum[tot],money[que[top]]);inin[que[top--]]=0;}}
}
int main()
{freopen("a.in","r",stdin);freopen("a.out","w",stdout);scanf("%d%d",&n,&p);int x,y;for(int i=1;i<=n;i++)money[i]=minnum[i]=inf;for(int i=1;i<=p;i++){scanf("%d%d",&x,&y);money[x]=y;}scanf("%d",&m);for(int i=1;i<=m;i++) scanf("%d%d",&x,&y),add(x,y);for(int i=1;i<=n;i++)if(!dfn[i] && money[i]!=inf) tarjan(i);for(int i=1;i<=n;i++)if(!dfn[i]){printf("NO\n");printf("%d\n",i);return 0;}for(int i=1;i<=n;i++)for(int j=head[i];j;j=G[j].nxt)if(col[i]!=col[G[j].to]) inin[col[G[j].to]]++;for(int i=1;i<=tot;i++)if(!inin[i]) ans+=minnum[i];printf("YES\n%d\n",ans);return 0;
}