Codeforces 1080B - Margarite and the best present

140 篇文章 0 订阅
80 篇文章 0 订阅

Codeforces 1080B - Margarite and the best present

题解链接

https://lucien.ink


题目链接

https://codeforces.com/contest/1080/problem/B


题目

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 a a of the size of 1 0 9 10^9 109 elements that is filled as follows:

  • a 1 = − 1 a_1 = -1 a1=1
  • a 2 = 2 a_2 = 2 a2=2
  • a 3 = − 3 a_3 = -3 a3=3
  • a 4 = 4 a_4 = 4 a4=4
  • a 5 = − 5 a_5 = -5 a5=5
  • And so on …

That is, the value of the i i i-th element of the array a a a is calculated using the formula a i = i ⋅ ( − 1 ) i a_i = i \cdot (-1)^i ai=i(1)i.

She immediately came up with q q q queries on this array. Each query is described with two numbers: l l l and r r r. The answer to a query is the sum of all the elements of the array at positions from l l l to r r 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.

Help her find the answers!


题意

  给你 q q q 次询问,每次询问一个区间 [ l , r ] [l, r] [l,r],输出 ∑ i = l r i ⋅ ( − 1 ) i \sum_{i = l}^{r}i \cdot (-1)^i i=lri(1)i


思路

  用两次等差数列求和公式,注意边界即可,单次询问复杂度为 O ( 1 ) O(1) O(1)


实现

https://pasteme.cn/2337

#include <bits/stdc++.h>
typedef long long ll;
ll calc(ll l, ll r) {
    return (r + l) / 2 * ((r - l) / 2 + 1);
}
int main() {
    int _, l, r;
    for (scanf("%d", &_); _; _--) {
        scanf("%d%d", &l, &r);
        ll ans = calc(l + (l & 1), r - (r & 1));
        ans -= calc(l | 1, r - (r % 2 == 0));
        printf("%lld\n", ans);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值