拒绝前往德克萨斯州
Dijkstra才是真正优美的最短路算法,不服来辩!
基本策略是贪心,正因为此性质,我们可以用一个小根堆维护,每次从堆定取出一个最小的
代码(+heap优化)
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <queue>
const int maxn = 200005;
using namespace std;
int tot;
int t,c,ts,te;
int head[maxn];
int dist[maxn];
bool used[maxn];
struct edge{
int f,t,c,next;
}es[maxn << 1];
struct node{
int u,v;
bool operator < (const node &a)const
{
return v > a.v;
}
};
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;
}
inline void rd(int &x)
{
scanf("%d",&x);
}
inline void init()
{
memset(head,0,sizeof(head));
memset(used,0,sizeof(used));
tot = 0;
return ;
}
priority_queue<node >q;
inline void dijkstra(int ss,int ee)
{
memset(dist,108,sizeof(dist));
dist[ss] = 0;
q.push((node){ss,0});
while(!q.empty())
{
node now = q.top();
int u = now.u;
q.pop();
if(used[u] == true) continue;
used[u] = true;
if(u == ee) return ;
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;
q.push((node){v,dist[v]});
}
}
}
}
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);
}
dijkstra(ts,te);
printf("%d\n",dist[te]);
return 0;
}
THE END
By Peacefuldoge