poj 3225 分类: poj templates 2015-04-14 13:18 37人阅读 评论(0) 收藏
但是这样不怎么好,于是我还是写了一个最短路算法。居然比原来慢。。。
#include<map>
#include<queue>
#include<stack>
#include<utility>
#include<string>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<ctime>
#include<cmath>
#include<iostream>
#include<algorithm>
#define Mp(x,y) std::make_pair(x,y)
#define Num second
#define Min1 first
#define Min2 second
#define Dis first.first
#define Tag first.second
const int MAXN = 5e3+5, MAXM = 1e5+5, INF = 2e8;
typedef std::pair<long long,long long> DistType;
typedef std::pair<std::pair<long long,int>,int> HeapNode;
typedef std::priority_queue<HeapNode,std::vector<HeapNode>,std::greater<HeapNode> > HeapType;
struct Edge{int v,next;long long w; Edge(int v = 0,long long w = 0,int next = 0):v(v),w(w),next(next){}};
int n, m;
Edge edge[MAXM<<1];
int el = 0, head[MAXN] = {0};
HeapType line;
bool flag[MAXN][2] = {false};
DistType dist[MAXN];
void NewEdge(int u,int v,long long w)
{++el; edge[el] = Edge(v,w,head[u]); head[u] = el;}
void Dijstra()
{
for(int i = 1; i <= n ; i++)
dist[i] = Mp(INF,INF);
dist[1] = Mp(0,INF);
line.push(Mp(Mp(0,0),1));
while(!line.empty())
{
HeapNode t = line.top();
line.pop();
if(flag[t.Num][t.Tag])continue;
flag[t.Num][t.Tag] = true;
for(int i = head[t.Num]; i ; i = edge[i].next)
{
int p = edge[i].v;
long long tmp = t.Dis + edge[i].w;
if(tmp < dist[p].Min1)
{
dist[p].Min2 = dist[p].Min1;
dist[p].Min1 = tmp;
line.push(Mp(Mp(dist[p].Min1,0),p));
line.push(Mp(Mp(dist[p].Min2,1),p));
}
else if(tmp < dist[p].Min2)
{
dist[p].Min2 = tmp;
line.push(Mp(Mp(dist[p].Min2,1),p));
}
else;
}
}
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("poj3255.in","r",stdin);
freopen("poj3255.out","w",stdout);
#endif
std::cin >> n >> m;
for(int i = 1 , a, b, l; i <= m ; i++)
{
scanf("%d%d%d",&a,&b,&l);
NewEdge(a,b,l); NewEdge(b,a,l);
}
Dijstra();
std::cout << dist[n].Min2 << std::endl;
fprintf(stderr,"%f",clock()*1.0/CLOCKS_PER_SEC);
#ifndef ONLINE_JUDGE
fclose(stdin);
fclose(stdout);
#endif
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。