题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1827
思路:求出所有的SCC,将一个SCC看作一个节点,取入度为0的SCC数量为联系人数,每个入度为0的SCC中取花费最小者加到答案中。
Tarjan同样是求SCC(强连通分量)的算法,比起Kosaraju更为高级,虽然时间复杂度同样是O(V+E),但是由于DFS只要进行一遍,常数更小。原理是,利用和求割点相同的方法,最远祖先相同的点属于同一个SCC之中。
#include <bits/stdc++.h>
using namespace std;
const int M = 2000 + 5;
const int N = 1000 + 5;
int cnt;
int num[N], low[N], dfn;
int sccno[N], Stack[N], top;
vector<int> G[N];
int cost[N], in[N], add[N], ansNum, ansCost;
void dfs(int u) {
Stack[top++] = u;
low[u] = num[u] = ++dfn;
for (int i = 0; i < G[u].size(); i++) {
int v = G[u][i];
if (!num[v]) {
dfs(v);
low[u] = min(low[v], low[u]);
}
else if (!sccno[v]) // 标记SCC仅仅在SCC的根节点操作
low[u] = min(low[u], num[v]);
}
if (low[u] == num[u]) {
cnt++;
int add = 0x3f3f3f3f;
while(1) {
int v = Stack[--top];
sccno[v] = cnt;
if (u == v) break;
}
// printf("root = %d, sccno = %d\n", u, sccno[u]);
}
}
void Tarjan(int n) {
cnt = top = dfn = 0;
memset(sccno, 0, sizeof(sccno));
memset(num, 0, sizeof(num));
memset(low, 0, sizeof(low));
for (int i = 1; i <= n; i++)
if (!num[i]) dfs(i);
memset(in, 0, sizeof(in));
ansNum = ansCost = 0;
for (int i = 1; i <= cnt; i++) add[i] = 0x3f3f3f3f;
for (int i = 1; i <= n; i++) {
int u = sccno[i];
for (int j = 0; j < G[i].size(); j++) {
int v = sccno[G[i][j]];
if (v == u) continue;
in[v]++;
}
add[u] = min(cost[i], add[u]);
}
for (int i = 1; i <= cnt; i++) {
// printf("in[%d] = %d\n", i, in[i]);
if (!in[i]) {
ansNum++;
ansCost += add[i];
}
}
}
int main(void) {
// freopen("in.txt", "r", stdin);
int n, m, a, b;
while (~scanf("%d%d", &n, &m)) {
for (int i = 1; i <= n; i++) {
G[i].clear();
scanf("%d", &cost[i]);
}
for (int i = 1; i <= m; i++) {
scanf("%d%d", &a, &b);
G[a].push_back(b);
}
Tarjan(n);
printf("%d %d\n", ansNum, ansCost);
}
return 0;
}