HDU 1402 大数相乘 解决超时

来源:互联网 发布:挖财记账理财软件 编辑:程序博客网 时间:2024/06/04 00:39

A * B Problem Plus

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 7853    Accepted Submission(s): 1237


Problem Description
Calculate A * B.
 

Input
Each line will contain two integers A and B. Process to end of file.

Note: the length of each integer will not exceed 50000.
 

Output
For each case, output A * B in one line.
 

Sample Input
1210002
 

Sample Output
22000



直接用以前的模板做会超时

/*网上复制思路:
  *        把9个1位数压缩成1个9位数
  *        相当于1个5W位数变成了1个6K位数
  *        复杂度变成了: 6000 * 6000 = 3600W
  *        杭电提交: 900+MS 低空掠过
*/
#include <algorithm>
 #include <iostream>
 #include <string.h>
 using namespace std;
 #define N 13000
 #define M 51000
 __int64 a[N],b[N],ans[N];
 char ca[M], cb[M];
 int StrToNum(char c[],__int64 num[])        //将字符串转成数字
 {
     int n=strlen(c),k=0;
     __int64 tp=0,p=1,d=1;
     for(int j=n-1;j>=0;j--)
     {
         tp+=(__int64)(c[j]-'0')*d;    //注意数字的顺序,合成一个数也是从低位到高位
         if(p>=9)            //把9个1位数压成1个9位数,减少循环
         {
             num[k++] = tp;
             tp = 0;
             p = d = 1;
         }else{
             p++;
             d*=10;
         }
     }
     num[k++] = tp;
     return k;
 }
 int main()
 {
     int na,nb,n,t,d=0,i,j;
     const int width = 9;
     __int64 MOD =1000000000;    //9位的模数
     while(scanf("%s%s", ca, cb)!=EOF)
     {
         memset(a,0,sizeof(a));
         memset(b,0,sizeof(b));
         na=StrToNum(ca,a);
         nb=StrToNum(cb,b);
         memset(ans, 0, sizeof(ans));
         for(i=0;i<na;i++)
         {
             for(j=0;j<nb;j++)
             {
                 ans[i+j]+=a[i]*b[j];
             }
             for(j=0;j<nb;j++)
             {
                 if(ans[i+j]>=MOD)
                 {
                     ans[i+j+1]+=ans[i+j]/MOD;
                     ans[i+j]%=MOD;
                 }
             }
         }
         n=i+j+2;
         while(!ans[n]&&n>0) n--;
         if(n>=0) printf("%I64d",ans[n--]);
         while(n>=0) printf("%0*I64d",width,ans[n--]);//神马意识???  不懂啊  求大神解释
         printf("\n");
     }
     return 0;
 }

原创粉丝点击