[programmer]level-2 next配列を用いて集団撮影を行う


https://programmers.co.kr/learn/courses/30/lessons/1835
これはアルゴリズムヘッダのnext permutation()でn個の要素のシーケンスを解くことができる問題であり,まとめてください。 next permutation()の使い方 include <algorithm> next permutation()は、昇順に並べられたコンテナを次のシーケンスの形式に変換し、シーケンスが存在しない場合はfalseを返します。 デフォルトではdo...whileと併用 do { //.... } while (next_permutation(s.begin(), s.end())); sは昇順に並べなければなりません(文字列もそうです) ソース) https://mjmjmj98.tistory.com/38

問題を解く

  • という問題では、Kakaの友人達を文字列順で記憶しています.string str = "ACFJMNRT";
  • 上記の例として
  • next permutationを用いて、各シーケンスにおいてそれぞれの距離を求めて比較検査を行うと終了する.
  • #include <string>
    #include <vector>
    #include <algorithm>
    
    using namespace std;
    
    bool check(string str, char f, char s, char d, int dist) {
        int a = str.find(f) - str.find(s);
        int distance = abs(a) - 1;
        
        if (d == '=') {
            return distance == dist;
        }
        else if (d == '>') {
            return distance > dist;
        }
        else {
            return distance < dist;
        }
    }
    
    // 전역 변수를 정의할 경우 함수 내에 초기화 코드를 꼭 작성해주세요.
    int solution(int n, vector<string> data) {
        int answer = 0;
        string str = "ACFJMNRT";
        
        do {
            bool flag = true;
            for (string s : data) {
                char first = s[0];
                char second = s[2];
                char diff = s[3];
                int dist = s[4] - '0';
                
                if (!check(str, first, second, diff, dist)) {
                    flag = false;
                    break;
                }
            }
            if (flag) answer++;
        } while (next_permutation(str.begin(), str.end()));
        
        return answer;
    }
  • checkは、データが各条件を通過しているかどうかを確認する関数です.
    すべて
  • 条件を通過した後、その順序++に答える.