#30498: NA70%


chen199940@gmail.com (CGIBE)

學校 : 國立臺中科技大學
編號 : 179887
來源 : [59.126.118.189]
最後登入時間 :
2024-09-30 14:43:59
g503. 109北二6.一元多項式計算機 -- 109北二區桃竹苗資訊學科能力複賽 | From: [36.231.189.173] | 發表日期 : 2022-05-25 19:13

C++算是正確寫法,整個大數運算完,才求最後M位數(等測資改正...
#include <iostream> using namespace std; int n,m; string add(string a,string b){ int len1=a.size(),len2=b.size(); if(len1<len2){ swap(len1,len2); swap(a,b); } for(int i=len2;i<len1;i++){ b="0"+b; } string str(len1,0); int cy=0,v; for(int i=1;i<=len1;i++){ v=(a[len1-i]-'0')+(b[len1-i]-'0')+cy; cy=0; if(v>=10){ str[len1-i]=(char)(v-10+'0'); cy=1; } else{ str[len1-i]=(char)(v+'0'); } } if(cy==1)return "1"+str; return str; } string sub(string a,string b){ int len1=a.size(),len2=b.size(); for(int i=len2;i<len1;i++){ b="0"+b; } string str(len1,0); int rt=0,v; for(int i=1;i<=len1;i++){ v=(a[len1-i]-'0')-(b[len1-i]-'0')-rt; rt=0; if(v<0){ str[len1-i]=(char)(v+10+'0'); rt=1; } else{ str[len1-i]=(char)(v+'0'); } } return str; } string mult(string a, string b){ if(a=="0"||b=="0")return "0"; int len1=a.size(),len2=b.size(); string str(len1+len2,0); for(int i=len1-1;i>=0;i--){ for(int j=len2-1;j>=0;j--){ int n=(a[i]-'0')*(b[j]-'0')+str[i+j+1]; str[i+j+1]=n%10; str[i+j]+=n/10; } } for(int i=0;i<len1+len2;i++){ str[i]+='0'; } if(str[0]=='0')str=str.substr(1); return str; } string fp(string x,int n){ if(n==0)return "1"; if(n==1)return x; if(n%2==0)return fp(mult(x,x),n/2); return mult(x,fp(mult(x,x),n/2)); } bool cmp(string a,string b){ if(a[0]=='-')a=a.substr(1); if(b[0]=='-')b=b.substr(1); if(a.size()>b.size())return true; if(a.size()<b.size())return false; for(int i=0;i<a.size();i++){ if((int)a[i]>(int)b[i])return true; } return true; } int main() { //ios_base::sync_with_stdio(false); //cin.tie(NULL); int b; string a,c; string total="",v,v2; cin>>n>>c>>m; while(n--){ cin>>a>>b; if(c[0]=='-'){ if(b%2==0)v=fp(c.substr(1),b); else v="-"+fp(c.substr(1),b); } else{ v=fp(c,b); } if((a[0]=='-'&&v[0]!='-'))v2="-"+mult(a.substr(1),v); else if(a[0]!='-'&&v[0]=='-')v2="-"+mult(a,v.substr(1)); else if(a[0]=='-'&&v[0]=='-')v2=mult(a.substr(1),v.substr(1)); else v2=mult(a,v); if(total[0]=='-'&&v2[0]=='-'){ total="-"+add(total.substr(1),v2.substr(1)); } else if(total[0]!='-'&&v2[0]!='-'){ total=add(total,v2); } else if(total[0]!='-'&&v2[0]=='-'){ if(total==v2.substr(1)){ total="0"; } else if(cmp(total,v2)){ if(total!="0")total=sub(total,v2.substr(1)); else total=v2; } else total="-"+sub(v2.substr(1),total); } else if(total[0]=='-'&&v2[0]!='-'){ if(total.substr(1)==v2){ total="0"; } else if(cmp(v2,total)){ if(total!="0")total=sub(v2,total.substr(1)); else total=v2; } else total="-"+sub(total.substr(1),v2); } //cout<<"v2:"<<v2<<endl; //cout<<"total:"<<total<<endl; } string ans=""; for(int i=1;i<=m;i++){ if(i<=total.size()&&total[total.size()-i]!='-')ans=total[total.size()-i]+ans; else ans="0"+ans; } cout<<ans; return 0; }
 
ZeroJudge Forum