HDU 1827:Summer Holiday(强连通)

http://acm.hdu.edu.cn/showproblem.php?pid=1827

思路:强连通分量缩点后找入度为0的点,然后对于属于该强连通分量的找一个最小耗费的入口。

 #include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <queue>
#include <cmath>
#include <map>
#include <vector>
#include <stack>
using namespace std;
#define N 80010
#define M 30010
#define INF 0x3f3f3f3f
struct node
{
int u, v, next;
}edge[N*];
stack<int> sta;
int tot, cnt, num, head[N], belong[N], dfn[N], low[N], n, m, a[N], in[N], mi[N];
bool vis[N]; void init()
{
tot = cnt = num = ;
while(sta.size()) sta.pop();
memset(head, -, sizeof(head));
memset(belong, , sizeof(belong));
memset(dfn, , sizeof(dfn));
memset(low, , sizeof(low));
memset(vis, false, sizeof(vis));
memset(in, , sizeof(in));
memset(mi, INF, sizeof(mi));
} void add(int u, int v)
{
edge[tot].u = u; edge[tot].v = v; edge[tot].next = head[u]; head[u] = tot++;
} void tarjan(int u)
{
vis[u] = ;
sta.push(u);
dfn[u] = low[u] = ++cnt;
for(int i = head[u]; ~i; i = edge[i].next) {
int v = edge[i].v;
if(!dfn[v]) {
tarjan(v);
if(low[v] < low[u]) low[u] = low[v];
} else if(vis[v]) {
if(dfn[v] < low[u]) low[u] = dfn[v];
}
}
if(dfn[u] == low[u]) {
++num;
int top = -;
while(top != u) {
top = sta.top(); sta.pop();
belong[top] = num;
vis[top] = ;
}
}
} int main()
{
while(~scanf("%d%d", &n, &m)) {
init();
for(int i = ; i <= n; i++) scanf("%d", &a[i]);
for(int i = ; i < m; i++) {
int u, v;
scanf("%d%d", &u, &v);
add(u, v);
}
for(int i = ; i <= n; i++)
if(!dfn[i]) tarjan(i);
for(int u = ; u <= n; u++) {
for(int i = head[u]; ~i; i = edge[i].next) {
int v = edge[i].v;
if(belong[u] != belong[v]) { //缩点后找入度为0的点
in[belong[v]]++;
}
}
}
int ans = , sum = ;
for(int i = ; i <= num; i++) {
if(!in[i]) {
ans++;
for(int j = ; j <= n; j++) {
if(belong[j] == i) {
if(a[j] < mi[i]) {
mi[i] = a[j]; //对于不同的强连通分量之间找耗费最小的入口
}
}
}
sum += mi[i];
}
}
printf("%d %d\n", ans, sum);
}
return ;
} /*
4 3
1 2 3 4
1 2
1 3
1 4
*/
上一篇:引用类型之Array类型


下一篇:HDU - 1827 Summer Holiday (强连通)