[Python] 백준 #10971- 외판원 순회 2

2021. 12. 29. 22:15·코딩테스트/백준[Python]

문제


 

 

10971번: 외판원 순회 2

첫째 줄에 도시의 수 N이 주어진다. (2 ≤ N ≤ 10) 다음 N개의 줄에는 비용 행렬이 주어진다. 각 행렬의 성분은 1,000,000 이하의 양의 정수이며, 갈 수 없는 경우는 0이 주어진다. W[i][j]는 도시 i에서 j

www.acmicpc.net

코드


My answer

import sys
from itertools import permutations

n,cost=int(input()),0
city,result=[],1000000*n
order=[i for i in range(n)]

for i in range(n):
    city.append(list(map(int,sys.stdin.readline().split())))

for i in permutations(order,n):
    if(city[i[-1]][i[0]]!=0):
        for j in range(n-1):
            if(city[i[j]][i[j+1]]==0):
                cost=0
                break
            cost+=city[i[j]][i[j+1]]
        if(cost!=0):
            cost+=city[i[-1]][i[0]]
            result=min(cost,result)
    cost=0
print(result)

Another answer

from itertools import permutations
from sys import stdin
N = int(stdin.readline())
per = list(permutations([(i+1) for i in range(N)], N))
data = []
for i in range(N):
    data.append(list(map(int, stdin.readline().split())))

result = 10 ** 10
for i in range(len(per)//N):
    result_tem = 0
    judge = True
    for j in range(N):
        if data[(per[i][j]) - 1][(per[i][(j+1) % N]) - 1] == 0:
            judge = False
        result_tem += data[(per[i][j]) - 1][(per[i][(j+1) % N]) - 1]
    if result_tem < result and judge:
        result = result_tem
print(result)

 

풀이


우선 내 코드는 pypy에서는 돌아갔지만 python3에서는 시간초과가 떴다...python3으로 해결해보려했으나 pypy로 돌아가면 그냥 pass하라는 어떤분의 답변으로 그냥 넘어가기로했다. python으로 성공한 답변들중 내것과 가장 유사한걸 another answer에 올려놨는데 어떻게 한건지 모르겠다.. 내코드와 어느 부분이 다른거지?.. 우선 judge는 나는 cost=0으로 만듦으로써 따로 체크안해줘도됐고 어디가 문젠지 모겠다.. 반복문에서 len(per)//N인것 같은데 이 코드가 무엇을 의미하는지 모르겠다. 다른분의 코드에서도 아래코드를 작성한뒤 반복문을 돌리니까 돌아가던데 이해를 못했다.. 아래코드만 사용해서 내 코드를 바꾸면 python으로도 통과과 된다..

path = permutation[:len(permutation) // n]

 

import sys
from itertools import permutations

n,cost=int(input()),0
city,result=[],1000000*n
order=[i for i in range(n)]

for i in range(n):
    city.append(list(map(int,sys.stdin.readline().split())))
permutation = list(permutations(list(range(0, n ))))
path = permutation[:len(permutation) // n]

for i in path:
    if(city[i[-1]][i[0]]!=0):
        for j in range(n-1):
            if(city[i[j]][i[j+1]]==0):
                cost=0
                break
            cost+=city[i[j]][i[j+1]]
        if(cost!=0):
            cost+=city[i[-1]][i[0]]
            #result=min(cost,result)
            if(result>cost):
                result=cost
    cost=0
print(result)
728x90

'코딩테스트 > 백준[Python]' 카테고리의 다른 글

[Python] 백준 #15486- 퇴사 2 [try_again]  (0) 2021.12.30
[Python] 백준 #1697- 숨바꼭질[try_again]  (0) 2021.12.30
[Python] 백준 #10819- 차이를 최대로  (0) 2021.12.28
[Python] 백준 #9465- 스티커[try_again]  (0) 2021.12.21
[Python] 백준 #2193 - 이친수  (0) 2021.12.21
'코딩테스트/백준[Python]' 카테고리의 다른 글
  • [Python] 백준 #15486- 퇴사 2 [try_again]
  • [Python] 백준 #1697- 숨바꼭질[try_again]
  • [Python] 백준 #10819- 차이를 최대로
  • [Python] 백준 #9465- 스티커[try_again]
창빵맨
창빵맨
  • 창빵맨
    Let's be Developers
    창빵맨
    로그인/로그아웃
  • 전체
    오늘
    어제
    • 분류 전체보기 (471)
      • 알쓸신잡 (79)
      • ML & DL (85)
        • Computer v.. (22)
        • NLP (22)
        • 파이썬 머신러닝 완.. (3)
        • 개념정리 (38)
      • 리눅스 (21)
      • 프로젝트 (29)
        • 산불 발생 예측 (6)
        • 음성비서 (12)
        • pdf 병합 프로그.. (0)
        • 수위 예측 (5)
        • 가짜 뉴스 분류 (5)
        • 전력사용량 예측 (1)
      • 코딩테스트 (217)
        • 프로그래머스[Pyt.. (17)
        • 프로그래머스[Fai.. (3)
        • 백준[Python] (160)
        • 이것이취업을위한코딩.. (18)
        • 파이썬 알고리즘 (19)
      • 데이터분석실습 (25)
        • 데이터 과학 기반의.. (18)
        • 헬로 데이터 과학 (7)
      • 메모장 (0)
      • 잡담 (4)
  • Personal

    GITHUB
    Instagram
  • 공지사항

  • 인기 글

  • 태그

    dp
    BFS
    파이썬
    나동빈
    이분탐색
    백준
    이코테
    이것이취업을위한코딩테스트다
    DFS
    그리디
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3

HOME

HOME

상단으로

티스토리툴바