最短路径 (path)
题目描述 :
给出一张包含n个节点m条边的无向图,请你求出图上两点s,t间的最短路径长度(请大家自行处理重边和自环)。
输入 :
第一行两个数n,m,分别表示节点数和边数,以空格隔开。
之后m行,每行3个数u,v,w,表示点u和v间有一条权值为w的边。
最后一行,两个数s,t表示选择的两个点,以空格隔开。
输出 :
输出一个数,表示s,t间最短路径的长度。
样例输入:
4 3
1 2 6
1 3 4
2 4 2
3 4
样例输出:
12
就这道题的话,暴力就可以过,但是若是数据大一点,用前向星+spfa的写法会好一点。
#pragma GCC optimize(3,"Ofast","inline")
#pragma G++ optimize(3)
#include<bits/stdc++.h>
#include <iostream>
#include <cstdio>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#include <map>
#include <stack>
#include <set>
#include <sstream>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll,ll> pll;
typedef pair<int,int> pii;
typedef queue<int> q_i;
typedef queue<string> q_s;
typedef queue<double> q_d;
typedef queue<ll> q_ll;
typedef queue<char> q_c;
typedef priority_queue<int> pq_i;
typedef priority_queue<string> pq_s;
typedef priority_queue<double> pq_d;
typedef priority_queue<ll> pq_ll;
typedef stack<int> s_i;
typedef stack<string> s_s;
typedef stack<double> s_d;
typedef stack<ll> s_ll;
typedef stack<char> s_c;
typedef map<ll,ll> m_ll_ll;
typedef map<int,ll> m_i_ll;
typedef map<int,int> m_i_i;
typedef map<string,ll> m_s_ll;
typedef map<char,int> m_c_i;
typedef map<char,ll> m_c_ll;
const ll INF=0x3f3f3f3f;
#define rep(i,l,r) for(register int i=l;i<=r;i++)
#define per(i,l,r) for(register int i=r;i>=l;i--)
#define eif else if
#define N 2000005
#define mm(dp) memset(dp,0,sizeof(dp))
#define mm1(dp) memset(dp,-1,sizeof(dp))
#define mm2(dp) memset(dp,0x3f,sizeof(dp))
#define IT set<int>::iterator
#define fs(n) fixed<< setprecision(n)
//const double e=2.71828182845;
const double pi = acos(-1.0);
ll book[50005];
typedef struct
{
ll to,next,value;
}STU;
STU e[50005];
int num=0;
void add(int x,int y,int z)
{
e[++num].to=y;
e[num].next=book[x];
book[x]=num;
e[num].value=z;
}
ll dis[50015],vis[50015];
void spfa(int u)
{
memset(vis,0,sizeof(vis));
queue<int>que;
que.push(u);
vis[u]=1;
while(!que.empty())
{
int now=que.front();
que.pop();
vis[now]=0;
for(int i=book[now];i;i=e[i].next)
{
int t=e[i].to;
if(dis[t]>dis[now]+e[i].value)
{
dis[t]=dis[now]+e[i].value;
if(vis[t]==0)
{
que.push(t);
vis[t]=1;
}
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int n,m;
cin>>n>>m;
rep(i,1,m)
{
int a,b,c;
cin>>a>>b>>c;
add(a,b,c);
add(b,a,c);
}
int s,t;
cin>>s>>t;
mm2(dis);
dis[s]=0;
spfa(s);
cout<<dis[t]<<endl;
return 0;
}