Description
Polycarpus participates in a competition for hacking into a new secure messenger. He's almost won.
Having carefully studied the interaction protocol, Polycarpus came to the conclusion that the secret key can be
obtained if he properly cuts the public key of the application into two parts. The public key is a long integer which
may consist of even a million digits!
Polycarpus needs to find such a way to cut the public key into two nonempty parts, that the first (left) part is divisible
by a as a separate number, and the second (right) part is divisible by b as a separate number. Both parts should
be positive integers that have no leading zeros. Polycarpus knows values a and b.
Help Polycarpus and find any suitable method to cut the public key.
The first line of the input contains the public key of the messenger — an integer without leading zeroes, its length is
in range from 1 to 106digits. The second line contains a pair of space-separated positive integers a, b (1 ≤ a, b ≤ 108).
In the first line print "YES" (without the quotes), if the method satisfying conditions above exists. In this case, next
print two lines — the left and right parts after the cut. These two parts, being concatenated, must be exactly
identical to the public key. The left part must be divisible by a, and the right part must be divisible by b. The two
parts must be positive integers having no leading zeros. If there are several answers, print any of them.
If there is no answer, print in a single line "NO" (without the quotes).
题意:给你一串数字和两个数字a,b,问那串数字是否能分成两部分,左边一部分能被a整除,右边一部分能被b整
除,每一个部分都不能有前导零。如果能就输出“YES”,并将这两部分分别输出;反之,只输出“NO”。
吐槽:当时比赛时想着输入那串数字时肯定是以字符串的形式输入并存储,然后从第一个数字开始遍历取a的同余
模,只要满足取a的同余模为0那就从此位置往后不为0的位置(记录下此位置以便输出结果)开始对b进行同余模,如
果到该数字串的最后一个数字时对b的同余模也是0,则说明该数字串能分成两部分,反之,不能。但是当时比赛时忽
略了一种情况,就是对a取同余模时万一有多个位置都是0且剩余部分都不符合对b同余模为0的话,肯定会超时,所以
当时就卡在这了2333333!!!
正确思路:开两个数组L[],R[]分别记录从左边开始当前位置对a的同余模,从右边开始当前位置对b的同余模。每次只
需遍历一边那串数字就可以把从两边开始对两个数当前位置的同余模记录下来,然后再同时遍历一边那两个数组即
可。详细请看代码。
#include <cstdio>
#include <cstring>
#define ll long long
using namespace std;
char num[2000000];
ll L[2000000],R[2000000];
int main()
{
//freopen("lalala.text","r",stdin);
int a,b,i;
while(~scanf("%s",num))
{
memset(L,0,sizeof(L));
memset(R,0,sizeof(R));
scanf("%d %d",&a,&b);
int len=strlen(num);
ll c=0;
for(i=0; i<len; i++) //遍历一边数字串,记录从左边开始对a的同余模
{
c=(c*10+num[i]-'0')%a;
L[i]=c;
}
c=0;
ll ten=1;
for(i=len-1; i>=0; i--) //遍历一边数字串,记录从右边开始对b的同余模
{
c=(c+(num[i]-'0')*ten)%b;
R[i]=c;
ten=(ten*10)%b;
}
bool flag=0;
int k;
for( i=0; i<len-1; i++)
{
if(L[i]==0&&R[i+1]==0&&num[i+1]!='0') //只要从当前位置左数组的同余模为0且下一个位置的右数组的同余模为0且数字串下一个位置不为0(去掉前导零)
{
k=i+1; //记录下来当前位置的下一个位置以便输出结果
flag=1;
break; //直接跳出,如果有多种分割方案只输出一种即可
}
}
if(flag)
{
printf("YES\n");
for(i=0; i<k; i++)
printf("%c",num[i]);
printf("\n");
for(; i<len; i++)
printf("%c",num[i]);
printf("\n");
}
else
printf("NO\n");
}
return 0;
}