1048 Find Coins (25 分)

本文探讨了一个有趣的问题,即如何从大量的硬币中找到两枚,其面值之和等于特定金额。通过使用C++和数据结构,如map,文章提供了一种有效的解决方案,包括输入处理、重复元素的去除以及特殊情况的考虑。

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 10
​5
​​ 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 (≤10
​5
​​ , the total number of coins) and M (≤10
​3
​​ , 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 V
​1
​​ and V
​2
​​ (separated by a space) such that V
​1
​​ +V
​2
​​ =M and V
​1
​​ ≤V
​2
​​ . If such a solution is not unique, output the one with the smallest V
​1
​​ . 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
有几个注意点:
1.测试点里有输入小于2个数的
2.有输入两个数恰好为m/2的
3.还有就是大量数据如何提速的问题

事实上这道题一开始我是用二重循环过了的,只要合理的剪枝,并不会超时,而且第三第四个测试点的速度还优于这种方法,我记得好像两个都只是10ms+,只不过代码量要多一些。有三个地方对代码进行了优化,其中之一的方法就是去重,大量输入元素有很多重复的元素,另外需要把特例取出来单独处理,就是题目中的两个输入分别是m/2的情况,那么问题又来了,毕竟题目的测试点有限,针对这一道题而言,我私以为裁判程序并不能完全决定这个题的代码的正确性,我现在回想起来用这种方法过应该算是蒙混过关的。
另外,谁能帮我修改一下最长的那一行代码就再好不过了,三目运算符嵌在cout里有点用不明白。

#include<iostream>
#include<map>
#include<algorithm>
using namespace std;
int main()
{
	int n, m,a,Min = 1 << 30;;
	scanf("%d %d", &n, &m);
	map<int,int>re;
	for (int i = 0; i < n; i++)
	{
		scanf("%d", &a);
		re[a]++;
		if (re[m - a] == 1)
			Min = min(min(a,m-a),Min);
	}
	Min == 1 << 30 ? cout << "No Solution" : Min == m / 2 ? re[Min] > 1 ? cout << Min << " " << m - Min : cout << "No Solution" : cout << Min << " " << m - Min;
	return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值