Files
python/GESP/资料/灰阶图像/糖豆版本.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

103 lines
2.2 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;
//将一个16进制的灰阶转为一个整数,方便用来当数组的下标索引值
int toDec(char a, char b) {
int res = 0;
if (a >= '0' && a <= '9')
res += (a - '0') * 16;
else if (a >= 'A' && a <= 'F')
res += (a - 'A' + 10) * 16;
if (b >= '0' && b <= '9')
res += b - '0';
else if (b >= 'A' && b <= 'F')
res += b - 'A' + 10;
return res;
}
//将一个十进制的灰阶值[0,255]转化成十六进制[0,FF]
string toHex(int x) {
char c1, c2;
int a = x % 16; // 0 ~ 15
int b = x / 16; //
if (a >= 10)
c1 = 'A' + a - 10;
else
c1 = '0' + a;
if (b >= 10)
c2 = 'A' + b - 10;
else
c2 = '0' + b;
string res;
res.push_back(c2);
res.push_back(c1);
return res;
}
const int N = 256;
//桶
int bucket[N];//0 ~ 255
//原始的字符串数组
string q[30];
//结构体,用来把桶中的灰阶按数量排序用的
struct Node {
int id;//数组下标
int cnt;//个数
const bool operator<(const Node &b) const {
if (cnt == b.cnt)
return id < b.id;
return cnt > b.cnt;
}
};
vector<Node> vec;//需要把bucket组装成Node放到数组p中,才能使用结构体排序吧
int main() {
freopen("D://HuiJie.txt", "r", stdin);
int n;
cin >> n;//有n行数据组成了图像
for (int i = 1; i <= n; i++) {
string s;
cin >> s;
q[i] = s;//存入原始字符串数组
for (int j = 0; j < s.size(); j += 2) {
char a = s[j], b = s[j + 1];
int k = toDec(a, b); //灰阶对应的数组位置
bucket[k]++;
}
}
for (int i = 0; i <= 255; i++)
vec.push_back({i, bucket[i]});
sort(vec.begin(), vec.end());
//前十六位字符打印出来
for (int i = 0; i < min(16, (int)vec.size()); i++)
cout << toHex(vec[i].id) ;
cout << endl;
//第二问的回答
for (int i = 1; i <= n; i++) { //枚举每个原始字符串,每2个一组,判断这个小串应该与尺子数组中的哪一个更接近
for (int j = 0; j < q[1].size(); j += 2) {
char a = q[i][j], b = q[i][j + 1]; //0 F ,0 F
int x = toDec(a, b);
int mi = INT_MAX;
int mi_p = 0;
for (int k = 0; k < min(16, (int)vec.size()); k++) { //16是有风险的,因为可能没有16个那么多
if (mi > abs(vec[k].id - x)) {
mi = abs(vec[k].id - x);
mi_p = k;
}
}
cout << toHex(mi_p)[1];
}
cout << endl;
}
return 0;
}