D Magic Multiplication
链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=5818
题意
有两个数 A 与 B ,这两个数每位数相乘除去前导0可以得到一个串,现在给你数A的位数n,与数B的位数m
是否能通过此串还原A与B 若答案存在多个输出他们中最小的B
思路
枚举A的第一位,用去推出B,再用B回推A,看A是否成立
例如样例
2 2
8101215
当暴力找到A的第一个数字为2时,即A[0]=2;
那么我们可以通过 s[0]=8 推出B[0]=4,继续判断下一位,我们发现s[1]=1,1<2 通过9*9乘法表,我们无法得出一位整数,我们还需继续向下要一位,那么这个数变成了10 B[1]=10/2。那么我们已经得到了B=45
接下来我们需要用B去还原A
s[3]=1,1<4同理,我们需要继续向下一位,这个数变成了12那么我们A[1]=12/B[0]=12/4=3;这样我们即得出了A,又得到了B,那么我们需要用 ai * bj去验证 s中的数是否成立
A[1]*B[1]=15并且s数组也到了最后一个,所以此答案成立并且输出
代码比较丑,随便看看
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<queue>
#include<climits>
#include<set>
#include<map>
#define ll long long
using namespace std;
const int maxn = 2e5+10;
/**********************************************Head-----Template****************************************/
bool Finish_read;
template<class T>inline void read(T &x){Finish_read=0;x=0;int f=1;char ch=getchar();while(!isdigit(ch)){if(ch=='-')f=-1;if(ch==EOF)return;ch=getchar();}while(isdigit(ch))x=x*10+ch-'0',ch=getchar();x*=f;Finish_read=1;}
template<class T>inline void print(T x){if(x/10!=0)print(x/10);putchar(x%10+'0');}
template<class T>inline void writeln(T x){if(x<0)putchar('-');x=abs(x);print(x);putchar('\n');}
template<class T>inline void write(T x){if(x<0)putchar('-');x=abs(x);print(x);}
ll gcd(ll a,ll b){return b==0?a:gcd(b,a%b);}
ll lcm(ll a,ll b){ll gg=gcd(a,b);a/=gg;if(a<=LLONG_MAX/b) return a*b;return LLONG_MAX;}
/********************************Head----Temlate**********************************************/
int main(){
int T;
read(T);
while(T--){
int n,m;
int ps;
int pa;
char s[maxn];
char a[maxn],b[maxn];
read(n),read(m);
scanf("%s",s);bool flag=0;
int len=strlen(s);
if(len==1&&s[0]=='0'&&n==1&&m==1){
printf("0 0\n");
continue;
}
for(int xx = 1; xx <= 9; xx++){
ps=0;
a[0]=xx+'0';
flag=0;
for(int i = 0; i < m; i++){
if(s[ps]=='0'){b[i]='0';ps++;}
else if(s[ps] < a[0]){
//cout<<s[ps]<<' '<<a[0]<<endl;
int ans=(s[ps]-'0')*10+(s[ps+1]-'0');
if(ans%(a[0]-'0')!=0){
flag=1;
break;
}
b[i]=ans/(a[0]-'0')+'0';
ps+=2;
}
else{
if((s[ps]-'0')%(a[0]-'0')!=0){
flag=1;
break;
}
b[i]=(s[ps]-'0')/(a[0]-'0')+'0';
ps++;
}
}
if(flag)continue;
b[m]='\0';
for(int i = 1; i < n; i++){
if(s[ps]=='0'){a[i]='0';ps++;}
else if(s[ps] < b[0]){
int ans = (s[ps]-'0')*10+(s[ps+1]-'0');
if(ans%(b[0]-'0')!=0){
flag=1;
break;
}
a[i]=ans/(b[0]-'0')+'0';
ps+=2;
}
else{
if((s[ps]-'0')%(b[0]-'0')!=0){
flag=1;
break;
}
a[i]=(s[ps]-'0')/(b[0]-'0')+'0';
ps++;
}
for(int j = 1; j < m; j++){
if(s[ps]=='0'){
if(b[j]!='0'&&a[i]!='0'){
flag=1;
break;
}
ps++;
}
else if(s[ps]<b[j]){
int ans = (s[ps]-'0')*10+(s[ps+1]-'0');
if((b[j]-'0')*(a[i]-'0')!=ans){
flag=1;
break;
}
ps+=2;
}
else{
if((b[j]-'0')*(a[i]-'0')!=(s[ps]-'0')){
flag=1;
break;
}
ps++;
}
}
if(flag){break;}
}
//cout<<len<<' '<<ps<<endl;
if(len!=ps)continue;
if(!flag){break;}
}
a[n]='\0';b[m]='\0';
if(flag||len!=ps)printf("Impossible\n");
else{
printf("%s %s\n",a,b);
}
}
return 0;
}