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 15Sample Output 1:
4 11Sample Input 2:
7 14 1 8 7 2 4 11 15Sample Output 2:
No Solution
找出序列中的两个数使得这两个数的和等于给定的m,如果不知一种答案,输出使得较小的那个数最小的答案,如果没有这么两个数,输出“No Solution”。首先对序列进行排序。设定左,右端索引,初始指向序列的左,右端,由于要使答案中较小的数最小,故先从右边开始缩进,一直到两个数的和不大于m,这时候如果两数之和等于m就输出答案,不等于即两数之和小于m,于是从左边开始缩进,直到两数之和不小于m,此时如果两数之和等于m就输出答案,不等于即两数之和大于m,于是从右边开始缩进。如此循环。在此过程中一旦出现l>=r,说明没有符合的答案,就输出“No Solution”并结束程序。
代码:
#include <iostream>
#include <vector>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
using namespace std;
int main()
{
int n,m;
cin>>n>>m;
vector<int>coins(n);
for(int i=0;i<n;i++)
{
cin>>coins[i];
}
sort(coins.begin(),coins.end());
int l=0,r=n-1;
while(true)
{
while(coins[l]+coins[r]>m)
{
r--;
if(l>=r)
{
cout<<"No Solution";
return 0;
}
}
if(coins[l]+coins[r]==m)
{
cout<<coins[l]<<" "<<coins[r];
return 0;
}
while(coins[l]+coins[r]<m)
{
l++;
if(l>=r)
{
cout<<"No Solution";
return 0;
}
}
if(coins[l]+coins[r]==m)
{
cout<<coins[l]<<" "<<coins[r];
return 0;
}
}
}