codeforces 解题报告 1006C. Three Parts of the Array brute force / binary search

http://codeforces.com/contest/1006/problem/C

解题思路:


1.暴力:

  • 弄两根指针分别指向头尾,再弄一个前序和和一个后序和

  • 两和相等,更新ans,并增加前序和(左指针右移)

  • 前序和比后序和小,增加前序和(左指针右移)

  • 前序和比后序和大,增加后序和(右指针左移)

  • 直到两指针相遇


2.二分:

  • 枚举前序和

  • 枚举后序和,在前序和中二分查找后序和,找到就更新ans


总结:其实两个思路都是枚举前序和与后序和,其实根本不需要二分,只是二分可能相对更好懂,毕竟指针这种东西很多人都比较讨厌

brute force:

import java.util.Scanner;

public class Main {

    public static void main(String args[]) {

        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] num = new int[200010];
        for(int i = 1;i <= n;i++) {
            num[i] = sc.nextInt();
        }
        int i = 1,j = n;
        long left = num[1],right = num[n];
        long ans = 0;
        while(i < j) {
            if(left == right) {
                ans = Math.max(ans,left);
            }
            if(left <= right) {
                i++;
                left += num[i];
            } else if(left > right) {
                j--;
                right += num[j];
            }

        }
        System.out.println(ans);
    }
}

binary search:


import java.util.Collections;
import java.util.Scanner;
import java.util.Vector;

public class Main {

    public static void main(String args[]) {

        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] num = new int[200010];
        long cnt = 0;
        for(int i = 1;i <= n;i++) {
            num[i] = sc.nextInt();
            cnt += num[i];
        }
        Vector<Long> ve = new Vector<>();        //存下小于1/2序列和的所有左序列和
        long res = 0;
        for(int i = 1;i <= n;i++) {
            if(res > cnt / 2) {
                break;
            }
            ve.add(res);
            res += num[i];
        }

        res = 0;
        long ans = 0;
        for(int i = n;i >= 1;i--) {
            res += num[i];
            if (res > cnt / 2) {
                break;
            }
            if(Collections.binarySearch(ve,res) >= 0) { //二分找到相等和就更新ans
                ans = Math.max(ans,res);
            }
        }
        System.out.println(ans);
    }
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值