Codeforces Round #431 (Div. 2) C.From Y to Y
题目原文
From beginning till end, this message has been waiting to be conveyed.
For a given unordered multiset of n lowercase English letters ("multi" means that a letter may appear more than once), we treat all letters as strings of length 1, and repeat the following operation n - 1 times:
Remove any two elements s and t from the set, and add their concatenation s + t to the set.
The cost of such operation is defined to be , where f(s, c) denotes the number of times character c appears in string s.
Given a non-negative integer k, construct any valid non-empty set of no more than 100 000 letters, such that the minimum accumulative cost of the whole process is exactly k. It can be shown that a solution always exists.
Input
The first and only line of input contains a non-negative integer k (0 ≤ k ≤ 100 000) — the required minimum cost.
Output
Output a non-empty string of no more than 100 000 lowercase English letters — any multiset satisfying the requirements, concatenated to be a string.
Note that the printed string doesn't need to be the final concatenated string. It only needs to represent an unordered multiset of letters.
Examples
input
12
output
abababab
input
3
output
codeforces
Note
For the multiset {'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b'}, one of the ways to complete the process is as follows:
{"ab", "a", "b", "a", "b", "a", "b"}, with a cost of 0;
{"aba", "b", "a", "b", "a", "b"}, with a cost of 1;
{"abab", "a", "b", "a", "b"}, with a cost of 1;
{"abab", "ab", "a", "b"}, with a cost of 0;
{"abab", "aba", "b"}, with a cost of 1;
{"abab", "abab"}, with a cost of 1;
{"abababab"}, with a cost of 8.
The total cost is 12, and it can be proved to be the minimum cost of the process.
题目大意
很明显是构造题,输出一个长度不超过10W的字符串。这个字符串通过n-1次操作而来,操作规则就是从你选定的字符串集合里面选2个元素,将它们合并,然后再放回集合,代价就是所选的两个字符串里面公共的字母出现次数相乘的总和,最后求代价总和为k的字符串。
思路
其实当相同的字母互相连接的时候代价增长是最快的,有n个相同的字符产生的代价是(n-1)*n/2,所以做法就是假定初始字符为‘a’,找到一个最大的i使得(i-1)*i/2<=k,然后打印i个字符并让k=k-(i-1)*i/2,然后‘a’变成‘b’,重复这个过程,直到k=0。
代码
#include<bits/stdc++.h>
using namespace std;
string s;
char ch;
int a[1005];
void f(int k){
for (int i=1;i<=k;i++){
s=s+ch;
}
ch++;
return ;
}
int main(){
int k;
for (int i=1;i<=1000;i++){
a[i]=(i-1)*i/2;
}
cin>>k;
if (k==0) cout<<"a";
else{
s="";
ch='a';
while (k!=0){
int ans=lower_bound(a+1,a+1000+1,k)-a;
if (a[ans]==k){
f(ans); //打cf的时候这里写成了f(a[ans]),导致我这题没过,后来时间到了发现错了改掉秒过,绝了
break;
}
else{
ans--;
f(ans);
k=k-a[ans];
}
}
cout<<s;
}
return 0;
}
浙公网安备 33010602011771号