题目链接:点击打开链接
题目大意:给定n个点,m条有向边,求互不重叠的从起点到终点的最短路条数,点可以重复使用。
解题思路:
首先我们要找出所有的最短路使用的边。可以想到:对于一条边,如果从起点到它的一端的最短距离加上终点到它另一端的最短距离再加上边的长度等于起点到终点的最短距离,那么这条边必定是某一条最短路上的一条边。所以,使用两次dij求对于起点和终点的单源最短路,然后枚举边,就可以判断最短路是否经过该条边。
求出所有的边,然后从起点到终点做一遍BFS,求出路径个数,起点为INF,类似网络流。
#include <set>
#include <map>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
#define FIN freopen("in.txt", "r", stdin);
#define FOUT freopen("out.txt", "w", stdout);
#define lson l, mid, cur << 1
#define rson mid + 1, r, cur << 1 | 1
const int INF = 0x3f3f3f3f;
const LL INFLL = 0x3f3f3f3f3f3f3f3fLL;
const int MAXN = 1e3 + 50;
const int MAXM = 1e5 + 50;
const int MOD = 1e9 + 7;
int n, m;
LL cnt[MAXM << 1];
bool path[MAXM << 1], Evis[MAXM << 1];
struct Node
{
int v, val;
Node(int _v, int _val):v(_v), val(_val) {}
bool operator < (const Node& node) const
{
return val > node.val;
}
};
struct Edge
{
int from, to, weight, nxt;
}E[MAXM << 1];
int Head[MAXN], tot;
void edge_init()
{
tot = 0;
memset(Head, -1, sizeof(Head));
}
void edge_add(int u, int v, int w)
{
E[tot].from = u;
E[tot].to = v;
E[tot].weight = w;
E[tot].nxt = Head[u];
Head[u] = tot++;
}
LL mincost[MAXN], Smincost[MAXN], Emincost[MAXN];
bool vis[MAXM << 1];
void dijkstra(int start, int dir)
{
memset(mincost, INFLL, sizeof(mincost));
memset(vis, false, sizeof(vis));
mincost[start] = 0;
priority_queue<Node> q;
q.push(Node(start, 0));
while (!q.empty())
{
Node cur = q.top();
q.pop();
int u = cur.v;
if (vis[u])
continue;
vis[u] = true;
for (int i = Head[u]; ~i; i = E[i].nxt)
{
int v = E[i].to;
if ((i & 1) == dir && !vis[v] && mincost[v] > mincost[u] + E[i].weight)
{
mincost[v] = mincost[u] + E[i].weight;
q.push(Node(v, mincost[v]));
}
}
}
}
void solve(int s)
{
queue<int> q;
q.push(s);
cnt[s] = INFLL;
Evis[s] = true;
while (!q.empty())
{
int u = q.front();
q.pop();
for (int i = Head[u]; ~i; i = E[i].nxt)
{
int v = E[i].to;
if (Evis[i] || cnt[u] == 0 || !path[i])
continue;
Evis[i] = true;
cnt[u]--;
cnt[v]++;
q.push(v);
}
}
}
int main()
{
#ifndef ONLINE_JUDGE
FIN;
#endif // ONLINE_JUDGE
int tcase, s, e;
scanf("%d", &tcase);
while (tcase--)
{
scanf("%d%d", &n, &m);
edge_init();
memset(path, false, sizeof(path));
memset(cnt, 0, sizeof(cnt));
memset(Evis, true, sizeof(Evis));
for (int i = 0; i < m; i++)
{
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
edge_add(u, v, w);
edge_add(v, u, w);
}
scanf("%d%d", &s, &e);
dijkstra(s, 0);
memcpy(Smincost, mincost, sizeof(LL) * (n + 1));
dijkstra(e, 1);
memcpy(Emincost, mincost, sizeof(LL) * (n + 1));
for (int i = 0; i < m * 2; i += 2)
if (E[i].weight + Smincost[E[i].from] + Emincost[E[i].to] == Smincost[e])
{
path[i] = true;
Evis[i] = false;
}
solve(s);
printf("%lld\n", cnt[e]);
}
return 0;
}