三默网为您带来有关“Codeforces 886A 暴力 双指针”的文章内容,供您阅读参考。

Codeforces 886A 暴力 双指针

2023-01-20 12:31:26

这道题和LeetCode15有点像,这道题是双指针,LeetCode那道题是三指针

传送门:本题题目

LeetCode 15

题意:

6个数,选3个数组成一堆,剩下3个数组成另一堆,问两堆的sum能不能相等。

题解:

有一个很暴力的解法:
就是第一个数肯定属于一堆,我们只需要找到剩下的两个数,直接两个for循环遍历,枚举所有情况,时间复杂度为O(n2)

双指针解法可以把时间复杂度降到O(log2n+n)
我们可以先sort一遍,然后第一个数肯定属于一堆t1,我们只需要找到剩下的两个数,此时我们设置两个指针L指向第二个数,R指向最后一个数,如果我们发现t1<t2,我们就让l++。

AC代码:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#define INF 1010
using namespace std;

int main(void) {
    int a[6],sum = 0;
    for (int i = 0; i < 6; i++) 
        scanf("%d", &a[i]),sum += a[i];

    sort(a, a + 6);

    int l= 1, r = 5;//左 右三个指针
    while (l < r) {
        int t1 = a[0] + a[l] + a[r];
        int t2 = sum - t1;
        if (t1 < t2)
            l++;
        else if (t1 > t2)
            r--;
        else if (t1 == t2) {
            puts("YES");
            return 0;
        }
    }
    puts("NO");
    return 0;
}