C–最短路
Description
给出一个带权无向图,包含n个点,m条边。求出s,e的最短路。保证最短路存在。
Input
多组输入。
对于每组数据。
第一行输入n,m(1<= n && n<=510^5,1 <= m && m <= 310^6)。
接下来m行,每行三个整数,u,v,w,表示u,v之间有一条权值为w(w >= 0)的边。
最后输入s,e。
Output
对于每组数据输出一个整数代表答案。
Sample
Input
3 1
1 2 3
1 2
Output
3
#include<bits/stdc++.h>
using namespace std;
const int N = 5e5 + 5;
vector<pair<int, int > >edge[N];
int dis[N], vis[N];
int main() {
std::ios::sync_with_stdio(false);
int n, m, u, v, w, s, e;
while (cin >> n >> m) {
memset(vis, 0, sizeof(vis)); //memset比直接for循环一个一个的初始化稍微快一点 (快的不多)
memset(dis, 0x3f, sizeof(dis));
for (int i = 0; i < N; i++) {
edge[i].clear();
}
for (int i = 0; i < m; i++) {
cin >> u >> v >> w;
edge[u].push_back(make_pair(v, w));
edge[v].push_back(make_pair(u, w));
}
cin >> s >> e;
queue<int>q;
q.push(s);
vis[s] = 1;
dis[s] = 0;
while (!q.empty()) {
int now = q.front();
q.pop();
vis[now] = 0;
for (int i = 0; i < edge[now].size(); i++)
{
int x = edge[now][i].first;
if (dis[x] > dis[now] + edge[now][i].second) {
dis[x] = dis[now] + edge[now][i].second;
if (vis[x] == 0) {
q.push(x);
vis[x] = 1;
}
}
}
}
cout << dis[e] << endl;
}
return 0;
}