B. Preparing for Merge Sort(codeforces)

B. Preparing for Merge Sort

问题:用一个或几个递增的序列表示给定的数组。给定的数组每个元素都不相同。
对于数组,必须从左往右依次取元素,添加到序列当中,如果不满足递增的元素则创建一个新的序列。
求出每个序列

举个例子 数组:[1, 3, 2, 5, 4]
组成两个序列: [1, 3, 5],[2, 4]。

这道题的解题关键在于:你得发现所有序列末尾元素为降序排列,对于添加每个元素x,我们可以在末尾组成的序列中二分搜索找到它应该在的位置(也就是第一个小于等于x的元素所在的序列,如果找不到,就新建一个序列,第一个元素就是x)
晚点补注释

#include<bits/stdc++.h>
using namespace std;
const int N = 200010;
vector<int> V[N], U;
int find_(int x) {
    
    
	if(U.size() == 0) return -1;
	int l = 0, r = U.size()-1, mid;
	while(l < r) {
    
    
		mid = l + r >> 1; 
		if(U[mid] > x) l = mid + 1;
		else r = mid;
	}
	if(U[l] > x) return -1;
	else return l;
}
int main() {
    
    
	int n, x, p, idx = 0;
	scanf("%d", &n);
	memset(V, 0, sizeof V);
	
	for(int i=0; i<n; i++) {
    
    
		scanf("%d", &x);
		p = find_(x);
		if(p == -1) {
    
    
			V[idx++].push_back(x);
			U.insert(U.end(), x);
		}
		else {
    
     
			U[p] = x;
			V[p].push_back(x);
		}
	}
	for(int i=0; i<idx; i++) {
    
    
		for(int j=0; j<V[i].size(); j++) {
    
    
			printf("%d ", V[i][j]);
		}
		printf("\n");
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_45363113/article/details/106698242