1048 Find Coins (25 分) 模拟 ->二分

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 10e​5​​ 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

  1. 简单二分,找到一个数即可

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值