SRM 622 D1L1: BuildingRoutes,shortest path

本文介绍了一种解决特定最短路径问题的算法,通过计算所有顶点对间的最短路径,判断哪些边属于最短路径集合。使用了Floyd-Warshall算法进行预处理,并统计每条边作为最短路径的次数。

题目:http://community.topcoder.com/stat?c=problem_statement&pm=13193&rd=15855


开始的想法是求出所有的最短路径,但求两点之间所有的最短路径算法实现起来很麻烦。比较巧妙的方法是先求出所有两点之间的最短距离,再判断指定的边是否是两点之间最短路径的边。

代码:

#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <iostream>
#include <sstream>
#include <iomanip>

#include <bitset>
#include <string>
#include <vector>
#include <stack>
#include <deque>
#include <queue>
#include <set>
#include <map>

#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <cstring>
#include <ctime>
#include <climits>
using namespace std;

#define CHECKTIME() printf("%.2lf\n", (double)clock() / CLOCKS_PER_SEC)
typedef pair<int, int> pii;
typedef long long llong;
typedef pair<llong, llong> pll;
#define mkp make_pair
#define FOREACH(it, X) for(__typeof((X).begin()) it = (X).begin(); it != (X).end(); ++it)

/*************** Program Begin **********************/
int g[55][55];
int cost[55][55];
int cover[55][55];
class BuildingRoutes {
public:
	int build(vector <string> dist, int T) {
		int res = 0;
		int n = dist.size();

		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				g[i][j] = dist[i][j] - '0';
				cost[i][j] = g[i][j];
			}
		}
		for (int k = 0; k < n; k++) {
			for (int i = 0; i < n; i++) {
				for (int j = 0; j < n; j++) {
					cost[i][j] = min(cost[i][j], cost[i][k] + cost[k][j]);
				}
			}
		}
		memset(cover, 0, sizeof(cover));
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				for (int x = 0; x < n; x++) {
					for (int y = 0; y < n; y++) {
						if (cost[x][i] + g[i][j] + cost[j][y] == cost[x][y]) {
							++cover[i][j];
						}
					}
				}
			}
		}
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				if (cover[i][j] >= T) {
					res += g[i][j];
				}
			}
		}

		return res;
	}

};

/************** Program End ************************/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值