您的位置:首页 > 其它

[Poj]3613——快速幂优化矩阵操作

2012-04-27 18:46 393 查看
[题目大意]给定一张带权无向图,求从S到E经过恰好N条边(可重复)的最短路

[分析题解] 我们用f[k,i]表示走过k条边,现在在i的最短路.显然,f[k,i]:=min(f[k-1,j]+w(j,i)) if j可以到达i
又题目给出的N的范围相对于图来说特别的大,又是这种非常单调的转移,这样的话,考虑用矩阵+快速幂来优化。
与普通的矩阵乘法比,将对应相乘求和操作改为对应相加取最小值操作即可

[个人代码]View Code 1 //10128532 perseawe 3613 Accepted 1016K 329MS Pascal 1242B 2012-04-27 18:35:45
2
3 Const
4 Inf=1005000000;
5
6 Type
7 TypeArr=Array [0..100+10,0..100+10] of Longint;
8
9 Var
N,T,S,E,tot:Longint;
hash:Array [0..1000+10] of Longint;
f,Ans:TypeArr;

Procedure Init;
var
i,L,u,v:Longint;
begin
readln(N,T,S,E);
tot:=0;
Filldword(f,sizeof(f) shr 2,Inf);
for i:=1 to T do
begin
readln(L,u,v);
if hash[u]=0 then begin inc(tot);hash[u]:=tot;end;
if hash[v]=0 then begin inc(tot);hash[v]:=tot;end;
f[hash[u],hash[v]]:=L;f[hash[v],hash[u]]:=L;
end;
S:=hash[S];E:=hash[E];
end;

Procedure Add(var p,q:TypeArr);
var
res:TypeArr;
i,j,k:Longint;
begin
Filldword(res,sizeof(res) shr 2,Inf);
for k:=1 to tot do
for i:=1 to tot do
for j:=1 to tot do
if p[i,k]+q[k,j]<res[i,j] then
res[i,j]:=p[i,k]+q[k,j];
p:=res;
end;

Procedure Main;
var
I:Longint;
begin
Filldword(Ans,sizeof(Ans) shr 2,Inf);
For I:=1 to tot do ans[I,I]:=0;
Repeat
if N and 1=1 then Add(Ans,f);
Add(f,f);
N:=N shr 1;
Until N=0;
end;

Procedure Print;
begin
writeln(Ans[S,E]);
end;

Begin
Init;
Main;
Print;
End.[相关链接]
[启发总结] 挺厉害的矩阵
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: