题目地址:点击进入异空间
题意:求无向图的最短路 (尴尬,之前错误的代码还能AC??!!)
解法:SPFA加上SLF优化
代码:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <queue>
const int maxn = 100005;
using namespace std;
int tot;
int t,c,ts,te;
int dist[maxn];
int head[maxn];
bool used[maxn];
struct node
{
int f,t,c,next;
}es[maxn << 1];
inline void rd(int &x)
{
scanf("%d",&x);
}
inline void build(int x,int y,int z)
{
tot++;
es[tot].f = x;
es[tot].t = y;
es[tot].c = z;
es[tot].next = head[x];
head[x] = tot;
}
deque<int >q;
inline void spfa(int be)
{
memset(dist,0x3f,sizeof(dist));
while(!q.empty())q.pop_front();
q.push_back(be);
used[be] = true;
dist[be] = 0;
while(!q.empty())
{
int u = q.front();
used[u] = false;
q.pop_front();
for(int i = head[u];i;i = es[i].next)
{
int v = es[i].t;
if(dist[v] > dist[u] + es[i].c)
{
dist[v] = dist[u]+es[i].c;
if(!used[v])
{
if(dist[v] < dist[q.front()]) q.push_front(v);
else q.push_back(v);
used[v] = true;
}
}
}
}
}
void init()
{
memset(used,0,sizeof(used));
memset(head,0,sizeof(head));
tot = 0;
return ;
}
int main()
{
init();
rd(t);rd(c);rd(ts);rd(te);
for(int i = 1;i <= c;i++)
{
int x,y,z;
rd(x);rd(y);rd(z);
build(x,y,z);
build(y,x,z);
}
spfa(ts);
printf("%d\n",dist[te]);
return 0;
}
THE END