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 10e5 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.
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
Note
从第二行选俩数,等于第一行第二个
与1044类似,自己模拟的代码,两个点超时
Code
#include<iostream>
#include<algorithm>
using namespace std;
struct result{
int start;
int end;
}results[100010];
bool cmp(result a, result b){
return a.start < b.start;
}
int main(){
int num, target, min = 10010000, a[100010];
int cnt = 0;
cin >> num >> target;
for(int i = 0; i < num; i++){
cin >> a[i];
}
sort(a, a + num);
for(int i = 0; i <= num; i++){
if(a[i] > target / 2) break;
for(int j = i + 1; j < num; j++){
if(a[i] + a[j] == target){
results[cnt].start = a[i];
results[cnt++].end = a[j];
}
else if(a[i] + a[j] > target) break;
}
}
sort(results, results + cnt, cmp);
if(cnt > 0)
cout << results[0].start << " " << results[0].end << endl;
else cout << "No Solution";
return 0;
}
Note2
- 简单二分,找到一个数即可
Code
#include<iostream>
#include<algorithm>
using namespace std;
struct result{
int start;
int end;
}results[100010];
bool cmp(result a, result b){
return a.start < b.start;
}
int a[100010];
int num, target;
int lowerbound(int i){
int left = i, right = num;
while(left <= right){
int mid = left + (right - left) / 2;
if(a[mid] + a[i] > target) right = mid - 1;
else if(a[mid] + a[i] == target) return mid;
else left = mid + 1;
}
return -1;
}
int main(){
int cnt = 0;
cin >> num >> target;
for(int i = 0; i < num; i++){
cin >> a[i];
}
sort(a, a + num);
for(int i = 0; i < num; i++){
int j = lowerbound(i);
if(j != -1 && j != i){
results[cnt].start = a[i];
results[cnt++].end = a[j];
}
}
if(cnt > 0)
cout << results[0].start << " " << results[0].end << endl;
else cout << "No Solution";
return 0;
}