Life Engineering
[프로그래머스] 단체사진 찍기 (C++) 본문
https://programmers.co.kr/learn/courses/30/lessons/1835
#include <string>
#include <vector>
#include <algorithm>
#include <cstdlib>
using namespace std;
int solution(int n, vector<string> data) {
int answer = 0;
vector<char> v={'A', 'C', 'F', 'J', 'M', 'N', 'R', 'T'};
do{
vector<char> temp;
vector<char>::iterator it1;
vector<char>::iterator it2;
bool flag=true;
for (auto it=v.begin(); it!=v.end(); it++){
temp.push_back(*it);
}
for (string s : data){
int me=s[0];
int you=s[2];
it1=find(temp.begin(), temp.end(), me); //조건 불만족, flag=false 후 break
it2=find(temp.begin(), temp.end(), you);
if (s[3]=='='){
if ((abs(it1-it2)-1)!=(s[4]-'0')){
flag=false;
break;
}
}
else if (s[3]=='<'){
if ((abs(it1-it2)-1)>=(s[4]-'0')){
flag=false;
break;
}
}
else{
if ((abs(it1-it2)-1)<=(s[4]-'0')){
flag=false;
break;
}
}
}
if (flag){
answer++;
}
} while (next_permutation(v.begin(), v.end()));
return answer;
}
처음엔 막막했다.. 확률과 통계 문제 푸는 것처럼 해야하나?
했는데.. 잘 생각해보니 답은 완전탐색이었다. (8!=40320 이므로 완전탐색 완전 가능이다)
가능한 모든 순열을 탐색하고, 그 순열 중에 조건을 만족하는 애들만 세주면 된다.
me와 friend의 index를 찾은 후에 둘 간의 거리가 조건들을 모두 만족하면(하나라도 조건 만족하지 못하면 flag값을 false 를 주고, 조건을 따져보는 반복문을 탈출한다) answer++ 을 해주면 된다.
순열을 구할 땐 next_permutation 함수를 사용한다.
그런데 애초에 temp에 순열을 안 넣어줘도 된다.. v 로 그대로 진행해도 ok 다.
그리고 find 할 때 temp.begin() 이 부분 안넣어줘도 된다.. 그냥 찾고자 하는 문자만 넣어주면 ok다.
=,<,> 에 따라 if..else 로 하지 말고 차라리 함수로 따로 빼준다.
bool isRight(int diff, int dist, char c) 해줘서, diff가 dist 와 일치하면 c에 따라 (diff<dist, diff==dist, diff>dist ) 이런 식으로 해줘서 조건을 만족하면 true를 리턴하게 해주는 방식이 더 깔끔하다.
'Problem Solving' 카테고리의 다른 글
[프로그래머스] 소수 찾기 (C++) (0) | 2021.09.22 |
---|---|
[BOJ 16236] 아기 상어 (C++) (0) | 2021.09.17 |
[프로그래머스] 신규 아이디 추천 (C++) (0) | 2021.09.16 |
[프로그래머스] 메뉴 리뉴얼 (C++) (0) | 2021.09.14 |
[프로그래머스] 카카오프렌즈 컬러링북 (C++) (0) | 2021.09.14 |