专题三--1015

题目

Give you a number on base ten,you should output it on base two.(0 < n < 1000)

Input
For each case there is a postive number n on base ten, end of file.

Output
For each case output a number on base two.

Sample Input

1
 2
 3
 

Sample Output

1
 10
 11
 

解题思路

刚看到这道题,我的第一反应是应用输出控制直接输出二进制数字,仔细考虑了一下,用输出控制解决可能会出现多余的输出。
想到此问题的解具有子结构,可以分解为子问题的解,并考虑到此专题为dp,于是我尝试用dp的思路解决问题。
问题的解f(n)可简单的看作以下的树:
                     f(1)="1"   
          f(2)="10" f(3)="11"
   f(4)="100",f(5)="101"    f(6)="110",f(7)="111"

由此得出状态转移方程(伪代码):

    For i=1 to 1000
        if i为奇数
        f(i)=f(i/2)+"1"
    else i为偶数
         f(i)=f(i/2)+"0"

AC代码

#include<iostream>
#include<vector>
#include<string>
using namespace std;
string dp[1010];
int main(){
    dp[1] = "1";
    for (int i = 2; i<1001; i++){
        if (i % 2)
            dp[i] = dp[i / 2] + "1";
        else dp[i] = dp[i / 2] + "0";
        //v.push_back("0");
        //for(vector<char>::reverse_iterator it=v.rbegin();it!=v.rend();it++)
        //dp[]
    }
    int n;
    while (cin >> n)
        cout << dp[n]<<endl;
}
原文地址:https://www.cnblogs.com/liuzhanshan/p/5521575.html