Problem B. CLS and LCS
Claris is learning about the longest common subsequence problem.
(这里省略一段LCS的介绍,因为最长公共子序列是dp的经典问题,所以大家可以自行查询)
For homework she was given two strings A and B, both of length N and she had to determine the length of the LCS of A and B. She determined the answer to be K but lost B. Given A and K, help her find a possible value of B. It is possible that Claris may have made a mistake and no such B exists, in that case output “WRONGANSWER”(without quotes).
Input
The first line of input contains two integers N(1<= N<=2000), K(0<=K<=2000). The second line contains a string A consists of N lowercase letters.
Output
Output one line consisting of the string B of N lowercase letters, or “WRONGANSWER” if no B is valid. If there are multiple correct B output any of them.
Examples
standard input | standard output |
---|---|
3 2 cls | csl |
3 4 cls | WRONGANSWER |
Note
For the first example, another possible answer is “csy”.
- 题意 : A和B两字符串的LCS长度是k,现给定A和k,输出一个B。
- 思路 : 统计A中出现次数最少的字母,例如是a,就将B置为N个a,然后从前往后把A中不是a的字母替换B中字母,替换k-a个即可。
例如 A :acbdbaaad N = 9, K = 8.
其中c个数最少,则B = ccccccccc
K - c个数 = 7
则B = acbdbaaac。 - 代码 :
#include "bits/stdc++.h"
using namespace std;
#define mem(a,b) memset(a,b,sizeof(a))
#define fori(i,l,u) for(int i = l;i < u;i++)
#define forj(j,l,u) for(int j = l;j < u;j++)
#define F first
#define S second
#define pb push_back
#define mk make_pair
typedef long long ll;
typedef pair<int, int> pi;
typedef pair<string, int> ps;
typedef vector<int> vi;
typedef vector<string> vs;
typedef vector<pi> vpi;
const int maxn = 1e5 + 6;
int n,k;
char a[maxn],b[maxn];
int res[maxn];
void init(){
mem(res,0);
}
int main()
{
// freopen("1.txt", "r", stdin);
init();
cin>>n>>k;
fori(i, 0, n)cin>>a[i];
fori(i, 0, n){
res[a[i] - 'a'] ++;
}
int m = maxn;
int p = 0;
fori(i, 0, n){
if (res[i] != 0) {
if (m >= res[i]) {
m = res[i];
p = i;
}
}
}
char c = 'a' + p;
fori(i, 0, n) b[i] = c;
int num = 0;
fori(i, 0, n){
if (a[i] != c) {
b[i] = a[i];
num++;
if (num == k-res[p]) {
break;
}
}
}
if (num < k-res[p]) {
cout<<"WRONGANSWER"<<endl;
}
else
cout<<b<<endl;
return 0;
}
- 遇到的问题 : 一开始觉得自己技能点不够,不敢轻举妄动。这些构造类的题考验的就是思维,所以要仔细想。还是cf打得不够多啊。