牛客网Groundhog and 2-Power Representation
链接:https://ac.nowcoder.com/acm/contest/5674/A
来源:牛客网
题目描述
输入计算式,求解。
其中 2(x) 表示 2 的 x 次方,式中每一项都对应着答案在二进制表示下的数位为1的位。
比如说:
1315=210+28+25+2+1=2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0).
输入描述:
Given a string, indicating the power representation.
输出描述:
Output the original number.
输入:
2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)
输出:
1315
备注:
The range of answers :[10,10180][10,10^{180}][10,10180],and the length of the input data shall not exceed 20000{20000}20000.
分析:
- 很显然这题要用高精度。
- 因为“(”与“)”相配对,满足数量相等。
- 若在字符串中找到一个2;
- 若下一个字符是′(′ ,则进行递归;
- 否则在答案上直接加二。
- 若遇到左括号,h++;
- 若遇到右括号,h--;
- 如果h=0时,则已经完成了一串2;
- 快速幂得出答案并累加,退出递归。
代码(队友的心血):

#include<bits/stdc++.h> using namespace std; #define ll long long char a[20010]; ll sum; int ans[205],anslen; void aaa(int b[],int len){ anslen=max(anslen,len); for(int i=1;i<=anslen;++i){ ans[i]+=b[i]; ans[i+1]+=ans[i]/10; ans[i]%=10; } while(ans[anslen+1]) ++anslen; } int b[1005]; void ksm(ll c){ memset(b,0,sizeof(b)); b[1]=1; int k=1; for(int i=1;i<=c;++i){ int x=0; for(int j=1;j<=k;++j){ b[j]=b[j]*2+x; x=b[j]/10; b[j]%=10; if(x&&j==k) ++k; } } aaa(b,k); } ll ksm1(ll b,ll c) { ll d=1; while(c>0) { if(c&1)d*=b; c>>=1; b*=b; } return d; } int p,k; ll dg(ll x,ll h) { ll q=0;p=0; for(int i=x;i<k;i++) { p=max(p,i); if(a[i]=='(') h++; if(a[i]==')') h--; if(!h){ksm(q);return 0;} if(a[i]==')') return ksm1(2,q); if(a[i]=='2') { if(a[i+1]=='(') q+=dg(i+1,h),i=p; else q+=2; } } } int main() { scanf("%s",a); k=strlen(a); for(int i=0;i<k;i++) if(a[i]=='2') { if(a[i+1]!='('){ memset(b,0,sizeof(b)); b[1]=2; aaa(b,1); } else dg(i+1,0),i=p; } for(int i=anslen;i>=1;i--) printf("%d",ans[i]); }