有一个 n 个点 m 条边的无向图,请求出从 s到 t 的最短路长度。
输入格式
第一行四个正整数 n,m,s,t。 接下来 m 行,每行三个正整数 u,v,w 表示一条连接 u,v,长为 w 的边。
输出格式
输出一行一个整数,表示答案。
输入输出样例
输入 #1复制
7 11 5 4
2 4 2
1 4 3
7 2 2
3 4 3
5 7 5
7 3 3
6 1 1
6 3 4
2 4 3
5 6 3
7 2 1
输出 #1复制
7
说明/提示
【数据范围】
对于 100% 的数据,1\le n \le 25001≤n≤2500,1\le m \le 62001≤m≤6200,1\le w \le 10001≤w≤1000。
【样例说明】
5 \to 6 \to 1 \to 45→6→1→4 为最短路,长度为 3+1+3 = 73+1+3=7。
模板:
#include <bits/stdc++.h>
using namespace std;
#include <cstdio>
#define TLE std::ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define ll long long
const ll mod = 1000000007 ;
const int INF=0x3f3f3f3f;
const int mxn = 2500+7 ;
string str,s1,s2;
int t,n,m,k,l,r,prime[mxn],isprime[mxn],bit[mxn];
bool vis[mxn] ;
int pre[mxn] , lowcost[mxn] ,cost[mxn][mxn] ;
void Dijkstra()
{
for(int i=0;i<=n;i++)
lowcost[i] = INF , pre[i] = -1 , vis[i] = false ;
lowcost[l] = 0 ;
for(int j=1;j<=n;j++)
{
int index = -1 ,mn = INF ;
for(int i=1;i<=n;i++)
{
if(!vis[i] && mn>lowcost[i])
{
index = i ;
mn = lowcost[i] ;
}
}
if(index==-1) break;
vis[index] = true ;
for(int i=1;i<=n;i++)
{
if(!vis[i] && lowcost[index] + cost[index][i] < lowcost[i])
lowcost[i] = lowcost[index] + cost[index][i] ,pre[i] = k ;
}
}
cout<<lowcost[r]<<endl;
}
int main()
{
cin>>n>>m>>l>>r;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
i==j?cost[i][j]=0:cost[i][j] = INF;
for(int i=1,u,v,w;i<=m;i++)
{
cin>>u>>v>>w;
if(cost[u][v]>w)
cost[u][v] = w , cost[v][u] = w ;
}
Dijkstra();
}
优化:
#include <bits/stdc++.h>
using namespace std;
#include <cstdio>
#define TLE std::ios::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define ll long long
const ll mod = 1000000007 ;
const int INF=0x3f3f3f3f;
const int mxn = 2500+7 ;
string str,s1,s2;
int t,n,m,k,l,r,prime[mxn],isprime[mxn],bit[mxn];
struct node
{
int v,w;
node(int _v=0,int _w=0):v(_v),w(_w){}
bool operator < (const node & tmp) const{return w>tmp.w;}
};
struct edge
{
int v,cost ;
edge(int _v=0,int _cost=0):v(_v),cost(_cost){}
};
vector<edge>E[mxn];
bool vis[mxn];
int dis[mxn];
void add(int u,int v,int w) {E[u].push_back(edge(v,w));}
void Dijkstra()
{
priority_queue<node>q;
while(!q.empty()) q.pop();
dis[l] = 0 ;
q.push(node(l,0));
while(!q.empty())
{
node tmp = q.top();
q.pop();
int u = tmp.v ;
if(vis[u]) continue ;
vis[u] = false ;
for(int i=0;i<E[u].size();i++)
{
int v = E[u][i].v;
int cost = E[u][i].cost ;
if(!vis[v] && dis[v]>dis[u]+cost)
{
dis[v] = dis[u]+cost ;
q.push(node(v,dis[v]));
}
}
}
cout<<dis[r]<<endl;
}
void init() {for(int i=0;i<=n;i++) E[i].clear(),dis[i]=INF,vis[i]=false; }
int main()
{
cin>>n>>m>>l>>r;
init();
for(int i=1,u,v,w;i<=m;i++)
{
cin>>u>>v>>w;
add(u,v,w);
add(v,u,w);
}
Dijkstra();
}