USACO 2.1 Sorting a Three-Valued Sequence (贪心)

#include <stdio.h>
#define DEBUG 1
#define TESTCASES 8
#define MAX(x, y) ( (x) > (y) ? (x) : (y) )
#define MIN(x, y) ( (x) < (y) ? (x) : (y) )

int numOfRecords;
int recordArray[1001];
//bucket[num]表示数字为num的记录一共有多少个
int bucket[4];
//numbersInZone[zone][num]表示某个位置上,排序前的数字是num,排序后应该是zone,也就是说如果num不等于zone就得交换
int numbersInZone[4][4];

int main(){
#if DEBUG
	int testCase;
	for (testCase = 1; testCase <= TESTCASES; testCase++){
		char inputFileName[20] = "inputx.txt";
		inputFileName[5] = '1' +  (testCase - 1);
		freopen(inputFileName, "r", stdin);
		printf("\n#%d\n", testCase);
#endif

	int zone, num;
	for (zone = 1; zone <= 3; zone++){
		bucket[zone] = 0;
		for (num = 1; num <= 3; num++)
			numbersInZone[zone][num] = 0;
	}

	scanf("%d", &numOfRecords);
	int record;
	for (record = 1; record <= numOfRecords; record++){
		scanf("%d", &recordArray[record]);
		bucket[ recordArray[record] ]++;
	}


	for (record = 1; record <= numOfRecords; record++)
		if (record <= bucket[1])
			numbersInZone[1][ recordArray[record] ]++;
		else if (record <= bucket[1] + bucket[2] )
			numbersInZone[2][ recordArray[record] ]++;
		else
			numbersInZone[3][ recordArray[record] ]++;
	//贪心:先进行只需一次交换就能使两个交换的数都处于有序状态的交换,剩下还未交换的数,如果每交换两次就能使3个数有序
	printf("%d\n", MIN(numbersInZone[1][2], numbersInZone[2][1]) +
		MIN(numbersInZone[1][3], numbersInZone[3][1]) +
		MIN(numbersInZone[2][3], numbersInZone[3][2]) +
		2 * (MAX(numbersInZone[1][2], numbersInZone[2][1]) - MIN(numbersInZone[1][2], numbersInZone[2][1]) ) );

#if DEBUG
	}
#endif
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值