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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值