1048 Find Coins
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.
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.
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.
- 8 15
- 1 2 8 7 2 4 11 15
4 11
- 7 14
- 1 8 7 2 4 11 15
No Solution
总结:这道题目还是比较简单了,先排序然后二分,排序是为了找到最小的v1,二分是为了加快查找的速度,因为数据总量有10^5,双重循环远远超出了时间限制(也可以使用map哈希的做法)
- //使用二分查找结果,这样快点
- #include
- #include
- using namespace std;
-
- int main(){
- int n,m;
- scanf("%d %d",&n,&m);
- int a[n];
-
- for(int i=0;i
scanf("%d",&a[i]); - sort(a,a+n);
-
- for(int i=0;i
- int x=m-a[i];
- int l=0,r=n-1;
- while(l
- int mid=l+r>>1;
- if(a[mid]>=x) r=mid;
- else l=mid+1;
- }
- if(l!=i && a[l]==x){
- printf("%d %d\n",a[i],a[l]);
- return 0;
- }
- }
- printf("No Solution\n");
-
- return 0;
- }
-
- map
- #include
- #include
- #include
- using namespace std;
-
- int main(){
- int n,m;
- map<int,int> v;
- scanf("%d %d",&n,&m);
- int a[n];
-
- for(int i=0;i
scanf("%d",&a[i]); - sort(a,a+n);
- for(int i=0;i
-
- for(int i=0;i
- int x=m-a[i];
- auto it=v.find(x);
- if(it!=v.end() && v[x]!=i){
- printf("%d %d\n",a[i],x);
- return 0;
- }
- }
-
- printf("No Solution\n");
- return 0;
- }
还是看看大佬的代码会有意想不到的收获的!
直接用数组a存储每种不同面值硬币出现的次数,然后循环直接循环面值就行了(这样循环就固定下来了)
- #include
- using namespace std;
-
- int a[510];
-
- int main(){
- int n,m;
- scanf("%d %d",&n,&m);
-
- int x;
- for(int i=0;i
- scanf("%d",&x);
- a[x]++;
- }
-
- for(int i=0;i<510;i++){
- if(a[i]){
- a[i]--;
- if(a[m-i]){
- printf("%d %d\n",i,m-i);
- return 0;
- }
- a[i]++;
- }
- }
- printf("No Solution\n");
- return 0;
- }
好好学习,天天向上!
我要考研!
-
相关阅读:
MATLAB中使用IPOPT去解NLP问题的接口:AMPL 工具
Kubernetes 1.25 中的删除和主要变化
【退役记】NOI2022
智能语音外呼OKCC呼叫中心的各项指标KPI
Android学习笔记 1.2.7 自定义任务 && 1.2.8 自定义插件
14:00面试,14:06就出来了,问的问题有点变态。。。
MySQL数据库详解 二:数据库的高级语句(高级查询语句)
【ict云赛道备考】华为云介绍
JVM内存模型之深究模型特征
JavaAPI常用类01
-
原文地址:https://blog.csdn.net/weixin_50679551/article/details/127039498