题解:P14602 [NWRRC 2025] Compact Encoding

· · 题解

显然直接按照题意模拟。

n 转换成二进制(注意要倒序存),从低位到高位七位一分块,最高位的一个块可能不足七位就补 0。除最后一个块外其他块加 128

以及需要特判 n=0

代码

在众多可行的实现中选择了最唐的一种。

#include<iostream>
using namespace std;
int n;
int a[30];
int tmp[35]={0},cnt=0;
int idx=0;
void fz(int x){//二进制拆分
    while(x){
        tmp[++cnt]=x&1;
        x>>=1;
    }
    for(int i=1;i<=cnt/2;i++){
        int t=tmp[i];tmp[i]=tmp[cnt-i+1];tmp[cnt-i+1]=t;
    }//逆序
    int ans=0;
    for(int i=1;i<=cnt;i++){
        ans*=2;
        ans+=tmp[i];
    }
    n=ans;
}
void gtw(int x){
    int tag=(7-cnt%7)%7,tmpp=0;//补0
    for(int i=1;i<=cnt;i++){
        tmpp*=2;tmpp+=tmp[i];
        tag++;
        if(tag==7){
            if(i!=cnt)a[++idx]=tmpp+128;
            else a[++idx]=tmpp;
            tag=0;
            tmpp=0;
        }
    }
}
int main(){
    cin >> n;
    if(n==0){
        cout << 0;
        return 0;
    }
    fz(n);
    gtw(n);
    for(int i=1;i<=idx;i++)cout << a[i] << " ";
    return 0;
}