题目链接
题意:
给你 [ L,R ] 一个区间,区间内的元素,奇数为负,偶数为正,求出区间内的总和。
题解:
提供两种想法,第一种就是我自己做的,中规中矩。找出两个最前和最后的奇数和偶数,利用等差求和求得。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
ll Q;
scanf("%lld",&Q);
while(Q--){
ll L,R;
scanf("%lld%lld",&L,&R);
if(L==R){
if(L&1){
printf("%lld\n",-L);
}else{
printf("%lld\n",L);
}
}
else{
ll S1,S2,E1,E2,n1,n2,sum1=0,sum2=0,ans=0;
S1=L&1?L:L+1;
S2=L%2==0?L:L+1;
E1=R&1?R:R-1;
E2=R%2==0?R:R-1;
n1=(E1-S1)/2+1;
n2=(E2-S2)/2+1;
sum1=(S1+E1)*n1/2;
sum2=(S2+E2)*n2/2;
ans=sum2-sum1;
printf("%lld\n",ans);
}
}
return 0;
}
另外一种是运来哥提供的,他说是,利用第一项是否为奇偶和多少项组成二元关系,那么就有四种情况,只要仔细讨论一下就可以算出来。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
ll Q;
scanf("%lld",&Q);
while(Q--){
ll L,R;
scanf("%lld%lld",&L,&R);
if(L==R){
if(L&1){
printf("%lld\n",-L);
}else{
printf("%lld\n",L);
}
}
else{
ll cnt=(R-L+1),ans=0;
if(L&1){
if(cnt&1){
ans=-R+(cnt-1)/2;
}else{
ans=(cnt)/2;
}
}else{
if(cnt&1){
ans=R-(cnt-1)/2;
}else{
ans=-(cnt)/2;
}
}
printf("%lld\n",ans);
}
}
return 0;
}