感觉挺简单的。
题目大意:
计算每个数的二进制最长连续1长度,按此长度从小到大排序,长度相同按数值从小到大排序。
AC code:
#include <bits/stdc++.h>
#define int long long
#define fst ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
const int N = 4e6 + 7;
const int MOD = 998244353;
const int INF = 0X3F3F3F3F;
const int dx[] = {-1, 1, 0, 0, -1, -1, +1, +1};
const int dy[] = {0, 0, -1, 1, -1, +1, -1, +1};
// 定义结构体Node,用于存储每个数字及其连序值。
struct Node
{
int x; // x: 连序值(最大连续1的个数)。
int s; // s: 原始数字。
}a[N];
int n, k, m;
int t;
inline int read ()
{
int s = 0, w = 1;
char ch = getchar();
while (ch < '0' || ch > '9')
{
if (ch == '-')
w = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9')
{
s = s * 10 + ch - '0';
ch = getchar();
}
return s * w;
}
inline void write (int x)
{
if (x < 0) putchar('-'), x = -x;
if (x > 9) write(x / 10);
putchar(x % 10 + '0');
return;
}
// 比较函数:按照题目要求排序。
bool cmp (Node u, Node v)
{
if (u.x == v.x) // 如果连序值相同。
{
return u.s < v.s; // 则按原始数字大小升序。
}
else // 如果连序值不同。
{
return u.x < v.x; // 则按连序值升序。
}
}
signed main()
{
fst; // 加速输入输出。
// 输入数字个数n。
cin >> n;
// 处理每个输入的数字。
for (int i = 1; i <= n; i++)
{
cin >> m; // 读入当前数字。
int maxx = 0; // 最大连续1的个数(连序值)。
int uss = 0; // 当前连续1的个数。
int tpp = m; // 临时变量,用于二进制处理。
// 计算数字m的连序值(最大连续1的个数)。
while (tpp > 0)
{
if (tpp & 1) // 如果当前最低位是1。
{
uss++; // 连续1的个数加1。
maxx = max(maxx, uss); // 更新最大值。
}
else // 如果当前最低位是0。
{
uss = 0; // 重置连续1的计数。
}
tpp /= 2; // 右移一位,处理下一位。
}
// 将结果存入结构体数组。
a[i].x = maxx; // 存储连序值。
a[i].s = m; // 存储原始数字。
}
// 按照自定义的比较函数进行排序。
sort(a + 1, a + 1 + n, cmp);
// 输出排序后的结果。
for (int i = 1; i <= n; i++)
{
cout << a[i].s << ' ';
}
return 0;
}