#31834: Python 非資節解


seer852741@gmail.com (St418)

學校 : 國立中央大學
編號 : 170226
來源 : [114.24.161.39]
最後登入時間 :
2024-01-05 19:57:56
c291. APCS 2017-0304-2小群體 -- 2017年3月APCS | From: [220.129.81.29] | 發表日期 : 2022-08-22 22:50

用check來記錄是否讀取過union
一開始組長的index(start)定為0
next為組長的朋友
跑迴圈直到朋友的朋友...的朋友為組長自己(start == next)
這樣就是一個小群體了(count += 1)
接著尋找下一個start且不重複尋找
全部都check過後(找不到False)輸出count
 
(for迴圈可以改成內建index不過要記得抓錯
另外計數的地方可以用itertools的count比較有效率)
 
一般的寫法如下
n = int(input())
union = tuple(map(int, input().split()))
check = [False] * n
start = 0
count = 0
while True:
    check[start] = True
    next = union[start]
    while start != next:
        check[next] = True
        next = union[next]
    count += 1
    for i in range(start+1, n):
        if check[i] == False:
            start = i
            break
    else:
        print(count)
        break
優化版
from itertools import count
n = int(input())
union = tuple(map(int, input().split()))
check = [False] * n
start = 0
for i in count(1):
    check[start] = True
    next = union[start]
    while start != next:
        check[next] = True
        next = union[next]
    try:
        start = check.index(False, start+1)
    except ValueError:
        print(i)
        break
 
 
ZeroJudge Forum