各类模板

快速幂

 1 typedef long long ll;
 2 
 3 ll mod_pow(ll x,ll n,ll mod)
 4 {
 5     ll res=1;
 6     while(n>0)
 7     {
 8         if(n&1)//if(n%2==1)
 9             res=res*x%mod;
10         x=x*x%mod;//把x平方
11         n>>=1;//n=n/2 舍去最后一位
12     }
13     return res;
14 }
View Code

树状数组

查询区间和

引申:查询区间最值差

 1 int lowbit(int x)//lowbit(x)表示2^k
 2 {
 3     return x&(-x);
 4 }
 5 
 6 void update(int x,int k)//在位置x增加k
 7 {
 8     while(x<=n)
 9     {
10         c[x]+=k;
11         x+=lowbit(x);
12     }
13 }
14 
15 int sum(int x)
16 {
17     int res=0;
18     while(x>0)
19     {
20         res+=c[x];
21         x-=lowbit(x);
22     }
23     return res;
24 }
25 
26 memset(c,0,sizeof(c));//输入记得清空
27 
28 for(int i=1; i<=n; i++)//树状数组处理的是下标为1的数组
29 {
30     scanf("%d",&a[i]);
31     update(i,a[i]);//开始的时候每个元素初始值为0,对应位置加a[i]即可
32 }
View Code

猜你喜欢

转载自www.cnblogs.com/OFSHK/p/11518428.html