2668. 숫자고르기
2668번: 숫자고르기
세로 두 줄, 가로로 N개의 칸으로 이루어진 표가 있다. 첫째 줄의 각 칸에는 정수 1, 2, …, N이 차례대로 들어 있고 둘째 줄의 각 칸에는 1이상 N이하인 정수가 들어 있다. 첫째 줄에서 숫자를 적절
www.acmicpc.net
- 내 풀이
- 테케는 맞지만 오답
n=int(input())
lst=[i for i in range(n+1)]
tmp={}
tmp[0]=0
def union(x,y):
xroot=find(x)
yroot=find(y)
if (xroot<yroot):
lst[yroot]=xroot
else:
lst[xroot]=yroot
def find(x):
if x!=lst[x]:
lst[x]=find(lst[x])
return lst[x]
for i in range(1,n+1):
m=int(input())
tmp[i]=m
for idx,v in list(tmp.items()):
if idx==0:
continue
for i in lst:
if v==i and idx==list(tmp.values())[i]:
union(idx,v)
mcount=0
maxInt=[]
for i in lst:
if i==0: continue
if lst.count(i)<mcount: continue
if i in maxInt: continue
if lst.count(i)>mcount:
mcount=lst.count(i)
maxInt.clear()
maxInt.append(i)
c=0
result=[]
for mi in maxInt:
for idx, i in enumerate(lst):
if idx==0:
continue
if i==mi:
c+=1
result.append(idx)
elif idx==list(tmp.values())[idx]:
c+=1
result.append(idx)
print(c)
print(*sorted(result), sep="\n")
- 다른 사람 풀이
- dfs
N = int(input())
lst=[0]
for _ in range(N):
lst.append(int(input()))
answer = set()
# dfs 정의
def dfs(num):
first.add(num)
second.add(lst[num])
if lst[num] in first: # 이어졌던 값 중 lst[num]이 있을 때
if first == second: # 첫번째 줄 집합과 두번째 줄 집합이 같으면 사이클
answer.update(first) # 결과 업데이트
return True
return False
return dfs(lst[num]) # 두번째줄 값 이어서 탐색
# dfs 실행
for i in range(1, N+1):
if i not in answer: # 결과에 없을 경우만
#집합 초기화
first=set()
second=set()
dfs(i)
print(len(answer))
#리스트 한번에 출력하는 방법: print(*list)
print(*sorted(list(answer)), sep="\n")'코딩테스트 > BOJ' 카테고리의 다른 글
| [백준] [DFS] [union-find] 16562. 친구비 (0) | 2023.03.25 |
|---|---|
| [백준] [크루스칼 알고리즘] [union-find] 1647. 도시 분할 계획 (0) | 2023.03.25 |
| [백준] [BFS/DFS] 16928. 뱀과 사다리 게임 (0) | 2023.03.24 |
| [백준] [최단경로] [다익스트라][heap] 1238. 파티 (0) | 2023.03.19 |
| [백준] [최단경로] [다익스트라] 13549. 숨바꼭질 3 (0) | 2023.03.19 |