# 3036. 按数据中1的位数排序

//计算二进制数中1的个数有一个神奇的操作
int num=0,n;//n为二进制数
while(n){
n=n&(n-1);
num++;}
//num即为1的个数

struct Num {
int64_t num;
uint32_t one_cnt;
void count_one() {
auto temp = *reinterpret_cast<uint64_t*>(&num);
one_cnt = 0;
while (temp) {
one_cnt += temp & 1;
temp >>= 1;
}
}
};

int main() {
using namespace std;
uint32_t t; cin >> t;
for (uint32_t query = 0; query < t; ++query) {
printf("case #%u:\n", query);
uint32_t n; cin >> n;
vector<Num> nums(n);
for (auto &i : nums) {
cin >> i.num;
i.count_one();
}
sort(nums.begin(), nums.end(), [](Num const& a, Num const& b) {
if (a.one_cnt == b.one_cnt) {
return a.num < b.num;
} else {
return a.one_cnt > b.one_cnt;
}
});
for (auto const&i : nums) {
printf("%lld ", i.num);
}
putchar('\n');
}
}


### include

using namespace std;

### include

typedef struct{
long long int a;//十进制表示 64位
int cnt;//1的个数
}LIST;

int cmp(const void a,const void b)
{
LIST aa=(LIST)a;
LIST bb=(LIST)b;
if(aa.cnt!=bb.cnt)
return bb.cnt-aa.cnt;
else
return aa.a-bb.a;

}
int main(void)
{
LIST test[1001];
int T,i1,i,j,N;
cin>>T;
for(i1=0;i1>N;
for(i=0;i>test[i].a;
long long int d=1;
for(j=0;j<64;j++)
{
if(test[i].a&d)
test[i].cnt++;
d=d<<1;
}

    }
qsort(test,N,sizeof(LIST),cmp);
cout<<"case #"<<i1<<":"<<endl;
for(i=0;i<N;i++)
{
cout<<test[i].a<<" ";
}
cout<<endl;

}
return 0;


}

bitset，请

#include <iostream>
#include <bitset>
#include <algorithm>
using namespace std;
struct elem {
long long value;
bitset<64> bit;
};
bool cmp(const elem &a, const elem &b) {
if (a.bit.count() == b.bit.count()) {
return (a.value < b.value);
}
return (a.bit.count() > b.bit.count());
}
void solve()
{
int num; cin >> num;
elem *data = new elem[num];
for (int i = 0; i < num; i++) {
cin >> data[i].value;
bitset<64> tmp(data[i].value);
data[i].bit = tmp;
}
sort(data, data + num, cmp);
for (int i = 0; i < num; i++) {
cout << data[i].value << ((i + 1 == num) ? "\n" : " ");
}
}


### include

using namespace std;
bool cmp(long long a1,long long b1){

unsigned long long a = (unsigned long long) a1;
unsigned long long b = (unsigned long long) b1;
int aCnt = 0;
int bCnt = 0;
while(a!=0){
aCnt+=a&1;
a = a>>1;
}
while(b!=0){
bCnt+=b&1;
b = b>>1;
}
if(aCnt == bCnt)return a1<b1;
return (aCnt>bCnt);


}
int main(){
int T ;
int N;
scanf(“%d”,&T);
for(int i =0;i>nums[cnt++];
}
sort(nums,nums+N,cmp);
printf(“case #%d:\n”,i);
for(int i =0;i<N-1;i++){
cout<<nums[i]<<” “;
}
cout<<nums[N-1]<<endl;
}
}