zoukankan      html  css  js  c++  java
  • hdu1166树状数组

    这道题做了很多次了,从上个学期第一次见到,就想着用暴力模拟的方法去做。。。超时。。。暑假的时候学会了线段树,又做了几次。。。超时。。。。这次终于开始研究树状数组了。。不过前几次也是超时,最后把cin,改成了scanf才水过。。。。。

    传送门:敌兵布阵

    #include <iostream>
    #include <string>
    #include <vector>//本来是想顺便练习下STL,才使用的vector。不过最后也没有用到vector的特性。。。和一般数组处理方法无二。。囧。
    using namespace std;
    #define K(x) ((x)&(-x))
    int main()
    {
    	int t;
    	scanf("%d",&t);
    	for(int c=1;c<=t;c++)
    	{
    		cout<<"Case "<<c<<":"<<endl;
    		vector<int> tree(50005,0);
    		int n;
    		scanf("%d",&n);
    		int tem;
    		for(int i=1;i<=n;i++)
    		{
    			scanf("%d",&tem);
    			tree[i]+=tem;
    			if(i+K(i)<=n)
    				tree[i+K(i)]+=tree[i];
    		}
    		string ins;
    		int i,t;
    		while(cin>>ins&&ins!="End")
    		{
    			scanf("%d%d",&i,&t);
    			if(ins=="Query")
    			{
    				int x=0,answer=0;
    				i--;
    				while(i>0)
    				{
    					x+=tree[i];
    					i-=K(i);
    				}
    				while(t>0)
    				{
    					answer+=tree[t];
    					t-=K(t);
    				}
    				answer-=x;
    				cout<<answer<<endl;
    			}
    			else if(ins=="Add")
    			{
    				while(i<=n)
    				{
    					tree[i]+=t;
    					i+=K(i);
    				}
    			}
    			else if(ins=="Sub")
    			{
    				while(i<=n)
    				{
    					tree[i]-=t;
    					i+=K(i);
    				}
    			}
    		}
    		tree.clear();
    	}
    	return 0;
    }


     

  • 相关阅读:
    MySQL数据库分页
    Spring MVC
    Spring框架
    Java学习计划(转载)
    开发用户注册模块
    Ajax技术
    Jodd Email 发送邮件
    DOM技术
    MD5加密
    final关键字的使用
  • 原文地址:https://www.cnblogs.com/unclejelly/p/4082124.html
Copyright © 2011-2022 走看看