20110727 个人赛B题~

Description

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.

Input

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}

Output

A single line containing the number of exchanges required

Sample Input

9
2
2
1
3
3
3
2
3
1

Sample Output

4

 

学校个人赛A题~就是一道排序题~大意是有若干个1、2、3~需要按从小到大顺序排好~问交换数字的次数~

大概思想就是求数组中1、2、3的个数~然后在数组中分区~分别求2区中1的个数~以及3区中1和2的个数~

2区中有多少个1以及3区中有多少个2~就需交换多少次~3区中有多少个1~就需交换多少两次(即count+=2)~

需要注意的是要计算1区中3的个数~因为若1区中有3~就可以直接跟3区中的1交换~不需要交换两次~

#include"stdio.h"
#include"string.h"
int main()
{
	int i,j;
	int n;
	int a[1100];
	int s1=0,s2=0;
	int count=0,count2=0;
//	freopen("01in.txt","r",stdin);
	scanf("%d",&n);
	for(i=0;i<n;i++)
		scanf("%d",&a[i]);
	for(i=0;i<n;i++)
	{
		if(a[i]==1)
			s1++;
		if(a[i]==2)
			s2++;	
	}//计算1和2的数目	
	for(i=0;i<s1;i++)
	{
		if(a[i]==3)
			count2++;
	}//计算1区中3的数目
	for(i=s1;i<s1+s2;i++)
	{
		if(a[i]==1)
		count++;
	}计算2区中1的数目
	for(i=s1+s2;i<n;i++)
	{
	         if(a[i]==1)
		{
			if(count2==0)
				count+=2;
			else
			{
				count++;
				count2--;
			}
		}
		if(a[i]==2)
			count++;
	}
	printf("%d",count);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值