YBTOJ通讯问题(强连通分量)

YBTOJ通讯问题(强连通分量)

在这里插入图片描述
思路:
在这里插入图片描述

以上纯属水博客
有强连通分量这个算法提示,思路应该不难想
但是有一个小细节
我们枚举入边的时候要缩点之后反向建图,然后枚举出边
我没建反图调了一辈子
AC代码:

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int maxn=5e4+5,maxm=1e5+5;
int n,m,bcnt,ecnt,tmp,cnt,st[maxn],top,head[maxn],head1[maxn],dfn[maxn],ans;
int low[maxn],c[maxn],out[maxn];
bool v[maxn];
struct edge
{
	int from,to,nxt,w;
}e[maxm],b[maxm];
void add(int x,int y,int z)
{
	b[++bcnt]=(edge){x,y,head[x],z};
	head[x]=bcnt;
}
void add1(int x,int y,int z)
{
//	printf("u:%d v:%d w:%d\n",x-1,y-1,z);
	e[++ecnt]=(edge){x,y,head1[x],z};
	head1[x]=ecnt;	
}
void tarjan(int x)
{
	dfn[x]=low[x]=++cnt;v[x]=1;
	st[++top]=x;
	for(int i=head[x];i;i=b[i].nxt)
	{
		int y=b[i].to;
		if(!dfn[y])
		{
			tarjan(y);
			low[x]=min(low[x],low[y]);	
		}
		else if(v[y]) low[x]=min(low[x],dfn[y]);
	} 
	if(dfn[x]==low[x])
	{
		tmp++;
		do
		{
			c[st[top]]=tmp;
			v[st[top]]=0;
			top--;
		}while(x!=st[top+1]);
	}
}
void clear()
{
	memset(st,0,sizeof(st));
	memset(head,0,sizeof(head));
	memset(head1,0,sizeof(head1));
	memset(dfn,0,sizeof(dfn));
	memset(c,0,sizeof(c));
	memset(v,0,sizeof(v));
	memset(low,0,sizeof(low));
	ecnt=0;bcnt=0;tmp=0;cnt=0;top=0;ans=0; 
}
void work()
{
	for(int u=1;u<=tmp;u++)
	{
		int flag=0;
		if(!out[u]) continue;
		int minn=0x7fffffff;
//		cout<<head1[u]<<endl;
		for(int i=head1[u];i;i=e[i].nxt) minn=min(minn,e[i].w),flag=1;
//		cout<<out[u]<<" "<<flag<<" "<<minn<<endl;
		if(flag) ans+=minn;
	}
}
signed main()
{
	while(1)
	{
		scanf("%lld%lld",&n,&m);
		if(n==0&&m==0) break;
		clear();
		for(int i=1;i<=m;i++)
		{
			int x,y,z;
			scanf("%lld%lld%lld",&x,&y,&z);
			add(x+1,y+1,z);
		}
		for(int i=1;i<=n;i++) if(!dfn[i]) tarjan(i);
//		for(int i=1;i<=n;i++) cout<<c[i]<<" ";
//		cout<<endl;
		for(int i=1;i<=bcnt;i++)
		{
			int x=b[i].from,y=b[i].to,z=b[i].w;
			if(c[x]!=c[y]) add1(c[y],c[x],z),out[c[y]]++;
		}
//		cout<<tmp<<endl;
//		for(int i=1;i<=n;i++) cout<<out[i]<<" ";
//		cout<<endl;
		work();
		printf("%lld\n",ans);
	}
	return 0;
}
/*
7 6
0 1 22622
0 2 60946
2 3 12288
2 4 60583
0 5 22206
2 6 65358

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值