zoukankan      html  css  js  c++  java
  • BZOJ1601: [Usaco2008 Oct]灌水

    1601: [Usaco2008 Oct]灌水

    Time Limit: 5 Sec  Memory Limit: 162 MB
    Submit: 1280  Solved: 839
    [Submit][Status]

    Description

    Farmer John已经决定把水灌到他的n(1<=n<=300)块农田,农田被数字1到n标记。把一块土地进行灌水有两种方法,从其他农田饮水,或者这块土地建造水库。 建造一个水库需要花费wi(1<=wi<=100000),连接两块土地需要花费Pij(1<=pij<=100000,pij=pji,pii=0). 计算Farmer John所需的最少代价。

    Input

    *第一行:一个数n

    *第二行到第n+1行:第i+1行含有一个数wi

    *第n+2行到第2n+1行:第n+1+i行有n个被空格分开的数,第j个数代表pij。

    Output

    *第一行:一个单独的数代表最小代价.

    Sample Input

    4
    5
    4
    4
    3
    0 2 2 2
    2 0 3 3
    2 3 0 4
    2 3 4 0

    Sample Output

    9


    输出详解:

    Farmer John在第四块土地上建立水库,然后把其他的都连向那一个,这样就要花费3+2+2+2=9

    HINT

     

    Source

    题解:
    刚开始看着觉得是网络流。。。YY了十几分钟一直过不了样例,后来一百度就惊呆了。。。
    建立虚拟节点,向每个点连边,权值为在该点建立水库的费用,对这n+1个点求最小生成树。。。
    虚拟节点的连通保证了至少有一个点建造了水库
    漂亮!
    代码:
     1 var a,b,c,fa:array[0..100000] of longint;
     2     ans,i,j,n,tot:longint;
     3     procedure swap(var x,y:longint);
     4      var t:longint;
     5          begin
     6          t:=x;x:=y;y:=t;
     7          end;
     8 function find(x:longint):longint;
     9  begin
    10  if fa[x]<>x then fa[x]:=find(fa[x]);
    11  exit(fa[x]);
    12  end;
    13 
    14 procedure sort(l,r:longint);
    15  var i,j,x,y:longint;
    16  begin
    17  i:=l;j:=r;x:=c[(i+j)>>1];
    18  repeat
    19   while c[i]<x do inc(i);
    20   while c[j]>x do dec(j);
    21   if i<=j then
    22    begin
    23    swap(a[i],a[j]);swap(b[i],b[j]);swap(c[i],c[j]);
    24    inc(i);dec(j);
    25    end;
    26  until i>j;
    27  if i<r then sort(i,r);
    28  if j>l then sort(l,j);
    29  end;
    30 procedure init;
    31  begin
    32    readln(n);
    33    for i:=1 to n do
    34     begin
    35       readln(c[i]);
    36       a[i]:=i;b[i]:=n+1;
    37     end;
    38    tot:=n;
    39    for i:=1 to n do
    40     begin
    41     for j:=1 to i-1 do
    42      begin
    43        inc(tot);
    44        read(c[tot]);a[tot]:=i;b[tot]:=j;
    45      end;
    46     readln;
    47     end;
    48  end;
    49 procedure main;
    50  begin
    51  sort(1,tot);
    52  ans:=0;j:=1;
    53  for i:=1 to n+1 do fa[i]:=i;
    54  for i:=1 to n do
    55    begin
    56    while find(a[j])=find(b[j]) do inc(j);
    57    fa[find(a[j])]:=find(b[j]);inc(ans,c[j]);
    58    end;
    59  writeln(ans);
    60  end;
    61 
    62 begin
    63  assign(input,'input.txt');assign(output,'output.txt');
    64  reset(input);rewrite(output);
    65  init;
    66  main;
    67  close(input);close(output);
    68 end.  
    View Code
  • 相关阅读:
    php实现中文反转字符串的方法
    冒泡排序
    mac 安装ngnix
    二维数组排序可以用php内置函数
    mysql 利用explain 优化
    Jquery Datatable
    SSL证书(HTTPS)背后的加密算法
    HTTPS的误解(二)
    HTTPS的误解(一)
    电子商务信息安全与信任解决方案
  • 原文地址:https://www.cnblogs.com/zyfzyf/p/3905617.html
Copyright © 2011-2022 走看看