input
stringlengths 20
127k
| target
stringlengths 20
119k
| problem_id
stringlengths 6
6
|
---|---|---|
n= int(eval(input()))
card = input().split(' ')
card = [int(s) for s in card]
min_s = 1000000000000
for i in range(n -1):
if abs(sum(card[:i+1]) - sum(card[i+1:])) < min_s:
min_s= abs(sum(card[:i+1]) - sum(card[i+1:]))
print(min_s)
|
n= int(eval(input()))
card = input().split(' ')
card = [int(s) for s in card]
min_s = 20000000000
sum1 = sum(card[:1])
sum2 = sum(card[1:])
for i in range(n - 1):
dif = abs(sum1-sum2)
if dif < min_s:
min_s = dif
sum1 += card[i+1]
sum2 = sum2 - card[i+1]
print(min_s)
|
p03659
|
N = int(eval(input()))
a = list(map(int,input().split()))
ans = 2*10**9
allsum = sum(a)
for n in range(1,N):
ans_candidate = abs(2*sum(a[:n])- allsum)
if ans > ans_candidate:
ans = ans_candidate
print(ans)
|
N = int(eval(input()))
a = list(map(int,input().split()))
ans = 2*10**9
allsum = sum(a)
snukesum = 0
for n in range(1,N):
snukesum += a[n-1]
ans_candidate = abs(2*snukesum- allsum)
if ans > ans_candidate:
ans = ans_candidate
print(ans)
|
p03659
|
N = int(eval(input()))
src = list(map(int, input().split()))
s = [0]
for i in range(N):
s.append(s[-1] + src[i])
ans = float('inf')
for i in range(N-1):
a = s[i+1]
b = s[-1] - s[i+1]
df = abs(a-b)
ans = min(ans, df)
print(ans)
|
N = int(eval(input()))
src = list(map(int,input().split()))
s = sum(src)
ans = float('inf')
tmp = 0
for i in range(N-1):
tmp += src[i]
rem = s - tmp
ans = min(ans, abs(tmp - rem))
print(ans)
|
p03659
|
N = int(eval(input()))
A = list(map(int,input().split()))
cums = [0]
for a in A:
cums.append(cums[-1] + a)
ans = 10**20
for i in range(1,N):
x = cums[i]
y = cums[-1] - cums[i]
ans = min(ans, abs(x-y))
print(ans)
|
N = int(eval(input()))
A = list(map(int,input().split()))
cums = [0]
for a in A:
cums.append(cums[-1] + a)
ans = float('inf')
for i in range(1,N):
c = cums[i]
ans = min(ans, abs(cums[-1]-c - c))
print(ans)
|
p03659
|
def main():
N = int(eval(input()))
a = list(map(int, input().split()))
sum_a = sum(a)
min_diff = float('inf')
for i in range(1,N):
if min_diff > abs(sum_a-2 * sum(a[i:])):
min_diff = abs(sum_a-2 * sum(a[i:]))
print(min_diff)
main()
|
def main():
N = int(eval(input()))
a = list(map(int, input().split()))
sum_a = sum(a)
min_diff = float('inf')
sum_first = 0
for i in range(N-1):
sum_first += a[i]
if min_diff > abs(sum_a - 2 * sum_first):
min_diff = abs(sum_a - 2 * sum_first)
print(min_diff)
main()
|
p03659
|
n = int(eval(input()))
arr = input().split()
x = 0
y = 0
for i in range(n):
arr[i] = int(arr[i])
min_xy = abs(arr[0] - sum(arr[1:]))
for i in range(1,n):
x = sum(arr[:i])
y = sum(arr[i:])
if min_xy > abs(x - y):
min_xy = abs(x - y)
print(min_xy)
|
n = int(eval(input()))
arr = list(map(int,input().split()))
sum_arr = sum(arr)
ans=[]
x = 0
for i in range(n-1):
x += arr[i]
y = sum_arr - x
ans.append(abs(x - y))
print((min(ans)))
|
p03659
|
n = int(eval(input()))
a = list(map(int, input().split()))
sum_a = sum(a)
lis = [sum_a]
for i in range(n-1):
lis.append(abs(sum_a - 2 * sum(a[:i+1])))
print((min(lis[1:])))
|
n = int(eval(input()))
a = list(map(int, input().split()))
if n == 2:
print((abs(a[1] - a[0])))
exit()
s = [0]
for i in range(n):
s.append(s[-1]+a[i])
s = s[1:]
ma = s[-1]
ans = 10 ** 18
for i in s[:-1]:
ans = min(ans, abs(ma-2*i))
print(ans)
|
p03659
|
n = int(eval(input()))
A = list(map(int, input().split()))
S = [0]*(n+1)
for i in range(n):
S[i+1] = S[i]+A[i]
INF = 10**18
ans = INF
for R in range(1, n):
ans = min(ans, abs((S[R]-S[0])-(S[n]-S[R])))
print(ans)
|
n = int(eval(input()))
A = list(map(int, input().split()))
sum_A = sum(A)
INF = 10**18
ans = INF
X = 0
for a in A[:-1]:
X += a
ans = min(ans, abs(2*X-sum_A))
print(ans)
|
p03659
|
N = int(eval(input()))
I = list(map(int, input().split()))
minX = 10000000000
end = I.pop()
for i in range(len(I)):
minX = min(minX, abs(sum(I) - end ) )
end += I.pop()
print(minX)
|
N = int(eval(input()))
I = list(map(int, input().split()))
minX = 10000000000
end = I.pop()
sumI = sum(I)
for i in range(len(I)):
minX = min(minX, abs(sumI - end ) )
popped = I.pop()
sumI -= popped
end += popped
print(minX)
|
p03659
|
# vim: set fileencoding=utf-8 :
n = int(input())
a = list(map(int, input().split()))
diff = None
min_diff = 999999999999999999
for i in range(n - 1):
x = sum(a[0:i + 1])
y = sum(a[i + 1:])
diff = abs(x - y)
if diff < min_diff:
min_diff = diff
print(min_diff)
|
# vim: set fileencoding=utf-8 :
n = int(input())
a = list(map(int, input().split()))
diff = None
min_diff = 999999999999999999
x = 0
y = sum(a)
for i in range(n - 1):
x += a[i]
y -= a[i]
diff = abs(x - y)
if diff < min_diff:
min_diff = diff
print(min_diff)
|
p03659
|
def main():
N, *a = list(map(int, open(0).read().split()))
print((min(abs(2 * sum(a[:i]) - sum(a)) for i in range(1, N))))
return
main()
|
INF = float('inf')
def main():
N, *a = list(map(int, open(0).read().split()))
ans = INF
tmp = 0
total = sum(a)
for i in range(N - 1):
tmp += a[i]
ans = min(ans, abs(2 * tmp - total))
print(ans)
return
main()
|
p03659
|
from itertools import accumulate
def main():
N, *a = list(map(int, open(0).read().split()))
a = tuple(accumulate(a))
print((min(abs(2 * a[i] - a[-1]) for i in range(N - 1))))
return
main()
|
from itertools import accumulate
def main():
N, *a = list(map(int, open(0).read().split()))
a = tuple(accumulate(a))
total = a[-1]
print((min(abs(2 * a[i] - total) for i in range(N - 1))))
return
main()
|
p03659
|
n = int(eval(input()))
l = list(map(int,input().split()))
l.reverse()
x = 0
sum_x = []
for i in range(n-1):
x += l[i]
sum_x.append(x)
sum_y = [sum(l)]*(n-1)
for i in range(n-1):
sum_y[i] -= sum_x[i]
abs_xy = []
for i in range(n-1):
abs_xy.append(abs(sum_x[i]-sum_y[i]))
print((min(abs_xy)))
|
n = int(eval(input()))
l = list(map(int,input().split()))
l.reverse()
x = 0
sum_x = []
sum_y = [sum(l)]*(n-1)
abs_xy = []
for i in range(n-1):
x += l[i]
sum_x.append(x)
sum_y[i] -= sum_x[i]
abs_xy.append(abs(sum_x[i]-sum_y[i]))
print((min(abs_xy)))
|
p03659
|
n=int(eval(input()))
a=list(map(int,input().split()))
ans=[]
for i in range(1,n):
snuke=sum(a[0:i])
raccoon=sum(a)-snuke
ans.append(abs(snuke-raccoon))
print((min(ans)))
|
n=int(eval(input()))
a=list(map(int,input().split()))
X=sum(a)
ans=[]
snuke=0
for i in range(n-1):
snuke+=a[i]
ans.append(abs(X-2*snuke))
print((min(ans)))
|
p03659
|
N = int(eval(input()))
a = [int(i) for i in input().split()]
sum_a = sum(a)
b = []
for i in range(N-1):
b.append(abs(2*sum(a[:i+1])-sum_a))
print((min(b)))
|
N = int(eval(input()))
a = [int(i) for i in input().split()]
sum_a = sum(a)
b = []
c = 0
for i in range(N-1):
c += a[i]
b.append(abs(2*c-sum_a))
print((min(b)))
|
p03659
|
def splitting_pile():
n = int(input())
nums = list(map(int, input().split(" ")))
ans = abs(sum(nums[:1])-sum(nums[1:]))
for i in range(1, n):
ans = min(ans, abs(sum(nums[:i])-sum(nums[i:])))
print(ans)
if __name__ == "__main__":
splitting_pile()
|
def splitting_pile_2():
n = int(input())
nums = list(map(int, input().split(" ")))
total_sum = sum(nums)
left_sum = nums[0]
ans = abs(total_sum-left_sum*2)
for i in range(1, n-1):
left_sum = left_sum + nums[i]
ans = min(ans, abs(total_sum-left_sum*2))
print(ans)
if __name__ == "__main__":
splitting_pile_2()
|
p03659
|
N = int(eval(input()))
a = list(map(int, input().split(" ")))
min_a = 999999999999999
for i in range(1, len(a)):
cal = abs(sum(a[:i]) - sum(a[i:]))
if cal < min_a:
min_a = cal
print(min_a)
|
N = int(eval(input()))
a = list(map(int, input().split(" ")))
su = sum(a)
diff = 1e10
cc = 0
for i in range(len(a)-1):
cc += a[i]
diff = min(diff, abs(su-2*cc))
print(diff)
|
p03659
|
n = int(eval(input()))
num_list = list(map(int, input().split()))
dis = n * 10**9
for i in range(1,n):
a = sum(num_list[:i])
b = sum(num_list[i:])
if abs(a-b) < dis:
dis = abs(a-b)
print(dis)
|
n = int(eval(input()))
num_list = list(map(int, input().split()))
total = sum(num_list)
dis = []
a=0
for i in range(n-1):
a += num_list[i]
b = total - a
dis.append(abs(a-b))
print((min(dis)))
|
p03659
|
n = int(eval(input()))
a = list(map(int, input().split()))
cumsum = [a[0]]
for i in range(len(a)-1):
cumsum.append(cumsum[i] + a[i+1])
min = float('inf')
for i in range(len(cumsum)-1):
f1 = cumsum[i]
f2 = cumsum[-1] - cumsum[i]
d = abs(f1 - f2)
if min > d:
min = d
print(min)
|
N = int(eval(input()))
a = list(map(int, input().split()))
sa = a[:]
for i in range(N-1):
sa[i+1] += sa[i]
diff = float('inf')
for i in range(N-1):
if abs(sa[i] - (sa[-1] - sa[i])) < diff:
diff = abs(sa[i] - (sa[-1] - sa[i]))
print(diff)
|
p03659
|
n=int(eval(input()))
a=[int(i) for i in input().split()]
m=float("inf")
for i in range(1,n):
m = min(abs(sum(a[:i]) - sum(a[i:])),m)
print((int(m)))
|
n=int(eval(input()))
a=[int(i) for i in input().split()]
x=a[0]
y=sum(a[1:])
m=abs(x - y)
i=1
while i < n-1:
x+=a[i]
y-=a[i]
m = min(abs(x - y),m)
i+=1
print(m)
|
p03659
|
# Splitting Pile
N = int(eval(input()))
a = list(map(int, input().split()))
s = [abs(sum(a[:i+1])-sum(a[i+1:])) for i in range(N-2)]
if len(a)==2:
print((abs(a[0]-a[1])))
else:
print((min(s)))
|
# Splitting Pile
N = int(eval(input()))
a = list(map(int, input().split()))
s = [sum(a[1:]) - a[0]]
for i in range(N-2):
s.append( s[i]- 2*a[i+1] )
a = list(map(abs, s))
print((min(a)))
|
p03659
|
n = int(eval(input()))
a = list(map(int,input().split()))
x = sum(a)
difference = []
for i in range(n-1):
x = x - a[i]
difference.append(abs(sum(a)-2*x))
print((min(difference)))
|
n = int(eval(input()))
a = list(map(int,input().split()))
x = sum(a)
t = sum(a)
difference = []
for i in range(n-1):
x = x - a[i]
difference.append(abs(t-2*x))
print((min(difference)))
|
p03659
|
# C - pushpush
N = int(eval(input()))
a = list(map(int,input().split()))
S = sum(a)
lst = [0]*N
x = 0
y = 0
for i in range(N):
x = sum(a[0:i])
y = S - x
lst[i] = abs(x-y)
lst.pop(0)
ans = min(lst)
print(ans)
|
# C - Splitting Pile
N = int(eval(input()))
a = list(map(int,input().split()))
lst = [0]*(N-1)
x = [a[0]]*(N-1)
y = [sum(a)-a[0]]*(N-1)
lst[0] = abs(x[0]-y[0])
for i in range(1,N-1):
x[i] = x[i-1]+a[i]
y[i] = y[i-1]-a[i]
lst[i] = abs(x[i]-y[i])
"""
print(x)
print(y)
print(lst)
"""
ans = min(lst)
print(ans)
|
p03659
|
def 解():
iN = int(eval(input()))
aA = [int(_) for _ in input().split()]
#itertools をつかわず 累積和でやってみると?
aAc = [0]*iN
aAc[0] = aA[0]
for i in range(1,iN):
aAc[i] = aAc[i-1] + aA[i]
iD = aAc[-1]
minDiff = 10**9 *2
for i in range(iN-1):
minDiff = min(minDiff,abs(iD-2*aAc[i]))
print(minDiff)
解()
|
def 解():
iN = int(eval(input()))
aA = [int(_) for _ in input().split()]
iD = sum(aA)
iF = 0
minDiff = 10**9 * 2
for a in aA[:-1] :
iF += a
thisDiff = abs(iD - 2*iF)
minDiff = min(minDiff , thisDiff)
print(minDiff)
解()
|
p03659
|
def 解():
iN = int(eval(input()))
aA = [int(_) for _ in input().split()]
iD = sum(aA)
iF = 0
minDiff = 10**9 * 2
for a in aA[:-1] :
iF += a
thisDiff = abs(iD - 2*iF)
minDiff = min(minDiff , thisDiff)
print(minDiff)
解()
|
def 解():
iN = int(eval(input()))
aA = [int(_) for _ in input().split()]
aDiff = [0]*(iN-1)
iD = sum(aA)
iF = 0
for i in range(iN-1):
iF += aA[i]
aDiff[i] = abs(iD - 2*iF)
print((min(aDiff)))
解()
|
p03659
|
N = int(eval(input()))
A = list(map(int,input().split()))
num = []
for i in range(1,N):
num.append(abs(sum(A[:i]) - sum(A[i:])))
print((min(num)))
|
N = int(eval(input()))
A = list(map(int,input().split()))
X = sum(A)
x = 0
result = []
for i in range(N-1):
x += A[i]
result.append(abs(X - 2*x))
print((min(result)))
|
p03659
|
n = int(eval(input()))
a = [int(x) for x in input("").split()]
min = 0
for i in range(1,n):
all = 0
for j in range(0,i):
all += a[j]
for j in range(i,n):
all -= a[j]
if i == 1:
min = abs(all)
else:
if min > abs(all):
min = abs(all)
print(min)
|
n = int(eval(input()))
a = [int(x) for x in input("").split()]
min = 0
left = []
for i in range(n-1):
left.append(a[i])
if i > 0:
left[i] += left[i-1]
a.reverse()
right = []
for i in range(n-1):
right.append(a[i])
if i > 0:
right[i] += right[i-1]
right.reverse()
min = 0
for i in range(1,n):
if i == 1:
min = abs(left[i-1] - right[i-1])
else:
if min > abs(left[i-1] - right[i-1]):
min = abs(left[i-1] - right[i-1])
print(min)
|
p03659
|
#!/usr/bin/env python3
import math
N = int(input().split()[0])
a_list = list(map(int, input().split()))
total = sum(a_list)
work_list = []
for i in range(N - 1):
sunuke = sum(a_list[: i + 1])
arai = total - sunuke
work_list.append(abs(sunuke - arai))
ans = min(work_list)
print(ans)
|
#!/usr/bin/env python3
import math
N = int(input().split()[0])
a_list = list(map(int, input().split()))
total = sum(a_list)
work_list = []
sunuke = 0
for i in range(N - 1):
sunuke += a_list[i]
arai = total - sunuke
work_list.append(abs(sunuke - arai))
ans = min(work_list)
print(ans)
|
p03659
|
n=int(eval(input()))
A=list(map(int,input().split()))
L=[A[0]]
R=[A[-1]]
for i in range(1,n-1):
l=L[i-1]+A[i]
L.append(l)
r=R[i-1]+A[-(i+1)]
R.append(r)
c=2*10**14
for i in range(n-1):
s=abs(L[i]-R[-(i+1)])
c=min(c,s)
print(c)
|
n=int(eval(input()))
A=list(map(int,input().split()))
X=sum(A)
x=0
c=2*10**14
for i in range(n-1):
x+=A[i]
s=abs(X-2*x)
c=min(c,s)
print(c)
|
p03659
|
n=int(eval(input()))
l=list(map(int,input().split()))
m=float('inf')
for i in range(1,n):
m=min(m,abs(sum(l[:i])-sum(l[i:])))
print(m)
|
n=int(eval(input()))
l=list(map(int,input().split()))
a,b=l[0],sum(l[1:])
m=abs(a-b)
for v in l[1:-1]:
a+=v
b-=v
m=min(m,abs(a-b))
print(m)
|
p03659
|
n = int(eval(input()))
a = list(map(int, input().split()))
s = [0] * (n + 1)
for i in range(n):
s[i + 1] = s[i] + a[i]
ans = 3e9
for i in range(n - 1):
ans = min(ans, abs((s[n] - s[i + 1]) - s[i + 1]))
print(ans)
|
N=int(eval(input()))
A=list(map(int,input().split()))
s=[0]*(N+1)
for i in range(N): s[i + 1]=s[i]+A[i]
C=[0]*(N)
C[0]=-s[N]
x=10**10
p=0
for i in range(1, N):
C[i]=C[i-1]+2*A[i-1]
if x>abs(C[i]):
x=abs(C[i])
p=i
print(x)
#print(C)
|
p03659
|
n=int(eval(input()))
a=list(map(int,input().split()))
A=a[0]
for i in range(n-1):
if i==0:
ans=abs(sum(a)-2*A)
else:
ans=min(abs(sum(a)-2*A),ans)
A+=a[i+1]
print(ans)
|
n=int(eval(input()))
a=list(map(int,input().split()))
b=sum(a)
A=a[0]
for i in range(n-1):
if i==0:
ans=abs(b-2*A)
else:
ans=min(abs(b-2*A),ans)
A+=a[i+1]
print(ans)
|
p03659
|
N = int(eval(input()))
L = list(map(int,input().split()))
S = sum(L)
A = []
for i in range(1,N):
p = abs(2*sum(L[0:i])-S)
A.append(p)
print((min(A)))
|
N = int(eval(input()))
L = list(map(int,input().split()))
S = sum(L)
k = 0
ans = abs(2*sum(L[0:1])-S)
for i in range(0,N-1):
k += L[i]
ans = min(ans,abs(2*k-S))
print(ans)
|
p03659
|
n=int(eval(input()))
a = list(map(int,input().split()))
m=n*(10**9)
for i in range(n-1):
if m > abs(sum(a[:i+1])-sum(a[i+1:])):
m=abs(sum(a[:i+1])-sum(a[i+1:]))
print(m)
|
n=int(eval(input()))
a = list(map(int,input().split()))
m=n*(10**9)
s=sum(a)
M=0
for i in range(n-1):
M+=a[i]
if abs(s-2*M) < m:
m=abs(s-2*M)
print(m)
|
p03659
|
def solve(): # 068C - Splitting Pile
N = int(eval(input()))
a = [int(x) for x in input().split(" ")]
X = sum(a)
min_sum = 2 * 1e10
for i in range(N - 1):
if abs(X - 2 * sum(a[:i + 1])) < min_sum:
min_sum = abs(X - 2 * sum(a[:i + 1]))
print(min_sum)
solve()
|
def solve(): # 068C - Splitting Pile
N = int(eval(input()))
a = [int(x) for x in input().split(" ")]
X = sum(a)
sum_val = 0
min_sum = 2 * 1e20
for i in range(N-1):
sum_val += a[i]
y = X - sum_val
min_sum = min(min_sum, abs(sum_val - y))
print(min_sum)
solve()
|
p03659
|
def c_splitting_pile(N, A):
# Aの要素の総和をX、カードの山の先頭i枚の総和をxとすると、
# |y-x|=|X-2x|である。各i(1<=i<=N-1)についてこの値を計算すればよい
from itertools import accumulate
total = sum(A)
return min([abs(total - 2 * x) for x in accumulate(A[:-1])])
N = int(eval(input()))
A = [int(i) for i in input().split()]
print((c_splitting_pile(N, A)))
|
def c_splitting_pile():
# X = sum(A)、カードの山の先頭 i 枚の総和を x とすると、
# |y-x| = |X-2x| である。各 i(1<=i<=N-1) についてこの値を計算すればよい
from itertools import accumulate
N = int(eval(input()))
A = [int(i) for i in input().split()]
total = sum(A)
return min([abs(total - 2 * x) for x in accumulate(A[:-1])])
print((c_splitting_pile()))
|
p03659
|
import sys
from itertools import accumulate
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007
def main():
N, *A = list(map(int, read().split()))
csum = [0]
csum.extend(accumulate(A))
ans = INF
for i in range(1, N):
tmp = abs(csum[i] - (csum[N] - csum[i]))
if ans > tmp:
ans = tmp
print(ans)
return
if __name__ == '__main__':
main()
|
import sys
from itertools import accumulate
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007
def main():
N, *A = list(map(int, read().split()))
total = sum(A)
ans = INF
s = 0
for a in A[:-1]:
s += a
if ans > abs(total - 2 * s):
ans = abs(total - 2 * s)
print(ans)
return
if __name__ == '__main__':
main()
|
p03659
|
n=int(eval(input()))
a=list(map(int,input().split()))
s=sum(a)
sunuke=0
arai=0
ans=10**18
for i in range(1,n):
sunuke=sum(a[:i])
arai=s-sunuke
t=abs(sunuke-arai)
ans=min(t,ans)
print(ans)
|
from itertools import accumulate
n=int(eval(input()))
a=list(map(int,input().split()))
s=sum(a)
# a=[0]+a
acc=accumulate(a)
acc=list(acc)
sunuke=0
arai=0
ans=10**18
for i in range(1,n):
sunuke=acc[i-1]
arai=s-sunuke
t=abs(sunuke-arai)
ans=min(t,ans)
print(ans)
|
p03659
|
from itertools import accumulate
n=int(eval(input()))
a=list(map(int,input().split()))
s=sum(a)
# a=[0]+a
acc=accumulate(a)
acc=list(acc)
sunuke=0
arai=0
ans=10**18
for i in range(1,n):
sunuke=acc[i-1]
arai=s-sunuke
t=abs(sunuke-arai)
ans=min(t,ans)
print(ans)
|
n=int(eval(input()))
a=list(map(int,input().split()))
from itertools import accumulate
s=list(accumulate(a))
a_sum=sum(a)
ans=10**18
if n==2:
print((abs(a[0]-a[1])))
exit(0)
for i in range(1,n-1):
x=s[i]
y=a_sum-x
ans=min(ans,abs(x-y))
print(ans)
|
p03659
|
n = int(eval(input()))
a = [int(x) for x in input().split()]
suma = sum(a)
x = a[0]
ans = abs(suma - x * 2)
for i in range(1, n - 1):
x += a[i]
ans = min(ans, abs(suma - x * 2))
else:
print(ans)
|
n = int(eval(input()))
a = [int(x) for x in input().split()]
x = 0
ans = []
suma = sum(a)
for i in range(n - 1):
x += a[i]
ans.append(abs(suma - x * 2))
else:
print((min(ans)))
|
p03659
|
def test(L):
T = abs(sum(A[:L]) - sum(A[L:]))
return T < answer
N = int(eval(input()))
A = list(map(int, input().split()))
left = 0
right = N
answer = float("inf")
for i in range(1, N):
if test(i):
answer = abs(sum(A[:i]) - sum(A[i:]))
print(answer)
|
from itertools import accumulate
N = int(eval(input()))
A = list(map(int, input().split()))
A = list(accumulate(A))
answer = abs((A[-1] - A[0]) - A[0])
for i in range(N - 1):
L = A[-1] - A[i]
K = abs(L - A[i])
if K < answer:
answer = K
print(answer)
|
p03659
|
n = int(eval(input()))
A = [int(i) for i in input().split()]
sumA = sum(A)
tmp = 0
ans = 10 ** 10
for i in range(n - 1):
tmp += A[i]
ans = min(ans, abs(tmp -(sumA - tmp)))
print(ans)
|
N = int(eval(input()))
A = [int(i) for i in input().split()]
x = sum(A)
tmp = 0
ans = float('inf')
for i in range(N - 1):
tmp += A[i]
ans = min(ans, abs(tmp - (x - tmp)))
print(ans)
|
p03659
|
N = int(eval(input()))
a = list(map(int, input().split()))
ans = 10**10
for i in range(1, N):
x = sum(a[:i])
y = sum(a[i:])
check = abs(x - y)
if ans > check:
ans = check
print(ans)
|
N = int(eval(input()))
a = list(map(int, input().split()))
ans = 10**10
for i in range(1, N):
if i == 1:
x = sum(a[:i])
y = sum(a[i:])
else:
x += a[i-1]
y -= a[i-1]
check = abs(x - y)
if ans > check:
ans = check
print(ans)
|
p03659
|
N=int(eval(input()))
a=[int(x) for x in input().split()]
min=50000000000
for i in range(N-1):
sunuke=sum(a[0:i+1])
arai=sum(a[i+1:N])
if(abs(sunuke-arai)<=min):
min=abs(sunuke-arai)
print(min)
|
n = int(eval(input()))
a = [int(x) for x in input().split()]
sm = sum(a)//2
mn = 10**10
ar = a[0]
su = a[-1]
for i in range(1,len(a)-1):
if abs(sm - ar) < mn:
mn = abs(sm - ar)
mn_i = i
ar += a[i]
if len(a) > 2:
ar = sum(a[0:mn_i])
su = sum(a[mn_i::])
print((abs(ar-su)))
else:
print((abs(ar-su)))
|
p03659
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
input:
5
5
1
3
2
4
or
3
1
1
1
output:
3
or
1
"""
import sys
from bisect import bisect_left
def solve():
dis_rec = [float('inf')] * array_length
dis_rec[0] = array[0]
length = 1
for j in range(1, array_length):
if dis_rec[length - 1] < array[j]:
dis_rec[length] = array[j]
length += 1
else:
position = bisect_left(dis_rec, array[j])
dis_rec[position] = array[j]
return length
if __name__ == '__main__':
_input = sys.stdin.readlines()
array_length = int(_input[0])
array = list(map(int, _input[1:]))
print((solve()))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
input:
5
5
1
3
2
4
or
3
1
1
1
output:
3
or
1
"""
import sys
from bisect import bisect_left
def solve():
dis_rec = [float('inf')] * array_length
dis_rec[0] = array[0]
length = 1
for i, ele in enumerate(array, 1):
if dis_rec[length - 1] < ele:
dis_rec[length] = ele
length += 1
else:
position = bisect_left(dis_rec, ele)
dis_rec[position] = ele
return length
if __name__ == '__main__':
_input = sys.stdin.readlines()
array_length = int(_input[0])
array = list(map(int, _input[1:]))
print((solve()))
|
p02317
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
input:
5
5
1
3
2
4
or
3
1
1
1
output:
3
or
1
"""
import sys
from bisect import bisect_left
def solve():
dis_rec = [float('inf')] * array_length
dis_rec[0] = array[0]
length = 1
for i, ele in enumerate(array, 1):
if dis_rec[length - 1] < ele:
dis_rec[length] = ele
length += 1
else:
position = bisect_left(dis_rec, ele)
dis_rec[position] = ele
return length
if __name__ == '__main__':
_input = sys.stdin.readlines()
array_length = int(_input[0])
array = list(map(int, _input[1:]))
print((solve()))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
input:
5
5
1
3
2
4
or
3
1
1
1
output:
3
or
1
"""
import sys
from bisect import bisect_left
def solve():
dis_rec = [float('inf')] * array_length
dis_rec[0] = array[0]
length = 1
for ele in array:
if dis_rec[length - 1] < ele:
dis_rec[length] = ele
length += 1
else:
position = bisect_left(dis_rec, ele)
dis_rec[position] = ele
return length
if __name__ == '__main__':
_input = sys.stdin.readlines()
array_length = int(_input[0])
array = list(map(int, _input[1:]))
print((solve()))
|
p02317
|
import sys
from bisect import bisect_left
N = int(eval(input()))
inf = float("inf")
dp = [inf]*N
for n in map(int, sys.stdin.readlines()):
dp[bisect_left(dp, n)] = n
for i, num in zip(list(range(N, 0, -1)), dp[::-1]):
if num < inf:
print(i)
break
|
import sys
from bisect import bisect_left
N = int(eval(input()))
dp = [float("inf")]*N
result = -1
for n in map(int, sys.stdin.readlines()):
i = bisect_left(dp, n)
dp[i] = n
result = i if i > result else result
print((result+1))
|
p02317
|
import bisect
N = int(eval(input()))
numbers = []
for i in range(N):
numbers.append(int(eval(input())))
lis = [numbers[0]]
for last in numbers[1:]:
pos = bisect.bisect_left(lis, last)
if len(lis) < pos:
lis.append(last)
else:
lis = lis[:pos] + [last] + lis[pos+1:]
print((len(lis)))
|
import bisect
N = int(eval(input()))
numbers = []
for i in range(N):
numbers.append(int(eval(input())))
lis = [numbers[0]]
for last in numbers[1:]:
if lis[-1] < last:
lis.append(last)
else:
pos = bisect.bisect_left(lis, last)
lis[pos] = last
print((len(lis)))
|
p02317
|
import bisect
n = int(eval(input()))
A = [int(eval(input())) for j in range(n)]
dp = [A[0]]
for i in range(1, n):
if dp[-1] < A[i]:
dp.append(A[i])
else:
dp[bisect.bisect_left(dp, A[i])] = A[i]
print((len(dp)))
|
import bisect
n = int(eval(input()))
A = [int(eval(input())) for j in range(n)]
dp = A[:1]
for a_i in A[1:]:
if dp[-1] < a_i:
dp.append(a_i)
else:
dp[bisect.bisect_left(dp, a_i)] = a_i
print((len(dp)))
|
p02317
|
import bisect
n = int(eval(input()))
A = [int(eval(input())) for j in range(n)]
dp = A[:1]
for a_i in A[1:]:
if dp[-1] < a_i:
dp.append(a_i)
else:
dp[bisect.bisect_left(dp, a_i)] = a_i
print((len(dp)))
|
import sys
import bisect
n = int(sys.stdin.readline())
A = [int(sys.stdin.readline()) for j in range(n)]
dp = A[:1]
for a_i in A[1:]:
if dp[-1] < a_i:
dp.append(a_i)
else:
dp[bisect.bisect_left(dp, a_i)] = a_i
print((len(dp)))
|
p02317
|
from sys import stdin
readline = stdin.readline
n = int(readline())
a = [int(readline()) for _ in range(n)]
dp = [-float('inf')]
for ai in a:
for i in range(1, len(dp)):
if dp[i - 1] < ai and ai < dp[i]:
dp[i] = ai
if dp[-1] < ai:
dp.append(ai)
print((len(dp) - 1))
|
from sys import stdin
from bisect import bisect_left, bisect_right
readline = stdin.readline
dp = [-float('inf')]
for ai in (int(readline()) for _ in range(int(readline()))):
if dp[-1] < ai:dp.append(ai)
for i in range(bisect_right(dp, ai), bisect_left(dp, ai) + 1):dp[i] = ai
print((len(dp) - 1))
|
p02317
|
from sys import stdin
from bisect import bisect_left, bisect_right
readline = stdin.readline
dp = [-float('inf')]
for ai in (int(readline()) for _ in range(int(readline()))):
if dp[-1] < ai:dp.append(ai)
for i in range(bisect_right(dp, ai), bisect_left(dp, ai) + 1):dp[i] = ai
print((len(dp) - 1))
|
from sys import stdin
from bisect import bisect_left
readline = stdin.readline
dp = [-float('inf')]
n = int(readline())
a = (int(readline()) for _ in range(n))
for ai in a:
if dp[-1] < ai:
dp.append(ai)
else:
dp[bisect_left(dp, ai)] = ai
print((len(dp) - 1))
|
p02317
|
from bisect import bisect
n = int(eval(input()))
A = []
for i in range(n):
A.append(int(eval(input())))
L = [None for i in range(n)]
def LIS():
L[0] = A[0]
length = 0
for i in range(n):
if L[length] < A[i]:
length += 1
L[length] = A[i]
else:
if A[i] in L: continue
j = bisect(L, A[i], 0, length)
L[j] = A[i]
return length + 1
print((LIS()))
|
from bisect import bisect
import sys
n = int(eval(input()))
A = [int(i.rstrip("\n")) for i in sys.stdin.readlines()]
#?????????i+1??§???????¢??????¨??????????????????????´????????°???????????´?
L = []
def LIS():
L.append(A[0])
length = 0
for i in range(n):
if L[length] < A[i]:
length += 1
L.append(A[i])
else:
if A[i] in L: continue
j = bisect(L, A[i], 0, length) #L????????§?????????A[i]??\?????¨????????????????????????
L[j] = A[i]
return length + 1
print((LIS()))
|
p02317
|
from bisect import bisect
import sys
n = int(eval(input()))
A = [int(i.rstrip("\n")) for i in sys.stdin.readlines()]
#?????????i+1??§???????¢??????¨??????????????????????´????????°???????????´?
L = []
def LIS():
L.append(A[0])
length = 0
for i in range(n):
if L[length] < A[i]:
length += 1
L.append(A[i])
else:
if A[i] in L: continue
j = bisect(L, A[i], 0, length) #L????????§?????????A[i]??\?????¨????????????????????????
L[j] = A[i]
return length + 1
print((LIS()))
|
from bisect import bisect_left
import sys
n = int(eval(input()))
A = [int(i.rstrip("\n")) for i in sys.stdin.readlines()]
def LIS():
L = A[:1]
for i in A[1:]:
if L[-1] < i:
L.append(i)
else:
j = bisect_left(L, i)
L[j] = i
return len(L)
print((LIS()))
|
p02317
|
import sys
import bisect
inf = float('inf')
def solve():
n = int(input())
A = [int(input()) for i in range(n)]
dp = [inf] * n
max_ = 1
for a in A:
j = bisect.bisect_left(dp, a, lo=0, hi=max_)
max_ = max(max_, j + 1)
dp[j] = a
# print(dp)
ans = max_
print(ans)
def debug(x, table):
for name, val in table.items():
if x is val:
print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
return None
if __name__ == '__main__':
solve()
|
import sys
import bisect
inf = float('inf')
def solve():
n = int(input())
A = [int(input()) for i in range(n)]
dp = [inf] * n
# max_ = 1
for a in A:
j = bisect.bisect_left(dp, a)
# max_ = max(max_, j + 1)
dp[j] = a
# print(dp)
ans = 1
for i, v in enumerate(dp):
if v == inf:
ans = i
break
else:
ans = n
print(ans)
def debug(x, table):
for name, val in table.items():
if x is val:
print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr)
return None
if __name__ == '__main__':
solve()
|
p02317
|
import sys
r=sys.stdin.readline
N,M=list(map(int,r().split()))
city=[[] for _ in range(N+1)]
for _ in range(M):
a,b=list(map(int,r().split()))
city[a].append(b)
city[b].append(a)
check=[True]+[False]*(N)
def dfs(v):
stack=[v]
visited=[False]*(N+1)
visited[v]=True
while stack:
cur=stack.pop()
check[cur]=True
for v in city[cur]:
if not visited[v]:
stack.append(v)
cnt=0
for i in range(1,N+1):
if not check[i]:
dfs(i)
cnt+=1
print((cnt-1))
|
import sys
r=sys.stdin.readline
N,M=list(map(int,r().split()))
city=[[] for _ in range(N+1)]
for _ in range(M):
a,b=list(map(int,r().split()))
city[a].append(b)
city[b].append(a)
check=[True]+[False]*(N)
def dfs(v):
stack=[v]
while stack:
cur=stack.pop()
check[cur]=True
for v in city[cur]:
if not check[v]:
stack.append(v)
cnt=0
for i in range(1,N+1):
if not check[i]:
dfs(i)
cnt+=1
print((cnt-1))
|
p02536
|
import sys
sys.setrecursionlimit(10**7)
def I(): return int(sys.stdin.readline().rstrip())
def MI(): return list(map(int,sys.stdin.readline().rstrip().split()))
def LI(): return list(map(int,sys.stdin.readline().rstrip().split())) #空白あり
def LI2(): return list(map(int,sys.stdin.readline().rstrip())) #空白なし
def S(): return sys.stdin.readline().rstrip()
def LS(): return list(sys.stdin.readline().rstrip().split()) #空白あり
def LS2(): return list(sys.stdin.readline().rstrip()) #空白なし
class UnionFind:
def __init__(self,n):
self.par = [i for i in range(n+1)] # 親のノード番号
self.rank = [0]*(n+1)
def find(self,x): # xの根のノード番号
if self.par[x] == x:
return x
else:
self.par[x] = self.find(self.par[x])
return self.par[x]
def same_check(self,x,y): # x,yが同じグループか否か
return self.find(x) == self.find(y)
def unite(self,x,y): # x,yの属するグループの併合
x = self.find(x)
y = self.find(y)
if self.rank[x] < self.rank[y]:
x,y = y,x
if self.rank[x] == self.rank[y]:
self.rank[x] += 1
self.par[y] = x
N,M = MI()
UF = UnionFind(N)
for _ in range(M):
a,b = MI()
if not UF.same_check(a,b):
UF.unite(a,b)
A = UF.par
for i in range(1,N+1):
A[i] = UF.find(A[i])
del A[0]
print((len(set(A))-1))
|
import sys
sys.setrecursionlimit(10**7)
def MI(): return list(map(int,sys.stdin.readline().rstrip().split()))
class UnionFind:
def __init__(self,n):
self.par = [i for i in range(n+1)] # 親のノード番号
self.rank = [0]*(n+1)
def find(self,x): # xの根のノード番号
if self.par[x] == x:
return x
else:
self.par[x] = self.find(self.par[x])
return self.par[x]
def same_check(self,x,y): # x,yが同じグループか否か
return self.find(x) == self.find(y)
def unite(self,x,y): # x,yの属するグループの併合
x = self.find(x)
y = self.find(y)
if self.rank[x] < self.rank[y]:
x,y = y,x
if self.rank[x] == self.rank[y]:
self.rank[x] += 1
self.par[y] = x
N,M = MI()
UF = UnionFind(N)
for _ in range(M):
a,b = MI()
UF.unite(a,b)
A = UF.par
A = [UF.find(A[i]) for i in range(1,N+1)]
print((len(set(A))-1))
|
p02536
|
f=lambda:list(map(int,input().split()))
n,m=f()
# Union Find
p=[-1]*n
def root(x):
while p[x]>=0: x=p[x]
return x
def unite(x,y):
x,y=root(x),root(y)
if x==y: return
if x>y: x,y=y,x
p[x]+=p[y]
p[y]=x
def same(x,y):
return root(x)==root(y)
def size(x):
return -p[root(x)]
for _ in range(m):
a,b=f()
unite(a-1,b-1)
print((sum(i<0 for i in p)-1))
|
f=lambda:list(map(int,input().split()))
def r(x):
while p[x]>=0: x=p[x]
return x
def u(x,y):
x,y=r(x),r(y)
if x==y: return
if x>y: x,y=y,x
p[x]+=p[y]
p[y]=x
n,m=f()
p=[-1]*n
for _ in range(m):
a,b=f()
u(a-1,b-1)
print((sum(i<0 for i in p)-1))
|
p02536
|
# UnionFind
import sys
sys.setrecursionlimit(1000000)
class UnionFind:
def __init__(self, n):
self.n = [-1]*n
self.r = [0]*n
self.siz = n
def find_root(self, x):
if self.n[x] < 0:
return x
else:
self.n[x] = self.find_root(self.n[x])
return self.n[x]
def unite(self, x, y):
x = self.find_root(x)
y = self.find_root(y)
if x == y:
return
elif self.r[x] > self.r[y]:
self.n[x] += self.n[y]
self.n[y] = x
else:
self.n[y] += self.n[x]
self.n[x] = y
if self.r[x] == self.r[y]:
self.r[y] += 1
self.siz -= 1
def root_same(self, x, y):
return self.find_root(x) == self.find_root(y)
def count(self, x):
return -self.n[self.find_root(x)]
def size(self):
return self.siz
n,m=list(map(int,input().split()))
u=UnionFind(n)
for _ in range(m):
a,b=list(map(int,input().split()))
a-=1
b-=1
u.unite(a,b)
print((u.size()-1))
|
class UnionFind:
def __init__(self, n):
self.n = [-1]*n
self.r = [0]*n
self.co = n
def find_root(self, x):
if self.n[x] < 0:
return x
else:
self.n[x] = self.find_root(self.n[x])
return self.n[x]
def unite(self, x, y):
x = self.find_root(x)
y = self.find_root(y)
if x == y:
return
elif self.r[x] > self.r[y]:
self.n[x] += self.n[y]
self.n[y] = x
else:
self.n[y] += self.n[x]
self.n[x] = y
if self.r[x] == self.r[y]:
self.r[y] += 1
self.co -= 1
def same(self, x, y):
return self.find_root(x) == self.find_root(y)
def size(self, x):
return -self.n[self.find_root(x)]
def set_count(self):
return self.co
import sys
input = lambda:sys.stdin.readline().rstrip()
n, m = list(map(int, input().split()))
uf = UnionFind(n)
for _ in range(m):
a, b = list(map(int, input().split()))
uf.unite(a-1, b-1)
print((uf.set_count()-1))
|
p02536
|
import sys
sys.setrecursionlimit(100000)
def dfs(A,N,M,i,j,visited):
visited[i][j]=1
rn=[-1,-1,-1,0,0,1,1,1]
cn=[-1,0,1,-1,1,-1,0,1]
for s in range(8):
r=i+rn[s]
c=j+cn[s]
if r>=0 and r<N and c>=0 and c<M and not visited[r][c] and A[r][c]:
dfs(A,N,M,r,c,visited)
from collections import defaultdict
n,m=list(map(int,input().split()))
A=[[0 for i in range(n)] for i in range(n)]
for _ in range(m):
a,b=list(map(int,input().split()))
A[a-1][b-1]=1
A[b-1][a-1]=1
count=0
visited=[[0 for i in range(n)] for i in range(n)]
for i in range(n):
for j in range(n):
if A[i][j] and not visited[i][j]:
count+=1
dfs(A,n,n,i,j,visited)
print(count)
|
from collections import deque
n,m=list(map(int,input().split()))
road=[[] for i in range(n)]
flag=[0]*n
for i in range(m):
a,b=list(map(int,input().split()))
road[a-1].append(b-1)
road[b-1].append(a-1)
count=0
for i in range(n):
if flag[i]!=0:
continue
count+=1
q=deque([i])
while q:
p=q.popleft()
flag[p]=1
for z in road[p]:
if flag[z]==0:
q.append(z)
print((count-1))
|
p02536
|
#dt = {} for i in x: dt[i] = dt.get(i,0)+1
import sys;input = sys.stdin.readline
inp,ip = lambda :int(eval(input())),lambda :[int(w) for w in input().split()]
"""
n,k = ip()
x = [inp() for i in range(n)]
"""
import sys
sys.setrecursionlimit(10**6)
def dfs(u):
global vis,graph
vis.add(u)
for i in graph[u]:
if i not in vis:
dfs(i)
n,m = ip()
graph = {i:[] for i in range(1,n+1)}
for i in range(m):
a,b = ip()
graph[a].append(b)
graph[b].append(a)
vis = set()
ct = 0
for i in range(1,n+1):
if i not in vis:
dfs(i)
ct += 1
print((ct-1))
|
#dt = {} for i in x: dt[i] = dt.get(i,0)+1
import sys;input = sys.stdin.readline
#import io,os; input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline #for pypy
inp,ip = lambda :int(eval(input())),lambda :[int(w) for w in input().split()]
class DisjSet:
def __init__(self,n):
self.rank = [1]*n
self.parent = [i for i in range(n)]
def find(self,x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def Union(self,x,y):
xset = self.find(x)
yset = self.find(y)
if xset == yset: return
if self.rank[xset] < self.rank[yset]:
self.parent[xset] = yset
elif self.rank[xset] > self.rank[yset]:
self.parent[yset] = xset
else:
self.parent[yset] = xset
self.rank[xset] += 1
n,m = ip()
obj = DisjSet(n)
for i in range(m):
a,b = ip()
obj.Union(a-1,b-1)
dt = {}
for i in range(n):
p = obj.find(i)
dt[p] = dt.get(p,0)+1
print((len(list(dt.keys()))-1))
|
p02536
|
n, m = list(map(int, input().split()))
groups = []
flag = [0 for i in range(n)]
for i in range(m):
a, b = list(map(int, input().split()))
temp = {a, b}
if flag[a-1] == 1 or flag[b-1] == 1:
for j in range(len(groups)):
if temp & groups[j]:
groups[j] |= temp
else:
groups.append(temp)
flag[a-1] = 1
flag[b-1] = 1
print((len(groups)+flag.count(0)-1))
|
class UnionFind:
def __init__(self, n):
self.r = [-1 for i in range(n)]
def root(self, x):
if self.r[x] < 0:
return x
self.r[x] = self.root(self.r[x])
return self.r[x]
def unite(self, x, y):
x = self.root(x)
y = self.root(y)
if x == y:
return False
if self.r[x] < self.r[y]:
temp = x
x = y
y = temp
self.r[x] += self.r[y]
self.r[y] = x
return True
def size(self, x):
return -self.r[self.root(x)]
n, m = list(map(int, input().split()))
UF = UnionFind(n)
for i in range(m):
a, b = [int(x)-1 for x in input().split()]
UF.unite(a, b)
ans = 0
for i in UF.r:
if i < 0:
ans += 1
print((ans-1))
|
p02536
|
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
return len(self.roots())
def all_group_members(self):
return {r: self.members(r) for r in self.roots()}
def __str__(self):
return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
n, m = list(map(int,input().split()))
uf = UnionFind(n)
for _ in range(m):
a , b = [int(x)-1 for x in input().split()]
uf.union(a , b)
print((len(uf.all_group_members())-1))
|
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
return len(self.roots())
def all_group_members(self):
return {r: self.members(r) for r in self.roots()}
def __str__(self):
return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
n, m = list(map(int,input().split()))
uf = UnionFind(n)
for _ in range(m):
a , b = [int(x)-1 for x in input().split()]
uf.union(a , b)
print((uf.group_count()-1))
|
p02536
|
N, M = list(map(int, input().split()))
F = [[] for _ in range(N)]
P = [0] * N
for i in range(M):
A, B = list(map(int, input().split()))
F[A-1].append(B-1)
F[B-1].append(A-1)
c=0
l = []
for i in range(N):
if P[i] == 0:
c+=1
l.append(i)
while len(l)>0:
p=l.pop()
P[p] = c
for j in F[p]:
if P[j] == 0:
l.append(j)
print((c-1))
|
N, M = list(map(int, input().split()))
Ne = [[] for _ in range(N)]
C = [0] * N
for i in range(M):
A, B = list(map(int, input().split()))
Ne[A-1].append(B-1)
Ne[B-1].append(A-1)
c=0
l = []
for i in range(N):
if C[i] == 0:
c+=1
l.append(i)
while len(l)>0:
v=l.pop()
C[v] = c
for j in Ne[v]:
if C[j] == 0:
l.append(j)
print((c-1))
|
p02536
|
import collections
N, M = list(map(int, input().split()))
lst = [0] * N
x = 1
for _ in range(M):
A, B = list(map(int, input().split()))
if lst[A-1] == 0 and lst[B-1] == 0:
lst[A-1] = x
lst[B-1] = x
x += 1
elif lst[A-1] == 0 and lst[B-1] != 0:
lst[A-1] = lst[B-1]
elif lst[A-1] != 0 and lst[B-1] == 0:
lst[B-1] = lst[A-1]
else:
y = max(lst[A-1], lst[B-1])
z = min(lst[A-1], lst[B-1])
for i in range(N):
if lst[i] == z:
lst[i] = y
c = collections.Counter(lst)
num_0 = c[0]
if num_0 == 0:
print((len(c) - 1))
else:
print((num_0 + len(c) - 2))
|
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def unite(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
return len(self.roots())
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline
n,m=list(map(int,input().split()))
u=UnionFind(n)
for i in range(m):
a,b=list(map(int,input().split()))
a-=1
b-=1
u.unite(a,b)
print((u.group_count()-1))
|
p02536
|
n, m = list(map(int, input().split()))
edges = [tuple(map(int, input().split())) for _ in range(m)]
par = [i for i in range(n + 1)]
rank = [1 for _ in range(n + 1)]
def root(x):
if par[x] == x:
return x
else:
par[x] = root(par[x])
return par[x]
def same(x, y):
return root(x) == root(y)
def unite(x, y):
x = root(x)
y = root(y)
if rank[x] < rank[y]:
par[x] = y
else:
par[y] = x
if rank[x] == rank[y]:
rank[x] += 1
for a, b in edges:
unite(a, b)
memo = []
ans = 0
for i in range(1, n + 1):
if root(i) not in memo:
memo.append(root(i))
ans += 1
print((ans - 1))
|
n, m = list(map(int, input().split()))
edges = [tuple(map(int, input().split())) for _ in range(m)]
par = [i for i in range(n + 1)]
rank = [1 for _ in range(n + 1)]
def root(x):
if par[x] == x:
return x
else:
par[x] = root(par[x])
return par[x]
def same(x, y):
return root(x) == root(y)
def unite(x, y):
x = root(x)
y = root(y)
if rank[x] < rank[y]:
par[x] = y
else:
par[y] = x
if rank[x] == rank[y]:
rank[x] += 1
for a, b in edges:
unite(a, b)
memo = [False for _ in range(n + 1)]
ans = 0
for i in range(1, n + 1):
r = root(i)
if memo[r] == False:
memo[r] = True
ans += 1
print((ans - 1))
|
p02536
|
from collections import deque
N, M = list(map(int, input().split()))
AB = [[] for _ in range(N)]
for _ in range(M):
a,b = [int(x)-1 for x in input().split()]
AB[a].append(b)
AB[b].append(a)
visited = [0] * N
ans = []
for i in range(N):
if visited[i]:
continue
group = [i]
d = deque(AB[i])
while d:
s = d.popleft()
if visited[s]:
continue
visited[s] = 1
group.append(s)
for k in AB[s]:
d.append(k)
ans.append(len(group))
print((len(ans)-1))
|
import sys
sys.setrecursionlimit(2 * (10 ** 6))
def main():
N, M = list(map(int, input().split()))
AB = [[] for _ in range(N)]
for _ in range(M):
a,b = [int(x)-1 for x in input().split()]
AB[a].append(b)
AB[b].append(a)
def dfs(v):
visited[v] = 1
for i in AB[v]:
if visited[i]:
continue
dfs(i)
visited = [0]*N
cnt = 0
for i in range(N):
if visited[i]:
continue
dfs(i)
cnt += 1
print((cnt-1))
if __name__ == "__main__":
main()
|
p02536
|
n,m=list(map(int,input().split()))
#Union-Find木
#par[i]:iの親 deep[i]:iの深さ size[i]:iの大きさ
par=[i for i in range(n)]
deep=[1]*n
size=[1]*n
#親を見つける
def find(x):
if par[x]==x:
return x
else:
return find(par[x])
#二つのグループを統合する
def unite(x,y):
x=find(x)
y=find(y)
if x==y:
return
if deep[x]<deep[y]:
par[x]=y
size[y]+=size[x]
else:
par[y]=x
size[x]+=size[y]
if deep[x]==deep[y]:
deep[x]+=1
#xとyが同じグループに属するかどうか
def same(x,y):
return find(x)==find(y)
#xが属するグループの要素数を返す
def group_count(x):
return size[find(x)]
for i in range(m):
a,b=list(map(int,input().split()))
unite(a-1,b-1)
from collections import Counter
x=[]
for i in par:
x.append(find(i))
x=Counter(x)
print((len(x)-1))
|
n,m=list(map(int,input().split()))
#Union-Find木
#par[i]:iの親 deep[i]:iの深さ size[i]:iの大きさ
par=[i for i in range(n)]
deep=[1]*n
size=[1]*n
#親を見つける
def find(x):
if par[x]==x:
return x
else:
return find(par[x])
#二つのグループを統合する
def unite(x,y):
x=find(x)
y=find(y)
if x==y:
return
if deep[x]<deep[y]:
par[x]=y
size[y]+=size[x]
else:
par[y]=x
size[x]+=size[y]
if deep[x]==deep[y]:
deep[x]+=1
#xとyが同じグループに属するかどうか
def same(x,y):
return find(x)==find(y)
#xが属するグループの要素数を返す
def group_count(x):
return size[find(x)]
#連結成分の個数を返す
def count():
check=set()
for i in range(n):
parent=find(i)
if parent not in check:
check.add(parent)
return len(check)
for i in range(m):
a,b=list(map(int,input().split()))
unite(a-1,b-1)
s=count()
print((s-1))
|
p02536
|
from collections import deque
N,M = list(map(int,input().split()))
l = [[] for _ in range(N+1)]
for _ in range(M):
a,b = list(map(int,input().split()))
l[a].append(b)
l[b].append(a)
ans = 0
check = [0]*(N+1)
for i in range(1,N+1):
st = deque([i])
check[i] = 1
while st:
s = st.popleft()
for t in l[s]:
if check[t] == 0:
check[t] = 1
st.append(t)
ans = max(ans,N-sum(check))
print(ans)
|
from collections import deque
N,M = list(map(int,input().split()))
l = [[] for _ in range(N+1)]
for _ in range(M):
a,b = list(map(int,input().split()))
l[a].append(b)
l[b].append(a)
check = [0]*(N+1)
cnt = 0
for i in range(1,N+1):
if check[i] == 1:
continue
st = deque([i])
check[i] = 1
while st:
s = st.popleft()
for t in l[s]:
if check[t] == 0:
check[t] = 1
st.append(t)
continue
cnt += 1
print((cnt-1))
|
p02536
|
# Template 1.0
import sys, re
from collections import deque, defaultdict, Counter, OrderedDict
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from heapq import heappush, heappop, heapify, nlargest, nsmallest
def STR(): return list(eval(input()))
def INT(): return int(eval(input()))
def MAP(): return list(map(int, input().split()))
def LIST(): return list(map(int, input().split()))
def list2d(a, b, c): return [[c] * b for i in range(a)]
def sortListWithIndex(listOfTuples, idx): return (sorted(listOfTuples, key=lambda x: x[idx]))
def sortDictWithVal(passedDic):
temp = sorted(list(passedDic.items()), key=lambda kv: (kv[1], kv[0]))
toret = {}
for tup in temp:
toret[tup[0]] = tup[1]
return toret
def sortDictWithKey(passedDic):
return dict(OrderedDict(sorted(passedDic.items())))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7
class Graph:
# init function to declare class variables
def __init__(self, V):
self.V = V
self.adj = [[] for i in range(V)]
def DFSUtil(self, temp, v, visited):
# Mark the current vertex as visited
visited[v] = True
# Store the vertex to list
temp.append(v)
# Repeat for all vertices adjacent
# to this vertex v
for i in self.adj[v]:
if visited[i] == False:
# Update the list
temp = self.DFSUtil(temp, i, visited)
return temp
# method to add an undirected edge
def addEdge(self, v, w):
self.adj[v].append(w)
self.adj[w].append(v)
# Method to retrieve connected components
# in an undirected graph
def connectedComponents(self):
visited = []
cc = []
for i in range(self.V):
visited.append(False)
for v in range(self.V):
if visited[v] == False:
temp = []
cc.append(self.DFSUtil(temp, v, visited))
return cc
# Driver Code
if __name__ == "__main__":
# Create a graph given in the above diagram
# 5 vertices numbered from 0 to 4
# g = Graph(5);
# g.addEdge(1, 0)
# g.addEdge(2, 3)
# g.addEdge(3, 4)
n,m = MAP()
g = Graph(n)
for _ in range(m):
u,v = MAP()
g.addEdge(u-1,v-1)
g.addEdge(v-1,u-1)
print((len(g.connectedComponents()) - 1))
|
# Template 1.0
import sys, re
from collections import deque, defaultdict, Counter, OrderedDict
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from heapq import heappush, heappop, heapify, nlargest, nsmallest
def STR(): return list(eval(input()))
def INT(): return int(eval(input()))
def MAP(): return list(map(int, input().split()))
def LIST(): return list(map(int, input().split()))
def list2d(a, b, c): return [[c] * b for i in range(a)]
def sortListWithIndex(listOfTuples, idx): return (sorted(listOfTuples, key=lambda x: x[idx]))
def sortDictWithVal(passedDic):
temp = sorted(list(passedDic.items()), key=lambda kv: (kv[1], kv[0]))
toret = {}
for tup in temp:
toret[tup[0]] = tup[1]
return toret
def sortDictWithKey(passedDic):
return dict(OrderedDict(sorted(passedDic.items())))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7
n,m = MAP()
graph = defaultdict(list)
for _ in range(m):
u,v = MAP()
graph[u].append(v)
graph[v].append(u)
comp = 0
vis = [False]*(n+1)
for i in range(1,n+1):
if(vis[i]==False):
comp+=1
stack = [i]
while(stack):
node = stack.pop()
vis[node] = True
for adj in graph[node]:
if(vis[adj]==False):
stack.append(adj)
print((comp - 1))
|
p02536
|
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**6)
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N,M = list(map(int,readline().split()))
road = [[] for _ in range(N+1)]
visit = [0]*(N+1)
for i in range(M):
x,y = list(map(int,readline().split()))
road[x].append(y)
road[y].append(x)
def dfs(v,prev):
for x in road[v]:
if x == prev:
continue
if visit[x] != 0:
continue
visit[x] = 1
dfs(x,v)
return
count = 0
for i in range(1,N+1):
if visit[i] == 0:
dfs(i,-1)
count += 1
print((count-1))
|
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**6)
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
#Union Find
#xの根を求める
def find(x):
if par[x] < 0:
return x
else:
par[x] = find(par[x])
return par[x]
#xとyの属する集合の併合
def union(x,y):
x = find(x)
y = find(y)
if x != y:
#sizeの大きいほうがx
if par[x] > par[y]:
x,y = y,x
par[x] += par[y] #xにyの個数くっつける
par[y] = x #yをxにくっつける
return
#xとyが同じ集合に属するかの判定
def same(x,y):
return find(x) == find(y)
#xが属する集合の個数
def size(x):
return -par[find(x)]
N,Q = list(map(int,readline().split()))
#0-index
par = [-1]*N
for _ in range(Q):
x,y = list(map(int,readline().split()))
x-=1; y-=1
union(x,y)
ans = set()
for i in range(N):
ans.add(find(i))
print((len(ans)-1))
|
p02536
|
# union-find
class UnionFind:
def __init__(self, n):
self.prsz = [-1] * n # parent & size
def find(self, v): # root
if self.prsz[v] < 0: return v
self.prsz[v] = self.find(self.prsz[v])
return self.prsz[v]
def union(self, v, u): # unite
v = self.find(v); u = self.find(u)
if v == u: return False
if self.prsz[v] > self.prsz[u]: v, u = u, v # size(v) < size(u)
self.prsz[v] += self.prsz[u]
self.prsz[u] = v
return True
n, m = list(map(int, input().split()))
uf = UnionFind(n)
for i in range(m):
a, b = [int(x)-1 for x in input().split()]
uf.union(a, b)
ans = set()
for i in range(n):
ans.add(uf.find(i))
print((len(ans) - 1))
|
# union-find
class UnionFind:
def __init__(self, n):
self.prsz = [-1] * n # parent & size
def find(self, v): # root
if self.prsz[v] < 0: return v
self.prsz[v] = self.find(self.prsz[v])
return self.prsz[v]
def union(self, v, u): # unite
v = self.find(v); u = self.find(u)
if v == u: return False
if self.prsz[v] > self.prsz[u]: v, u = u, v # size(v) < size(u)
self.prsz[v] += self.prsz[u]
self.prsz[u] = v
return True
n, m = list(map(int, input().split()))
uf = UnionFind(n)
for i in range(m):
a, b = [int(x)-1 for x in input().split()]
uf.union(a, b)
ans = -1
for a in uf.prsz:
if a < 0: ans += 1
print(ans)
|
p02536
|
def main():
n, m = list(map(int, input().split()))
# マイナスの場合は leader であり、同時にサイズ(*-1)を保持する
uf = [-1] * (n+1)
def uf_leader(a):
if uf[a]<0:
return a
uf[a] = uf_leader(uf[a])
return uf[a]
def uf_unite(a, b):
ua, ub = uf_leader(a), uf_leader(b)
if ua==ub:
return False
if uf[ua] > uf[ub]:
a, b = b, a
uf[ua] += uf[ub]
uf[ub] = ua
return True
def uf_leaders():
return set([uf_leader(v) for v in range(1,n+1)])
# print(uf[1:])
for _ in range(m):
a, b = list(map(int, input().split()))
uf_unite(a, b)
# print(uf[1:])
# print(uf_leaders())
ans = len(uf_leaders())-1
print(ans)
main()
|
def main():
n, m = list(map(int, input().split()))
# マイナスの場合は leader であり、同時にサイズ(*-1)を保持する
uf = [-1] * (n+1)
def uf_leader(a):
if uf[a]<0:
return a
uf[a] = uf_leader(uf[a])
return uf[a]
def uf_unite(a, b):
ua, ub = uf_leader(a), uf_leader(b)
if ua==ub:
return False
if uf[ua] > uf[ub]:
ua, ub = ub, ua
uf[ua] += uf[ub]
uf[ub] = ua
return True
def uf_leaders():
return set([uf_leader(v) for v in range(1,n+1)])
# print(uf[1:])
for _ in range(m):
a, b = list(map(int, input().split()))
uf_unite(a, b)
# print(uf[1:])
# print(uf_leaders())
ans = len(uf_leaders())-1
print(ans)
main()
|
p02536
|
def main():
n, m = list(map(int, input().split()))
# マイナスの場合は leader であり、同時にサイズ(*-1)を保持する
uf = [-1] * (n+1)
def uf_leader(a):
if uf[a]<0:
return a
uf[a] = uf_leader(uf[a])
return uf[a]
def uf_unite(a, b):
ua, ub = uf_leader(a), uf_leader(b)
if ua==ub:
return False
if uf[ua] > uf[ub]:
ua, ub = ub, ua
uf[ua] += uf[ub]
uf[ub] = ua
return True
def uf_leaders():
return set([uf_leader(v) for v in range(1,n+1)])
# print(uf[1:])
for _ in range(m):
a, b = list(map(int, input().split()))
uf_unite(a, b)
# print(uf[1:])
# print(uf_leaders())
ans = len(uf_leaders())-1
print(ans)
main()
|
def main():
n, m = list(map(int, input().split()))
# マイナスの場合は leader であり、同時にサイズ(*-1)を保持する
uf = [-1] * (n+1)
def uf_leader(a):
if uf[a]<0:
return a
uf[a] = uf_leader(uf[a])
return uf[a]
def uf_unite(a, b):
ua, ub = uf_leader(a), uf_leader(b)
if ua==ub:
return False
if uf[ua] > uf[ub]:
ua, ub = ub, ua
uf[ua] += uf[ub]
uf[ub] = ua
return True
def uf_leaders():
return [v for v in range(1,n+1) if uf[v]<0]
# print(uf[1:])
for _ in range(m):
a, b = list(map(int, input().split()))
uf_unite(a, b)
# print(uf[1:])
# print(uf_leaders())
ans = len(uf_leaders())-1
print(ans)
main()
|
p02536
|
N,M = list(map(int,input().split()))
ans = N-1
d = []
for m in range(M):
A,B = list(map(int,input().split()))
for i,di in enumerate(d):
if set([A,B]).issubset(di):
d[i] = di|set([A,B])
break
else:
d.append(set([A,B]))
ans -= 1
print(ans)
|
def f(x):
while p[x]>0: x = p[x]
return x
N,M = list(map(int,input().split()))
p = [-1]*N
for _ in range(M):
A,B = [f(int(x)-1) for x in input().split()]
if A==B: continue
elif A<B: A,B=B,A
p[A] += p[B]
p[B] = A
print((sum(i<0 for i in p)-1))
|
p02536
|
#入力:N,M(int:整数)
def input2():
return list(map(int,input().split()))
#入力:[n1,n2,...nk](int:整数配列)
def input_array():
return list(map(int,input().split()))
class UnionFind():
"""docstring for UnionFind"""
def __init__(self, n):
self.parents = [-1]*n
def find(self,x):
if self.parents[x] < 0: #自分が親である時
return x
else: #自分が子供である時
self.parents[x]=self.find(self.parents[x])
return self.parents[x]
def union(self,x,y):
# 各要素の親要素を返す
x=self.find(x)
y=self.find(y)
if x==y:
return
if self.parents[x] > self.parents[y]:
x,y=y,x
self.parents[x]+=self.parents[y]
self.parents[y]=x
n,m=input2()
AB=[input_array() for _ in range(m)]
D=[[0]*n for _ in range(n)]
uf = UnionFind(n)
for ab in AB:
a=ab[0]
b=ab[1]
uf.union(a-1,b-1)
ans=0
for i in uf.parents:
if i < 0:
ans+=1
print((ans-1))
|
#入力:N,M(int:整数)
def input2():
return list(map(int,input().split()))
#入力:[n1,n2,...nk](int:整数配列)
def input_array():
return list(map(int,input().split()))
class UnionFind():
"""docstring for UnionFind"""
def __init__(self, n):
self.parents = [-1]*n
def find(self,x):
if self.parents[x] < 0: #自分が親である時
return x
else: #自分が子供である時
self.parents[x]=self.find(self.parents[x])
return self.parents[x]
def union(self,x,y):
# 各要素の親要素を返す
x=self.find(x)
y=self.find(y)
if x==y:
return
if self.parents[x] > self.parents[y]:
x,y=y,x
self.parents[x]+=self.parents[y]
self.parents[y]=x
# print(self.parents)
n,m=input2()
AB=[input_array() for _ in range(m)]
uf = UnionFind(n)
for ab in AB:
a=ab[0]
b=ab[1]
uf.union(a-1,b-1)
ans=0
for i in uf.parents:
if i < 0:
ans+=1
print((ans-1))
|
p02536
|
n, m = list(map(int,input().split()))
lst = [-1 for i in range(n + 1)]
lst[0] = 0
def find (x):
if (lst[x] < 0):
return(x)
else:
return (find(lst[x]))
def unit(x, y):
xp = find(x)
yp = find(y)
if (xp == yp):
pass
else:
lst[yp] = xp
for i in range(m):
a, b = list(map(int,input().split()))
unit(a, b)
ans = -1
for i in range(n + 1):
if (lst[i] == -1):
ans = ans + 1
print(ans)
|
n, m = list(map(int,input().split()))
lst = [-1 for i in range(n + 1)]
lst[0] = 0
def find (x):
if (lst[x] < 0):
return(x)
else:
z = find(lst[x])
lst[x] = z
return (z)
def unit(x, y):
xp = find(x)
yp = find(y)
if (xp == yp):
pass
else:
lst[yp] = xp
for i in range(m):
a, b = list(map(int,input().split()))
unit(a, b)
ans = -1
for i in range(n + 1):
if (lst[i] == -1):
ans = ans + 1
print(ans)
|
p02536
|
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.buffer.readline
N, M = list(map(int, input().split()))
nextcity = [[] for _ in range(N)]
sgn = [0 for _ in range(N)]
while M:
M -= 1
A, B = list(map(int, input().split()))
A -= 1
B -= 1
nextcity[A].append(B)
nextcity[B].append(A)
def dfs(cnt, city):
for item in nextcity[city]:
if sgn[item] == 0:
sgn[item] = cnt
dfs(cnt, item)
return None
cnt = 0
for k in range(N):
if sgn[k] == 0:
cnt += 1
sgn[k] = cnt
dfs(cnt, k)
print((cnt -1))
|
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.buffer.readline
N, M = list(map(int, input().split()))
nextcity = [[] for _ in range(N)]
sgn = [0 for _ in range(N)]
while M:
M -= 1
A, B = list(map(int, input().split()))
A -= 1
B -= 1
nextcity[A].append(B)
nextcity[B].append(A)
def bfs(cnt, lis):
nextvisit = []
for j in lis:
for item in nextcity[j]:
if sgn[item] == 0:
nextvisit.append(item)
sgn[item] = cnt
if nextvisit:
bfs(cnt, nextvisit)
return None
else:
return None
cnt = 0
for k in range(N):
if sgn[k] == 0:
cnt += 1
sgn[k] = cnt
bfs(cnt, [k])
print((cnt -1))
|
p02536
|
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
return len(self.roots())
def all_group_members(self):
return {r: self.members(r) for r in self.roots()}
def __str__(self):
return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
if __name__ == '__main__':
n, m = list(map(int, input().split()))
uf = UnionFind(n)
for i in range(m):
a, b = list(map(int, input().split()))
a -= 1
b -= 1
uf.union(a, b)
print((len(list(uf.all_group_members().values()))-1))
|
import sys
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
return len(self.roots())
def all_group_members(self):
return {r: self.members(r) for r in self.roots()}
def __str__(self):
return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
if __name__ == '__main__':
input = sys.stdin.readline
n, m = list(map(int, input().split()))
uf = UnionFind(n)
for i in range(m):
a, b = list(map(int, input().split()))
a -= 1
b -= 1
uf.union(a, b)
print((uf.group_count()-1))
|
p02536
|
# -*- coding: utf-8 -*-
from heapq import heappop, heappush
def resolve(T,v):
while v != T[v]:
v = T[v]
return v
def solve():
N, M = list(map(int, input().split()))
E = set()
for _ in range(M):
a, b = list(map(int, input().split()))
E.add((a-1,b-1))
T = list(range(N))
while E:
e = E.pop()
u, v = e
lu = resolve(T,u)
lv = resolve(T,v)
if lv == lu:
continue
T[lu] = lv
continue
return len(set(resolve(T,v) for v in range(N)))-1
if __name__ == '__main__':
print((solve()))
|
# -*- coding: utf-8 -*-
def resolve(T,v):
lv = v
while lv != T[lv]:
lv = T[lv]
T[v] = lv
return lv
def solve():
N, M = list(map(int, input().split()))
T = list(range(N+1))
for i in range(M):
u, v = list(map(int, input().split()))
lu = resolve(T,u)
lv = resolve(T,v)
if lv == lu:
continue
T[lv] = lu
#print(f'===round{i}===')
#print(T)
#print([resolve(T,v) for v in range(N+1)])
return len(set(resolve(T,v) for v in range(1,N+1)))-1
if __name__ == '__main__':
print((solve()))
|
p02536
|
import sys,io,os
I = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
#I = input
n,m = list(map(int, I().split()))
p=[-1]*(n+1)
s=[0]*(n+1)
S=n-1
def t(a):
while p[a] != -1:
a = p[a]
return a
for _ in range(m):
a,b=list(map(int, I().split()))
a,b = t(a), t(b)
if a != b:
S -= 1
if s[a] > s[b]:
a,b = b,a
p[a] = b
s[b] += s[a]
print(S)
|
import sys,io,os
I = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
#I = input
n,m = list(map(int, I().split()))
p=[-1]*(n+1)
s=[0]*(n+1)
S=n-1
def t(a):
b = a
while p[b] != -1:
b = p[b]
while p[a] != -1:
p[a],a = b,p[a]
return a
for _ in range(m):
a,b=list(map(int, I().split()))
a,b = t(a), t(b)
if a != b:
S -= 1
if s[a] > s[b]:
a,b = b,a
p[a] = b
s[b] += s[a]
print(S)
|
p02536
|
class UnionFind():
# 作りたい要素数nで初期化
# 使用するインスタンス変数の初期化
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
# ノードxのrootノードを見つける
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def unite(self, x, y):
# 木の併合、入力は併合したい各ノード⇒(a,b)
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
# ノードxが属する木のサイズを返す
return -self.parents[self.find(x)]
def same(self, x, y):
# 入力ノード(x,y)が同じグループに属するかを返す
return self.find(x) == self.find(y)
def members(self, x):
#ノードxが属するメンバーをリスト形式で返す
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
#親全てをリスト形式で返す
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
#グループ数の合計を返す
return len(self.roots())
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline
n,m=list(map(int,input().split()))
u=UnionFind(n)
for i in range(m):
a,b=list(map(int,input().split()))
a-=1
b-=1
u.unite(a,b)
ans=0
for i in range(n):
ans=u.roots()
print((len(ans)-1))
|
class UnionFind():
# 作りたい要素数nで初期化
# 使用するインスタンス変数の初期化
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
# ノードxのrootノードを見つける
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def unite(self, x, y):
# 木の併合、入力は併合したい各ノード⇒(a,b)
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
# ノードxが属する木のサイズを返す
return -self.parents[self.find(x)]
def same(self, x, y):
# 入力ノード(x,y)が同じグループに属するかを返す
return self.find(x) == self.find(y)
def members(self, x):
#ノードxが属するメンバーをリスト形式で返す
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
#親全てをリスト形式で返す
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
#グループ数の合計を返す
return len(self.roots())
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline
n,m=list(map(int,input().split()))
u=UnionFind(n)
for i in range(m):
a,b=list(map(int,input().split()))
a-=1
b-=1
u.unite(a,b)
ans=u.roots()
print((len(ans)-1))
|
p02536
|
import sys
from collections import deque
N, M = list(map(int, input().split()))
edge = [[] for _ in range(N)]
for s in sys.stdin.readlines():
a, b = [int(x) - 1 for x in s.split()]
edge[a].append(b)
edge[b].append(a)
path = [-1] * N
cnt = 0
for i in range(N):
if path[i] < 0:
cnt += 1
q = deque()
path[i] = i
q.append(i)
while q:
p = q.popleft()
for np in edge[p]:
if path[np] < 0:
path[np] = i
q.append(np)
print((cnt - 1))
|
import sys
from collections import deque
N, M = list(map(int, input().split()))
edge = [[] for _ in range(N)]
for s in sys.stdin.readlines():
a, b = [int(x) - 1 for x in s.split()]
edge[a].append(b)
edge[b].append(a)
path = [0] * N
cnt = 0
for i in range(N):
if path[i] == 0:
cnt += 1
q = deque()
path[i] = 1
q.append(i)
while q:
p = q.popleft()
for np in edge[p]:
if path[np] == 0:
path[np] = 1
q.append(np)
print((cnt - 1))
|
p02536
|
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
return len(self.roots())
def all_group_members(self):
return {r: self.members(r) for r in self.roots()}
def __str__(self):
return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
N,M=list(map(int,input().split()))
A=[0]*M
B=[0]*M
for i in range(M):
A[i],B[i]=list(map(int,input().split()))
uf=UnionFind(N+1)
for i in range(M):
uf.union(A[i],B[i])
#print(uf.find(1))
#print()
a=[0]*N
#print(uf)
print((len(list(uf.all_group_members().values()))-2))
|
class UnionFind():
def __init__(self, n):
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
N,M=list(map(int,input().split()))
A=[0]*M
B=[0]*M
for i in range(M):
A[i],B[i]=list(map(int,input().split()))
uf=UnionFind(N+1)
for i in range(M):
uf.union(A[i],B[i])
a=[0]*(N+1)
con=0
for i in uf.parents:
if(i<0):
con=con+1
print((con-2))
|
p02536
|
import collections
n, m = list(map(int, input().split()))
linked = collections.defaultdict(set)
for i in range(1, n + 1):
linked[i] = [i]
for i in range(m):
a, b = list(map(int, input().split()))
if linked[a] == linked[b]: continue
linked[a].extend(linked[b])
for t in linked[b]:
linked[t] = linked[a]
n_connected = 0
n_group = 0
for s in list(linked.values()):
if s:
n_group += 1
n_connected += len(s)
s.clear()
print(((n - n_connected) + (n_group - 1)))
|
import collections
n, m = list(map(int, input().split()))
linked = collections.defaultdict(list)
i2group = dict()
gid = n + 1
def get_root(i):
if i not in linked:
return i
j = get_root(linked[i])
linked[i] = j
return j
def get_groups():
return [get_root(i) for i in range(1, n + 1)]
for i in range(m):
a, b = list(map(int, input().split()))
ra, rb = get_root(a), get_root(b)
if ra == rb: continue
linked[ra] = gid
linked[rb] = gid
gid += 1
g = get_groups()
print((len(set(g)) - 1))
exit()
n_connected = 0
n_group = 0
for s in list(linked.values()):
s = s[0]
if s:
n_group += 1
n_connected += len(s)
s.clear()
print(((n - n_connected) + (n_group - 1)))
|
p02536
|
def main():
N, M = list(map(int, input().split()))
connect_list = [0] * N
max_road_num = 0
for i in range(M):
A, B = list(map(int, input().split()))
A = A - 1
B = B - 1
A_road_num = connect_list[A]
B_road_num = connect_list[B]
if A_road_num == 0 and B_road_num == 0:
max_road_num = max_road_num + 1
connect_list[A] = max_road_num
connect_list[B] = max_road_num
elif A_road_num != 0 and B_road_num == 0:
connect_list[B] = connect_list[A]
elif A_road_num == 0 and B_road_num != 0:
connect_list[A] = connect_list[B]
else:
connect_list = [A_road_num if B_road_num == road_num else road_num for road_num in connect_list]
answer = 0
set_connect_list = set(connect_list)
set_connect_list.discard(0)
if len(set_connect_list) != 1:
answer = len(set_connect_list) - 1
print((answer + connect_list.count(0)))
if __name__ == "__main__":
main()
|
def root(list_parent, x):
if(list_parent[x] == x):
return x
else:
list_parent[x] = root(list_parent, list_parent[x])
return list_parent[x]
def unite(list_parent, x, y):
x = root(list_parent, x)
y = root(list_parent, y)
if(x == y):
return list_parent
if x > y:
list_parent[y] = x
else:
list_parent[x] = y
return list_parent
def main():
N, M = list(map(int, input().split()))
list_parent = []
for i in range(N):
list_parent.append(i)
for i in range(M):
A, B = list(map(int, input().split()))
list_parent = unite(list_parent, A-1, B-1)
set_root = set()
for i in list_parent:
root_i = root(list_parent, i)
if root_i not in set_root:
set_root.add(root_i)
print((len(set_root) - 1))
if __name__ == "__main__":
main()
|
p02536
|
# import sys
# import math #sqrt,gcd,pi
# import decimal
import queue # queue
import bisect
# import heapq # priolity-queue
# from time import time
# from itertools import product,permutations,\
# combinations,combinations_with_replacement
# 重複あり順列、順列、組み合わせ、重複あり組み合わせ
# import collections # deque
# from operator import itemgetter,mul
# from fractions import Fraction
# from functools import reduce
mod = int(1e9+7)
# mod = 998244353
INF = 1<<50
def readInt():
return list(map(int,input().split()))
def main():
n,m = readInt()
road = [[] for i in range(n)]
for i in range(m):
a,b = readInt()
road[a-1].append(b-1)
road[b-1].append(a-1)
ans = 0
city = set(i for i in range(n))
while len(city):
q = queue.Queue()
q.put(city.pop())
visit = set()
while not q.empty():
x = q.get()
visit.add(x)
for i in road[x]:
if i not in visit:
q.put(i)
city.discard(i)
if len(city):
ans += 1
print(ans)
return
if __name__=='__main__':
main()
|
# queueのライブラリをインポート
import queue
n,m = list(map(int,input().split()))
# 各都市から繋がっている都市を記録
road = [[] for i in range(n)]
for i in range(m):
a,b = list(map(int,input().split()))
road[a-1].append(b-1)
road[b-1].append(a-1)
ans = 0
# まだ訪れていない都市を記録
city = set(i for i in range(n))
# まだ訪れていない都市がある間繰り返す
while len(city):
# queueを用意する
q = queue.Queue()
# 初期値としてまだ訪れていない都市を入れる
q.put(city.pop())
# 1つのグループを全て辿る
while not q.empty():
x = q.get()
for i in road[x]:
# 既に訪れたか調べる
if i in city:
# 訪れていなければqueueに追加する
q.put(i)
# 未訪問の都市のリストから除外する
city.discard(i)
# まだ訪れていない都市があれば答えを増やす
if len(city):
ans += 1
print(ans)
|
p02536
|
v, e = list(map(int,input().split()))
par = [i for i in range(v+1)]
def find(x):
if par[x] == x:
return x
else:
par[x] = find(par[x])
return par[x]
def unite(x, y):
x = find(x)
y = find(y)
if x == y:
return 0
par[x] = y
for i in range(e):
a, b = list(map(int, input().split()))
unite(a, b)
cnt = 0
for i in range(v+1):
if i == par[i]:
cnt += 1
print((cnt-2))
|
class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):
return -self.parents[self.find(x)]
def same(self, x, y):
return self.find(x) == self.find(y)
def members(self, x):
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):
return len(self.roots())
def all_group_members(self):
return {r: self.members(r) for r in self.roots()}
def __str__(self):
return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
v, e = list(map(int, input().split()))
uf = UnionFind(v)
for i in range(e):
a, b = list(map(int, input().split()))
uf.union(a-1, b-1)
print((uf.group_count()-1))
|
p02536
|
from collections import deque
n, m = list(map(int,input().split()))
edge = [[] for _ in range(n)]
for i in range(m):
a, b = list(map(int,input().split()))
edge[a-1].append(b-1)
edge[b-1].append(a-1)
visited = [0]*n
visited[0] = 1
q = deque([0])
ans = 0
while sum(visited) < n:
while q:
now = q.popleft()
for to in edge[now]:
if visited[to] == 0:
q.append(to)
visited[to] = 1
#print(visited)
if sum(visited) < n:
ans += 1
for i,v in enumerate(visited):
if v == 0:
q.append(i)
visited[i] = 1
break
print(ans)
|
class UnionFind:
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):#要素xが属するグループの根を返す
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):#要素xが属するグループと要素yが属するグループとを併合する
x = self.find(x)
y = self.find(y)
if x == y:
return
if self.parents[x] > self.parents[y]:
x, y = y, x
self.parents[x] += self.parents[y]
self.parents[y] = x
def size(self, x):#要素xが属するグループのサイズ(要素数)を返す
return -self.parents[self.find(x)]
def same(self, x, y):#要素x, yが同じグループに属するかどうかを返す
return self.find(x) == self.find(y)
def members(self, x):#要素xが属するグループに属する要素をリストで返す
root = self.find(x)
return [i for i in range(self.n) if self.find(i) == root]
def roots(self):#すべての根の要素をリストで返す
return [i for i, x in enumerate(self.parents) if x < 0]
def group_count(self):#グループの数を返す
return len(self.roots())
def all_group_members(self):#{ルート要素: [そのグループに含まれる要素のリスト], ...}の辞書を返す
return {r: self.members(r) for r in self.roots()}
def __str__(self):#print()での表示用 ルート要素: [そのグループに含まれる要素のリスト]を文字列で返す
return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())
n, m = list(map(int,input().split()))
uf = UnionFind(n)
edge = []
for i in range(m):
a,b = list(map(int,input().split()))
edge.append((a-1,b-1))
for a,b in edge:
uf.union(a, b)
print((uf.group_count()-1))
|
p02536
|
N = 100000
g = [[] for i in range(N)]
# To check if the vertex
# has been visited or not
vis = [False for i in range(N)]
# To store if vertex is reachable
# from source or not
good = [False for i in range(N)]
def ADD_EDGE(u, v):
g[u].append(v)
# Function to find all good vertices
def dfs1(v):
good[v] = True
for to in g[v]:
if not good[to]:
dfs1(to)
# Function to find cnt of
# all unreachable vertices
def dfs2(v):
global cnt
vis[v] = True
cnt += 1
for to in g[v]:
if not vis[to] and not good[to]:
dfs2(to)
# Function to return
# the minimum edges required
def Minimum_Edges():
global vis, cnt
# Find all vertices reachable
# from the source
dfs1(x)
# To store all vertices
# with their cnt value
val = []
for i in range(0, n):
# If vertex is bad i.e. not reachable
if not good[i]:
cnt = 0
vis = [False for i in range(N)]
# Find cnt of this vertex
dfs2(i)
val.append((cnt, i))
# Sort all unreachable vertices
# in non-decreasing order of
# their cnt values
val.sort(reverse = True)
# Find the minimum number of edges
# needed to be added
ans = 0
for it in val:
if not good[it[1]]:
ans += 1
dfs1(it[1])
return ans
# Driver code
if __name__ == "__main__":
# Number of nodes and source node
n, m = list(map(int, input().split()))
x = 0
# Add edges to the graph
for i in range(m):
u, v = list(map(int, input().split()))
ADD_EDGE(u, v)
print((Minimum_Edges()))
|
import sys
input = sys.stdin.readline
n,m=list(map(int,input().split()))
d={i+1:[] for i in range(n)}
for i in range(m):
x,y=list(map(int,input().split()))
d[x].append(y)
d[y].append(x)
visit=set()
ans= 0
for i in range(1,n+1):
if i not in visit:
ans+=1
stack = [i]
while stack:
c=stack.pop()
visit.add(c)
for i in d[c]:
if i not in visit:
stack.append(i)
print((ans-1))
|
p02536
|
N, M = list(map(int, input().split()))
L = [0] * N
D = {}
c = 1
for i in range(M):
A, B = list(map(int, input().split()))
if L[A - 1] == L[B - 1] == 0:
D[c] = set()
D[c].add(A)
D[c].add(B)
L[A - 1] = c
L[B - 1] = c
c += 1
elif L[A - 1] == 0:
D[L[B - 1]].add(A)
L[A - 1] = L[B - 1]
elif L[B - 1] == 0:
D[L[A - 1]].add(B)
L[B - 1] = L[A - 1]
elif L[A - 1] != L[B - 1]:
D[L[A - 1]] |= D[L[B - 1]]
for j in D.pop(L[B - 1]):
L[j - 1] = L[A - 1]
#print(L, D, sep = "\n")
print((len(D) + L.count(0) - 1))
|
N, M = list(map(int, input().split()))
L = [0] * N
D = {}
c = 1
for i in range(M):
A, B = list(map(int, input().split()))
if L[A - 1] == L[B - 1] == 0:
D[c] = set()
D[c].add(A)
D[c].add(B)
L[A - 1] = c
L[B - 1] = c
c += 1
elif L[A - 1] == 0:
D[L[B - 1]].add(A)
L[A - 1] = L[B - 1]
elif L[B - 1] == 0:
D[L[A - 1]].add(B)
L[B - 1] = L[A - 1]
elif L[A - 1] != L[B - 1]:
if len(D[L[A - 1]]) < len(D[L[B - 1]]):
A, B = B, A
D[L[A - 1]] |= D[L[B - 1]]
for j in D.pop(L[B - 1]):
L[j - 1] = L[A - 1]
#print(L, D, sep = "\n")
print((len(D) + L.count(0) - 1))
|
p02536
|
n,m = list(map(int, input().split()))
def g(u,parent):
if parent[u]!= u:
parent[u] = g(parent[u], parent)
return parent[u]
parent = {u:u for u in range(1, n+1)}
for _ in range(m):
u,v = list(map(int, input().split()))
pu,pv = g(u,parent), g(v,parent)
if pu!= pv:
parent[pu] = pv
ans = 0
for u in parent:
if g(u,parent) == u:
ans+=1
print(ans -1)
|
n,m = list(map(int, input().split()))
def g(u,parent):
if parent[u]!= u:
parent[u] = g(parent[u], parent)
return parent[u]
parent = list(range(n+1))
for _ in range(m):
u,v = list(map(int, input().split()))
pu,pv = g(u,parent), g(v,parent)
if pu!= pv:
parent[pu] = pv
ans = 0
for u in range(1, n+1):
if g(u,parent) == u:
ans+=1
print(ans -1)
|
p02536
|
import sys
sys.setrecursionlimit(2 * (10 ** 6))
n, m = list(map(int, input().split()))
edges = [[] for i in range(n)]
visit = [False for i in range(n)]
def dfs(v):
visit[v] = True
for i in edges[v]:
if not visit[i]:
dfs(i)
for i in range(m):
a, b = list(map(int, input().split()))
edges[a - 1].append(b - 1)
edges[b - 1].append(a - 1)
cnt = 0
for i in range(n):
if not visit[i]:
dfs(i)
cnt += 1
print((cnt - 1))
|
class UnionFind():
def __init__(self, n):
self.n = n
self.par = list(range(self.n))
self.rank = [1] * n
self.cnt = n
def find(self, x):
if self.par[x] == x:
return x
else:
self.par[x] = self.find(self.par[x])
return self.par[x]
def unite(self, x, y):
p = self.find(x)
q = self.find(y)
if p == q:
return None
if p > q:
p, q = q, p
self.rank[p] += self.rank[q]
self.par[q] = p
self.cnt -= 1
def same(self, x, y):
return self.find(x) == self.find(y)
def size(self, x):
return self.rank[x]
def count(self):
return self.cnt
n, m = list(map(int, input().split()))
UF = UnionFind(n)
for _ in range(m):
a, b = list(map(int, input().split()))
UF.unite(a - 1, b - 1)
print((UF.count() - 1))
|
p02536
|
n,m=list(map(int,input().split()))
xy = [list(map(int, input().split())) for _ in range(m)]
x, y = [list(i) for i in zip(*xy)]
ans=0
l=[-1]*n
def rootfind(a):
while 1:
if l[a-1]>0:
a=l[a-1]
else:
break
return a
def rootunion(c,d):
cr=rootfind(c)
dr=rootfind(d)
if cr==dr:
pass
else:
l[cr-1]=dr
for j in range(m):
p=x[j]
q=y[j]
rootunion(p,q)
for o in l:
if o<0:
ans+=1
print((ans-1))
|
n,m=list(map(int,input().split()))
xy = [list(map(int, input().split())) for _ in range(m)]
x, y = [list(i) for i in zip(*xy)]
ans=0
l=[-1]*n
def rootfind(a):
changelist=[]
while 1:
if l[a-1]>0:
changelist.append(a)
a=l[a-1]
else:
break
for e in changelist:
l[e-1]=a
return a
def rootunion(c,d):
cr=rootfind(c)
dr=rootfind(d)
if cr==dr:
pass
else:
l[cr-1]=dr
for j in range(m):
p=x[j]
q=y[j]
rootunion(p,q)
for o in l:
if o<0:
ans+=1
print((ans-1))
|
p02536
|
n,m=list(map(int,input().split()))
data=list(range(n))
cnt=n-1
for i in range(m):
a,b=list(map(int,input().split()))
a-=1
b-=1
while data[a]!=a:
a=data[a]
while data[b]!=b:
b=data[b]
if a!=b:
data[a]=b
cnt-=1
print(cnt)
|
n,m=list(map(int,input().split()))
data=list(range(n))
cnt=n-1
def find(x):
if data[x]==x:
return x
else:
data[x]=find(data[x])
return data[x]
for i in range(m):
a,b=list(map(int,input().split()))
a=find(a-1)
b=find(b-1)
if a!=b:
data[a]=b
cnt-=1
print(cnt)
|
p02536
|
#!/usr/bin/env python
n, m = list(map(int, input().split()))
a = [0 for _ in range(m)]
b = [0 for _ in range(m)]
for i in range(m):
a[i], b[i] = list(map(int, input().split()))
a[i] -= 1
b[i] -= 1
class UnionFind():
def __init__(self, n):
self.n = n
self.par = [i for i in range(n)]
self.rank = [0 for _ in range(n)]
self.sizes = [1 for _ in range(n)]
def root(self, x):
if self.par[x] == x:
return x
else:
self.par[x] = self.root(self.par[x]) # 圧縮経路
return self.par[x]
# return root(par[x]) # 圧縮しない場合
def same(self, x, y):
return self.root(x) == self.root(y)
def unite(self, x, y):
rx = self.root(x)
ry = self.root(y)
if rx == ry:
return
# par[rx] = ry # naiveな連結
# 低い木を高い方にくっつける。
if self.rank[rx] < self.rank[ry]:
self.par[rx] = ry
self.sizes[ry] += self.sizes[rx]
else:
self.par[ry] = rx
self.sizes[rx] += self.sizes[ry]
# rx木とry木の高さが同じならば、rx木を深くする。
if self.rank[rx] == self.rank[ry]:
self.rank[rx] += 1
def size(self, x):
'''
xが属するグループのサイズを返す
(連結成分の大きさ)
'''
return self.sizes[self.root(x)]
def connected(self):
'''
連結成分の数
'''
return len(set(self.par))
uf = UnionFind(n)
for i in range(m):
uf.unite(a[i], b[i])
for i in range(n):
_ = uf.root(i)
ans = uf.connected()-1
print(ans)
|
#!/usr/bin/env python
n, m = list(map(int, input().split()))
a = [0 for _ in range(m)]
b = [0 for _ in range(m)]
for i in range(m):
a[i], b[i] = list(map(int, input().split()))
a[i] -= 1
b[i] -= 1
class UnionFind():
def __init__(self, n):
self.n = n
self.par = [i for i in range(n)]
self.rank = [0 for _ in range(n)]
self.sizes = [1 for _ in range(n)]
def root(self, x):
if self.par[x] == x:
return x
else:
self.par[x] = self.root(self.par[x]) # 圧縮経路
return self.par[x]
# return root(par[x]) # 圧縮しない場合
def same(self, x, y):
return self.root(x) == self.root(y)
def unite(self, x, y):
rx = self.root(x)
ry = self.root(y)
if rx == ry:
return
# par[rx] = ry # naiveな連結
# 低い木を高い方にくっつける。
if self.rank[rx] < self.rank[ry]:
self.par[rx] = ry
self.sizes[ry] += self.sizes[rx]
else:
self.par[ry] = rx
self.sizes[rx] += self.sizes[ry]
# rx木とry木の高さが同じならば、rx木を深くする。
if self.rank[rx] == self.rank[ry]:
self.rank[rx] += 1
def size(self, x):
'''
xが属するグループのサイズを返す
(連結成分の大きさ)
'''
return self.sizes[self.root(x)]
def roots(self):
'''
全ての頂点の根のlistを返す
'''
return [self.root(i) for i in range(self.n)]
def connected(self):
'''
連結成分の数を返す
'''
#return len(set(self.par))
return len(set(self.roots()))
uf = UnionFind(n)
for i in range(m):
uf.unite(a[i], b[i])
ans = uf.connected()-1
print(ans)
|
p02536
|
_=int(eval(input()));print((['Three','Four']['Y'in input().split()]))
|
N=eval(input());print((['Three','Four']['Y'in input().split()]))
|
p03424
|
n = eval(input())
str = input().split()
dict = []
for s in str:
if not s in dict:
dict.append(s)
print(("Three" if len(dict) == 3 else "Four"))
|
n = eval(input())
dict = set(input().split())
print(("Three" if len(dict) == 3 else "Four"))
|
p03424
|
from collections import Counter
n = int(eval(input()))
s = list(map(str, input().split()))
if len(Counter(s)) == 4:
print ("Four")
else:
print ("Three")
|
n = int(eval(input()))
s = list(map(str, input().split()))
ss = set(s)
if len(ss) == 3:
print ("Three")
else:
print ("Four")
|
p03424
|
n = int(eval(input()))
s = list(map(str, input().split()))
d = {}
for i in range(n):
if s[i] not in d:
d[s[i]] = 1
else:
d[s[i]] += 1
if len(list(d.keys())) == 3:
print('Three')
else:
print('Four')
#print(d)
|
n = int(eval(input()))
s = list(map(str, input().split()))
if len(set(s)) == 4:
print('Four')
else:
print('Three')
|
p03424
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.