zoukankan      html  css  js  c++  java
  • 可持久化数据结构

    可持久化数据结构

    题目链接:http://acm.xidian.edu.cn/problem.php?id=1181

    用vector实现可持久化

    这题要求的是一个支持区间查询的可持久化数据结构。这里使用vector巧妙地实现:pair<time,value>用pair存储时间戳以及当前时间的值,query的时候使用二分查找即可。

    代码如下:

     1 #include<cstdio>
     2 #include<vector>
     3 #include<iostream>
     4 #include<algorithm>
     5 #define X first
     6 #define Y second
     7 #define N 1000005
     8 using namespace std;
     9 typedef pair<int,int> P;
    10 int n,q,times,type,c,arr[N];
    11 vector<P>a[N];
    12 vector<P>::iterator it;
    13 int lowbit(int x){
    14     return x&-x;
    15 }
    16 int query(int l,int r,int t){
    17     int ans=0;
    18     for(int i=r;i>0;i-=lowbit(i)){
    19         it=upper_bound(a[i].begin(),a[i].end(),make_pair(t,0));
    20         if(it!=a[i].end()&&it->X==t)ans+=it->Y;
    21         else if(it!=a[i].begin()){
    22             it--;
    23             ans+=it->Y;
    24         }
    25     }
    26     for(int i=l-1;i>0;i-=lowbit(i)){
    27         it=upper_bound(a[i].begin(),a[i].end(),make_pair(t,0));
    28         if(it!=a[i].end()&&it->X==t)ans-=it->Y;
    29         else if(it!=a[i].begin()){
    30             it--;
    31             ans-=it->Y;
    32         }
    33     }
    34     return ans;
    35 }
    36 void add(int index,int addition){
    37     int pre;
    38     for(int i=index;i<=n;i+=lowbit(i)){
    39         if(a[i].empty())pre=0;
    40         else pre=a[i].back().Y;
    41         a[i].push_back(make_pair(times,pre+addition));
    42     }
    43 }
    44 int main(void){
    45     scanf("%d%d",&n,&q);
    46     while(q--){
    47         scanf("%d",&type);
    48         if(type==1){
    49             times++;
    50             int i,x;
    51             scanf("%d%d",&i,&x);
    52             add(i^c,x);
    53             arr[i^c]+=x;
    54             c=arr[i^c];
    55         }else if(type==2){
    56             int l,r,t;
    57             scanf("%d%d%d",&l,&r,&t);
    58             c=query(l^c,r^c,t);
    59             printf("%d
    ",c);
    60         }
    61     }
    62 }
  • 相关阅读:
    Linux Shell编程 sort、wc命令
    Linux Shell编程 sed命令
    Linux Shell编程 awk命令
    Linux Shell编程 cut、print命令
    Linux Shell基础 环境变量配置文件
    Linux Shell基础 read命令
    Linux Shell基础 位置参数变量、预定义变量
    MS DOS 命令大全
    sublime 快捷键
    滚动到页面底部继续加载页面其他内容
  • 原文地址:https://www.cnblogs.com/barrier/p/5847139.html
Copyright © 2011-2022 走看看