北大AMC(1013 Counterfeit Dollar)代码

/*
	Memory: 100K		Time: 16MS
*/
#include 
#include 
#include 
#include 

/*
	该程序是对于假币问题进行求解

	假设存在A-L 12枚硬币 现在需要称重三次进行求解 每次称重时输入两组硬币组进行称重 然后给出称重结果
	结果可以是  even down up  每个硬币需要至少出现一次  最后求出哪一个硬币是假
	并且打印出假币是重或是轻
*/
/*
	该程序的解决方法是 记录硬币出现的次数
	当硬币出现在相反位置的时候 次数-1 
	最后得出的出现次数最多的硬币则为假币
*/


#define GROUP_NUMBER  3				//硬币组
#define MAX_COIN 12					//最大硬币数
#define REAL  5						//表示硬币是真的


typedef struct
{
	char coin;				//硬币的字母
	int time;				//硬币出现的次数
}CoinPair;

int cmp_by_times(const CoinPair *x, const CoinPair * y)			//按降序给结构进行排序
{
	return abs(y->time) - abs(x->time);
}

int main()
{
	char lCoinComb[MAX_COIN];
	char rCoinComb[MAX_COIN];
	char weightInfo[MAX_COIN];
	
	int i, j;
	int n;			//输入的循环次数

	CoinPair coinInfo[MAX_COIN];		//保存硬币的信息			


	scanf_s("%d", &n);

	while (n--)
	{
		///初始化结构数组
		for (i = 0; i < MAX_COIN; ++i)
		{
			coinInfo[i].time = 0;
			coinInfo[i].coin = '\0';
		}

		for (i = 0; i < GROUP_NUMBER; ++i)
		{
			scanf("%s %s %s", lCoinComb, rCoinComb, weightInfo);

			if (strcmp(weightInfo, "even") == 0)			//如果为even标识  两边都设置为真
			{
				for (j = 0; lCoinComb[j]; ++j)					
				{
					coinInfo[lCoinComb[j] - 'A'].time = REAL;
					coinInfo[rCoinComb[j] - 'A'].time = REAL;
				}
			}
			else if (strcmp(weightInfo, "down") == 0)		//当出现down标记 左边的字母次数-1 右边的字母次数+1
			{
				for (j = 0; lCoinComb[j]; ++j)
				{
					if (coinInfo[lCoinComb[j] - 'A'].time != REAL)
					{
						coinInfo[lCoinComb[j] - 'A'].coin = lCoinComb[j];
						coinInfo[lCoinComb[j] - 'A'].time -= 1;
					}
					if (coinInfo[rCoinComb[j] - 'A'].time != REAL) {
						coinInfo[rCoinComb[j] - 'A'].coin = rCoinComb[j];
						coinInfo[rCoinComb[j] - 'A'].time += 1;
					}
				}
			}
			else if (strcmp(weightInfo, "up") == 0)		//当出现up标记 左边的字母次数加1 右边的字母次数-1 
			{
				for (j = 0; lCoinComb[j]; ++j)
				{
					if (coinInfo[lCoinComb[j] - 'A'].time != REAL)
					{
						coinInfo[lCoinComb[j] - 'A'].coin = lCoinComb[j];
						coinInfo[lCoinComb[j] - 'A'].time += 1;
					}
					if (coinInfo[rCoinComb[j] - 'A'].time != REAL)
					{
						coinInfo[rCoinComb[j] - 'A'].coin = rCoinComb[j];
						coinInfo[rCoinComb[j] - 'A'].time -= 1;
					}
				}
			}
		}
		for (i = 0; i < MAX_COIN; ++i)				//将真硬币设置为0
			if (coinInfo[i].time == REAL)
				coinInfo[i].time = 0;

		qsort(coinInfo, MAX_COIN, sizeof(CoinPair), cmp_by_times);		//按照降序排列

		if (coinInfo[0].time > 0)		//如果time > 0表示重于真币  否则轻与真币
			printf_s("%c is the counterfeit coin and it is heavy.\n", coinInfo[0].coin);
		else 
			printf_s("%c is the counterfeit coin and it is light.\n", coinInfo[0].coin);


	}


	return 0;
}

你可能感兴趣的:(北大ACM题目)