Minimum Integer sequence
问题描述 :
Now we have two integers A and B, after insert B into A, we can get a new integer C, and then the problem comes: how to get a smallest C? For example, let A = 345, B = 478. As there are there digits in A, so there are four places for B to insert into. We can get 478345, 347845, 344785, 345478.After comparing, we could know that the smallest C is 344785.
输入:
There are multiple test cases. Each test case takes one line, Each line contents two integers A and B(there will be less than 100000 digits in A and B and there is no digit values 0 in A and B), the two integers are separated by a space, process to the end of file.
输出:
There are multiple test cases. Each test case takes one line, Each line contents two integers A and B(there will be less than 100000 digits in A and B and there is no digit values 0 in A and B), the two integers are separated by a space, process to the end of file.
样例输入:
345 478
12345 678
123 123
样例输出:
344785
12345678
112323
参考https://vjudge.net/solution/2446097 用的是exkmp
也有用hash 的 https://vjudge.net/solution/2352588
下面代码是错的。
#include<algorithm>
#include<vector>
#include<cstring>
#include<string>
#include<iomanip>
#include<cstdio>
#include<stack>
#include<iostream>
#include<map>
#include<queue>
#include<cmath>
#include<strstream>
using namespace std;
#define sf scanf
#define pf printf
#define mem(a,b) memset(a,b,sizeof(a));
#define rep(i,a,b) for(int i=(a);i<=(b);++i)
#define MP make_pair
#define N 3030
#define M 200020
#define mod 998244353
#define ULL unsigned long long
#define LL long long
#define inf 0x3f3f3f3f
//freopen("in.txt","r",stdin);
char num1[N],num2[N];
int ex[N],nxt[N];
int ls1,ls2;
void exkmp(char s1[],char s2[],int nxt[],int ex[]){
int i,j,p;
for(i=0,j=0,p=-1;s1[i]!='\0';++i,++j,--p){
if(p==-1){
j=0;
do p++;
while(s1[i+p]!='\0'&&s1[i+p]==s2[i+p]);
ex[i]=p;
}
else if(nxt[j]<p){
ex[i]=nxt[j];
}
else if(nxt[j]>p){
ex[i]=p;
}
else{
j=0;
while(s1[i+p]!='\0'&&s1[i+p]==s2[i+p])p++;
ex[i]=p;
}
}
}
//看不懂。。。
bool smallerthan(int i,int j){
if(ex[j]<i-j)return num1[ex[j]+j]<num2[ex[j]];
if(nxt[i-j]<ls2-(i-j)){ return num2[nxt[i-j]]<num2[i-j+nxt[i-j]];}
if(nxt[ls2-(i-j)]<(i-j))return num2[ls2-(i-j)+nxt[ls2-(i-j)]]<num2[nxt[ls2-(i-j)]];
return false;
}
int main(){
while(~sf("%s%s",num1,num2)){
exkmp(num2+1,num2,nxt,nxt+1);
exkmp(num1,num2,nxt,ex);
ls1=strlen(num1);
ls2=strlen(num2);
int ans=0;
for(int i=0;i<ls1;++i){
if(smallerthan(i+1,ans))ans=i+1;
}
for(int i=0;i<ans;++i)pf("%c",num1[i]);
pf("%s",num2);
for(int i=ans;i<ls1;++i)pf("%c",num1[i]);
puts("");
}
}