POJ2389 Bull Math
1 /* 2 POJ2389 Bull Math 3 http://poj.org/problem?id=2389 4 高精度乘法 5 * 6 */ 7 #include <cstring> 8 #include <cstdio> 9 #include <algorithm> 10 using namespace std; 11 const int Nmax=1000; 12 struct BigInt 13 { 14 int a[Nmax]; 15 int n; 16 void init() 17 { 18 for(int i=0;i<Nmax;i++) 19 a[i]=0; 20 } 21 BigInt() 22 { 23 init(); 24 n=0; 25 } 26 BigInt(int _a[],int _n) 27 { 28 init(); 29 n=_n; 30 //for(int i=0;i<Nmax;i++) 31 //a[i]=0; 32 for(int i=1;i<=n;i++) 33 a[i]=_a[i]; 34 maintain(); 35 } 36 BigInt(char s[]) 37 { 38 init(); 39 n=strlen(s+1); 40 for(int i=1;i<=n;i++) 41 a[i]=s[n-i+1]-'0'; 42 maintain(); 43 } 44 BigInt(long long x) 45 { 46 init(); 47 n=0; 48 while(x>0LL) 49 { 50 a[++n]=x%10LL; 51 x/=10LL; 52 } 53 } 54 BigInt(int x) 55 { 56 init(); 57 n=0; 58 while(x>0) 59 { 60 a[++n]=x%10; 61 x/=10; 62 } 63 } 64 void read() 65 { 66 init(); 67 n=0; 68 char c=getchar(); 69 if(c==-1) 70 return; 71 while(c==' ' || c=='\n' ) 72 { 73 c=getchar(); 74 if(c==-1) 75 break; 76 } 77 int num[Nmax]; 78 while(c!=' ' && c!='\n' && c!=-1) 79 { 80 num[++n]=c-'0'; 81 c=getchar(); 82 } 83 for(int i=1;i<=n;i++) 84 a[i]=num[n-i+1]; 85 maintain(); 86 } 87 void print() 88 { 89 if(n==0) 90 printf("0"); 91 for(int i=n;i>=1;i--) 92 printf("%d",a[i]); 93 } 94 void maintain() 95 { 96 for(int i=1;i<=n;i++) 97 { 98 a[i+1]+=a[i]/10; 99 a[i]%=10; 100 } 101 int j=n+1; 102 while(a[j]!=0) 103 { 104 a[j+1]+=a[j]/10; 105 a[j]%=10; 106 j++; 107 } 108 n=j-1; 109 while(a[n]==0 && n>1) 110 n--; 111 } 112 friend BigInt operator + (BigInt a,BigInt b) 113 { 114 int len=max(a.n,b.n); 115 BigInt ans; 116 ans.n=len; 117 for(int i=1;i<=len;i++) 118 ans.a[i]=a.a[i]+b.a[i]; 119 ans.maintain(); 120 return ans; 121 } 122 //friend BigInt operator - (BigInt a,BigInt b) 123 //{ 124 //int len=max(a.n,b.n); 125 //BigInt ans; 126 //ans.n=len; 127 //for(int i=1;i<=len;i++) 128 //ans.a[i]=a.a[i]-b.a[i]; 129 //for(int i=1;i<=len;i++) 130 //{ 131 //if(ans.a[i]<0) 132 //{ 133 //ans.a[i]+=10; 134 //a.a[i+1]--; 135 //} 136 //ans.a[i]+=10 137 //} 138 //} 139 friend BigInt operator * (BigInt b,int a) 140 { 141 int n=b.n; 142 BigInt ans; 143 ans.n=n; 144 for(int i=1;i<=n;i++) 145 ans.a[i]=b.a[i]*a; 146 ans.maintain(); 147 return ans; 148 } 149 friend BigInt operator * (int a,BigInt b) 150 { 151 int n=b.n; 152 BigInt ans; 153 ans.n=n; 154 for(int i=1;i<=n;i++) 155 ans.a[i]=b.a[i]*a; 156 ans.maintain(); 157 return ans; 158 } 159 friend BigInt operator * (BigInt a,BigInt b) 160 { 161 BigInt ans; 162 ans.n=a.n+b.n+1; 163 int k; 164 for(int i=1;i<=a.n;i++) 165 for(int j=1;j<=b.n;j++) 166 ans.a[j+i-1]+=a.a[i]*b.a[j]; 167 ans.maintain(); 168 return ans; 169 } 170 }; 171 int main() 172 { 173 char s[1002]; 174 char s1[1002]; 175 BigInt a,b; 176 //freopen("test.in","r",stdin); 177 a.read(); 178 b.read(); 179 (a*b).print(); 180 printf("\n"); 181 return 0; 182 }