14383: Prison
时间限制: 1 Sec 内存限制: 128 MB
题目描述
We have N ID cards, and there are M gates.
We can pass the i-th gate if we have one of the following ID cards: the Li-th, (Li+1)-th, …, and Ri-th ID cards.
How many of the ID cards allow us to pass all the gates alone?
Constraints
·All values in input are integers.
·1≤N≤105
·1≤M≤105
·1≤Li≤Ri≤N
输入
Input is given from Standard Input in the following format:
N M
L1 R1
L2 R2
⋮
LM RM
输出
Print the number of ID cards that allow us to pass all the gates alone.
样例输入 Copy
4 2
1 3
2 4
样例输出 Copy
2
提示
Two ID cards allow us to pass all the gates alone, as follows:
·The first ID card does not allow us to pass the second gate.
·The second ID card allows us to pass all the gates.
·The third ID card allows us to pass all the gates.
·The fourth ID card does not allow us to pass the first gate.
题目大概意思就是求M个区间的并集元素个数,
差分水题
代码如下:
#include <cstdio>
const int N = 1e5 + 10;
int a[N] = {0};
int main()
{
int n,m,cnt = 0;
scanf("%d%d",&n,&m);
int M = m;
while(m--){
int l,r;
scanf("%d%d",&l,&r);
a[l] += 1, a[r + 1] -= 1;
}
for(int i = 1; i <= n; i++){
a[i] += a[i - 1];
if(a[i] == M) cnt++;
}
printf("%d\n",cnt);
}