Files
python/GESP/Level4/GESP202306/4_2.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

104 lines
2.3 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
const int N = 256;
int b[N]; // 桶
vector<int> top16;
// 十六进制转十进制
int toDec(string s) {
int sum = 0;
if (s[0] >= 'A' && s[0] <= 'F')
sum = (s[0] - 'A' + 10) * 16;
else
sum = (s[0] - '0') * 16;
if (s[1] >= 'A' && s[1] <= 'F')
sum += (s[1] - 'A' + 10);
else
sum += (s[1] - '0');
return sum;
}
// 十进制转十六进制
string toHex(int x) {
string res;
while (x) {
int t = x % 16;
if (t >= 10)
res += t - 10 + 'A';
else
res += t + '0';
x /= 16;
}
reverse(res.begin(), res.end());
if (res.empty())
return "00";
if (res.size() == 1)
return "0" + res;
return res;
}
// 在重新排完序的数据中找出离q最近的灰阶索引号
char find(int q) {
int mi = INT_MAX, mp = 0;
for (int i = 0; i < top16.size(); i++) {
if (abs(q - top16[i]) < mi) {
mi = abs(q - top16[i]);
mp = i;
}
}
if (mp >= 10)
return (char)(mp - 10 + 'A');
return (char)(mp + '0');
}
string c[N]; // 原始数组
int main() {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
string s;
cin >> s; // 录入字符串
c[i] = s; // 记录原始录入的数据
for (int j = 0; j < s.size(); j += 2) {
string x;
x.push_back(s[j]);
x.push_back(s[j + 1]);
b[toDec(x)]++; // 记录桶
}
}
// 开始查找前16位数量多的数字,那我就直接找16次最大的数字是多少,找到后我就把它的数量修改为0
for (int i = 1; i <= 16; i++) {
int mx = 0, mp = 0;
for (int j = 0; j < 256; j++)
if (b[j] > mx) {
mx = b[j];
mp = j;
}
b[mp] = 0; // 清零
// 前十六位的灰阶索引号
top16.push_back(mp);
}
// 输出前16位的灰阶索引号
for (int i = 0; i < top16.size(); i++)
cout << toHex(top16[i]);
cout << endl;
// 遍历原始数据
for (int i = 1; i <= n; i++) {
string s = c[i];
// 两位一组
for (int j = 0; j < s.size(); j += 2) {
string x;
x.push_back(s[j]);
x.push_back(s[j + 1]);
int q = toDec(x);
// 这个数字,与res中哪个数字最接近,接近的含义是差的绝对值最小
cout << find(q);
}
cout << endl;
}
return 0;
}