题目链接:
题目大意:
多组。给n个点,m条边的图,无重边和自环。 Alice和Bob在图上走,Alice先走,并且走的是最短的路径。现在该Bob走,要走出一条最短的且不与Alice所走路线相同的路径。
数据范围:
1≤T≤152≤n,m≤100000
1≤w≤1000000000(w为边权)
解题思路:
既要最短又要不同,裸裸的次短路。比赛的时候改了LL就把板子往上扔,一扔就过了,意外收获!
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <queue>
using namespace std;
const int MaxN = 1e5;
typedef long long LL;
const LL INF = 1LL << 60;
int T;
int n, m, all;
int pre[2 * MaxN + 5], last[MaxN + 5], other[2 * MaxN + 5];
LL cost[2 * MaxN + 5];
LL dis[MaxN + 5]; //最短路
LL dist[MaxN + 5]; //次短路
struct Node
{
int id;
LL d;
bool friend operator < (Node x, Node y)
{
return x.d > y.d;
}
};
void build(int x, int y, LL w)
{
pre[++all] = last[x];
last[x] = all;
other[all] = y;
cost[all] = w;
}
void Dijkstra()
{
priority_queue <Node> pq;
for(int i = 1; i <= n; i++) {
dis[i] = INF;
dist[i] = INF;
}
dis[1] = 0;
Node tmp;
tmp.d = 0, tmp.id = 1;
pq.push(tmp);
while(!pq.empty())
{
if(pq.empty()) break;
Node now = pq.top();
pq.pop();
int ed = last[now.id], dr;
if(dist[now.id] < now.d) continue;
while(ed != -1) {
dr = other[ed];
//把dis[now.id]改为now.d就过了!
//why!?
LL D = now.d + cost[ed];
if(D < dis[dr]) {
dist[dr] = dis[dr];
dis[dr] = D;
tmp.d = dis[dr]; tmp.id = dr;
pq.push(tmp);
}
else if(D > dis[dr] && D < dist[dr]) {
dist[dr] = D;
tmp.d = dist[dr]; tmp.id = dr;
pq.push(tmp);
}
ed = pre[ed];
}
}
}
int main()
{
scanf("%d", &T);
while(T--) {
scanf("%d %d", &n, &m);
all = -1;
memset(last, -1, sizeof(last));
for(int i = 1; i <= m; i++) {
int u, v;
LL w;
scanf("%d %d %lld", &u, &v, &w);
build(u, v, w); build(v, u, w);
}
Dijkstra();
printf("%lld\n", dist[n]);
}
return 0;
}
次短路有疑惑?点这里,希望能有所帮助。