题意:求次短路。
思路:求次短路
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
#define siz 200005
#define LL long long
namespace fastIO {
#define BUF_SIZE 100000
//fread -> read
bool IOerror = 0;
inline char nc() {
static char buf[BUF_SIZE], *p1 = buf + BUF_SIZE, *pend = buf + BUF_SIZE;
if(p1 == pend) {
p1 = buf;
pend = buf + fread(buf, 1, BUF_SIZE, stdin);
if(pend == p1) {
IOerror = 1;
return -1;
}
}
return *p1++;
}
inline bool blank(char ch) {
return ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t';
}
inline void read(int &x) {
char ch;
while(blank(ch = nc()));
if(IOerror)
return;
for(x = ch - '0'; (ch = nc()) >= '0' && ch <= '9'; x = x * 10 + ch - '0');
}
#undef BUF_SIZE
};
using namespace fastIO;
using namespace std;
const LL INF = 1e18;
struct qnode{
int v;
LL c;
qnode(int _v = 0,LL _c = 0) : v(_v),c(_c){}
bool operator < (const qnode &r) const{
return c>r.c;
}
};
struct Edge{
int v;
LL cost;
Edge(int _v = 0,LL _cost = 0) : v(_v),cost(_cost){}
};
int n,m;
vector<Edge>E[siz];
bool vis[siz];
LL dist1[siz];
LL dist2[siz];
void addedge(int u,int v,LL w){
E[u].push_back(Edge(v,w));
}
void dijstra(int n,int start){
//memset(vis,0,sizeof(vis));
for(int i=1;i<=n;i++){
dist1[i] = INF;
dist2[i] = INF;
}
priority_queue<qnode> que;
while(!que.empty()) que.pop();
dist1[start] = 0;
que.push(qnode(start,0));
qnode tmp;
while(!que.empty()){
tmp = que.top();
que.pop();
int u = tmp.v;
LL d = tmp.c;
if(dist2[u] < d) continue;
for(int i = 0;i<E[u].size();i++){
int v = E[u][i].v;
LL cost = E[u][i].cost;
LL d2 = d + cost;
if(dist1[v] > d2){
swap(d2,dist1[v]);
que.push(qnode(v,dist1[v]));
}
if(dist2[v] > d2&&dist1[v] <d2){
dist2[v] = d2;
que.push(qnode(v,dist2[v]));
}
}
}
printf("%lld\n",dist2[n]);
}
void solve(){
dijstra(n,1);
}
int main()
{
int T;
//scanf("%d",&T);
read(T);
while(T--){
//scanf("%d%d",&n,&m);
read(n);
read(m);
for(int i=0;i<=n;i++){
E[i].clear();
}
for(int i = 1;i<=m;i++){
int u,v;
int w;
//scanf("%d%d%lld",&u,&v,&w);
read(u);
read(v);
read(w);
addedge(u,v,w);
addedge(v,u,w);
}
solve();
}
return 0;
}
保存一波大佬的A*求k短路模板。