Little girl Margarita is a big fan of competitive programming. She especially loves problems about arrays and queries on them.
Recently, she was presented with an array a
of the size of 1e9 elements that is filled as follows:
a1=−1
a2=2
a3=−3
a4=4
a5=−5
And so on …
That is, the value of the i-th element of the array a is calculated using the formula ai=i⋅(−1)i.
She immediately came up with q queries on this array. Each query is described with two numbers: l and r. The answer to a query is the sum of all the elements of the array at positions from l to r inclusive.
Margarita really wants to know the answer to each of the requests. She doesn’t want to count all this manually, but unfortunately, she couldn’t write the program that solves the problem either. She has turned to you — the best programmer.
Input
The first line contains a single integer q (1≤q≤103) — the number of the queries.
Each of the next q lines contains two integers l and r (1≤l≤r≤109) — the descriptions of the queries.
Output
Print q lines, each containing one number — the answer to the query.
用等差数列前n项和即可以O(1)的时间复杂度求出查询区间的值。
注意在计算时,若所有变量均为 int 型,则计算结果自动转换为 int 型,所以需要在可能超出 int 范围的计算式中加入强制转换(long long),或者改变其中任意变量的数据类型为long long。
#include <stdio.h>
#include <climits>
#include <cstring>
#include <math.h>
#include <iostream>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <utility>
#include <vector>
#include <string>
#define ll long long
#define re return
#define Pair pair<int,int>
#define Make(a,b) make_pair(a,b)
#define Push push_back
#define rep(index,star,finish) for(int index=star;index<finish;index++)
#define drep(index,finish,star) for(int index=finish;index>=star;index--)
using namespace std;
int len;
inline int calPow(int n);
inline ll calculate(int a1,int n,int d);
int main(){
scanf("%d",&len);
while(len--){
int fir1,fir2;
int last1,last2;
int a1,a2;
int l,r;
scanf("%d %d",&l,&r);
if(l==r){
printf("%d\n",l*calPow(l));
continue;
}
if(l%2){
fir1=l;
a1=-l;
fir2=l+1;
a2=l+1;
}else{
fir1=l+1;
a1=-(l+1);
fir2=l;
a2=l;
}
if(r%2){
last1=r;
last2=r-1;
}else{
last2=r;
last1=r-1;
}
int n1=(last1+1)/2-(1+fir1)/2+1;
int n2=last2/2-fir2/2+1;
ll sum=calculate(a1,n1,-2)+calculate(a2,n2,2);
printf("%lld\n",sum);
}
re 0;
}
inline int calPow(int n){
if(n%2) //n is odd number
re -1;
else
re 1;
}
inline ll calculate(int a1,int n,int d){
re 1LL*n*a1+(n*1LL*(n-1)*d)/2;
}