https://codeforces.com/problemset/problem/20/C
题意:找到从1到 n 的最短路。
n o t e : note: note: 这题数据没有卡bfs, 所以用普通spfa过了,给两个版本的代码。
s p f a spfa spfa
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6 + 5;
int head[maxn];
struct Edge
{
int u, to, w, next;
} edge[maxn];
int cnt = 0;
void add_edge(int u, int to, int w)
{
edge[cnt].u = u;
edge[cnt].to = to;
edge[cnt].w = w;
edge[cnt].next = head[u];
head[u] = cnt;
cnt++;
}
long long Distance[maxn];
int p[maxn];
queue<int> Q;
void bfs()
{
Q.push(1);
Distance[1] = 0;
p[1] = -1;
while(!Q.empty())
{
int u = Q.front();
Q.pop();
for(int i = head[u];i!= -1;i = edge[i].next)
{
int to = edge[i].to;
if(Distance[to] > Distance[u] + edge[i].w) //如果每一次都入队,那么复杂度是O(nm)
{
Distance[to] = Distance[u] + edge[i].w;
Q.push(to);
p[to] = u;
cout<<to<<endl;
}
}
}
}
/*
3 6
1 2 2
1 2 3
1 2 4
2 3 2
2 3 3
2 3 4
* */
int main()
{
int n, m;
cin >> n >> m;
for (int i = 0; i < maxn; i++)
{
head[i] = -1;
Distance[i] = 9223372036854775806;
}
for (int i = 0; i < m; i++)
{
int u, to, w;
cin >> u >> to >> w;
add_edge(u, to, w);
add_edge(to,u,w);
}
bfs();
if(Distance[n] == 9223372036854775806)
{
cout<<-1<<endl;
return 0;
}
stack<int> ss;
ss.push(n);
for(int i = n;;i = p[i])
{
if(p[i] == -1)
break;
ss.push(p[i]);
}
while(!ss.empty())
{
cout<<ss.top()<<" ";
ss.pop();
}
cout<<endl;
return 0;
}
d i j k s t r a dijkstra dijkstra
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e6 + 5;
struct edge
{
int v, w;
};
vector<edge> e[MAXN];
const long long INF = 0x3f3f3f3f3f3f3f3f;
long long dis[MAXN];
int vis[MAXN];
int p[MAXN];
struct node{
int to;
long long dis;
bool operator < (const node& a) const //第一个const保证传入参数不被修改,第二个const保证自有参数不被修改
{
return dis > a.dis;
}
};
priority_queue<node> que;
void dijkstra(int n, int s)
{
dis[s] = 0;
que.push(node{s,0});
while(!que.empty())
{
int u = que.top().to;
que.pop();
for (auto ed: e[u])
{
int v = ed.v, w = ed.w;
if (dis[v] > dis[u] + w)
{
dis[v] = dis[u] + w;
p[v] = u;
que.push(node{v,dis[v]});
}
}
}
}
/*
3 6
1 2 2
1 2 3
1 2 4
2 3 2
2 3 3
2 3 4
* */
int main()
{
int n, m;
cin >> n >> m;
for (int i = 0; i < m; i++)
{
int u, v, w;
cin >> u >> v >> w;
e[u].push_back(edge{v, w});
e[v].push_back(edge{u, w});
}
p[1]= -1;
for(int i = 0;i < MAXN;i++)
{
dis[i] = INF;
}
dijkstra(n, 1);
if(dis[n] == INF)
{
cout<<-1<<endl;
return 0;
}
stack<int> ss;
ss.push(n);
for(int i = n;;i = p[i])
{
if(p[i] == -1)
break;
ss.push(p[i]);
}
while(!ss.empty())
{
cout<<ss.top()<<" ";
ss.pop();
}
cout<<endl;
return 0;
}