Educational Codeforces Round 89 B. Shuffle

题目描述

You are given an array consisting of n integers a1, a2, …, an. Initially ax=1, all other elements are equal to 0.
You have to perform m operations. During the i-th operation, you choose two indices c and d such that li≤c,d≤ri, and swap ac and ad.
Calculate the number of indices k such that it is possible to choose the operations so that ak=1 in the end.

Input

The first line contains a single integer t (1≤t≤100) — the number of test cases. Then the description of t testcases follow.
The first line of each test case contains three integers n, x and m (1≤n≤109; 1≤m≤100; 1≤x≤n).
Each of next m lines contains the descriptions of the operations; the i-th line contains two integers li and ri (1≤li≤ri≤n).

Output

For each test case print one integer — the number of indices k such that it is possible to choose the operations so that ak=1 in the end.

Example

input
3
6 4 3
1 6
2 3
5 5
4 1 2
2 4
1 2
3 3 2
2 3
1 2
output
6
2
3

Note

In the first test case, it is possible to achieve ak=1 for every k. To do so, you may use the following operations:
1.swap ak and a4;
2.swap a2 and a2;
3.swap a5 and a5.
In the second test case, only k=1 and k=2 are possible answers. To achieve a1=1, you have to swap a1 and a1 during the second operation. To achieve a2=1, you have to swap a1 and a2 during the second operation.

题目大意

有n个数,a[1]-a[n],其中a[x]为1,其余的都为0。我们可以进行m次操作,每次操作可以选择两个数c,d(l[i]<=c,d<=r[i]),然后交换a[c]和a[d]两个数。
问经过这m次操作,a[]中有多少数可能会变成1.

题目分析

c=d时,也可以进行交换。因此,只要1在任何一步中到达某个位置,该位置的值在最后都可能是1。所以,这个题就变成了求1通过m次的操作可以到达那些位置。
设 1的范围为[a,b] (一开始 a=b=x)。
当一次的操作区间 [l,r] 与1的范围 [a,b] 没有交集时,1就不能通过交换到达这个区间。因此1的范围不变。
当一次的操作区间 [l,r] 与1的范围 [a,b] 有交集时,1可以交换到该区间上,因此1的范围更新为 [min(l,a) , max(r,b)]。
最后,答案就是这个区级中数的个数,即b-a+1

代码如下
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include  
#include 
#include 
#define LL long long
using namespace std;
const int N=55;
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		int n,m,x;
		scanf("%d%d%d",&n,&x,&m);
		int a=x,b=x;                 //初始化区间[a,b]
		for(int i=1;i<=m;i++)
		{
			int l,r;
			scanf("%d%d",&l,&r);
			if(l>b||a>r) continue;   //如果两区间没有交集,则继续下一次操作
			a=min(a,l);              //否则跟新a,b的值。
			b=max(b,r);
		}
		cout<<b-a+1<<endl;
	}
	return 0;
}

你可能感兴趣的:(Codeforces)