Waterloo Cup algorithm training 2 Zhi = __ algorithm

Source: Internet
Author: User
Zhi of algorithm Training 2 indicates time limit: 1.0s memory Limit: 512.0MB problem description Any positive integer can be represented in 2, for example: 137 of 2 is represented as 10001001.
This type of 2 is represented as the sum of the powers of 2, so that the power of the exponent is in the first place, and the following expression can be obtained: 137=2^7+2^3+2^0
Now the appointment power is expressed in parentheses, that is, a^b is represented as a (b).
At this point, 137 can be expressed as: 2 (7) +2 (3) +2 (0)
Further: 7=2^2+2+2^0 (2^1 with 2)
3=2+2^0
So the last 137 can be expressed as: 2 (2 (2) +2+2 (0)) +2 (2+2 (0)) +2 (0)
Another example: 1315=2^10+2^8+2^5+2+1
So 1315 can finally be expressed as:
2 (2 (2+2 (0)) +2) +2 (2 (2+2 (0))) +2 (2 (2) +2 (0)) +2+2 (0 Input format positive integer (1<=n<=20000) output format conforming to the agreed N 0,2 representation (no spaces in representations) sample input 137 sample loss 2 (2 (2) +2+2 (0)) +2 (2+2 (0)) +2 (0) sample input 1315 sample output 2 (2 (2+2 (0)) +2) +2 (2 (2+2 (0))) +2 (2 (2) +2 (0)) +2+2 (0)

Tips

The recursive implementation will be simpler, you can output the side recursively


#include <iostream>
#include <stdio.h>
#include <memory.h>
using namespace Std;


void Cimi (int n)
{
int a[20],num=0,i=0;
while (n)
{
if (n%2)
A[num++]=i;
i++;
n/=2;
}
for (int i=num-1;i>=0;i--)
{


if (a[i]==0) printf ("2 (0)");
if (a[i]==1) printf ("2");
if (a[i]==2) printf ("2 (2)");
if (a[i]>2) {printf ("2 (");
Cimi (A[i]);
printf (")");}
if (i)
printf ("+");




}


}


int main (void)
{


int n;
while (scanf ("%d", &n)!=eof)
{
Cimi (n);
printf ("\ n");
}
return 0;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.