zoukankan      html  css  js  c++  java
  • pku2421 Constructing Roads

    求一个图的最小生成树,其中某些边不收费(可以这样理解)。

    这次用kruscal打的,对于不收费的边先全部加入,再维护即可。

    View Code
      1 program pku2421(input,output);
    2 var
    3 father : array[0..200] of longint;
    4 f : array[0..200,0..200] of longint;
    5 x,y,w : array[0..40000] of longint;
    6 n,m,q,answer : longint;
    7 procedure init;
    8 var
    9 i,j : longint;
    10 begin
    11 readln(n);
    12 for i:=1 to n do
    13 father[i]:=i;
    14 m:=0;
    15 for i:=1 to n do
    16 begin
    17 for j:=1 to n do
    18 begin
    19 read(f[i,j]);
    20 if (i<=j)and(f[i,j]<>0) then
    21 begin
    22 inc(m);
    23 x[m]:=i;
    24 y[m]:=j;
    25 w[m]:=f[i,j];
    26 end;
    27 end;
    28 readln;
    29 end;
    30 end; { init }
    31 procedure swap(var aa,bb :longint );
    32 var
    33 tt : longint;
    34 begin
    35 tt:=aa;
    36 aa:=bb;
    37 bb:=tt;
    38 end; { swap }
    39 procedure sort(p,q :longint );
    40 var
    41 i,j,mm : longint;
    42 begin
    43 i:=p;
    44 j:=q;
    45 mm:=w[(i+j)>>1];
    46 repeat
    47 while w[i]<mm do
    48 inc(i);
    49 while w[j]>mm do
    50 dec(j);
    51 if i<=j then
    52 begin
    53 swap(w[i],w[j]);
    54 swap(x[i],x[j]);
    55 swap(y[i],y[j]);
    56 inc(i);
    57 dec(j);
    58 end;
    59 until i>j;
    60 if i<q then sort(i,q);
    61 if j>p then sort(p,j);
    62 end; { sort }
    63 function getfather(x :longint ):longint;
    64 begin
    65 if father[x]=x then
    66 exit(x);
    67 father[x]:=getfather(father[x]);
    68 exit(father[x]);
    69 end; { getfather }
    70 function check():boolean;
    71 var
    72 i : longint;
    73 begin
    74 for i:=2 to n do
    75 if getfather(1)<>getfather(i) then
    76 exit(false);
    77 exit(true);
    78 end; { check }
    79 procedure main;
    80 var
    81 i : longint;
    82 xx,yy : longint;
    83 begin
    84 readln(q);
    85 for i:=1 to q do
    86 begin
    87 readln(xx,yy);
    88 xx:=getfather(xx);
    89 yy:=getfather(yy);
    90 if xx<>yy then
    91 father[xx]:=yy;
    92 end;
    93 for i:=1 to m do
    94 begin
    95 xx:=getfather(x[i]);
    96 yy:=getfather(y[i]);
    97 if xx=yy then
    98 continue
    99 else
    100 begin
    101 inc(answer,w[i]);
    102 father[xx]:=yy;
    103 if check then
    104 break;
    105 end;
    106 end;
    107 writeln(answer);
    108 end; { main }
    109 begin
    110 init;
    111 sort(1,m);
    112 main;
    113 end.



  • 相关阅读:
    HashMap按键排序和按值排序
    LeetCode 91. Decode Ways
    LeetCode 459. Repeated Substring Pattern
    JVM
    LeetCode 385. Mini Parse
    LeetCode 319. Bulb Switcher
    LeetCode 343. Integer Break
    LeetCode 397. Integer Replacement
    LeetCode 3. Longest Substring Without Repeating Characters
    linux-网络数据包抓取-tcpdump
  • 原文地址:https://www.cnblogs.com/neverforget/p/2402973.html
Copyright © 2011-2022 走看看