0最大数字 - 蓝桥云课
问题描述
我们有 n 个连续的整数 1,2,3,⋯,n,可以自由排列它们的顺序。
然后,我们把这些数字转换成二进制表示,按照排列顺序拼接形成一个新的二进制数。
我们的目标是让这个二进制数的值最大,并输出这个二进制对应的十进制表示。
输入格式
输入一行包含一个正整数 n。
输出格式
输出一行包含一个整数表示答案。
样例输入
3样例输出
30评测用例规模与约定
对于 20% 的评测用例,1≤n≤10;
对于 40% 的评测用例,1≤n≤100;
对于 60% 的评测用例,1≤n≤500;
对于 80% 的评测用例,1≤n≤1000;
对于所有评测用例,1≤n≤10000。
#include<bits/stdc++.h> using namespace std; #define ios ios::sync_with_stdio(0),cin.tie(0),cout.tie(0); using LL = long long ; /////////////////////////////////////////////////////// __attribute__((unused)) int io_ = []() { ios return 0; }(); ///////////////////////////////////////////////////////////////////////// const int N = 1e6 + 10 ; int n, m; string get(int x){ string res=""; while(x){ res += x % 2 + '0'; x /= 2 ; } reverse(res.begin(),res.end()); return res ; } int res[N]; void solve() { cin >> n ; vector<string> a(n); for(int i= 1;i <= n; i ++ ) { a[i-1]= get(i); } sort(a.begin(),a.end(),[](string &x,string &y){ return x + y > y + x ; }); string s = ""; for(auto t : a ) s += t ; int cnt =0 ; for(auto c : s){ int t= 0 ; for(int i= 0;i <= cnt; i ++ ) { int u= res[i] * 2 + t ; res[i] = u % 10 ; t = u / 10 ; } if(t) res[++ cnt ] = t ; if(c == '0') continue; t = 1 ; for(int i =0;i <= cnt && t ;i ++ ){ int u = res[i] + t ; res[i] = u % 10; t = u / 10 ; } if(t) res[ ++ cnt ] = t ; } string ans = ""; for(int i= cnt ;i >=0 ;i -- ) ans += (res[i] + '0'); cout << ans << endl; } ///////////////////////////////////////////////////////////////////// signed main() { int t=1; // cin>>t; while(t -- ) solve(); return 0; }