반응형
[문제 풀이]
1. 1에서 9까지의 서로 다른 숫자 세 개로 구성된 세 자리 수 생성
2. 입력받은 숫자들과 생성한 세 자리 수의 스트라이크 수와 볼 수 체크
3. 입력받은 숫자들과 생성한 세 자리 수의 스트라이크와 볼 수가 모두 일치한다면 가능한 답
[코드]
- 1에서 9까지의 서로 다른 숫자 세 개로 구성된 세 자리 수 생성
- 입력받은 숫자들과 생성한 세 자리 수의 스트라이크와 볼 수가 모두 일치하는지 체크
void find(int cnt, int tmp){
if(cnt == 3){
int check = 0;
for(int i=0; i<N; i++){
int cs = check_strike(num[i], tmp);
int cb = check_ball(num[i], tmp);
if(cs != strike[i] || cb != ball[i]){
check = 1;
break;
}
}
if(check == 0) answer++;
return;
}
for(int i=1; i<=9; i++){
if(visit[i] == 0){
visit[i] = 1;
find(cnt+1, tmp*10+i);
visit[i] = 0;
}
}
}
- 스트라이크 수 체크 함수
int check_strike(int a, int b){
int cnt = 0;
for(int i=0; i<3; i++){
if(a%10 == b%10){
cnt++;
}
a /= 10;
b /= 10;
}
return cnt;
}
- 볼 수 체크 함수
int check_ball(int a, int b){
int cnt = 0;
for(int i=0; i<3; i++){
int m_b = b%10;
int tmp = a;
for(int j=0; j<3; j++){
if(i != j && tmp%10 == m_b){
cnt++;
}
tmp /= 10;
}
b /= 10;
}
return cnt;
}
[전체 코드]
#include <iostream>
using namespace std;
int N, num[101] = {0, }, strike[101] = {0, }, ball[101] = {0, }, answer = 0, visit[10] = {0, };
int check_strike(int a, int b){
int cnt = 0;
for(int i=0; i<3; i++){
if(a%10 == b%10){
cnt++;
}
a /= 10;
b /= 10;
}
return cnt;
}
int check_ball(int a, int b){
int cnt = 0;
for(int i=0; i<3; i++){
int m_b = b%10;
int tmp = a;
for(int j=0; j<3; j++){
if(i != j && tmp%10 == m_b){
cnt++;
}
tmp /= 10;
}
b /= 10;
}
return cnt;
}
void find(int cnt, int tmp){
if(cnt == 3){
int check = 0;
for(int i=0; i<N; i++){
int cs = check_strike(num[i], tmp);
int cb = check_ball(num[i], tmp);
if(cs != strike[i] || cb != ball[i]){
check = 1;
break;
}
}
if(check == 0) answer++;
return;
}
for(int i=1; i<=9; i++){
if(visit[i] == 0){
visit[i] = 1;
find(cnt+1, tmp*10+i);
visit[i] = 0;
}
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin>>N;
for(int i=0; i<N; i++){
cin>>num[i]>>strike[i]>>ball[i];
}
find(0, 0);
cout<<answer<<"\n";
}
https://www.acmicpc.net/problem/2503
반응형
'Algorithm > Baekjoon' 카테고리의 다른 글
[ 백준 9037 ] The candy war (C++) (0) | 2025.03.22 |
---|---|
[ 백준 10994 ] 별 찍기 - 19 (C++) (0) | 2025.02.23 |
[ 백준 1431 ] 시리얼 번호 (C++) (0) | 2025.02.10 |
[ 백준 1388 ] 바닥 장식 (JAVA) (0) | 2025.01.31 |
[ 백준 12789 ] 도키도키 간식드리미 (C++) (0) | 2025.01.26 |