普及练习场之排序

P1177 【模板】快速排序
总:看题目,模板啊!

var
  n,i:longint;
  a:array [1..100001] of longint;

procedure qsort(l,r:longint);
var
  i,j,temp,key:longint;
begin
  if l>=r then exit;
  i:=l; j:=r; key:=a[random(r-l+1)+l];
  repeat
    while a[i]<key do inc(i);
    while a[j]>key do dec(j);
    if i<=j then
    begin
      temp:=a[i]; a[i]:=a[j]; a[j]:=temp;
      inc(i); dec(j);
    end;
  until i>j;
  qsort(l,j);
  qsort(i,r);
end;
begin
  readln(n);
  for i:=1 to n do read(a[i]);
  qsort(1,n);
  for i:=1 to n do
   write(a[i],' ');
end.

P1059 明明的随机数
总:看数据范围,可以用桶排。然而我用了十分暴力的方法。

var i,j,n,t,p,s:longint;
    a,b:array [1..5000] of longint;
begin
 read(n);
 for i:=1 to n do
  read(a[i]);
 for i:=1 to n-1 do
  for j:=i+1 to n do
   if a[i]>a[j] then begin t:=a[i]; a[i]:=a[j]; a[j]:=t; end; s:=0;
 p:=a[1];
 for i:=1 to n do
  if p<>a[i+1] then
   begin
    inc(s); b[s]:=p;
    p:=a[i+1];
   end;
 writeln(s);
 for i:=1 to s do write(b[i],' ');
end.

P1068 分数线划定
总:不错的多关键字排序。

var
  a,b:array [1..5000] of longint;
  n,m,k,s,i,j,t:longint;
begin
  read(n,m);
  m:=trunc(m*1.5);
  for i:=1 to n do
    read(b[i],a[i]);
  for i:=1 to n-1 do
    for j:=i+1 to n do
      if (a[i]<a[j]) or (a[i]=a[j]) and (b[i]>b[j]) then
        begin
          k:=a[i]; a[i]:=a[j]; a[j]:=k;
          t:=b[i]; b[i]:=b[j]; b[j]:=t;
        end;
  s:=m;
  for i:=m+1 to n do
    begin
      if a[i]=a[m] then inc(s);
      if a[i]<a[m] then break;
    end;
  writeln(a[m],' ',s);
  for i:=1 to s-1 do
    writeln(b[i],' ',a[i]);
  write(b[s],' ',a[s]);
end.

P1781 宇宙总统
总:这就是很单纯很单纯的排序啊!好吧,“故事”很深啊。看到读的数有100位之多,字符串!将字符串排序,或找最大的字符串。
注:有相同的要取后面那个,坑。

var
  n:integer;
  l,num:array [0..21] of integer;
  a:array [0..21] of string;
procedure init;
var
  i:longint;
begin
  readln(n);
  for i:=1 to n do
    begin
      readln(a[i]);
      l[i]:=length(a[i]);
      num[i]:=i;
    end;
end;

procedure main;
var
  i,j:integer;
begin
  for i:=1 to n-1 do
    for j:=i+1 to n do
      if (l[i]<l[j]) or (l[i]=l[j]) and (a[i]<=a[j]) then
        begin
          l[0]:=l[i]; l[i]:=l[j]; l[j]:=l[0];
          a[0]:=a[i]; a[i]:=a[j]; a[j]:=a[0];
          num[0]:=num[i]; num[i]:=num[j]; num[j]:=num[0];
        end;
  writeln(num[1]);
  write(a[1]);
end;

begin
  init;
  main;
end.
posted @ 2017-02-04 21:17  猪都哭了  阅读(122)  评论(0编辑  收藏  举报