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
思路
  • 说白了这一题就是寻找两数使得和为定值,如果是两重循环遍历找面对这么大的数据是肯定要超时的
  • 比较好的一个想法就是用键值对,也就是map容器,假设目前遍历到的值为t,我们要查询的是m-t是否存在数组里,用map查询代替一个for循环会快很多,这题在Leetcode上也是有类似的
代码
#include<bits/stdc++.h>
using namespace std;
int a[100010];
int main()
{
int n, m;
cin >> n >> m; map<int, int> mp;
for(int i=0;i<n;i++)
{
cin >> a[i];
if(mp.count(a[i]) != 0) //存在相同的数字个数要对应相加
mp[a[i]]++;
else
mp[a[i]] = 1;
}
sort(a, a+n); //升序保证v1<=v2
for(int i=0;i<n;i++)
{
int t = m - a[i];
if( (t != a[i] && mp.count(t) != 0) ||
(t == a[i] && mp[t] > 1) ) //两个数不相等的时候有就行了,否则该数要不止一个
{
cout << a[i] << " " << t;
return 0;
}
}
cout << "No Solution";
return 0;
}
引用

https://pintia.cn/problem-sets/994805342720868352/problems/994805432256675840

最新文章

  1. angularjs内置指令 - form
  2. Bash 中为 _ 变量赋空值的三个场景
  3. IHTMLDocument2
  4. SaltStack 最新版WebUI部署
  5. bzoj 1060 [ZJOI2007]时态同步(树形DP)
  6. Cloud Test 单页面即时监测功能上线!
  7. javascript的几个问题
  8. UVA 707 - Robbery(内存搜索)
  9. HDU1233--还是畅通工程(最小生成树)
  10. Angular4 后台管理系统搭建(2) - flexgrid 单元格模板 wjFlexGridCellTemplate 的坑
  11. mybatis 的逆向工程
  12. java常量池中基本数据类型包装类的小陷阱
  13. 探究c# lock
  14. django的models模型 关联关系和关系查询
  15. nginx介绍 - 部署到linux中
  16. luogu3628 特别行动队 (斜率优化dp)
  17. MT7601 AP模式移植
  18. 洛谷P2325王室联邦 SCOI2005 构造+树上分块
  19. 入门系列之在Ubuntu 14.04上备份,还原和迁移MongoDB数据库
  20. nginx配置ThinkPHP5二级目录访问

热门文章

  1. linux下core dump--转载
  2. .net+文件夹上传
  3. 51nod 1086
  4. [Luogu] 最小差值生成树
  5. centos7安装gitlab 支持带认证https,开启邮件功能 超级简单.
  6. Java学习之路(2)
  7. 本地项目文件通过git提交到GitHub上
  8. iOS-VideoToolbox硬编码H264
  9. LightGBM两种使用方式
  10. java.util.concurrent.DelayQueue 源码学习