Codeforces 1080B - Margarite and the best present

版权声明:来自https://lucien.ink,转载请注明文章出处。 https://blog.csdn.net/xs18952904/article/details/84901385

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 aa of the size of 10910^9 elements that is filled as follows:

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

That is, the value of the ii-th element of the array aa is calculated using the formula ai=i(1)ia_i = i \cdot (-1)^i.

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


题意

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


思路

  用两次等差数列求和公式,注意边界即可,单次询问复杂度为 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;
}

没有更多推荐了,返回首页