前置芝士:次短路、最短路计数
这道题让我们对最短路和次短路(本质上其实不是次短路,只不过我这里当次短路来处理)进行计数。
回顾一下求次短路的过程,只需要 数组开两维,一维记最短路,一维记次短路,然后每次作松弛操作的同时进行一下分类讨论,选择性更新就好了。再回顾一下最短路计数,就是开一个 数组,然后每次做松弛操作的时候,设当前点为 ,目标点为 ,那么如果 ,那么就用 直接覆盖 。如果 ,那么就让 加上 即可。
回到本题,我们也可以用类似的套路。 数组开两维,第一维记最短路,第二维记次短路,在松弛操作的分类讨论中:
- 如果 ,那么让 代替 ,让 覆盖 。此处 且 ,下同。
- 如果 ,那么让 加上 。
- 如果 ,那么让 覆盖 。
- 如果 ,那么让 加上 。
最后答案为:
CODE
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int maxn = 1e+4 + 4;
int n, m, t, tot, st, ed;
int h[maxn], to[maxn], val[maxn], nxt[maxn], dis[maxn][2], cnt[maxn][2], vis[maxn][2];
class node
{
public:
int p, w;
bool op;
friend bool operator < (const node &x, const node &y)
{
return x.w > y.w;
}
};
priority_queue<node> q;
void add(int x, int y, int z)
{
to[++tot] = y;
val[tot] = z;
nxt[tot] = h[x];
h[x] = tot;
}
void init()
{
tot = 0;
memset(h, 0, sizeof(h));
memset(to, 0, sizeof(to));
memset(val, 0, sizeof(val));
memset(nxt, 0, sizeof(nxt));
memset(dis, 0x3f, sizeof(dis));
memset(cnt, 0, sizeof(cnt));
memset(vis, 0, sizeof(vis));
}
void dijkstra()
{
q.push({st, 0, 0});
while (!q.empty())
{
node now = q.top();
q.pop();
if (vis[now.p][now.op])
{
continue;
}
vis[now.p][now.op] = true;
for (int i = h[now.p]; i; i = nxt[i])
{
if (dis[to[i]][0] > now.w + val[i])
{
cnt[to[i]][1] = cnt[to[i]][0];
cnt[to[i]][0] = cnt[now.p][now.op];
dis[to[i]][1] = dis[to[i]][0];
dis[to[i]][0] = now.w + val[i];
q.push({to[i], now.w + val[i], 0});
q.push({to[i], dis[to[i]][1], 1});
}
else if (dis[to[i]][0] == now.w + val[i])
{
cnt[to[i]][0] += cnt[now.p][now.op];
}
else if (dis[to[i]][1] > now.w + val[i])
{
dis[to[i]][1] = now.w + val[i];
cnt[to[i]][1] = cnt[now.p][now.op];
q.push({to[i], now.w + val[i], 1});
}
else if (dis[to[i]][1] == now.w + val[i])
{
cnt[to[i]][1] += cnt[now.p][now.op];
}
}
}
}
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin >> t;
while (t--)
{
cin >> n >> m;
init();
for (int i = 1; i <= m; i++)
{
int x, y, z;
cin >> x >> y >> z;
add(x, y, z);
}
cin >> st >> ed;
dis[st][0] = 0;
cnt[st][0] = 1;
dijkstra();
int ans = cnt[ed][0];
if (dis[ed][1] == dis[ed][0] + 1)
{
ans += cnt[ed][1];
}
cout << ans << '\n';
}
return 0;
}