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 threedifferent 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




虽然第一直觉告诉我要把每个数字的数目保存下来,但是处于懒还是先dfs了一遍果然错了!然后改了下,先换前面的3和后面的1,再换前面的3和后面的2,果然又不行!捉鸡,后来发现要同时换,而且,换1要从头,换2要从2区间的尾。才是最快的嗯整体的思想很重要。

/*
ID: des_jas1
PROG: sort3
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
#include <string.h>
#include <cmath>
#include <algorithm>
//#define fin cin
//#define fout cout
using namespace std;

const int MAX=1005;
int N,a[MAX],cn=0,b[4]={0};

void exchange()
{
	int i=0,j=N-1,t=b[1]+b[2];
	for(i=N-1;i>=t;i--)
    {
        if(a[i]==1)
        {
            for(j=0;j<t && a[j]!=3;j++);
            if(j<t)
            {
				a[j]=1;
				a[i]=3;
				cn++;
            }
        }
        if(a[i]==2)
        {
            for(j=t-1;j>=b[1] && a[j]!=3;j--);
            if(a[j]==3)
            {
                a[i]=3;
                a[j]=2;
                cn++;
            }
        }
    }

}
int main() 
{
	ifstream fin("sort3.in");
	ofstream fout("sort3.out");
	fin>>N;
	int i;
	for(i=0;i<N;i++)
	{
		fin>>a[i];
		b[a[i]]++;
	}
	exchange();
	for(i=0;i<b[1];i++)
		if(a[i]==2)
			cn++;
	fout<<cn<<endl;
	fout.close();
	fin.close();
    return 0;
}


minimal   ['mɪnɪm(ə)l]   详细 X
基本翻译
adj. 最低的;最小限度的
网络释义
minimal: 最小的
minimal surface: 极小曲面
Minimal pairs: 最小对立体
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值