INSUL - Cách nhiệt

Tác giả: ladpro98

Ngôn ngữ: Pascal

program insul;
uses    math;
const   fi='';
        maxN=100001;
var     a:array[1..maxN] of longint;
        n,res:longint;


procedure input;
var     inp:text;
        i:longint;
begin
        assign(inp,fi);
        reset(inp);
        readln(inp,n);
        for i:=1 to n do
        readln(inp,a[i]);
        close(inp);
end;

procedure swap(i,j:longint);
var     t:longint;
begin
        t:=a[i];
        a[i]:=a[j];
        a[j]:=t;
end;

procedure sort(l,r:longint);
var     i,j,pivot:longint;
begin
        if l>=r then exit;
        pivot:=a[random(r-l+1)+l];
        i:=l;
        j:=r;
        repeat
                while a[i]<pivot do inc(i);
                while a[j]>pivot do dec(j);
                if i<=j then
                begin
                        if i<j then swap(i,j);
                        inc(i);
                        dec(j);
                end;
        until i>j;
        sort(l,j);
        sort(i,r);
end;

procedure process;
var     i:longint;
begin
        res:=0;
        for i:=1 to n do
        inc(res,a[i]);
        for i:=1 to n div 2 do
        inc(res,a[n-i+1]-a[i]);
end;

begin
        input;
        sort(1,n);
        process;
        write(res);

end.

Download