AcWing 802. 区间和 离散化

802. 区间和 - AcWing题库

为什么这里二分写int mid = (l + (r - l)) >> 1;就会TLE 而改为int mid = (l + r) >> 1;就AC(换成 / 也是一样的) 不懂
 

import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        int N = 300010;
        int[] a = new int[N];
        int[] s = new int[N];
        
        List<Integer> alls = new ArrayList<>();
        List<Pair> add = new ArrayList<>();
        List<Pair> query = new ArrayList<>();
        
        for(int i = 0;i < n; i++){
            int x = sc.nextInt();
            int c = sc.nextInt();
            add.add(new Pair(x, c));
            alls.add(x);
        }
        
        for(int i = 0; i < m; i ++){
            int l = sc.nextInt();
            int r = sc.nextInt();
            query.add(new Pair(l, r));
            alls.add(l);
            alls.add(r);
        }
        
        Collections.sort(alls);
        int unique = unique(alls);
        alls = alls.subList(0, unique);
        
        for(Pair item : add){
            int index = find(item.first, alls);
            a[index] = item.second;
        }
        
        for(int i = 1; i <= alls.size(); i++) s[i] = s[i-1] + a[i];
        
        for(Pair item : query){
            int l = find(item.first, alls);
            int r = find(item.second,alls);
            System.out.println(s[r] - s[l-1]);
        }
    }
    
    
    
    public static int unique(List<Integer> list) {
    // 定义一个变量j,用于记录不重复元素的索引位置
    int j = 0;
    // 循环遍历列表,直到列表的最后一个元素
    for (int i = 0; i <= list.size() - 1; i++) {
        // 如果当前元素是列表的第一个元素,或者当前元素与前一个元素不同
        if (i == 0 || list.get(i) != list.get(i - 1)) {
            // 将当前元素复制到索引j的位置
            list.set(j, list.get(i));
            // 更新j的值,指向下一个不重复元素的索引位置
            j++;
        }
    }

    // 返回不重复元素的数量
    return j;
}

    public static int find(int x, List<Integer> list){
        int l = 0;
        int r = list.size() - 1;
        while(l < r){
            int mid = (l + r) >> 1;
            if(list.get(mid) >= x) r = mid;
            else l = mid + 1;
        }
        return l + 1;
    }
    
    
    static class Pair{
        int first;
        int second;
        public Pair(int x, int c){
            this.first = x;
            this.second = c;
        }
    }
    
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JWenzz1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值