知识点:tarjan算法 、 缩点。
题解:通过缩点把所有的强连通分量看成一个点,进而把图缩成一DAG,从中在选取入度为0的点的数量即是最少需要通知人的数量,那些点里的最小花费相加就是老师的最小花费。
注意:在输入时一定要用scanf 别用 cin 否则会TLE;
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
#include <iostream>
#include <stack>
#include <vector>
#include<cstdio>
#include<cmath>
#include<cstring>
using namespace std;
const int inf = 0x3f3f3f3f;
int low[1005], num[1005], cost[1005], cost1[1005], belong[1005], into[1005];
bool flag[1005];
vector<int>G[1005];
stack<int>s;
int dfn, sum, ans;
int min(int a, int b) {
return a < b ? a : b;
}
void tarjan(int u) {
s.push(u);
low[u] = num[u] = ++dfn;
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i];
if (!num[v]) {
tarjan(v);
low[u] = min(low[u], low[v]);
}
else if (flag[v]) {
low[u] = min(low[u], num[v]);
}
}
if (num[u] == low[u]) {
ans++;
while (true) {
int v = s.top(); s.pop();
flag[v] = false;
cost1[ans] = min(cost1[ans], cost[v]);
belong[v] = ans;
if (v == u) break;
}
}
}
int main() {
int n, m, a, b;
while (scanf("%d %d", &n, &m) != EOF) {
//cin >> a;
memset(low, 0, sizeof(low));
memset(num, 0, sizeof(num));
memset(flag, true, sizeof(flag));
memset(cost1, inf, sizeof(cost1));
memset(belong, 0, sizeof(belong));
memset(into, 0, sizeof(into));
for (int i = 0; i <= n; i++) {
G[i].clear();
}
dfn = 0; sum = 0; ans = 0;
for (int i = 1; i <= n; i++)
scanf("%d", &cost[i]);
for (int i = 1; i <= m; i++) {
scanf("%d %d", &a, &b);
G[a].push_back(b);
}
for (int i = 1; i <= n; i++)
if (!num[i])
tarjan(i);
a = b = 0;
for (int i = 1; i <= n; i++) {
for (int j = 0; j < G[i].size(); j++) {
int v = G[i][j];
if (belong[i] != belong[v]) {
into[belong[v]]++;
}
}
}
for (int i = 1; i <= ans; i++) {
if (into[i] == 0) {
a++;
b += cost1[i];
}
}
cout << a << " " << b << endl;
}
system("pause");
return 0;
}