练习cf1721A. Image

题目如下
You have an image file of size 2×2, consisting of 4 pixels. Each pixel can have one of 26 different colors, denoted by lowercase Latin letters.

You want to recolor some of the pixels of the image so that all 4 pixels have the same color. In one move, you can choose no more than two pixels of the same color and paint them into some other color (if you choose two pixels, both should be painted into the same color).

What is the minimum number of moves you have to make in order to fulfill your goal?

Input
The first line contains one integer 𝑡 (1≤𝑡≤1000) — the number of test cases.

Each test case consists of two lines. Each of these lines contains two lowercase letters of Latin alphabet without any separators, denoting a row of pixels in the image.

Output
For each test case, print one integer — the minimum number of moves you have to make so that all 4 pixels of the image have the same color.

题目大意
一共四个像素格,每次可以涂掉一个,或者两个相同颜色的格子,对现有的四个像素格至少需要几步才能使他们颜色统一。

题目分析
一共四个格子进行涂色,要求步数尽量少,那么对格子中颜色的分布进行统计,找到分布最广的颜色,统计剩下的格子即可。
因为是四宫格分两行输出先合并成一个串便于统计

点击查看代码
string r1, r2;
        cin >> r1 >> r2;
        string s = r1 + r2;
首先要对每个颜色的频率(分布)进行统计,
点击查看代码
map<char, int> freq;
        for(char ch : s){
            freq[s[ch]]++;
        }
然后将频率存在新的amount数组中便于降序排序,
点击查看代码
vector<int> amount;
        for(auto &p : freq){ //把频率存入amount数组并降序排列
            amount.push_back(p.second);
        }
        sort(amount.rbegin(), amount.rend());
最后分类讨论 完整代码
点击查看代码
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

int main(){
    int t;
    scanf("%d", &t);
    while(t--){
        string r1, r2;
        cin >> r1 >> r2;
        string s = r1 + r2;
        map<char, int> freq;
        for(char ch : s){
            freq[ch]++;
        }
        vector<int> amount;
        for(auto &p : freq){ //把频率存入amount数组并降序排列
            amount.push_back(p.second);
        }
        sort(amount.rbegin(), amount.rend());
        int moves;
        if(amount[0] == 4){
            moves = 0;
        }else if(amount[0] == 3){
            moves = 1;
        }else if(amount[0] == 2 && amount.size() >= 2 && amount[1] == 2){
            moves = 1;
        }else if(amount[0] == 2){
            moves = 2;
        }else{
            moves = 3;
        }
        printf("%d\n", moves);
    }
    return 0;
}
posted @ 2025-07-16 21:36  sirro1uta  阅读(14)  评论(0)    收藏  举报