PAT 1048. Find Coins

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/zhangfengz1995/article/details/77867418

1048. Find Coins (25)

时间限制
100 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

Eva loves to collect coins from all over the universe, including some other planets like Mars. One day she visited a universal shopping mall which could accept all kinds of coins as payments. However, there was a special requirement of the payment: for each bill, she could only use exactly two coins to pay the exact amount. Since she has as many as 105 coins with her, she definitely needs your help. You are supposed to tell her, for any given amount of money, whether or not she can find two coins to pay for it.

Input Specification:

Each input file contains one test case. For each case, the first line contains 2 positive numbers: N (<=105, the total number of coins) and M(<=103, the amount of money Eva has to pay). The second line contains N face values of the coins, which are all positive numbers no more than 500. All the numbers in a line are separated by a space.

Output Specification:

For each test case, print in one line the two face values V1 and V2 (separated by a space) such that V1 + V2 = M and V1 <= V2. If such a solution is not unique, output the one with the smallest V1. If there is no solution, output "No Solution" instead.

Sample Input 1:
8 15
1 2 8 7 2 4 11 15
Sample Output 1:
4 11
Sample Input 2:
7 14
1 8 7 2 4 11 15
Sample Output 2:
No Solution

不需要用经典2-sum,排序,再两头向中间扫。


这题硬币的值最大500,

直接读的时候记录一下,某个硬币值是否出现过。


然后找能凑齐钱的硬币值,出现过就凑成了一对。注意要小值最小。


因为记录的是之前出现过的值,所以两个值相同的情况直接并进普通情况里。


(推广一下,就是K-sum的哈希优化)


#include <cstdio>
#include <vector>
#include <algorithm>
#include <map>

bool valShowed[510];

int main()
{
	int N, M;

	scanf("%d%d", &N, &M);

	int minValA=0x7fffffff, minValB;

	for (int i = 0; i < N; ++i)
	{
		int val;
		scanf("%d", &val);

		int other = M - val;

		if ((0<=other && other<=500) && valShowed[other])
		{
			// 可以配对成功
			// 留最小的
			if (std::min(other,val) < minValA)
			{
				minValA = std::min(other, val);
				minValB = std::max(other, val);
			}
				
		}

		valShowed[val] = true;
	}

	if (minValA == 0x7fffffff)
	{
		printf("No Solution");
		return 0;
	}
	else
	{
		printf("%d %d", minValA, minValB);
	}


	system("pause");

	return 0;
}



展开阅读全文

没有更多推荐了,返回首页