题目描述
Eva loves to collect coins from all over the universe, includingsome other planets like Mars. One dayshe visited a universal shopping mall which could accept all kinds of coins aspayments. However, there was a specialrequirement of the payment: for each bill, she could only use exactly two coinsto pay the exact amount. Since she hasas many as 105 coins with her, she definitely needsyour help. You are supposed to tell her,for any given amount of money, whether or not she can find two coins to pay forit.
输入描述:
Each input file contains one test case. For each case, the first line contains 2positive numbers: N (<=105, the total number of coins) and M(<=103, the amount of money Eva has topay). The second line contains N facevalues of the coins, which are all positive numbers no more than 500. All the numbers in a line are separated by aspace.
输出描述:
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
这题给你一个数组,问你这个数组里面是否有两个数,相加为题目中给定的一个数
这里需要注意的一个地方就是,题目中并没有说给定的所有数都是正整数,只说了是正数,但是实际上,你在编程的时候只需要考虑给定的数都是正整数就好了,不知道这算不算是一个BUG
这一题使用解决这一类问题的传统方法,设定两个指针,分别指向排序后的数组的第一个元素和最后一个元素,如果这两个元素的和大于给定的数,将第二个指针前移,如果这两个数的和小于给定的数,则将第一个指针后移,一直到找到和为给定的数的两个数或者是前指针和后指针重合,算法结束
#include <iostream>
#include <algorithm>
using namespace std;
int coins[100003];
int main()
{
int N,M;
int pointOne,pointTwo;
cin>>N>>M;
for(int i=0;i<N;i++)
cin>>coins[i];
sort(coins,coins+N);
pointOne = 0;
pointTwo = N-1;
while(1)
{
while(pointOne < pointTwo && coins[pointOne] + coins[pointTwo] <M) pointOne++;
if(pointOne == pointTwo || coins[pointOne] + coins[pointTwo] == M) break;
while(pointOne < pointTwo && coins[pointOne] + coins[pointTwo] >M) pointTwo--;
if(pointOne == pointTwo || coins[pointOne] + coins[pointTwo] == M) break;
}
if(pointTwo == pointOne) cout<<"No Solution";
else
{
cout<<coins[pointOne]<<" "<<coins[pointTwo];
}
return 0;
}