pku 1258 Agri-Net

求一个图的最小生成树,用了prim,0ms,但前面WA了几次,这里进一步理解了prim,外部循环i只是控制次数,内部不用看i与j的值的关系,把d赋值成0,表示在树里,节省了一个布尔数组。

View Code
 1 program pku1258(input,output);
2 var
3 f : array[0..200,0..200] of longint;
4 d : array[0..200] of longint;
5 n : longint;
6 answer : longint;
7 procedure init;
8 var
9 i,j : longint;
10 begin
11 readln(n);
12 fillchar(f,sizeof(f),0);
13 for i:=1 to n do
14 for j:=1 to n do
15 read(f[i,j]);
16 readln;
17 for i:=1 to n do
18 d[i]:=f[1,i];
19 end; { init }
20 procedure prim;
21 var
22 i,j : longint;
23 min,minn : longint;
24 begin
25 answer:=0;
26 for i:=1 to n-1 do
27 begin
28 min:=maxlongint;
29 for j:=1 to n do
30 if (d[j]>0)and(d[j]<min) then
31 begin
32 min:=d[j];
33 minn:=j;
34 end;
35 inc(answer,d[minn]);
36 d[minn]:=0;
37 for j:=1 to n do
38 if (d[j]>0)and(f[minn,j]<d[j]) then
39 d[j]:=f[minn,j];
40 end;
41 writeln(answer);
42 end; { prim }
43 begin
44 while not eof do
45 begin
46 init;
47 prim;
48 end;
49 end.



posted @ 2012-03-15 12:01  Codinginging  阅读(208)  评论(0编辑  收藏  举报