Not Only Algorithm,不仅仅是算法,关注数学、算法、数据结构、程序员笔试面试以及一切涉及计算机编程之美的内容 。。
你的位置:NoAlGo博客 » 题解 » 

PAT 1003. Emergency

As an emergency rescue team leader of a city, you are given a special map of your country. The map shows several scattered cities connected by some roads. Amount of rescue teams in each city and the length of each road between any pair of cities are marked on the map. When there is an emergency call to you from some other city, your job is to lead your men to the place as quickly as possible, and at the mean time, call up as many hands on the way as possible.

Input

Each input file contains one test case. For each test case, the first line contains 4 positive integers: N (<= 500) – the number of cities (and the cities are numbered from 0 to N-1), M – the number of roads, C1 and C2 – the cities that you are currently in and that you must save, respectively. The next line contains N integers, where the i-th integer is the number of rescue teams in the i-th city. Then M lines follow, each describes a road with three integers c1, c2 and L, which are the pair of cities connected by a road and the length of that road, respectively. It is guaranteed that there exists at least one path from C1 to C2.

Output

For each test case, print in one line two numbers: the number of different shortest paths between C1 and C2, and the maximum amount of rescue teams you can possibly gather.
All the numbers in a line must be separated by exactly one space, and there is no extra space allowed at the end of a line.

Sample Input

5 6 0 2
1 2 1 5 3
0 1 1
0 2 2
0 3 1
1 2 1
2 4 1
3 4 1

Sample Output

2 4

解答

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int mx = 510, oo = 1 << 30;
int n, m, st, ed, w[mx], map[mx][mx]; //输入数据
bool vs[mx]; //已访问
int dis[mx], cnt[mx], mxw[mx]; //最短距离,最短路数量,最大权重和

void Dijkstra()
{
	memset(vs, 0, sizeof(vs));
	for (int i = 0; i < n; i++) 
		dis[i] = oo, cnt[i] = 0, mxw[i] = 0;

	dis[st] = 0, cnt[st] = 1, mxw[st] = w[st];
	for (int i = 0; i < n; i++)
	{
		int mnid, mndis = oo;
		for (int j = 0; j < n; j++)
			if (!vs[j] && dis[j] < mndis)
				mndis = dis[j], mnid = j;
		if (mndis == oo) return;

		vs[mnid] = 1;
		for (int j = 0; j < n; j++)
			if (!vs[j] && map[mnid][j]) //未访问 && 连通
				if (dis[j] > mndis + map[mnid][j])
					dis[j] = mndis + map[mnid][j], cnt[j] = cnt[mnid], mxw[j] = mxw[mnid] + w[j];
				else if(dis[j] == mndis + map[mnid][j])
					cnt[j] += cnt[mnid], mxw[j] = max(mxw[j], mxw[mnid] + w[j]);

		if (mnid == ed) return;
	}
}

int main()
{
	scanf("%d%d%d%d", &n, &m, &st, &ed);
	for (int i = 0; i < n; i++) scanf("%d", w+i);
	memset(map, 0, sizeof(map));
	for (int i = 0, x, y, z; i < m; i++)
		scanf("%d%d%d", &x, &y, &z), map[x][y] = map[y][x] = z;

	Dijkstra();

	printf("%d %d\n", cnt[ed], mxw[ed]);
	return 0;
}
上一篇: 下一篇:

我的博客

NoAlGo头像编程这件小事牵扯到太多的知识,很容易知其然而不知其所以然,但真正了不起的程序员对自己程序的每一个字节都了如指掌,要立足基础理论,努力提升自我的专业修养。

站内搜索

最新评论