Professor GukiZ doesn't accept string as they are. He likes to swap some letters in string to obtain a new one.
GukiZ has strings a, b, and c. He wants to obtain stringk by swapping some letters in a, so that k should contain as many non-overlapping substrings equal either tob or c as possible. Substring of stringx is a string formed by consecutive segment of characters fromx. Two substrings of string x overlap if there is position i in stringx occupied by both of them.
GukiZ was disappointed because none of his students managed to solve the problem. Can you help them and find one of possible stringsk?
The first line contains string a, the second line contains stringb, and the third line contains string c (1 ≤ |a|, |b|, |c| ≤ 105, where|s| denotes the length of string s).
All three strings consist only of lowercase English letters.
It is possible that b and c coincide.
Find one of possible strings k, as described in the problem statement. If there are multiple possible answers, print any of them.
aaa a b
aaa
pozdravstaklenidodiri niste dobri
nisteaadddiiklooprrvz
abbbaaccca ab aca
ababacabcc
In the third sample, this optimal solutions has three non-overlaping substrings equal to eitherb or c on positions1 – 2 (ab), 3 – 4 (ab), 5 – 7 (aca). In this sample, there exist many other optimal solutions, one of them would beacaababbcc.
解析:先根据b中所含字母数算出a中最多能含有的b的数量,然后再枚举b的数量,贪心求出结果最大的情况。
AC代码:
#include <bits/stdc++.h>
using namespace std;
int ta[30], tb[30], tc[30];
int main(){
#ifdef sxk
freopen("in.txt", "r", stdin);
#endif // sxk
string a, b, c;
while(cin>>a>>b>>c){
memset(ta, 0, sizeof(ta));
memset(tb, 0, sizeof(tb));
memset(tc, 0, sizeof(tc));
for(int i=0; i<a.size(); i++) ta[ a[i] - 'a' ] ++;
for(int i=0; i<b.size(); i++) tb[ b[i] - 'a' ] ++;
for(int i=0; i<c.size(); i++) tc[ c[i] - 'a' ] ++;
int ans = 123456789;
for(int i=0; i<26; i++)
if(tb[i]) ans = min(ans, ta[i] / tb[i]);
int ansb = 0, ansc = 0;
for(int i=0; i<=ans; i++){
int cnt = 123456789;
for(int j=0; j<26; j++)
if(tc[j]) cnt = min(cnt, (ta[j] - tb[j] * i) / tc[j]);
if(i + cnt > ansb + ansc){
ansb = i;
ansc = cnt;
}
}
for(int i=0; i<ansb; i++) cout<<b;
for(int i=0; i<ansc; i++) cout<<c;
for(int i=0; i<26; i++)
for(int j=0; j<ta[i] - tb[i] * ansb - tc[i] * ansc; j++){
printf("%c", i + 'a');
}
puts("");
}
return 0;
}