非官方题解
2025-04-08 18:28:30
发布于:北京
19阅读
0回复
0点赞
进制转换怎么写我就不多讲了,网上一抓一大把 (主要因为作者比较懒),这里我用的是 除n取余,倒序读取
的方法:
std::string q = "0123456789ABCDEF";
std::string ten_n (int n, int x)
{
std::string s;
while (x)
{
s = q[x % n] + s;
x = x / n;
}return s;
}
然后我们简简单单写个输入,再把所有的 8 进制数都算好,如下:
int n; std::cin >> n;
int a[N] {};
for (int i = 0; i < n; ++ i)
std::cin >> a[i];
std::string b[N] {};
for (int i = 0; i < n; ++ i)
b[i] = ten_n (8, a[i]);
再来个排序:
std::sort (b + 0, b + n, cmp);
这里的 cpm
函数比较难写,所以我们一步一步来。
题目中要求“先比最低位”,那我们就按照它说的写:
bool cmp (std::string x, std::string y)
{
int len_x = (int) x.length ();
int len_y = (int) y.length ();
if (x[len_x - 1] != y[len_y - 1])
return x[len_x - 1] > y[len_y - 1];
}
最低位相同,“直接从小到大比”:
bool cmp (std::string x, std::string y)
{
int len_x = (int) x.length ();
int len_y = (int) y.length ();
if (x[len_x - 1] != y[len_y - 1])
return x[len_x - 1] > y[len_y - 1];
if (len_x != len_y)
return len_x < len_y;
return x < y;
}
这里注意,由于数据类型是 std::string
,所以要自己写比较方法:先比位数,再比字典序。
最后再来个输出:
for (int i = 0; i < n; ++ i)
std::cout << b[i] << ' ';
C++ Code:
#include <bits/stdc++.h>
#define Ll long long
//using namespace std;
const int N = 2e5 + 10, M = 1e2 + 10;
std::string q = "0123456789ABCDEF";
std::string ten_n (int n, int x)
{
std::string s;
while (x)
{
s = q[x % n] + s;
x = x / n;
}return s;
}bool cmp (std::string x, std::string y)
{
int len_x = (int) x.length ();
int len_y = (int) y.length ();
if (x[len_x - 1] != y[len_y - 1])
return x[len_x - 1] > y[len_y - 1];
if (len_x != len_y)
return len_x < len_y;
return x < y;
}void solve ()
{
//main;
int n; std::cin >> n;
int a[N] {};
for (int i = 0; i < n; ++ i)
std::cin >> a[i];
std::string b[N] {};
for (int i = 0; i < n; ++ i)
b[i] = ten_n (8, a[i]);
/*for (int i = 0; i < n; ++ i)
std::cout << b[i] << ' ';*/
std::sort (b + 0, b + n, cmp);
for (int i = 0; i < n; ++ i)
std::cout << b[i] << ' ';
return ;
}int main ()
{
//main;
int T = 1; //cin >> T;
while (T --)
solve ();
return 0;
}
这里空空如也
有帮助,赞一个