题目: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 ************************/