pku 3463 dijkstra求次短路

#include <iostream>
#include <vector>
using namespace std;
const int MAXN = 1010;
const int INF = 2100000000;

typedef pair<int, int> PAIR;
vector < PAIR > map[MAXN];
int dist[MAXN][2], n, m, cnt[MAXN][2];
bool hash[MAXN][2];
int dijkstra(int start, int end)
{
	memset(hash, 0, sizeof(hash));
	memset(cnt, 0, sizeof(cnt));
	int i, j;
	for (i = 1; i <= n; ++i)
	{
		dist[i][0] = dist[i][1] = INF;
	}
	
	dist[start][0] = 0;
	cnt[start][0] = 1;
	
	for (i = 0; i < 2*n; ++i)
	{
		int MIN = INF, p = -1, k;
		for (j = 1; j <= n; ++j)
		{
			if (!hash[j][0] && dist[j][0] < MIN)
			{
				MIN = dist[j][0];
				p = j;
				k = 0;
			}
			else if (!hash[j][1] && dist[j][1] < MIN)
			{
				MIN = dist[j][1];
				p = j;
				k = 1;
			}
		}
		if (p == -1)
		{
			break;
		}
		hash[p][k] = true;

		for (j = 0; j < map[p].size(); ++j)
		{
			int q = MIN + map[p][j].second;
			int pos = map[p][j].first;
			if (q < dist[pos][0])
			{
				dist[pos][1] = dist[pos][0];
				cnt[pos][1] = cnt[pos][0];
				dist[pos][0] = q;
				cnt[pos][0] = cnt[p][k];
			}
			else if (q == dist[pos][0])
			{
				cnt[pos][0] += cnt[p][k];
			}
			else if (q < dist[pos][1])
			{
				dist[pos][1] = q;
				cnt[pos][1] = cnt[p][k];
			}
			else if (q == dist[pos][1])
			{
				cnt[pos][1] += cnt[p][k];
			}
		}
	}

	int num = cnt[end][0];
	if (dist[end][0]+1 == dist[end][1])
	{
		num += cnt[end][1];
	}
	return num;
}
int main()
{
	int T;
	scanf("%d", &T);
	while (T--)
	{
		int i;
		scanf("%d %d", &n, &m);
		for (i = 1; i <= n; ++i)
		{
			map[i].clear();
		}
		for (i = 0; i < m; ++i)
		{
			int a, b, c;
			scanf("%d %d %d", &a, &b, &c);
			map[a].push_back(make_pair(b, c));
		}
		int start, end;
		scanf("%d %d", &start, &end);

		printf("%d\n",dijkstra(start, end));
	}
	return 0;
}

posted on 2009-07-31 18:01  ZAFU_VA  阅读(920)  评论(0编辑  收藏  举报

导航