51nod 1090 & 1267 【二分简单题】

本文介绍了一种寻找数组中三个数相加等于特定值的有效算法。通过先排序再使用双指针技巧与二分查找结合的方法,快速定位符合条件的三元组。此算法能够高效解决三数求和问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

做法:从左往右枚举前两个数的和sum,剩余的数二分找-sum是否存在。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <bits/stdc++.h>
using namespace std;
struct Node {
    int a, b, c;
}temp;
int main() {
    int n;
    int a[1010];
    scanf("%d", &n);
    for(int i = 0; i < n; i++) scanf("%d", &a[i]);
    sort(a, a+n);
    vector<Node>ans;
    for(int i = 0; i < n-2; i++) {
        for(int j = i+1; j < n-1; j++) {
            int sum = a[i] + a[j];
            int pos = lower_bound(a+j+1, a+n, -sum) - a;
            if(pos >= n || a[pos] != -sum) continue;
//            cout << i << ' ' << j <<' ' << pos << endl;
            temp.a = a[i];
            temp.b = a[j];
            temp.c = a[pos];
            ans.push_back(temp);
        }
    }
    if(ans.size() == 0) {
        puts("No Solution");
        return 0;
    }
    for(int i = 0; i < ans.size(); i++) {
        cout << ans[i].a << ' ' << ans[i].b << ' ' << ans[i].c << endl;
    }
}

 

 

 

感觉比第一题还简单,是因为数据太弱? 三个for枚举前三个数和sum, 二分剩余的数找-sum。

测试数据三个数sum居然不会爆int

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <bits/stdc++.h>
using namespace std;
int main() {
    int n;
    int a[1010];
    scanf("%d", &n);
    for(int i = 0; i < n; i++) scanf("%d", &a[i]);
    sort(a, a+n);
    for(int i = 0; i < n-3; i++) {
        for(int j = i+1; j < n-2; j++) {
            for(int k = j+1; k < n-1; k++) {
                int sum = a[i] + a[j]; sum += a[k];
                int pos = lower_bound(a+k+1, a+n, -sum) - a;
                if(pos >= n || a[pos] != -sum) continue;
                puts("Yes");
                return 0;
            }
        }
    }
    puts("No");
}

转载于:https://www.cnblogs.com/bestwzh/p/6636963.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值