1 条题解

  • 0
    @ 2025-9-6 13:38:22

    C++ :

    #include <bits/stdc++.h>
    using namespace std;
    #define N 25
    struct Node
    {
    	int col, num;
    };
    int a[N][N], ct[256], mp[256];
    int toNum(char c)//十六进制数码字符转为整数 
    {
    	return c >= '0' && c <= '9' ? c-'0' : c-'A'+10;
    }
    char toChar(int v)//0~15的整型值转为十六进制字符 
    {
    	return v <= 9 ? v+'0' : v-10+'A';
    }
    string toStr(int n)//0~255的整型值转为十六进制字符串 
    {
    	return string{toChar(n/16),toChar(n%16)};
    }
    bool cmp (Node a, Node b)//排序规则:取数量最多的前16种灰阶(如某种灰阶的数量与另外一种灰阶的数量相同,则以灰阶值从小到大为序)
    {
    	return a.num > b.num || a.num == b.num && a.col < b.col;
    }
    int main()
    {
    	string s; 
    	vector<Node> v;
    	int n, m;
    	cin >> n;
    	for(int i = 0; i < n; ++i)
    	{
    		cin >> s;
    		m = s.length()/2;//m:列数 
    		for(int j = 0; j < m; ++j)
    		{
    			a[i][j] = toNum(s[2*j])*16+toNum(s[2*j+1]);//s[2*j]和s[2*j+1]构成a[i][j]的数值 
    			ct[a[i][j]]++;//颜色a[i][j]出现的次数增加1 
    		}
    	}
    	for(int col = 0; col < 256; ++col) if(ct[col] > 0) 
    		v.push_back(Node{col, ct[col]});//将所有颜色和其出现的次数加入vector 
    	sort(v.begin(), v.end(), cmp);//根据要求排序 
    	for(int i = 0; i < 16; ++i)//取前16个颜色 
    		cout << toStr(v[i].col);
    	cout << endl;
    	for(int col = 0; col < 256; ++col)
    	{
    		int mni = 0;
    		for(int i = 0; i < 16; ++i)//求出v[0]~v[15]这前16项中,与col差值的绝对值最小的颜色的下标mni 
    			if(abs(col-v[i].col) < abs(col-v[mni].col))
    				mni = i;
    		mp[col] = mni;//颜色col(0~255)压缩后的颜色数值为mni(0~15) 
    	}
    	for(int i = 0; i < n; ++i)
    	{
    		for(int j = 0; j < m; ++j)
    			cout << toChar(mp[a[i][j]]);//将颜色a[i][j]转为压缩后的颜色数值mp[a[i][j]],再转为十六进制字符输出 
    		cout << endl;
    	}
    	return 0;
    }
    
    
    • 1

    信息

    ID
    5537
    时间
    1000ms
    内存
    128MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者