일단 정답코드 받고 싶어서 만든 코드
(4번만에 정답을 받았는데 왜 틀렸나 했더니 11~12라인에서 마지막도시->첫번째도시 길이 있는지 없는지를 체크를 안했었다.)
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 | #include<cstdio> int n, arr[12][12]; bool check[12]; int ans[12]; int minVal=1e9; void tsp(int cnt,int cur) { if(cnt==n) { int temp=0,i; for(i=0; i<n-1; i++) temp+=arr[ans[i]][ans[i+1]]; if(arr[ans[i]][ans[0]]!=0) temp+=arr[ans[i]][ans[0]]; else return; minVal=minVal>temp?temp:minVal; return; } for(int i=1; i<=n; i++) { if(!check[i] && arr[cur][i]!=0) { check[i]=true; ans[cnt]=i; tsp(cnt+1, i); check[i]=false; } } } int main(void) { scanf("%d", &n); for(int i=1; i<=n; i++) for(int j=1; j<=n; j++) scanf("%d", &arr[i][j]); tsp(0, 1); printf("%d", minVal); return 0; } | cs |
근데 이 방식 말고 다른 방법으로도 풀어보고 싶어서 나중에 또 풀어볼 예정ㅠ
'백준 2 > 완전탐색' 카테고리의 다른 글
| [백준 10448] 유레카 이론 (C++) (0) | 2020.12.07 |
|---|---|
| [백준 2231] 분해합 (C++/Python) (0) | 2020.12.07 |
| [백준 2309] 일곱 난쟁이 (C++/Python) (0) | 2020.12.07 |
| [백준 10819] 차이를 최대로 (0) | 2020.12.07 |
| [백준 10974] 모든 순열 (0) | 2020.12.07 |