题目链接 https://vjudge.net/problem/UVA-10917
【题意】
gbn最近打算穿过一个森林,但是他比较傲娇,于是他决定只走一些特殊的道路,他打算只沿着满足如下条件的(A,B)道路走:存在一条从B出发回家的路,比所有从A出发回家的路径都短。你的任务是计算一共有多少条不同的回家路径。其中起点的编号为1,终点的编号为2.
【思路】
现求出以家为源点的所有点的最短路径,按照题意,如果可以走边(A,B)则dist[A]>dist[B],dist为最短路径,那么就可以构建一个新的有向图,如果dist[A]>dist[B]就添加一条A指向B的有向边,表示可以从A往B走,这样一来这张图是一个DAG,可以动态规划求解,设dp(u)是从公司到达u点的可行路径总数,则dp(u)=sum{dp(v)|存在有向边(v,u)}
#include<bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 1050;
const int maxm = 500050;
struct Edge {
int from, to, dist;
Edge(int f, int t, int d) :from(f), to(t), dist(d) {}
};
struct HeapNode {
int d, u;
HeapNode(int dd, int uu) :d(dd), u(uu) {}
bool operator < (const HeapNode& rhs) const {
return d > rhs.d;
}
};
struct Dijkstra {
int n, m;
vector<Edge> edges;
vector<int> g[maxn];
bool done[maxn];
int d[maxn];
int p[maxn];
void init(int n) {
this->n = n;
for (int i = 0; i < n; ++i) g[i].clear();
edges.clear();
}
void add(int from, int to, int dist) {
edges.push_back(Edge(from, to, dist));
m = edges.size();
g[from].push_back(m - 1);
}
void dijkstra(int s) {
priority_queue<HeapNode> que;
for (int i = 0; i < n; ++i) d[i] = inf;
d[s] = 0;
memset(done, 0, sizeof(done));
que.push(HeapNode(0, s));
while (!que.empty()) {
HeapNode x = que.top();
que.pop();
int u = x.u;
if (done[u]) continue;
done[u] = true;
for (int i = 0; i < g[u].size(); ++i) {
Edge& e = edges[g[u][i]];
if (d[e.to] > d[u] + e.dist) {
d[e.to] = d[u] + e.dist;
p[e.to] = g[u][i];
que.push(HeapNode(d[e.to], e.to));
}
}
}
}
};
int n, m;
int d[maxn], dp[maxn];
int g[maxn][maxn], g2[maxn][maxn];
Dijkstra solver;
int dfs(int u) {
if (u == 0) return 1;
if (dp[u] != -1) return dp[u];
int ans = 0;
for (int v = 0; v < n; ++v) {
if (g2[v][u]) ans += dfs(v);
}
return dp[u] = ans;
}
int main() {
while (scanf("%d", &n) == 1 && n) {
scanf("%d", &m);
solver.init(n);
memset(g, 0, sizeof(g));
memset(g2, 0, sizeof(g2));
memset(dp, -1, sizeof(dp));
for (int i = 0; i < m; ++i) {
int u, v, c;
scanf("%d%d%d", &u, &v, &c);
--u, --v;
solver.add(u, v, c);
solver.add(v, u, c);
g[u][v] = g[v][u] = 1;
}
solver.dijkstra(1);
memcpy(d, solver.d, sizeof(d));
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (d[j] < d[i] && g[i][j]) g2[i][j] = 1;
else if (d[i] < d[j] && g[j][i]) g2[j][i] = 1;
}
}
int ans = dfs(1);
printf("%d\n", ans);
}
return 0;
}