雕刻时光

just do it……nothing impossible
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

单源最短路pku2387

Posted on 2011-02-15 13:44  huhuuu  阅读(290)  评论(0编辑  收藏  举报

http://poj.org/problem?id=2387

SPFA模板换一种,n,m,就可过,其实是有重边的,用SPFA(它已包含所有边,他从边的角度思考最短路),但是用diskar做要小心(因为他是从点的角度思考,map[][]点对点要更新到最小化)

View Code
#include<iostream>
#include
<queue>
using namespace std;
const long maxn=999999999;
const long edge_maxn = 4005;
const long point_maxn = 1005;
struct node
{
int v;
int w;
int next;
}edge[edge_maxn];
int pre[point_maxn];
int n;
int m;
queue
<int>Q;
int dirs[point_maxn];
bool vis[point_maxn];
void Init()
{
memset(pre,
-1,sizeof(pre));
int x,y,z;
int index=1;
int i,j;
for(i=1;i<=m;i++)
{
scanf(
"%d%d%d",&x,&y,&z);
edge[index].v
=y;
edge[index].w
=z;
edge[index].next
=pre[x];
pre[x]
=index++;
swap(x,y);
edge[index].v
=y;
edge[index].w
=z;
edge[index].next
=pre[x];
pre[x]
=index++;

}
}
void print(int end)
{
printf(
"%d\n",dirs[end]);
}
void SPFA()
{
int start=1;
int end=n;
while(!Q.empty())
{
Q.pop();
}

memset(vis,
0,sizeof(vis));
fill(dirs,dirs
+point_maxn,maxn);
dirs[start]
=0;
vis[start]
=1;
Q.push(start);
while(!Q.empty())
{
int top=Q.front();
Q.pop();
vis[top]
=0;
for(int j=pre[top];j!=-1;j=edge[j].next)
{
int e=edge[j].v;
if(dirs[e]>edge[j].w+dirs[top])
{
dirs[e]
=edge[j].w+dirs[top];
if(!vis[e])
{
Q.push(e);
vis[e]
=1;
}
}
}
}
print(end);
}
int main()
{
while(scanf("%d%d",&m,&n)!=EOF)
{
Init();
SPFA();
}
return 0;
}