[Poj]3613——快速幂优化矩阵操作
[题目大意]
- 给定一张带权无向图,求从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
10 N,T,S,E,tot:Longint;
11 hash:Array [0..1000+10] of Longint;
12 f,Ans:TypeArr;
13
14 Procedure Init;
15 var
16 i,L,u,v:Longint;
17 begin
18 readln(N,T,S,E);
19 tot:=0;
20 Filldword(f,sizeof(f) shr 2,Inf);
21 for i:=1 to T do
22 begin
23 readln(L,u,v);
24 if hash[u]=0 then begin inc(tot);hash[u]:=tot;end;
25 if hash[v]=0 then begin inc(tot);hash[v]:=tot;end;
26 f[hash[u],hash[v]]:=L;f[hash[v],hash[u]]:=L;
27 end;
28 S:=hash[S];E:=hash[E];
29 end;
30
31 Procedure Add(var p,q:TypeArr);
32 var
33 res:TypeArr;
34 i,j,k:Longint;
35 begin
36 Filldword(res,sizeof(res) shr 2,Inf);
37 for k:=1 to tot do
38 for i:=1 to tot do
39 for j:=1 to tot do
40 if p[i,k]+q[k,j]<res[i,j] then
41 res[i,j]:=p[i,k]+q[k,j];
42 p:=res;
43 end;
44
45 Procedure Main;
46 var
47 I:Longint;
48 begin
49 Filldword(Ans,sizeof(Ans) shr 2,Inf);
50 For I:=1 to tot do ans[I,I]:=0;
51 Repeat
52 if N and 1=1 then Add(Ans,f);
53 Add(f,f);
54 N:=N shr 1;
55 Until N=0;
56 end;
57
58 Procedure Print;
59 begin
60 writeln(Ans[S,E]);
61 end;
62
63 Begin
64 Init;
65 Main;
66 Print;
67 End.
2
3 Const
4 Inf=1005000000;
5
6 Type
7 TypeArr=Array [0..100+10,0..100+10] of Longint;
8
9 Var
10 N,T,S,E,tot:Longint;
11 hash:Array [0..1000+10] of Longint;
12 f,Ans:TypeArr;
13
14 Procedure Init;
15 var
16 i,L,u,v:Longint;
17 begin
18 readln(N,T,S,E);
19 tot:=0;
20 Filldword(f,sizeof(f) shr 2,Inf);
21 for i:=1 to T do
22 begin
23 readln(L,u,v);
24 if hash[u]=0 then begin inc(tot);hash[u]:=tot;end;
25 if hash[v]=0 then begin inc(tot);hash[v]:=tot;end;
26 f[hash[u],hash[v]]:=L;f[hash[v],hash[u]]:=L;
27 end;
28 S:=hash[S];E:=hash[E];
29 end;
30
31 Procedure Add(var p,q:TypeArr);
32 var
33 res:TypeArr;
34 i,j,k:Longint;
35 begin
36 Filldword(res,sizeof(res) shr 2,Inf);
37 for k:=1 to tot do
38 for i:=1 to tot do
39 for j:=1 to tot do
40 if p[i,k]+q[k,j]<res[i,j] then
41 res[i,j]:=p[i,k]+q[k,j];
42 p:=res;
43 end;
44
45 Procedure Main;
46 var
47 I:Longint;
48 begin
49 Filldword(Ans,sizeof(Ans) shr 2,Inf);
50 For I:=1 to tot do ans[I,I]:=0;
51 Repeat
52 if N and 1=1 then Add(Ans,f);
53 Add(f,f);
54 N:=N shr 1;
55 Until N=0;
56 end;
57
58 Procedure Print;
59 begin
60 writeln(Ans[S,E]);
61 end;
62
63 Begin
64 Init;
65 Main;
66 Print;
67 End.
[相关链接]
[启发总结]
- 挺厉害的矩阵
——————————————————————————————————————
你说,我们的存在,永不消逝。对吧?
如果,我们都在努力创造了存在。我们,会幸福的。对吧?