zoukankan      html  css  js  c++  java
  • Sorting a Three-Valued Sequence(三值的排序)

    Description

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

    Input

    Line 1: N (1 <= N <= 1000) Lines 2-N+1: 每行一个数字,共N行。(1..3)

    Output

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

    Sample Input

    9
    2
    2
    1
    3
    3
    3
    2
    3
    1
    

    Sample Output

    4

    题解:

    首先统计有多少个1,2,3,然后判断前a[1](1的个数)有多少非1的元素,再找a到a[1]+a[2]内多少个3和a[1]+a[2]到n内多少个2,两个区域中的1已和第一区域中的非1元素交换。最后,找出后两个区域中最大的那个值。

    代码如下:

     1 #include<iostream>
     2 #include<cstdio>
     3 #include<cstdlib>
     4 #include<cstring>
     5 #include<string>
     6 #include<cmath>
     7 #include<map>
     8 #include<stack>
     9 #include<vector>
    10 #include<queue>
    11 #include<set>
    12 #include<algorithm>
    13 #define max(a,b)   (a>b?a:b)
    14 #define min(a,b)   (a<b?a:b)
    15 #define swap(a,b)  (a=a+b,b=a-b,a=a-b)
    16 #define X (sqrt(5)+1)/2.0
    17 #define maxn 320007
    18 #define N 100000000
    19 #define INF 0x3f3f3f3f
    20 #define PI acos(-1)
    21 #define lowbit(x) (x&(-x))
    22 #define read(x) scanf("%d",&x)
    23 #define put(x) printf("%d
    ",x)
    24 #define memset(x,y) memset(x,y,sizeof(x))
    25 #define Debug(x) cout<<x<<" "<<endl
    26 #define lson i << 1,l,m
    27 #define rson i << 1 | 1,m + 1,r
    28 #define mod 1000000009
    29 #define e  2.718281828459045
    30 #define eps 1.0e18
    31 #define ll long long
    32 using namespace std;
    33 
    34 int a[1111],b[4],c[4];
    35 
    36 int main()
    37 {
    38     int n;
    39     cin>>n;
    40     for(int i=0;i<n;i++)
    41     {
    42         cin>>a[i];
    43         b[a[i]]++;
    44     }
    45     for(int i=0;i<b[1];i++)
    46         if(a[i]!=1)
    47             c[1]++;
    48     for(int i=b[1];i<b[2]+b[1];i++)
    49         if(a[i]==3)
    50             c[2]++;
    51     for(int i=b[1]+b[2];i<n;i++)
    52         if(a[i]==2)
    53             c[3]++;
    54     cout<<c[1]+max(c[2],c[3])<<endl;
    55     return 0;
    56 }
    View Code
  • 相关阅读:
    605. Can Place Flowers
    1184. Distance Between Bus Stops
    1711. Count Good Meals
    1710. Maximum Units on a Truck
    566. Reshape the Matrix
    980. Unique Paths III
    212. Word Search II
    每日总结
    每日总结
    每日总结
  • 原文地址:https://www.cnblogs.com/baiyi-destroyer/p/9612537.html
Copyright © 2011-2022 走看看