1. 程式人生 > 實用技巧 >Educational Codeforces Round 100 (Rated for Div. 2) 1463D. Pairs

Educational Codeforces Round 100 (Rated for Div. 2) 1463D. Pairs

題意:你有1~2n這2n個數,給你一個長度為n的陣列b,讓你去構造出b並且滿足條件。構造要求:對於每一組合法的b,先定義計數x=0,每次從2n個數中選一對數,取其中的一個數去對應某一個bi,若這個數為這兩個數中小的,則x++;最後讓你求構造完每一個合法的b陣列後選取的x的覆蓋範圍的大小

大概就是這個意思,原題面: https://codeforces.com/problemset/problem/1463/D

做法:考慮去計算這個覆蓋範圍的最大x與最小x之差加1作為答案。先貪心去求有多少個bi必須和一個大於它的數組合,計它為l,則n-l為x的最大值;
再去倒著貪心求有多少個數必須結合一個小於它的數,計它為r,r為x的最小值,則最終答案為n-l-r+1。

#include<bits/stdc++.h>
using namespace std;
#define ll unsigned long long
#define fastio ios::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL)
const int maxn = 1e5 + 10;

int main()
{
	fastio;
	int t;
	cin >> t;
	while (t--)
	{
		int n;
		cin >> n;
		vector<int>a(n + 2, 0);
		a[n + 1] = n * 2 + 1;
		for (int i = 1; i <= n; i++)cin >> a[i];
		sort(a.begin() + 1, a.end());
		int sum = 0;
		int l = 0, r = 0;
		for (int i = 1; i <= n; i++)
		{
			sum += a[i] - a[i - 1]-1;
			if (sum)
				sum--;
			else l++;
		}
		sum = 0;
		for (int i = n; i >= 1; i--)
		{
			sum += a[i + 1] - a[i]-1;
			if (sum)
				sum--;
			else r++;
		}
		cout << (n-l) - r + 1 << endl;
	}
	return 0;

}