16. 혼자 놀기의 달인

aj4941·2023년 9월 4일
0

https://school.programmers.co.kr/learn/courses/30/lessons/131130

idx를 이동시키는 과정의 while 문에 약간의 혼동이 있어서 정리했다.

#include <bits/stdc++.h>
using namespace std;
int n;
int pos[200];
bool cache[200];

int solution(vector<int> a) 
{   
    n = a.size();
    
    vector<int> v;
    
    for (int i = 0; i < n; i++)
    {
        if (cache[i]) continue;
        int cnt = 0, idx = i;
        while (!cache[idx])
        {
            // cout << idx << endl;
            cache[idx] = true;
            int nidx = a[idx] - 1;
            idx = nidx; cnt++;
        }
        
        // cout << "end" << endl;
        v.push_back(cnt);
    }
    
    if (v.size() < 2) return 0;
    sort(v.rbegin(), v.rend());
    // for (auto to : v) cout << to << ' ';
    return v[0] * v[1];
    
}
profile
안녕하세요 aj4941 입니다.

0개의 댓글