티스토리 뷰


하반기 코테를 위해 백준문제를 오랜만에 풀어봤따..!!
골고루 틀리면서 정신을 차리고 있다
이 문제는 dfs로 가장 1~n까지 간다고 생각하면 된다
대신 check[현재][이전에 고른 수]를 체크해 가며 가야한다
ans배열을 만들고 내가 수를 고르고 다음수로 넘어갈 때 현재의 수를 넣어주면
탐색이 끝나고 그대로 출력하면 된다
소스코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int n;
int arr[1111][11];
bool check[1111][11];
int ans[1111];
bool solve(int pos,int prev){
if(pos==n-1){
for(int i=1;i<10;i++){
if(i==prev) continue;
if(arr[pos][i]){
ans[pos]=i;
return true;
}
}
}
for(int i=1;i<10;i++){
if(i==prev) continue;
if(arr[pos][i] && !check[pos+1][i]){
check[pos+1][i]=true;
ans[pos]=i;
if(solve(pos+1,i)) return true;
}
}
return false;
}
int main(){
//freopen("input.txt","r",stdin);
scanf(" %d",&n);
for(int i=0;i<n;i++){
int k; scanf(" %d",&k);
for(int j=0;j<k;j++){
int a; scanf(" %d",&a);
arr[i][a]=1;
}
}
if(solve(0,0)){
for(int i=0;i<n;i++) printf("%d\n",ans[i]);
} else puts("-1");
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
|
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs |
'알고리즘 > BOJ' 카테고리의 다른 글
[백준] 16437 양 구출 작전 (0) | 2019.09.20 |
---|---|
[백준] 16434 드래곤 앤 던전 (0) | 2019.09.19 |
[백준] 5052 전화번호 목록 (0) | 2019.09.03 |
[백준] 2751 수 정렬하기 2 (0) | 2019.09.02 |
[백준] 1911 흙길 보수하기 (0) | 2019.08.27 |