B. Draw! (思维 贪心)

B. Draw!

You still have partial information about the score during the historic football match. You are given a set of pairs (ai,bi), indicating that at some point during the match the score was “ai: bi”. It is known that if the current score is «x:y», then after the goal it will change to “x+1:y” or “x:y+1”. What is the largest number of times a draw could appear on the scoreboard?

The pairs “ai:bi” are given in chronological order (time increases), but you are given score only for some moments of time. The last pair corresponds to the end of the match.

Input

The first line contains a single integer n (1≤n≤10000) — the number of known moments in the match.

Each of the next n lines contains integers ai and bi (0≤ai,bi≤109), denoting the score of the match at that moment (that is, the number of goals by the first team and the number of goals by the second team).

All moments are given in chronological order, that is, sequences xi and yj are non-decreasing. The last score denotes the final result of the match.

Output

Print the maximum number of moments of time, during which the score was a draw. The starting moment of the match (with a score 0:0) is also counted.

Examples

inputCopy
3
2 0
3 1
3 4
outputCopy
2
inputCopy
3
0 0
0 0
0 0
outputCopy
1
inputCopy
1
5 4
outputCopy
5

Hint

In the example one of the possible score sequences leading to the maximum number of draws is as follows: 0:0, 1:0, 2:0, 2:1, 3:1, 3:2, 3:3, 3:4.




题意:

在一场比赛中, 初始比分为0:0, 给出若干过程中的比分, 求出最大的可能出现平局的次数(注意比赛时比分的变化规律)

题解:

先看数据规模, 枚举肯定是不行了, 先列几组数找规律吧 !
2:1 -> 5:4, 1:2 -> 5:4, 2:2 -> 5:4
我们定义ca, cb为当前分数, 可以找到规律 ans += min(a[i], b[i]) - max(ca, cb)+1
然后还有一些特殊情况我们考虑一下

  1. 由于min(a[i], b[i]) 可能小于 max(ca, cb), 所以要与0比较
  2. 像例2中多个相同的比分我们过滤一下
  3. 如果当前比分相同, 可能会存在重复计算, 要减去
  4. 记得开long long
    其实这道题比赛时候也写出来关系式了…忘了细节, 结果炸了…所以一定要细心

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
#define ms(x, n) memset(x,n,sizeof(x));
typedef  long long LL;
const LL maxn = 1e4+10;

int n, a[maxn], b[maxn];
int main()
{
    cin >> n;
    a[0] = b[0] = 1<<30;
    for(int i = 1; i <= n; i++){
        cin >> a[i] >> b[i];
        if(a[i]==a[i-1] && b[i]==b[i-1])
            i--, n--;
    }

    LL ans = 1, ca = 0, cb = 0;
    for(int i = 1; i <= n; i++){
        ans += max(0LL, min(a[i], b[i]) - max(ca, cb)+1);
        if(ca == cb) ans--;
        ca = a[i];
        cb = b[i];
    }
    cout << ans << endl;

	return 0;
}

猜你喜欢

转载自blog.csdn.net/a1097304791/article/details/87920260