Summer Holiday |
---|
Problem Description
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
思路
给定一个电话联系网,问主人公至少要通知几个人才能让所有人都收到。Tarjan强连通 + 贪心 + 缩点
大概思路就是先求强连通分量,每个强连通分量都是可以相互通知的,那么可以在这个强连通分量里面通知花费最小的即可(贪心),求完之后对每个强连通分量进行缩点。缩点完成之后就是一个简单图,对这个简单图只需要统计入度为0的缩点,将这些费用加起来输出即可。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cstdlib>
#include <queue>
#include <vector>
#include <stack>
using namespace std;
const int maxn = 1005;
vector<int>e[maxn];
stack<int>s;
int a[maxn];
int num[maxn];
int dfn[maxn];
int low[maxn];
int d[maxn];
int scc[maxn];
int cnt,tot;
inline void clear_set()
{
cnt = tot = 0;
for(int i = 0;i < maxn;i++){
e[i].clear();
}
memset(num,0x3f,sizeof(num));
memset(scc,0,sizeof(scc));
memset(dfn,0,sizeof(dfn));
memset(d,0,sizeof(d));
memset(low,0,sizeof(low));
while(!s.empty()) s.pop();
}
inline void tarjan(int x)
{
dfn[x] = low[x] = ++cnt;
s.push(x);
for(int i = 0;i < e[x].size();i++){
int y = e[x][i];
if(!dfn[y]){
tarjan(y);
low[x] = min(low[x],low[y]);
}
else if(!scc[y]){
low[x] = min(low[x],dfn[y]);
}
}
if(low[x] == dfn[x]){
tot++;
while(true){
int p = s.top();
s.pop();
scc[p] = tot;
num[tot] = min(num[tot],a[p]); //记录该强连通分量里最小的花费
if(x == p){
break;
}
}
}
}
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m)){
clear_set();
int x,y;
for(int i = 1;i <= n;i++){ //从1号开始存,便于处理
scanf("%d",&a[i]);
}
for(int i = 0;i < m;i++){
scanf("%d%d",&x,&y);
e[x].push_back(y);
}
for(int i = 1;i <= n;i++){
if(!dfn[i]){
tarjan(i);
}
}
// printf("%d\n",tot);
for(int i = 1;i <= n;i++){
for(int j = 0;j < e[i].size();j++){
y = e[i][j];
if(scc[i] != scc[y]){
d[scc[y]]++;
}
}
}
int ans_sum = 0,ans_scc = 0;
for(int i = 1;i <= tot;i++){
if(d[i] == 0){
ans_scc++;
ans_sum += num[i];
}
}
printf("%d %d\n",ans_scc,ans_sum);
}
return 0;
}
愿你走出半生,归来仍是少年~