• 【USACO 2.1.3】三值的排序


    【题目描述】

    排序是一种很频繁的计算任务。现在考虑最多只有三值的排序问题。一个实际的例子是,当我们给某项竞赛的优胜者按金银铜牌排序的时候。在这个任务中可能的值只有三种1,2和3。我们用交换的方法把他排成升序的。

    写一个程序计算出,给定的一个1,2,3组成的数字序列,排成升序所需的最少交换次数。

    【格式】

    INPUT FORMAT:

    (file sort3.in)

    第一行:

    奖牌个数N (1 <= N <= 1000)

    第 2行到第N+1行:

    每行一个数字,表示奖牌。共N行。(1..3)

    OUTPUT FORMAT:

    (file sort3.out)

    共一行,一个数字。表示排成升序所需的最少交换次数。

    【分析】

    这个真的没有什么好讲的了。

    分两种情况就行了,看程序吧。

     1 #include <cstdlib>
     2 #include <iostream>
     3 #include <cstdio>
     4 #include <cstring>
     5 #include <cmath>
     6 #include <queue>
     7 #include <algorithm>
     8 const int maxn=1000+10;
     9 using namespace std;
    10 int shu[maxn],Sort[maxn];
    11 int num[5][5];//在i中的j数量 
    12 int main()
    13 {
    14     int lj=0,ans=0,n,i;//总共不同的个数 
    15     //文件操作
    16     freopen("sort3.in","r",stdin);
    17     freopen("sort3.out","w",stdout); 
    18     memset(num,0,sizeof(num)); 
    19     scanf("%d",&n);
    20     for (i=1;i<=n;i++)
    21     {
    22         scanf("%d",&shu[i]);
    23         Sort[i]=shu[i];
    24     }
    25     sort(Sort+1,Sort+1+n);//排序
    26     for (i=1;i<=n;i++)
    27     {
    28         if (Sort[i]!=shu[i])
    29         {
    30             num[Sort[i]][shu[i]]++;
    31             lj++;
    32         }
    33     } 
    34     ans+=min(num[1][2],num[2][1]);lj-=min(num[1][2],num[2][1])*2;
    35     ans+=min(num[1][3],num[3][1]);lj-=min(num[1][3],num[3][1])*2;
    36     ans+=min(num[3][2],num[2][3]);lj-=min(num[3][2],num[2][3])*2;
    37     printf("%d",ans+(lj/3)*2);
    38     return 0;
    39 }
  • 相关阅读:
    python_linux系统相关配置
    python_字典dict相关操作
    python_传参
    mapreduce 学习笔记
    linux 常用命令
    C++ stringstream介绍,使用方法与例子
    C++/C++11中std::numeric_limits的使用
    C++中string erase函数的使用
    C++中accumulate的用法
    malloc的用法和意义
  • 原文地址:https://www.cnblogs.com/hoskey/p/3788649.html
Copyright © 2020-2023  润新知