0分求调
查看原帖
0分求调
1382253
tyt_楼主2024/12/12 18:43

求调

#include<bits/stdc++.h>;
using namespace std;
int hexToDec(const string& hex) {
    int dec = 0;
    sscanf(hex.c_str(), "%x", &dec);
    return dec;
}
string decToHex(int dec) {
    char buffer[3];
    sprintf(buffer, "%02X", dec);
    return string(buffer);
}

int main() {
    int n;
    cin >> n;
    cin.ignore();
    map<int, int> grayLevels;
    for (int i = 0; i < n; ++i) {
        string line;
        getline(cin, line);
        for (size_t j = 0; j < line.length(); j += 2) {
            int gray = hexToDec(line.substr(j, 2));
            grayLevels[gray]++;
        }
    }
    vector<pair<int, int>> sortedLevels;
    for (auto& level : grayLevels) {
        sortedLevels.push_back({level.second, level.first});
    }
    sort(sortedLevels.begin(), sortedLevels.end(), [](const pair<int, int>& a, const pair<int, int>& b) {
        return a.first > b.first || (a.first == b.first && a.second < b.second);
    });
    cout << "Selected 16 gray levels (hex): ";
    for (int i = 0; i < 16; ++i) {
        cout << decToHex(sortedLevels[i].second);
    }
    cout << endl;
    vector<int> closest(256, 0);
    for (int i = 0; i < 256; ++i) {
        int minDist = abs(sortedLevels[0].second - i);
        closest[i] = sortedLevels[0].second;
        for (int j = 1; j < 16; ++j) {
            int dist = abs(sortedLevels[j].second - i);
            if (dist < minDist) {
                minDist = dist;
                closest[i] = sortedLevels[j].second;
            }
        }
    }
    for (int i = 0; i < n; ++i) {
        string line;
        getline(cin, line);
        for (size_t j = 0; j < line.length(); j += 2) {
            int gray = hexToDec(line.substr(j, 2));
            cout << decToHex(closest[gray]);
        }
        cout << endl;
    }

    return 0;
}
2024/12/12 18:43
加载中...