【noi 2.2_8758】2的幂次方表示(递归)

时间:2023-03-09 06:02:27
【noi 2.2_8758】2的幂次方表示(递归)

题意:将正整数N用2的幂次方表示(彻底分解至2(0),2)。

解法:将层次间和每层的操作理清楚,母问题分成子问题就简单了。但说得容易,操作没那么容易,我就打得挺纠结的......下面附上2个代码,都借用了数组储存,而代码2是我近期打的,应该是更优美一点的。

 1 #include<cstdio>
2 #include<cstdlib>
3 #include<cstring>
4
5 struct node
6 {
7 int s[100];
8 int t;
9 };
10 node a,c[30];
11
12 node div(int x)
13 {
14 int u=0;
15 a.t=0;
16 while (x>0)
17 {
18 if (x%2) a.s[++a.t]=u;
19 x/=2,u++;
20 }
21 return a;
22 }
23
24 int dep=0;
25
26 void print(int x)
27 {
28 if (!x) {printf("%d",x);return;}
29 dep++;
30 c[dep]=div(x);
31 int tmp=dep;
32 for (int i=c[tmp].t;i>=1;i--)
33 {
34 if (i!=c[tmp].t) printf("+");
35 if (c[tmp].s[i]==1) {printf("2");continue;}
36 printf("2(");
37 print(c[tmp].s[i]);
38 printf(")");
39 }
40 }
41
42 int main()
43 {
44 int n;
45 scanf("%d",&n);
46 print(n);//step1=step2=step3...directly recursion
47 return 0;
48 }

1

 1 #include<cstdio>
2 #include<cstdlib>
3 #include<cstring>
4 #include<iostream>
5 using namespace std;
6 #define N 20010
7 int s[20][6],h[20];//s[i][] i=sum{2^s[i][1~...]}
8
9 void print(int k)
10 {
11 if (!k) {printf("0");return;}
12 for (int i=1;i<=h[k];i++)
13 {
14 if (i!=1) printf("+");
15 if (s[k][i]==1) {printf("2");continue;}
16 printf("2(");
17 print(s[k][i]);
18 printf(")");
19 }
20 }
21 void init(int x,int id)
22 {
23 h[id]=0;
24 int t=0;
25 while (x)
26 {
27 if (x&1) s[id][++h[id]]=t;
28 x/=2,t++;
29 }
30 for (int i=1;i<=h[id]/2;i++)
31 {t=s[id][i]; s[id][i]=s[id][h[id]-i+1]; s[id][h[id]-i+1]=t;}
32 }
33 int main()
34 {
35 int n;
36 scanf("%d",&n);
37 for (int i=1;i<=16;i++) init(i,i);
38 init(n,17);
39 print(17);
40 return 0;
41 }

2