Codeforces 1080B. Margarite and the best present

我们先计算从l到r共有多少个数,如果是偶数个,那么答案就是flag*(r-l+1)/2,flag为1或-1,取决于l的奇偶性;如果是奇数个,就把第一个数拿出来单独考虑,后面的就又是偶数个了。

#include <bits/stdc++.h>
using namespace std;
int q,l,r,num,m;
int main(){
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	//freopen("data.in","r",stdin);
	//freopen("data.out","w",stdout);
	cin>>q;
	while(q--){
		cin>>l>>r;
		if(l==r){
			cout<<l*(l&1?-1:1)<<endl;
			continue;
		}
		num = (r-l+1)>>1;
		m = (r-l+1)%2;
		if(!m){
			if(l&1){
				cout<<num<<endl;
			}
			else {
				cout<<num*(-1)<<endl;
			}
		}
		else {
			if(l&1){
				cout<<l*(-1)-num<<endl;
			}
			else {
				cout<<l+num<<endl;
			}
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/winhcc/article/details/84453161