HDU5861 (线段树区间更新+单点查询)

题意:有n个村庄,每相邻两个村庄之间的路有一个费用,有m个查询,查询从l走到r需要的最小费用,保证l走到r时所有的路需要打开,每条路只能打开和关闭一次。


题解:因为只能打开和关闭一次,所以我们离线维护每条路最早的打开时间和最晚的关闭时间,那么对于每一个查询的l-r,可以用线段树区间赋值i,表示第几天开启,并且更新天数的最大最小值。nlogn可以解决第一个问题。那么对于每一天,我们维护一个当天需要开启的路和需要关闭的路,直接单点查询就OK,对于每一个查询都可以由前一个查询递推过来,见代码。


#include <iostream>
#include <algorithm>
#include <queue>
#include <stack>
#include <cstdio>
#include <string>
#include <cstring>
#include <vector>
#include <set>
#include <cmath>
#define LL long long
#define INF 0x3f3f3f3f
#define MOD 1000000007
const int maxn = 2e5 + 5;
const double eps = 1e-8;
int MIN[maxn*4];
int MAX[maxn*4];
using namespace std;
struct node{
    int s,e;
    node(){}
    node(int ss, int ee):s(ss),e(ee){}
}op[maxn];
int a[maxn];
vector <int> s[maxn], e[maxn];
void pushdown(int o){
    if(MIN[o] != INF){
        MIN[o*2] = min(MIN[o*2],MIN[o]);
        MIN[o*2+1] = min(MIN[o*2+1],MIN[o]);
    }
    if(MAX[o] != 0){
        MAX[o*2] = max(MAX[o*2],MAX[o]);
        MAX[o*2+1] = max(MAX[o*2+1],MAX[o]);
    }
    return;
}
void update(int ql, int qr, int l, int r, int o, int c){
    if(ql <= l && qr >= r){
        MIN[o] = min(MIN[o],c);
        MAX[o] = max(MAX[o],c);
        return;
    }
    int m = (l + r) / 2;
    pushdown(o);
    if(ql <= m)
        update(ql, qr, l, m, o*2, c);
    if(m < qr)
        update(ql, qr, m+1, r, o*2+1, c);
}
void query(int l, int r, int o){
    if(l == r){
        if(MIN[o] != INF){
            s[MIN[o]].push_back(l);
        }
        if(MAX[o] != -1){
            e[MAX[o]].push_back(l);
        }
        return;
    }
    int m = (l + r) / 2;
    pushdown(o);
    query(l,m,o*2);
    query(m+1,r,o*2+1);
    return;
}
void build(int l, int r, int o){
    MIN[o] = INF;
    MAX[o] = -1;
    if(l == r)
        return;
    int m = (l + r) / 2;
    build(l,m,o*2);
    build(m+1,r,o*2+1);
}
int main(){
    int n,m;
    while(scanf("%d%d",&n,&m) == 2){
        for(int i=0; i<maxn; i++){
            s[i].clear();
            e[i].clear();
        }
        build(1,n-1,1);
        for(int i=1; i<n; i++){
            scanf("%d",&a[i]);
        }
        for(int i=1; i<=m; i++){
            scanf("%d%d",&op[i].s,&op[i].e);
            if(op[i].s > op[i].e) swap(op[i].s,op[i].e);
            update(op[i].s,op[i].e-1,1,n-1,1,i);
        }
        query(1,n-1,1);
        int ans = 0;
        for(int i=1; i<=m; i++){
            for(int j=0; j<s[i].size(); j++){
                ans += a[s[i][j]];
            }
            printf("%d\n",ans);
            for(int j=0; j<e[i].size(); j++){
                ans -= a[e[i][j]];
            }
        }
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值