tyvj P1031:热浪
2010-08-26 21:28
302 查看
|
单源点最短路问题,理论上dijkstra应该可以,数据规模不大,可以直接用邻接矩阵存图。
我一开始写复杂了,写了个前向星+spfa。。。
代码如下
前向星+spfa
const
maxn=2500;
maxm=6200*2;
var
i,j,n,m,s,t:longint;
a,b,w:array[0..maxm] of longint;
f,d,dist:array[0..10000] of longint;
head,tail:longint;
h:array[1..maxn] of boolean;
procedure qsort(l,r:longint);
var
i,j,x,t1,t2,t3:longint;
begin
i:=l;j:=r;
x:=a[(i+j) div 2];
repeat
while a[i]<x do inc(i);
while a[j]>x do dec(j);
if i<=j then
begin
t1:=a[i];t2:=b[i];t3:=w[i];
a[i]:=a[j];b[i]:=b[j];w[i]:=w[j];
a[j]:=t1;b[j]:=t2;w[j]:=t3;
inc(i);dec(j);
end;
until i>j;
if i<r then qsort(i,r);
if j>l then qsort(l,j);
end;
procedure spfa;
var
now,i,k:longint;
begin
fillchar(h,sizeof(h),false);
fillchar(dist,sizeof(dist),$7f);
head:=0;tail:=0;dist[s]:=0;
inc(tail);
d[tail]:=s;
h[s]:=true;
while head<>tail do
begin
inc(head);now:=d[head];h[d[head]]:=false;
k:=f[d[head]];
i:=k;
while a[i]=a[k] do
begin
if dist[b[i]]>dist[now]+w[i] then
begin
dist[b[i]]:=dist[now]+w[i];
if h[b[i]]=false then
begin
inc(tail);
d[tail]:=b[i];
h[b[i]]:=true;
end;
end;
inc(i);
end;
end;
end;
begin
readln(n,m,s,t);
for i:=1 to m do
begin
read(a[i],b[i],w[i]);
a[i+m]:=b[i];
b[i+m]:=a[i];
w[i+m]:=w[i];
end;
m:=m*2;
qsort(1,m);
i:=1;f[a[i]]:=1;
repeat
while a[i+1]=a[i] do inc(i);
inc(i);
f[a[i]]:=i;
until i>=m;
spfa;
writeln(dist[t]);
end.
直接用邻接矩阵:
const
maxn=2500;
maxm=6200*2;
var
i,j,n,m,s,t,x,y,z:longint;
d,dist:array[0..10000] of longint;
head,tail:longint;
a:array[1..maxn,1..maxn] of longint;
h:array[1..maxn] of boolean;
procedure spfa;
var
now,i,k:longint;
begin
fillchar(h,sizeof(h),false);
fillchar(dist,sizeof(dist),$7f);
head:=0;tail:=0;dist[s]:=0;
inc(tail);
d[tail]:=s;
h[s]:=true;
while head<>tail do
begin
inc(head);now:=d[head];h[d[head]]:=false;
for i:=1 to n do
begin
if (a[now,i]>0) and (dist[i]>dist[now]+a[now,i]) then
begin
dist[i]:=dist[now]+a[now,i];
if h[i]=false then
begin
inc(tail);
d[tail]:=i;
h[i]:=true;
end;
end;
end;
end;
end;
begin
readln(n,m,s,t);
for i:=1 to m do
begin
readln(x,y,z);
a[x,y]:=z;
a[y,x]:=z;
end;
m:=m*2;
spfa;
writeln(dist[t]);
end.
这道题给我了一个很惨痛的教训。。spfa队列一定要开大点。。我一开始比着maxn=2500的数据开的队列,过了80分,数据很弱,然后一直不知道错在哪里。。感谢hjj大牛。。以后队列一定要开大点。。。
相关文章推荐
- Tyvj P1031 热浪
- [TYVJ] P1031 热浪
- |Tyvj|图论最短路|P1031 热浪
- tyvj 1031 热浪 最短路
- tyvj 1031 热浪(最短路)
- Dijkstra TYVJ 1031热浪 Dijkstra测试数据
- Dijkstra TYVJ 1031热浪 Dijkstra测试数据
- tyvj 1031 热浪
- 【tyvj1031】 热浪
- tyvj 1031 热浪 最短路
- tyvj1031热浪——初学spfa
- tyvj1031 热浪
- 热浪[TYVJ1031]
- 洛谷1339 热浪 最短路
- Tyvj P1336 火车进栈(栈的顺序问题)
- [bzoj3451]Tyvj1953 Normal
- tyvj 1080 N皇后
- 【bzoj3196】Tyvj 1730 二逼平衡树
- luogu P1339 [USACO09OCT]热浪Heat Wave
- Tyvj 1728 普通平衡树