您的位置:首页 > 产品设计 > UI/UE

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

2015-09-29 21:59 525 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息