알고리즘

[알고리즘] 백준 17140 - 이차원 배열과 연산 (C++)

blueberrysoda 2025. 1. 22. 22:59

[문제 링크] : https://www.acmicpc.net/problem/17140

#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;

int R, C, K;
int Arr[201][201];
int Cnt[101];
int rSize = 3, cSize = 3;

int main(){
    cin >> R >> C >> K;

    int inp;
    for(int i=1; i<=3; i++){
        for(int j=1; j<=3; j++){
            cin >> Arr[i][j];
        }
    }

    int Ans = 0;

    while(true){
        if(Ans > 100){
            cout << -1 << "\n";
            return 0;
        }

        if(Arr[R][C] == K){
            cout << Ans << "\n";
            return 0;
        }

        if(rSize >= cSize){
            int maxi = 0;
            for(int i=1; i<=rSize; i++){
                vector<pair<int, int>> V;
                memset(Cnt, 0, sizeof(Cnt));

                for(int j=1; j<=cSize; j++){
                    Cnt[Arr[i][j]]++;
                }

                for(int j=1; j<101; j++){
                    if(Cnt[j] == 0){
                        continue;
                    }
                    V.push_back({Cnt[j], j});
                }

                for(int j=1; j<=cSize; j++){
                    Arr[i][j] = 0;
                }

                sort(V.begin(), V.end());
                
                int idx = 1;
                for(auto at : V){
                    Arr[i][idx++] = at.second;
                    Arr[i][idx++] = at.first;
                    
                    if(idx > 100){
                        break;
                    }
                }
                idx--;
                maxi = max(maxi, idx);
            }
            cSize = maxi;
        }
        else{
            int maxi = 0;
            for(int i=1; i<=cSize; i++){
                vector<pair<int, int>> V;
                memset(Cnt, 0, sizeof(Cnt));

                for(int j=1; j<=rSize; j++){
                    Cnt[Arr[j][i]]++;
                }

                for(int j=1; j<101; j++){
                    if(Cnt[j] == 0){
                        Arr[j][i] = 0;
                        continue;
                    }
                    V.push_back({Cnt[j], j});
                }

                for(int j=1; j<=rSize; j++){
                    Arr[j][i] = 0;
                }

                sort(V.begin(), V.end());
                
                int idx = 1;
                for(auto at : V){
                    Arr[idx++][i] = at.second;
                    Arr[idx++][i] = at.first;
                    
                    if(idx > 100){
                        break;
                    }
                }
                idx--;
                maxi = max(maxi, idx);
            }
            rSize = maxi;
        }
        Ans++;
    }
    return 0;
}