zoukankan      html  css  js  c++  java
  • 2.1.3 Sorting a Three-Valued Sequence

    Sorting a Three-Valued Sequence
    IOI'96 - Day 2

    Sorting is one of the most frequently performed computational tasks. Consider the special sorting problem in which the records to be sorted have at most three different key values. This happens for instance when we sort medalists of a competition according to medal value, that is, gold medalists come first, followed by silver, and bronze medalists come last.

    In this task the possible key values are the integers 1, 2 and 3. The required sorting order is non-decreasing. However, sorting has to be accomplished by a sequence of exchange operations. An exchange operation, defined by two position numbers p and q, exchanges the elements in positions p and q.

    You are given a sequence of key values. Write a program that computes the minimal number of exchange operations that are necessary to make the sequence sorted.

    PROGRAM NAME: sort3

    INPUT FORMAT

    Line 1: N (1 <= N <= 1000), the number of records to be sorted
    Lines 2-N+1: A single integer from the set {1, 2, 3}

    SAMPLE INPUT (file sort3.in)

    9
    2
    2
    1
    3
    3
    3
    2
    3
    1
    

    OUTPUT FORMAT

    A single line containing the number of exchanges required

    SAMPLE OUTPUT (file sort3.out)

    4
    
    {
    ID: makeeca1
    PROG: sort3
    LANG: PASCAL
    }
    var n,i,j,ans:longint;
        num:array[0..3]of longint;
        a,b:array[0..1000]of longint;
        cnt:array[0..3,0..3]of longint;
    begin
      assign(input,'sort3.in');reset(input);
      assign(output,'sort3.out');rewrite(output);
      readln(n);
      for i:=1 to n do
      begin
        readln(a[i]);
        inc(num[a[i]]);
      end;
      n:=0;
      for i:=1 to 3 do
        for j:=1 to num[i]do
        begin
          inc(n);
          b[n]:=i;
        end;
      fillchar(num,sizeof(num),0);
      for i:=1 to n do
      if b[i]<>a[i]then inc(cnt[b[i],a[i]]);
      if cnt[2,1]>cnt[1,2]then ans:=cnt[3,2]else ans:=cnt[2,3];
      inc(ans,cnt[2,1]+cnt[3,1]);
      writeln(ans);
      close(input); close(output);
    end.
  • 相关阅读:
    解析iOS开发中的FirstResponder第一响应对象
    iOS9新特性——堆叠视图UIStackView
    IOS定位服务的应用
    iOS原生地图开发详解
    iOS原生地图开发进阶——使用导航和附近兴趣点检索
    iOS开发之----常用函数和常数
    iOS延时执行
    Mac快捷键、命令行
    UICollectionView使用
    iOS: 在代码中使用Autolayout (1) – 按比例缩放和优先级
  • 原文地址:https://www.cnblogs.com/makeecat/p/3274550.html
Copyright © 2011-2022 走看看