1. 程式人生 > 實用技巧 >I The Crime-solving Plan of Groundhog 大數乘法

I The Crime-solving Plan of Groundhog 大數乘法

題意:給出n個(0~9)的數,讓我們自由排列組合生成兩個正整數,要求乘積最小

思路:讓原本的數從小到大(不包括0)排序,將‘0’格外考慮;

   然後最小的數單獨最為一個正整數,其餘的數字,由最小的數+‘0’+剩下的從小到大排序的陣列成,然後跑大數乘法模板

  1 #include<bits/stdc++.h>
  2 using namespace std;
  3 typedef long long LL;
  4 const int maxx = 20010;
  5 string sum(string s1,string s2)
  6 {
7 if(s1.length()<s2.length()) 8 { 9 string temp=s1; 10 s1=s2; 11 s2=temp; 12 } 13 int i,j; 14 for(i=s1.length()-1,j=s2.length()-1;i>=0;i--,j--) 15 { 16 s1[i]=char(s1[i]+(j>=0?s2[j]-'0':0)); 17 if(s1[i]-'0'>=10) 18 {
19 s1[i]=char((s1[i]-'0')%10+'0'); 20 if(i) s1[i-1]++; 21 else s1='1'+s1; 22 } 23 } 24 return s1; 25 } 26 27 string Mult(string s,int x) 28 { 29 reverse(s.begin(),s.end()); 30 int cmp=0; 31 for(int i=0;i<s.size();i++) 32 {
33 cmp=(s[i]-'0')*x+cmp; 34 s[i]=(cmp%10+'0'); 35 cmp/=10; 36 } 37 while(cmp) 38 { 39 s+=(cmp%10+'0'); 40 cmp/=10; 41 } 42 reverse(s.begin(),s.end()); 43 return s; 44 } 45 string Multfa(string x,string y) 46 { 47 string ans; 48 for(int i=y.size()-1,j=0;i>=0;i--,j++) 49 { 50 string tmp=Mult(x,y[i]-'0'); 51 for(int k=0;k<j;k++) 52 tmp+='0'; 53 ans=sum(ans,tmp); 54 } 55 return ans; 56 } 57 string Except(string s,int x) 58 { 59 int cmp=0,ok=0; 60 string ans=""; 61 for(int i=0;i<s.size();i++) 62 { 63 cmp=(cmp*10+s[i]-'0'); 64 if(cmp>=x) 65 { 66 ok=1; 67 ans+=(cmp/x+'0'); 68 cmp%=x; 69 } 70 else{ 71 if(ok==1) 72 ans+='0'; 73 } 74 } 75 if(!ok)ans+='0'; 76 return ans; 77 } 78 string quick(string a,string b) 79 { 80 string res="1"; 81 while(b!="0") 82 { 83 if((b[b.size()-1]-'0')%2) 84 res=Multfa(res,a); 85 b=Except(b,2); 86 a=Multfa(a,a); 87 } 88 return res; 89 } 90 int main() 91 { 92 ios::sync_with_stdio(false); 93 string s; 94 cin>>s; 95 stack<string>st; 96 for(int i=0;i<s.size();i++){ 97 if(s[i]!=')'&&s[i]!='+'){ 98 string tmp; 99 tmp+=s[i]; 100 st.push(tmp); 101 } 102 if(s[i]==')'){ 103 string ans="0"; 104 while(!st.empty()){ 105 string t=st.top();st.pop(); 106 if(t=="(")break; 107 ans=sum(ans,t); 108 } 109 if(!st.empty()) 110 { 111 st.pop(); 112 ans=quick("2",ans); 113 } 114 st.push(ans); 115 } 116 } 117 string ans="0"; 118 while(!st.empty()) 119 { 120 string t=st.top();st.pop(); 121 ans=sum(ans,t); 122 } 123 cout<<ans<<endl; 124 return 0; 125 }
View Code