Sicily 1029 Rabbit(高精度运算+公式递推)

//高精度运算+公式递推 //当m = 1时,ans = 2^d; //当m > 1时,f[1] = 1,f[2] = 2....f[m] = m,f[m+1] = f[m] + f[1]......f[n] = f[n-1] + f[n-m]; #include #include #include #include using namespace std; struct Bigint { string num; Bigint(int n) { while(n != 0) { num.push_back(n % 10 + '0'); n /= 10; } reverse(num.begin(),num.end()); } }; int compare(string a,string b) { if(a.size() > b.size()) return 1; else if(a.size() < b.size()) return -1; else return a.compare(b); } string add(string num1,string num2) { int len = max(num1.size(),num2.size()) + 1; string ans; ans.assign(len,0); reverse(num1.begin(),num1.end()); reverse(num2.begin(),num2.end()); num1.append(len-num1.size(),'0'); num2.append(len-num2.size(),'0'); for(int i = 0;i < len;++i) { ans[i] += num1[i]-'0' + num2[i]-'0'; ans[i+1] += ans[i]/10; ans[i] %= 10; ans[i] += '0'; } while(ans[len-1] == '0' && ans.size() != 1)//除去前导零,当两个数相等时,保留0 { ans.erase(len-1,1); len--; } reverse(ans.begin(),ans.end()); return ans; } string multiply(string num1,string num2) { int len = num1.size() + num2.size(); string ans; ans.assign(len,0); reverse(num1.begin(),num1.end()); reverse(num2.begin(),num2.end()); for(int i = 0;i < num2.size();++i) { for(int j = 0;j < num1.size();++j) { ans[i+j] += (num2[i]-'0') * (num1[j]-'0'); ans[i+j+1] += ans[i+j] / 10; ans[i+j] %= 10; } } for(int i = 0;i < len;++i) ans[i] += '0'; while(ans[len-1] == '0' && ans.size() != 1)//除去前导零,当两个数相等时,保留0 { ans.erase(len-1,1); len--; } reverse(ans.begin(),ans.end()); return ans; } int main() { int m,d; while(cin >> m >> d && m != 0) { if(m == 1) { Bigint ans(1); Bigint factor(2); for(int i = 1;i <= d;++i) { ans.num = multiply(ans.num,factor.num); } cout << ans.num<< endl; } else { vector v; for(int i = 1;i <= m;++i) { Bigint a(i); v.push_back(a.num); } for(int i = 0;i <= 100;++i) { if(v.size() > d) break; v.push_back(add(v[i],v[i+m-1])); } cout << v[d] << endl; } } return 0; }  

你可能感兴趣的:(高精度运算)