UVa 10000 Longest Paths (单源最长路 - floyd or 拓扑排序)

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=941

由于n很小,floyd算法写起来方便,先用这个A了一下:

/*0.162s*/

#include<bits/stdc++.h>
using namespace std;
const int mx = 105;

int d[mx][mx];

void floyd(int n)
{
	int k, i, j;
	for (k = 1; k <= n; ++k)
		for (i = 1; i <= n; ++i)
			for (j = 1; j <= n; ++j)
				d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
}

int main()
{
	int cas = 0, n, s, i, a, b, dis, to;
	while (scanf("%d%d", &n, &s), n)
	{
		memset(d, 0x3f, sizeof(d));
		for (i = 1; i <= n; ++i) d[i][i] = 0;
		while (scanf("%d%d", &a, &b), a)
			d[a][b] = -1; ///取负值
		floyd(n);
		dis = 0;
		for (i = 1; i <= n; ++i)
		{
			if (d[s][i] < dis)
			{
				dis = d[s][i];
				to = i;
			}
		}
		printf("Case %d: The longest path from %d has length %d, finishing at %d.\n\n", ++cas, s, -d[s][to], to);
	}
	return 0;
}

然后由于是DAG,于是用拓扑排序A了一下,快的不是一点半点:

/*0.038s*/

#include<bits/stdc++.h>
using namespace std;
const int mx = 105;

vector<int> G[mx];
bool vis[mx];
int topo[mx], disTo[mx], cnt;

void dfs(int i)
{
	vis[i] = true;
	for (int j = 0; j < G[i].size(); ++j) ///对于vector,[0,size())
		if (!vis[G[i][j]]) dfs(G[i][j]);
	topo[cnt++] = i;
}

void dagSP(int s)
{
	int i = cnt, j, v;
	while (topo[--i] != s);
	memset(disTo, 0x3f, sizeof(disTo)); /// 初始化
	disTo[s] = 0;
	for (; i >= 0; --i)
	{
		v = topo[i];
		for (j = 0; j < G[v].size(); ++j) ///注意是以v为主
			disTo[G[v][j]] = min(disTo[G[v][j]], disTo[v] - 1);
	}
}

int main()
{
	int cas = 0, n, s, i, a, b, dis, to;
	while (scanf("%d%d", &n, &s), n)
	{
		for (i = 1; i <= n; ++i) G[i].clear();
		while (scanf("%d%d", &a, &b), a) G[a].push_back(b);
		cnt = 0; /// 最重要的初始化!
		memset(vis, 0, sizeof(vis));
		for (i = 1; i <= n; ++i)
			if (!vis[i]) dfs(i);
		dagSP(s);
		dis = 0;
		for (i = 1; i <= n; ++i)
		{
			if (disTo[i] < dis)
			{
				dis = disTo[i];
				to = i;
			}
		}
		printf("Case %d: The longest path from %d has length %d, finishing at %d.\n\n", ++cas, s, -disTo[to], to);
	}
	return 0;
}

    原文作者:拓扑排序
    原文地址: https://blog.csdn.net/synapse7/article/details/19283885
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞