Summer Holiday——Tarjan缩点

传送门HDU1827

描述

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计算出至少要通知多少人,至少得花多少电话费就能让所有人都被通知到吗?

输入

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

输出

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

样例

  • 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
  • Output
    3 6

题解

  • 通过Tarjan缩点后找出每个点的入度,入度为0的点需要Wiskey通知
  • 缩点的时候,强联通分量中的最小权值为此点的权值
  • 在存图时同时保存当前边的起点和终点,以便寻找入度。
  • 遍历所有的边,如果边i的起点和终点不属于同一强联通分量,则它们所属的两个强联通分量之间有一条边。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include<bits/stdc++.h>
#define INIT(a,b) memset(a,b,sizeof(a))
#define LL long long
using namespace std;
const int inf=0x3f3f3f3f;
const int maxn=1e3+7;
const int maxm=2e3+7;
const int mod=1e9+7;
struct Edge{int from,to,next;}edge[maxm];
int Begin[maxn],dfn[maxn],low[maxn],vis[maxn],sta[maxn],color[maxn];
int val[maxn],minV[maxn],inde[maxn];
int n,m,x,y,dfsNum,colNum,tot,top,ansV,ansN;
void init(){
INIT(Begin,-1);INIT(dfn,0);
INIT(low,0);INIT(vis,0);
INIT(color,0);INIT(minV,inf);
INIT(inde,0);
colNum=0,dfsNum=0,tot=0,top=-1,ansV=0,ansN=0;
}
void add(int x,int y){
edge[tot]=(Edge){x,y,Begin[x]};
Begin[x]=tot++;
}
void Tarjan(int x){
dfn[x]=low[x]=++dfsNum;
vis[x]=1;
sta[++top]=x;
for(int i=Begin[x];~i;i=edge[i].next){
int ne=edge[i].to;
if(!dfn[ne]){
Tarjan(ne);
low[x]=min(low[x],low[ne]);
}
else if(vis[ne]) low[x]=min(low[x],dfn[ne]);
}
if(low[x]==dfn[x]){
vis[x]=0;
color[x]=++colNum;
minV[colNum]=min(minV[colNum],val[x]);
while(sta[top]!=x){
vis[sta[top]]=0;
minV[colNum]=min(minV[colNum],val[sta[top]]);//找最小点权
color[sta[top--]]=colNum;
}
top--;
}
}
int main(){
while(~scanf("%d%d",&n,&m)){
init();
for(int i=1;i<=n;i++)
scanf("%d",&val[i]);
while(m--){
scanf("%d%d",&x,&y);
add(x,y);
}
for(int i=1;i<=n;i++){
if(!dfn[i]) Tarjan(i);
}
//找入度
for(int i=0;i<tot;i++){
if(color[edge[i].from]!=color[edge[i].to]){
inde[color[edge[i].to]]++;
}
}
for(int i=1;i<=colNum;i++){
if(inde[i]==0){
ansN++;
ansV+=minV[i];
}
}
printf("%d %d\n",ansN,ansV);
}
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值