HDU 1827 —— Summer Holiday

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


思路:先求强连通分量,缩点构建新图,新图中入度 = 0 的点的个数就是所求的最少人数,对于每个入度 = 0 的强连通分量选取最小的话费值,其和即为所求的最小花费;


#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#define inf 0x3f3f3f3f
using namespace std;
const int maxn = 1005;
const int maxm = 2005;
int n, m;
int val[maxn];
int DFN[maxn], Low[maxn], Stack[maxn], Belong[maxn];
int Time, taj, top;
bool Instack[maxn];
int head[maxn], edgenum;
int tmp[maxn], du[maxn];

struct Edge
{
	int from, to;
	int next;
}edge[maxm];

void Tarjan(int u)
{
	DFN[u] = Low[u] = ++Time;
	Stack[top++] = u;
	Instack[u] = true;
	for(int i = head[u];i != -1;i = edge[i].next)
	{
		int v = edge[i].to;
		if(DFN[v] == -1)
		{
			Tarjan(v);
			Low[u] = min(Low[u], Low[v]);
		}
		else if(Instack[v] && Low[u] > DFN[v])
			Low[u] = DFN[v];
	}
	if(DFN[u] == Low[u])
	{
		taj++;
		int k = inf;
		while(1)
		{
			int now = Stack[--top];
			k = min(k, val[now]);
			Instack[now] = false;
			Belong[now] = taj;
			if(now == u)	break;
		}
		tmp[taj] = k;
	}
}

void add(int u, int v)
{
	edge[edgenum].from = u;
	edge[edgenum].to = v;
	edge[edgenum].next = head[u];
	head[u] = edgenum++;
}

void init()
{
	memset(head, -1, sizeof head);
	edgenum = 0;
	memset(DFN, -1, sizeof DFN);
	memset(Instack, false, sizeof Instack);
	Time = taj = top = 0;
}

int main()
{
	while(~scanf("%d%d", &n, &m))
	{
		init();
		for(int i = 1;i<=n;i++)
			scanf("%d", &val[i]);
		while(m--)
		{
			int u, v;
			scanf("%d%d", &u, &v);
			add(u, v);
		}
		for(int i = 1;i<=n;i++)
		{
			if(DFN[i] == -1)
			Tarjan(i);
		}
		memset(du, 0, sizeof du);
		int ans = 0, cnt = 0;
		for(int i = 0;i<edgenum;i++)
		{
			int u = Belong[edge[i].from];
			int v = Belong[edge[i].to];
			if(u != v)
				du[v]++;
		}
		for(int i = 1;i<=taj;i++)
		{
			if(du[i] == 0)
			{
				cnt++;
				ans += tmp[i];
			}
		}
		printf("%d %d\n", cnt, ans);
	}
	return 0;
}


你可能感兴趣的:(强连通)