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 <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <stack>
#include <map>
#include <unordered_map>
#include <queue>
#include <vector>
#include <set> 
#include <algorithm>
#include <iomanip>
#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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章