#include <stdlib.h>#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
int n;
const int MAXN = 5e5 + 10;
const LL L = 1e8;
LL num[MAXN];
//計算 1 的數量
int CountOfOne(LL x) {
int cnt = 0;
//n-1:一個二進制的數減1,就是將這個二進制最右邊的那個1變成0,然后它后邊的所有位置都變成1~
//舉例:0011 0100,減1(n-1)后變成:0011 0011。
//n &= (n-1),并操作就會將有0的位置都變成0,
//上面的例子的結果就是0011 0000,然后再賦值給n,
//這時n就去掉了一個1,或者叫做計數了一個1
while (x) {
++cnt;
x &= (x - 1);
}
return cnt;
}
bool cmp(LL x, LL y) {
int a = CountOfOne(x);
int b = CountOfOne(y);
//1 的位數不同 -> 從大到小進行排序
if( a != b)
return a > b;
//快讀
LL read() {
LL f = 1, c = 0;
char ch = getchar();
while(!isdigit(ch)) {
if(ch == '-')
f = -1;
ch = getchar();
}
while(isdigit(ch)) {
c = c * 10 + ch - '0';
ch = getchar();
}
return c*f;
}
int main() {
//取消同步的操作
std::ios::sync_with_stdio(false);
n = read();
for(int i = 0; i < n; ++i) {
num[i] = read();
}
//排序
sort(num, num + n, cmp);
for(int i = 0; i < n; ++i) {
printf("%lld ", num[i]);
}
return 0;
}
#include <stdlib.h>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
int n;
const int MAXN = 5e5 + 10;
const LL L = 1e8;
LL num[MAXN];
//計算 1 的數量
int CountOfOne(LL x) {
int cnt = 0;
while (x) {
++cnt;
x &= (x - 1);
}
return cnt;
}
bool cmp(LL x, LL y) {
int a = CountOfOne(x);
int b = CountOfOne(y);
//1 的位數不同 -> 從大到小進行排序
if( a != b)
return a > b;
//若兩個數的二進制表示中 1 的位數相同,則按照數本身值由小到大排序
return x < y;
}
//快讀
LL read() {
LL f = 1, c = 0;
char ch = getchar();
while(!isdigit(ch)) {
if(ch == '-')
f = -1;
ch = getchar();
}
while(isdigit(ch)) {
c = c * 10 + ch - '0';
ch = getchar();
}
return c*f;
}
int main() {
//取消同步的操作
std::ios::sync_with_stdio(false);
n = read();
for(int i = 0; i < n; ++i) {
num[i] = read();
}
//排序
sort(num, num + n, cmp);
for(int i = 0; i < n; ++i) {
printf("%lld ", num[i]);
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/263504.html
標籤:其它技術問題
