[ABC371D] 1D Country 题解

这题,怎么说呢, STL 大法好。

前置芝士: lower_pound 函数在结构体上的使用。

那其实这题便是一个二分前缀和的水题了。结构体存储每个村庄的距离 x ,人口 d 。对于每个输入的 [l,r] 二分查找其对应的村庄,进行一次答案的统计,输出即可。

代码 :

#include <bits/stdc++.h>
#define seq(q, w, e) for (int q = w; q <= e; q++)
#define ll long long
using namespace std;
const int maxn = 2e5+10;
ll n,m,ans;
struct node{
    ll x,d;
    node(){}
    node(int a,int b):x(a),d(b){}           //初始化
    bool operator < (const node b)const{    //自定义比较函数
        return x<b.x;
    }
}a[maxn];                                   //村庄数组

bool cmp(node a,node b){
    return a.x<b.x;                         //排序函数,以距离为关键词
}

signed main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
    cin>>n;
    a[0].d=0;
    seq(i,1,n){
        cin>>a[i].x;
    }
    seq(i,1,n){
        cin>>a[i].d;
    } 
    sort(a+1,a+n+1,cmp);                  //输入结构体后按距离排序
    seq(i,1,n){
        a[i].d+=a[i-1].d;                 //维护前缀和
    }
    cin>>m;
    seq(i,1,m){
        ans=0;
        int l,r;
        cin>>l>>r;
        int sum1=lower_bound(a+1,a+1+n,node(l,0))-a,sum2=lower_bound(a+1,a+1+n,node(r,0))-a;  //二分查找求区间
        if(a[sum2].x!=r) sum2--;      //由于low_pound返回的是第一个大于等于的数,所以如果不相等,需要减一
        ans=a[sum2].d-a[sum1-1].d;    //前缀和查询操作。
        cout<<ans<<endl;
    }
    return 0;
}
posted @   adsd45666  阅读(27)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示