Summer Holiday (强连通分量tarjan)

题解:在tarjan中加一个数组用来保存一个强连通分量中的最小花费,之后suodian中寻找入度为0的点即可。

To see a World in a Grain of Sand 
And a Heaven in a Wild Flower, 
Hold Infinity in the palm of your hand 
And Eternity in an hour. 
                  —— William Blake 

听说lcy帮大家预定了新马泰7日游,Wiskey真是高兴的夜不能寐啊,他想着得快点把这消息告诉大家,虽然他手上有所有人的联系方式,但是一个一个联系过去实在太耗时间和电话费了。他知道其他人也有一些别人的联系方式,这样他可以通知其他人,再让其他人帮忙通知一下别人。你能帮Wiskey计算出至少要通知多少人,至少得花多少电话费就能让所有人都被通知到吗? 

Input

多组测试数组,以EOF结束。 
第一行两个整数N和M(1<=N<=1000, 1<=M<=2000),表示人数和联系对数。 
接下一行有N个整数,表示Wiskey联系第i个人的电话费用。 
接着有M行,每行有两个整数X,Y,表示X能联系到Y,但是不表示Y也能联系X。 

Output

输出最小联系人数和最小花费。 
每个CASE输出答案一行。 

Sample Input

12 16
2 2 2 2 2 2 2 2 2 2 2 2 
1 3
3 2
2 1
3 4
2 4
3 5
5 4
4 6
6 4
7 4
7 12
7 8
8 7
8 9
10 9
11 10

Sample Output

3 6
#include<stdio.h>
#include<string.h>
#include<vector>
#include<algorithm>
#define inf 0x3f3f3f3f
using namespace std;
#define maxn 2200
#define N 1100
int n,m;
int cost[N];
int costt[N];
struct Edge{
	int from,to,nex;
	bool sign;
}edge[maxn<<1];
int head[N],edgenum;
void add(int u,int v)
{
	Edge E={u,v,head[u],false};
	edge[edgenum]=E;
	head[u]=edgenum++;
}
int DFN[N],Low[N],Stack[N],top,time;
int taj;
int Belong[N];
bool Instack[N];
vector<int>bcc[N];
void tarjan(int u,int fa)
{
	DFN[u]=Low[u]=++time;
	Stack[top++]=u;
	Instack[u]=1;
	for(int i=head[u];~i;i=edge[i].nex)
	{
		int v=edge[i].to;
		if(DFN[v]==-1)
		{
			tarjan(v,u);
			Low[u]=min(Low[u],Low[v]);
			if(DFN[u]<Low[v])
			{
				edge[i].sign=1;
			}
		}
		else if(Instack[v]) Low[u]=min(Low[u],DFN[v]);
	}
	if(Low[u]==DFN[u])
	{
		int now;
		taj++;
		bcc[taj].clear();
		do{
			now=Stack[--top];
			Instack[now]=0;
			Belong[now]=taj;
			bcc[taj].push_back(now);
			if(cost[now]<costt[taj])
			{
				costt[taj]=cost[now];//修改寻找最小 
			}
		}while(now!=u);
	}
}
void tarjan_init(int all)
{
	memset(DFN,-1,sizeof(DFN));
	memset(Instack,0,sizeof(Instack));
	top=time=taj=0;
	for(int i=1;i<=all;i++)
	{
		if(DFN[i]==-1) tarjan(i,i);
	}
}
vector<int>G[N];
int du[N];
void suodian()
{
	memset(du,0,sizeof(du));
	for(int i=1;i<=taj;i++) G[i].clear();
	for(int i=0;i<edgenum;i++)
	{
		int u=Belong[edge[i].from],v=Belong[edge[i].to];
		if(u!=v) G[u].push_back(v),du[v]++; 
	}
	int sum=0,num=0;
	for(int i=1;i<=taj;i++)//注意i的范围 
	{
		if(du[i]==0)
		{
			sum+=costt[i];
			num++;
		}
	}
	printf("%d %d\n",num,sum);
}
void init()
{
	memset(head,-1,sizeof(head));
	edgenum=0;
}
int main() 
{

	while(scanf("%d%d",&n,&m)!=EOF)
	{
		init();
		memset(costt,inf,sizeof(costt));
		for(int i=1;i<=n;i++)
		{
			scanf("%d",&cost[i]);
		}
		for(int i=1;i<=m;i++)
		{
			int x,y;
			scanf("%d%d",&x,&y);
			add(x,y);
			 
		}
		tarjan_init(n);
			suodian();
	}
	return 0;
} 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值