HDU-4288 Coder 线段树

来源:互联网 发布:淘宝推广招聘要求 编辑:程序博客网 时间:2024/06/05 09:23

题目链接


题目大意:给你一个有序集合,给你n个坐标进行插入,删除,求最终所有下标摸为3的数和;



#include<stdio.h>#include<iostream>#include<string>#include<string.h>#include<math.h>#include<functional>#include<algorithm>#include<vector>#include<queue>using namespace std;const int maxn = 100005;const int inf = 1<<30;//0x7f;typedef __int64 LL;int n,q,tot;int pos,val;struct node{int cnt;LL sum[5];//sum[i]表示子树中模为i的所以数之和}tree[maxn<<2];int data[maxn],tmp[maxn];char ope[maxn][10];void buildtree( int root,int ld,int rd ){tree[root].cnt = 0;for( int i = 0; i < 5; i ++ )tree[root].sum[i] = 0;if( ld < rd ){int mid = (ld+rd)>>1;buildtree( root<<1,ld,mid );buildtree( root<<1|1,mid+1,rd );}}void pushup( int root ){for( int i = 0; i < 5; i ++ )tree[root].sum[i] = tree[root<<1].sum[i] + tree[root<<1|1].sum[((i-tree[root<<1].cnt)%5+5)%5];    //***}void updata( int root,int ld,int rd,int op ){tree[root].cnt += op;if( ld == rd ){tree[root].sum[0] += val;return;}int mid = (ld+rd)>>1;if( pos <= mid )updata( root<<1,ld,mid,op );elseupdata( root<<1|1,mid+1,rd,op );pushup(root);}int main(){#ifndef ONLINE_JUDGE    freopen("data.txt","r",stdin);#endifwhile( scanf("%d",&n) != EOF ){tot = 0;for( int i = 0; i < n; i ++ ){scanf("%s",&ope[i]);if( ope[i][0] != 's' ){scanf("%d",&data[i]);tmp[tot++] = data[i];}}sort( tmp,tmp+tot );              //排序tot = unique( tmp,tmp+tot ) - tmp;//去重buildtree( 1,1,tot );for( int i = 0; i < n; i ++ ){val = data[i];pos = lower_bound( tmp,tmp+tot,data[i] ) - tmp;if( ope[i][0] == 'a' )updata(1,1,tot,1);else if( ope[i][0] == 'd' )val *= -1,updata(1,1,tot,-1);else  printf("%I64d\n",tree[1].sum[2]);}}    return 0;}



网上找的暴力解:

#include <iostream>#include <cstdio>#include <string.h>#include <vector>#include <algorithm>using namespace std;int n;char str[5];vector<int> num;vector<int>::iterator it;int main(){    while(scanf("%d",&n)!=EOF)    {        num.clear();        for(int i=0;i<n;i++)        {            scanf("%s",str);            if(str[0]=='a')            {                int temp;                scanf("%d",&temp);                it=lower_bound(num.begin(),num.end(),temp);                num.insert(it,temp);            }            else if(str[0]=='d')            {                int temp;                scanf("%d",&temp);                it=lower_bound(num.begin(),num.end(),temp);                num.erase(it);            }            else            {                __int64 ans=0;                for(int i=2;i<num.size();i+=5)                {                    ans+=num[i];                }                printf("%I64d\n",ans);            }        }    }return 0;}


0 0
原创粉丝点击