给定长度为n(1e6)的数组a和b,可以进行任意次操作:选取l,r, 令m = max(a[l], a[l+1],...,a[r]), 则a[i] = m, l <= i <= r, 判断a能否变为b

题目

思路:若a[i] != b[i], 那么一定得一个包含i的区间进行操作,显然选离i最近的满足a[j] == b[i]的j,即选区间[i, j] 或 [j, i], 设maxa为该区间a的最大值,minb为该区间b的最小值,那么可以进行操作的必要条件是maxa <= a[j] && minb >= a[j](如果a[j]不是区间最大值,那么就取不到a[j]的值;如果该区间有一个b[k] < a[j],那么操作之后,a[k] > b[k],a[k]就永远不会等于b[k], 因为每次操作只会增大a[i]的值,不会减小)

#include 
using namespace std;
#define int long long
#define pb push_back
#define lson p << 1
#define rson p << 1 | 1
const int maxn = 2e5 + 5, maxm = 2e3 + 5;
int a[maxn], b[maxn];
int n;
int dx[8];
int dy[8];
vector vec[maxn];
set S[maxn];
int maxx[25][maxn], min2[25][maxn];
int ask(int l, int r){
	int k = __lg(r - l + 1);
	return max(maxx[k][l], maxx[k][r - (1LL << k) + 1]);
}
int ask2(int l, int r){
	int k = __lg(r - l + 1);
	return min(min2[k][l], min2[k][r - (1LL << k) + 1]);
}
void solve()
{
	cin >> n;
	// int k;
	// cin >> k;
	for(int i = 1; i <= n; i++){
		cin >> a[i];
		maxx[0][i] = a[i];
		vec[i].clear();
		S[i].clear();
	}
	for(int i = 1; i <= n; i++){
		S[a[i]].insert(i);
	}
	for(int i = 1; i <= 20; i++){
		for(int j = 1; j <= n; j++){
			if(j + (1LL << i) - 1 > n) break;
			int t = j + (1LL << (i - 1));
			maxx[i][j] = max(maxx[i - 1][j], maxx[i - 1][t]);
		}
	}
	for(int i = 1; i <= n; i++){
		cin >> b[i];
		min2[0][i] = b[i];
		if(a[i] != b[i]) vec[b[i]].pb(i);
		if(a[i] > b[i]){
			cout << "No\n";
			return;
		}
	}
	for(int i = 1; i <= 20; i++){
		for(int j = 1; j <= n; j++){
			if(j + (1LL << i) - 1 > n) break;
			int t = j + (1LL << (i - 1));
			min2[i][j] = min(min2[i - 1][j], min2[i - 1][t]);
		}
	}
	for(int i = 1; i <= n; i++){
		// for(auto x : vec[i]){
		// 	cout << x << " \n"[x == vec[i].back()];
		// }
		if(vec[i].empty()) continue;
		for(auto x : vec[i]){
			int l = 0, r = 0;
			bool flag = 1, tag = 0;
			auto it = S[i].lower_bound(x);
			if(it != S[i].end()){
				int pos = *it;
				int maxa = ask(x, pos);
				int minb = ask2(x, pos);
				if(!(maxa <= i && minb >= i)){
					flag = 0;
				}
				// cout << i << ' ' << x << ' ' << pos << ' ' << maxa << ' ' << minb << ' ' << flag << '\n';
			}
			else flag = 0;
			if(!flag){
				if(it == S[i].begin()){
					cout << "No\n";
					return;
				}
				else{
					it--;
					int pos = *it;
					int maxa = ask(pos, x);
					int minb = ask2(pos, x);
					if(!(maxa <= i && minb >= i)){
						cout << "No\n";
						return;
					}
				}
			}
		}		
	}
	cout << "Yes\n";
}
signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	int T = 1;
	cin >> T;
	while (T--)
	{
		solve();
	}
}
/*
1
4
2 4 8 12
*/

你可能感兴趣的:(codeforces,算法)