【强连通缩点】 HDOJ 3072 Intelligence System

先强连通缩点,然后对每个点挑指向这个点的权值最小的边,如果入度为0就不计算了。。最后全加起来就是答案了。。

#include <iostream>  
#include <queue>  
#include <stack>  
#include <map>  
#include <set>  
#include <bitset>  
#include <cstdio>  
#include <algorithm>  
#include <cstring>  
#include <climits>  
#include <cstdlib>
#include <cmath>
#include <time.h>
#define maxn 50005
#define maxm 100005
#define eps 1e-10
#define mod 1000000009
#define INF 0x3f3f3f
#define lowbit(x) (x&(-x))  
//#define lson o<<1, L, mid  
//#define rson o<<1 | 1, mid+1, R  
typedef long long LL;
//typedef int LL;
using namespace std;

int H[maxn], NEXT[maxm], V[maxm], W[maxm];
int h[maxn], next[maxm], v[maxm], w[maxm];
int dfn[maxn], low[maxn], ins[maxn];
int done[maxn], dis[maxn], id[maxn];
int n, m, top, scc_cnt;
stack<int> s;
queue<int> q;

void init(void)
{
	top = scc_cnt = 0;
	memset(h, -1, sizeof h);
	memset(H, -1, sizeof H);
	memset(dfn, 0, sizeof dfn);
	memset(done, 0, sizeof done);
	memset(dis, INF, sizeof dis);
}
void read(void)
{
	int a, b, c, cnt = 0;
	while(m--) {
		scanf("%d%d%d", &a, &b, &c);
		a++, b++;
		NEXT[cnt] = H[a], H[a] = cnt, V[cnt] = b, W[cnt] = c, cnt++;
	}
}
void narrow(void)
{
	int cnt = 0;
	for(int i = 1; i <= n; i++)
		for(int e = H[i]; ~e; e = NEXT[e])
			next[cnt] = h[id[i]], h[id[i]] = cnt, v[cnt] = id[V[e]], w[cnt] = W[e], cnt++;
}
void tarjan(int u)
{
	dfn[u] = low[u] = ++top;
	s.push(u), ins[u] = 1;
	for(int e = H[u]; ~e; e = NEXT[e])
		if(!dfn[V[e]]) {
			tarjan(V[e]);
			low[u] = min(low[u], low[V[e]]);
		}
		else if(ins[V[e]]) low[u] = min(low[u], dfn[V[e]]);
	if(dfn[u] == low[u]) {
		int tmp = s.top(); s.pop(), ins[tmp] = 0;
		++scc_cnt;
		while(tmp != u) {
			id[tmp] = scc_cnt;
			tmp = s.top();
			s.pop();
			ins[tmp] = 0;
		}
		id[tmp] = scc_cnt;
	}
}
void work(void)
{
	int i, ans = 0;
	for(i = 1; i <= n; i++)
		if(!dfn[i]) tarjan(i);
	narrow();
	for(i = 1; i <= scc_cnt; i++)
		for(int e = h[i]; ~e; e = next[e])
			if(v[e] != i)
				dis[v[e]] = min(dis[v[e]], w[e]);
	for(i = 1; i <= scc_cnt; i++) if(dis[i]<INF) ans += dis[i];
	printf("%d\n", ans);
}
int main(void)
{
	while(scanf("%d%d", &n, &m)!=EOF) {
		init();
		read();
		work();
	}
	return 0;
}


你可能感兴趣的:(HDU)