洛谷 P1262 间谍网络【傻逼tarjan缩点】

直接缩点就好了呀OvO

#include <cmath>
#include <stack>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#define ll long long
#define rep(i,x,y) for(ll i=(x);i<=(y);i++)
#define repd(i,x,y) for(ll i=(x);i>=(y);i--)
using namespace std;

const ll N=3e5+5;
const ll Inf=1e18;

stack<ll>s;

ll cnt,to[N<<1],nxt[N<<1],head[N];
ll n,m,ans,a[N],b[N],v[N],cost[N],check[N];
ll tot,num,dfn[N],low[N],bel[N],vis[N];

inline ll read() {
	ll x=0;char ch=getchar();bool f=0;
	while(ch>'9'||ch<'0'){if(ch=='-')f=1;ch=getchar();}
	while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}
	return f?-x:x;
}

void ins(ll x,ll y) {
	to[++cnt]=y;nxt[cnt]=head[x];head[x]=cnt;
}

void tarjan(ll x) {
	dfn[x]=low[x]=++num;vis[x]=1;s.push(x);
	for(ll i=head[x];i;i=nxt[i]) {
		ll y=to[i];
		if(!dfn[y]) tarjan(y),low[x]=min(low[x],low[y]);
		else if(vis[y]) low[x]=min(low[x],dfn[y]);
	}
	if(dfn[x]!=low[x]) return ;
	
	tot++;cost[tot]=Inf;
	
	while(true) {
		ll y=s.top();s.pop();
		vis[y]=0;bel[y]=tot;cost[tot]=min(cost[tot],v[y]);
		if(x==y) return ;
	}
}

int main() {
	n=read(),m=read();
	
	rep(i,1,n) v[i]=Inf;
	
	rep(i,1,m) {
		ll x=read(),y=read();v[x]=y;
	}
	
	m=read();
	
	rep(i,1,m) {
		ll x=read(),y=read();
		ins(x,y);a[i]=x,b[i]=y;	
	}
	
	rep(i,1,n) if(!dfn[i]) tarjan(i);
	
	rep(i,1,m) if(bel[a[i]]!=bel[b[i]]) check[bel[b[i]]]=1;
	
	ll pos,flag=0;
	
	rep(i,1,n) {
		if(check[bel[i]]==0) {
			if(cost[bel[i]]==Inf) {
				pos=i;flag=1;break;
			} else {
				ans+=cost[bel[i]];check[bel[i]]=1;
			}
		}
	}
	
	if(flag) printf("NO\n%lld",pos);
	else printf("YES\n%lld",ans);
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/yanzhenhuai/article/details/82776305
今日推荐