蓝桥杯 123 二分+打表
生活随笔
收集整理的這篇文章主要介紹了
蓝桥杯 123 二分+打表
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
參考代碼:
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll temp[1500000], sum[1500000]; //temp數(shù)組記錄序號(hào)和,sum數(shù)組記錄前綴和 ll cal(ll n) //計(jì)算自然數(shù)求和 {return (n+1)*n/2; }int main() {ios::sync_with_stdio(false); ll index = 1;ll endL;while(1) //打表法 {temp[index] = temp[index-1] + index;sum[index] = sum[index-1] + temp[index];if(temp[index] > 1e12) //當(dāng)序號(hào)和大于上限時(shí)退出 {endL = index; //記錄序號(hào)和退出時(shí)的下標(biāo),便于二分查找確立邊界 break; }index++;}ll T;cin >> T;ll l, r, res;for(ll i = 0; i < T; i++){cin >> l >> r;ll leftL = lower_bound(temp, temp+endL, l) - temp; //lower_bound二分法查找 ll rightL = lower_bound(temp, temp+endL, r) - temp;res = sum[rightL-1] - sum[leftL-1]; //首先得到兩個(gè)大段差 res -= cal(l-temp[leftL-1]-1); //其次減去左邊界到上個(gè)大段結(jié)束點(diǎn)之間的前綴和 res += cal(r-temp[rightL-1]); //最后加上右邊界到上個(gè)大段結(jié)束點(diǎn)之間的前綴和 cout << res << endl;}return 0; }總結(jié)
以上是生活随笔為你收集整理的蓝桥杯 123 二分+打表的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 减肥三餐食谱
- 下一篇: 蓝桥杯 k倍区间 前缀和