【Greedy】Codeforces Round #480 (Div. 2) C. Posterized

The meaning of the question: Let you arbitrarily divide the sequence [0,255] into some non-overlapping sub-segments, and the size of each sub-segment does not exceed K. Give you n numbers up to 255, and let you replace each number with any element of the subsection it is in, so that the final lexicographical order of the sequence of n numbers is the smallest.

If p[x] represents x as the representative element, who is the last element of the interval it controls.

When reading a number a, find the nearest marked number b in front of it on the [0,255] number line. If the distance from it does not exceed K, the representative element of a is b, and then p[ b] is updated to max(p[b], a).

If the distance between b and a is greater than K, the element that controls a is recorded as c=max(a-K+1, p[b]+1), because we cannot refer to the interval that b already controls. Then update p[c] to a.

#include<cstdio>
#include<algorithm>
using namespace std;
int n,K,p[256];
bool b[256];
int main(){
	int x,t,tt;
	scanf("%d%d",&n,&K);
	for(int i=1;i<=n;++i){
		scanf("%d",&x);
		t=-1;
		for(int j=x;j>=0;--j){
			if(b[j]){
				t=j;
				break;
			}
		}
		if(t==-1){
			if(x>=K){
				b[x-K+1]=1;
				p[x-K+1]=x;
				printf("%d%c",x-K+1,i==n ? '\n' : ' ');
			}
			else{
				b[0]=1;
				p[0]=x;
				printf("0%c",i==n ? '\n' : ' ');
			}
		}
		else if(t+K-1<x){
			tt = max (x-K + 1, p [t] +1);
			b [tt] = 1;
			p [tt] = x;
			printf("%d%c",tt,i==n ? '\n' : ' ');
		}
		else{
			p[t]=max(p[t],x);
			printf("%d%c",t,i==n ? '\n' : ' ');
		}
	}
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326168497&siteId=291194637