String
Problem Description
Tom has a string containing only lowercase letters. He wants to choose a subsequence of the string whose length is k and lexicographical order is the smallest. It’s simple and he solved it with ease.
But Jerry, who likes to play with Tom, tells him that if he is able to find a lexicographically smallest subsequence satisfying following 26 constraints, he will not cause Tom trouble any more.
The constraints are: the number of occurrences of the ith letter from a to z (indexed from 1 to 26) must in [Li,Ri].
Tom gets dizzy, so he asks you for help.
Input
The input contains multiple test cases. Process until the end of file.
Each test case starts with a single line containing a string S(|S|≤105)and an integer k(1≤k≤|S|).
Then 26 lines follow, each line two numbers Li,Ri(0≤Li≤Ri≤|S|).
It’s guaranteed that S consists of only lowercase letters, and ∑|S|≤3×105.
Output
Output the answer string.
If it doesn’t exist, output −1.
Sample Input
aaabbb 3
0 3
2 3
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
0 0
Sample Output
abb
思路
题目感觉还是很难读懂的,能看出来是贪心,但是get不到需要把字典序数小的字母往前面放,一开始只是单纯从小到大尽可能贪字典序数小的字母出现的数量,然后把字符串跑一遍不够就放下。后来它想要我们尽可能地把字典序数小的字母放在前面,那就需要从后往前数一下每一位字母后面有的不同字母的情况(cot[i][j]:i 表示当前是从前往后的第i位字母,j 表示的是a-z)然后经过处理之后,对k位所需的输出进行k次贪心,每一位都试一下能不能把尽可能小的字母放进去,并且开一个队列进行记录,如果最后队列里的数量少于k则说明不符合需求。
补题的时候WA了好多发都是因为循环的时候,初始用0和1的混淆产生了各种奇怪的问题,以为是我的算法有问题,所以部分地方参考了dalao的写法,最后发现问题与算法无关懒得改回来。
代码
#include<bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 1e5+5;
typedef long long ll;
char str[maxn];
int k,str_length,l[30],r[30];
int cot[maxn][30],num[maxn][30],res[30];
queue<char> ans;
int main() {
while(cin >> str+1 >> k) {
memset(cot, 0, sizeof(cot));
memset(num, 0, sizeof(num));
memset(res, 0, sizeof(num));
str_length = strlen(str+1);
for(int i=0; i<26; i++) {
cin >> l[i] >> r[i];
}
for(int i=str_length; i>=1; i--) {
for(int j=0; j<26; j++) {
num[i][j] = num[i+1][j];
cot[i][j] = cot[i+1][j] + ((str[i] - 'a')== j);
}
num[i][str[i] - 'a'] = i;
}
int cnt = 0;
for(int i=1; i<=k; i++) {
char sta='a';
bool flag1 = false;
for(int j=0; j<26; j++) {
if(!cot[cnt+1][j]) {
continue;
}
if(res[j] >= r[j]) {
continue;
}
res[j]++;
int need = 0;
int nxt;
nxt = num[cnt+1][j];
for(int m=0; m<26; m++) {
if(l[m] > res[m]) {
need += l[m] - res[m];
}
}
if(k-i < need || k-i > str_length - nxt) {
res[j]--;
continue;
}
bool flag2 = false;
for(int m=0; m<26; m++) {
if(cot[nxt][m] + res[m] < l[m]) {
flag2 = true;
break;
}
}
if(!flag2) {
sta += j;
flag1 = true;
break;
}
res[j]--;
}
if(!flag1) {
break;
}
cnt = num[cnt+1][sta - 'a'];
ans.push(sta);
}
if(ans.size() < k) {
puts("-1");
while(!ans.empty()) {
ans.pop();
}
}
else {
while(!ans.empty()) {
cout << ans.front();
ans.pop();
}
puts("");
}
}
}