[2841] A*B Problem (50pts WA & TLE程式碼)
阿新 • • 發佈:2020-12-06
TLE:
#include<iostream> #include<cstring> #include<algorithm> #define obj (void) const int L=1100; using namespace std; string mul(string a,string b)//高精度乘法a,b,均為非負整數 { string s; int na[L],nb[L],nc[L],La=a.size(),Lb=b.size();//na儲存被乘數,nb儲存乘數,nc儲存積 fill(na,na+L,0);fill(nb,nb+L,0);fill(nc,nc+L,0);//將na,nb,nc都置為0 for(int i=La-1;i>=0;i--) na[La-i]=a[i]-'0';//將字串表示的大整形數轉成i整形陣列表示的大整形數 for(int i=Lb-1;i>=0;i--) nb[Lb-i]=b[i]-'0'; for(int i=1;i<=La;i++) for(int j=1;j<=Lb;j++) nc[i+j-1]+=na[i]*nb[j];//a的第i位乘以b的第j位為積的第i+j-1位(先不考慮進位) for(int i=1;i<=La+Lb;i++) nc[i+1]+=nc[i]/10,nc[i]%=10;//統一處理進位 if(nc[La+Lb]) s+=nc[La+Lb]+'0';//判斷第i+j位上的數字是不是0 for(int i=La+Lb-1;i>=1;i--) s+=nc[i]+'0';//將整形陣列轉成字串 return s; } int main() { string add(string a,string b); string mul(string a,string b); bool cmp(string a); string a; cin>>a; string b; string dst="1"; while(1){ if(cmp(mul(dst,a))){ cout<<dst<<" "<<mul(dst,a);exit(0); }else{dst=add(dst,"1");} } return 0; } bool cmp(string a){ unsigned fff=0; for(unsigned i=0;i<a.size()+1;i++) (a[i]=='0'||a[i]=='1')? obj fff++: obj 0; //printf("\t%u",fff); return(fff==(unsigned)a.size()); } string add(string a,string b)//只限兩個非負整數相加 { string ans; int na[L]={0},nb[L]={0}; int la=a.size(),lb=b.size(); for(int i=0;i<la;i++) na[la-1-i]=a[i]-'0'; for(int i=0;i<lb;i++) nb[lb-1-i]=b[i]-'0'; int lmax=la>lb?la:lb; for(int i=0;i<lmax;i++) na[i]+=nb[i],na[i+1]+=na[i]/10,na[i]%=10; if(na[lmax]) lmax++; for(int i=lmax-1;i>=0;i--) ans+=na[i]+'0'; return ans; }
WA:
#include<stdio.h> #include<stdbool.h> #include<string.h> #include<stdlib.h> #define obj (void) using namespace std; int main(){ unsigned k; scanf("%u",&k); bool cmp(const char* a); char *s=(char*)malloc(sizeof(char)*1024*1024); unsigned sum; for(unsigned i=k;i<10*10*10*10+1;i++) { for(unsigned b=1;b<10*10*10*10+1;b++){ sum=i*b; sprintf(s,"%u",sum); /*printf("%u*%u=%llu",i,b,sum);*/ cmp(s)? obj printf("%u %u",b,sum), obj exit(0): obj 0/*printf(":: NO\n")*/; } } } bool cmp(const char* a){ unsigned fff=0; for(unsigned i=0;i<strlen(a)+1;i++) (a[i]=='0'||a[i]=='1')? obj fff++: obj 0; //printf("\t%u",fff); return(fff==(unsigned)strlen(a)); }