洛谷 P2841 A*B Problem

https://www.luogu.org/problemnew/show/P2841

根本不会啊。。。

大概就是:如果两个数模a的结果相同,那么它们前面同时加上一个0或1后模a的结果仍然相同,因此可以先求a*b,按照模a的结果来划分状态,模a相同的只保留较小的,这样可以求出a*b,然后高精除得到b

 1 #include<cstdio>
 2 #include<algorithm>
 3 #include<cstring>
 4 #include<vector>
 5 #include<string>
 6 #include<map>
 7 using namespace std;
 8 #define fi first
 9 #define se second
10 #define mp make_pair
11 #define pb push_back
12 typedef long long ll;
13 typedef unsigned long long ull;
14 typedef pair<int,int> pi;
15 typedef pair<int,string> ps;
16 int n;
17 map<int,string> a1,a2;
18 ps ans;
19 int ax[1010];
20 int main()
21 {
22     int i,now;
23     bool fl=0;
24     scanf("%d",&n);
25     if(n==1)
26     {
27         puts("1 1");
28         return 0;
29     }
30     a1[0]="0";a1[1]="1";now=1;
31     while(1)
32     {
33         now=now*10%n;
34         for(auto &x:a1)
35         {
36             if((x.fi+now)%n==0)
37             {
38                 ans=mp((x.fi+now)%n,"1"+x.se);
39                 goto xxx;
40             }
41             //printf("%d %s\n",(x.fi+now)%n,("1"+x.se).c_str());
42             //printf("%d %s\n",x.fi,("0"+x.se).c_str());
43             if(!a2.count((x.fi+now)%n))
44                 a2[(x.fi+now)%n]="1"+x.se;
45             else
46                 a2[(x.fi+now)%n]=min("1"+x.se,a2[(x.fi+now)%n]);
47             if(!a2.count(x.fi))
48                 a2[x.fi]="0"+x.se;
49             else
50                 a2[x.fi]=min("0"+x.se,a2[x.fi]);
51         }
52         a1=a2;a2.clear();
53         //printf("%d\n",now);
54     }
55     xxx:;
56     now=0;
57     for(i=0;i<ans.se.length();i++)
58     {
59         now=now*10+ans.se[i]-'0';
60         ax[i]=now/n;now%=n;
61     }
62     for(i=0;i<ans.se.length();i++)
63     {
64         if(ax[i]==0&&!fl)    continue;
65         fl=1;printf("%d",ax[i]);
66     }
67     printf(" %s",ans.se.c_str());
68     return 0;
69 }

猜你喜欢

转载自www.cnblogs.com/hehe54321/p/9282567.html