题目链接:https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=0&problem=2369&mosmsg=Submission+received+with+ID+26582716
可以修改一条边的权值,求起点到终点的最短路
从起点和终点分别做一次最短路,枚举修改权值的边是哪一条,新的最短路长度就是两边的最短路加上新的权值
还要输出路径,更新时记录前驱即可
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
const int maxn = 10010;
const int INF = 0x3f3f3f3f;
int n, s, t, m, k;
int u[maxn], v[maxn], w[maxn];
int h[maxn], cnt = 0;
struct E{
int to, cost, next;
}e[maxn];
void add(int u, int v, int w){
e[++cnt].to = v;
e[cnt].cost = w;
e[cnt].next = h[u];
h[u] = cnt;
}
vector<int> path;
int d[2][maxn];
int pre[2][maxn];
void dij(int S, int type){
priority_queue<pii, vector<pii>, greater<pii> > q;
d[type][S] = 0;
q.push(pii(0, S));
while(!q.empty()){
pii p = q.top(); q.pop();
int u = p.second;
if(p.first != d[type][u]) continue;
for(int i = h[u] ; i != -1 ; i = e[i].next){
int v = e[i].to;
if(d[type][v] > d[type][u] + e[i].cost){
d[type][v] = d[type][u] + e[i].cost;
pre[type][v] = u;
q.push(pii(d[type][v], v));
}
}
}
}
ll read(){ ll s = 0, f = 1; char ch = getchar(); while(ch < '0' || ch > '9'){ if(ch == '-') f = -1; ch = getchar(); } while(ch >= '0' && ch <= '9'){ s = s * 10 + ch - '0'; ch = getchar(); } return s * f; }
int main(){
int flag = 0;
while(scanf("%d%d%d", &n, &s, &t) == 3){
if(flag) printf("
");
flag = 1;
path.clear();
memset(pre, 0, sizeof(pre));
memset(h, -1, sizeof(h)); cnt = 0;
scanf("%d", &m);
for(int i = 1 ; i <= m ; ++i){
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
add(u, v, w); add(v, u, w);
}
scanf("%d", &k);
for(int i = 1 ; i <= k ; ++i){
scanf("%d%d%d", &u[i], &v[i], &w[i]);
}
memset(d, 0x3f, sizeof(d));
dij(s, 0);
dij(t, 1);
int ans = d[0][t];
int sta = -1, stb = -1;
for(int i = 1 ; i <= k ; ++i){
if(d[0][u[i]] + d[1][v[i]] + w[i] < ans){
ans = d[0][u[i]] + d[1][v[i]] + w[i];
sta = u[i]; stb = v[i];
}
if(d[0][v[i]] + d[1][u[i]] + w[i] < ans){
ans = d[0][v[i]] + d[1][u[i]] + w[i];
sta = v[i]; stb = u[i];
}
}
if(sta != -1){
int cur = sta;
while(1){
path.push_back(cur);
if(cur == s) break;
cur = pre[0][cur];
}
for(int i = path.size() - 1 ; i >= 0 ; --i){
printf("%d ", path[i]);
}
path.clear();
cur = stb;
while(1){
path.push_back(cur);
if(cur == t) break;
cur = pre[1][cur];
}
for(int i = 0 ; i <= path.size() - 1 ; ++i){
if(i > 0) printf(" ");
printf("%d", path[i]);
} printf("
");
} else{
int cur = t;
while(1){
path.push_back(cur);
if(cur == s) break;
cur = pre[0][cur];
}
for(int i = path.size() - 1 ; i >= 0 ; --i){
if(i < path.size()-1) printf(" ");
printf("%d", path[i]);
} printf("
");
}
if(sta != -1) printf("%d
", sta);
else printf("Ticket Not Used
");
printf("%d
", ans);
}
return 0;
}