题目描述
任何一个正整数都可以用22的幂次方表示。例如
137=2^7+2^3+2^0137=27+23+20
同时约定方次用括号来表示,即a^bab 可表示为a(b)a(b)。
由此可知,137137可表示为:
2(7)+2(3)+2(0)2(7)+2(3)+2(0)
进一步:
7= 2^2+2+2^07=22+2+20(2^1用2表示),并且
3=2+2^03=2+20
所以最后137137可表示为:
2(2(2)+2+2(0))+2(2+2(0))+2(0)2(2(2)+2+2(0))+2(2+2(0))+2(0)
又如:
1315=2^{10} +2^8 +2^5 +2+11315=210+28+25+2+1
所以13151315最后可表示为:
2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)
输入输出格式
输入格式:
一个正整数n(n≤20000)n(n≤20000)。
输出格式:
符合约定的nn的0,20,2表示(在表示中不能有空格)
输入输出样例
2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)
题解
经典的分治题,大问题化小问题递归求解。
递归过程:
n做参数m,把2^m从大到小划分为t个2^ai,m = 137时,次数分别为7、3、0,及2^138=2^7+2^3+2^0;
然后把7、3、0分别做参数m执行重复操作(递归)
m = 1输出2
m = 0输出0,由于0不能脱离"()"而单独存在,所以定义在函数开头
#include <iostream> #include <cmath> using namespace std; int n; void fz(int m) { if (m == 0) { cout << "0"; return; } int t = 0; int a[101]; while (m != 0) { int h = 0; while (1 << h <= m) h++; t++; a[t] = h - 1; m -= pow(2, h - 1); } for (int i = 1; i <= t; i++) { if (i != t) { if (a[i] == 1) { cout << "2+"; } else { cout << "2("; fz(a[i]); cout << ")+"; } } else { if (a[i] == 1) { cout << "2"; } else { cout << "2("; fz(a[i]); cout << ")"; } } } } int main() { cin >> n; fz(n); system("pause"); return 0; }