https://codeforces.com/contest/1138/problem/D
看了半天,才发现要用kmp,不过kmp一个多月前学会了就没用过,都不会写了,又复习了一遍。
思路:利用kmp的next数组,可以知道按最长前缀后缀一样的长度来输出,最后再补上剩下的,没什么难的,就是南想到kmp
#include <bits/stdc++.h>
#define fi first
#define se second
#define INF 0x3f3f3f3f
#define ll long long
#define mem(ar,num) memset(ar,num,sizeof(ar))
#define me(ar) memset(ar,0,sizeof(ar))
#define lowbit(x) (x&(-x))
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define DEBUG cout<<endl<<"DEBUG"<<endl;
using namespace std;
typedef pair<int, int> pii;
const int maxn = 3e5 + 200;
string s, b;
int cnt0, cnt1, net[1000010];
void getnetval(string p) {
int i = 1, j = 0;
net[0] = -1;
while(i < p.size()) {
if(j == -1 || p[i] == p[j]) {
++i, ++j;
net[i] = j;
} else
j = net[j];
}
}
int KmpSearch(char* s, char* p) {
int i = 0, j = 0;
int sLen = strlen(s);
int pLen = strlen(p);
while (i < sLen && j < pLen) {
if (j == -1 || s[i] == p[j])
i++, j++;
else
j = net[j];
}
return j == pLen ? i - j : -1;
}
int main() {
cin >> s >> b;
getnetval(b);
for (int i = 0; i < s.size(); i++) {
if (s[i] == '0')
cnt0++;
else
cnt1++;
}
int l = net[b.size()];
int flag = 0;
for (int i = 0; i < l; i++) {
if (b[i] == '0' && cnt0 > 0) {
cout << 0;
cnt0--;
} else if (b[i] == '1' && cnt1 > 0) {
cout << 1;
cnt1--;
} else {
flag = 1;
break;
}
}
if (!flag)
while (cnt0 > 0 || cnt1 > 0) {
flag = 0;
for (int i = l; i < b.size(); i++) {
if (b[i] == '0' && cnt0 > 0) {
cout << 0;
cnt0--;
} else if (b[i] == '1' && cnt1 > 0) {
cout << 1;
cnt1--;
} else {
flag = 1;
break;
}
}
if (flag)
break;
}
for (int i = 0; i < cnt0; i++)
cout << 0;
for (int i = 0; i < cnt1; i++)
cout << 1;
return 0;
}