Problem:


Score : 500 points

Problem Statement

There are N cards placed face down in a row. On each card, an integer 1 or 2 is written.

Let A_i be the integer written on the i-th card.

Your objective is to guess A_1, A_2, ..., A_N correctly.

You know the following facts:

For each i = 1, 2, ..., M, the value A_{X_i} + A_{Y_i} + Z_i is an even number.

You are a magician and can use the following magic any number of times:

Magic: Choose one card and know the integer A_i written on it. The cost of using this magic is 1.

What is the minimum cost required to determine all of A_1, A_2, ..., A_N?

It is guaranteed that there is no contradiction in given input.

Constraints

All values in input are integers.

2 \leq N \leq 10^5

1 \leq M \leq 10^5

1 \leq X_i < Y_i \leq N

1 \leq Z_i \leq 100

The pairs (X_i, Y_i) are distinct.

There is no contradiction in input. (That is, there exist integers A_1, A_2, ..., A_N that satisfy the conditions.)

Input

Input is given from Standard Input in the following format:

N M
X_1 Y_1 Z_1
X_2 Y_2 Z_2
\vdots
X_M Y_M Z_M

Output

Print the minimum total cost required to determine all of A_1, A_2, ..., A_N.

Sample Input 1

3 1
1 2 1

Sample Output 1

2

You can determine all of A_1, A_2, A_3 by using the magic for the first and third cards.

Sample Input 2

6 5
1 2 1
2 3 2
1 3 3
4 5 4
5 6 5

Sample Output 2

2

Sample Input 3

100000 1
1 100000 100

Sample Output 3

99999



Sample input:
3 1
1 2 1


Sample output:
2

Submission status: Wrong Answer

Solution code:
import sys

stdin = sys.stdin

ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces

n, m = na()
li = []
for i in range(m):
    x, y, w = na()
    if x not in li:
        li.append(x)
print(n - len(li))

Submission status: Wrong Answer

Solution code:
N, M = map(int, input().split())
X, Y, Z = [0]*M, [0]*M, [0]*M
A = [0]*N
cnt = 0

for i in range(M):
   X[i], Y[i], Z[i] = map(int, input().split()) 
   if A[X[i]-1] == 0 and A[Y[i]-1] == 0:
       cnt += 1
       A[X[i]-1] = 1
       A[Y[i]-1] = 1
   elif A[X[i]-1] == 1 or A[Y[i]-1] == 1:
       A[X[i]-1] = 1
       A[Y[i]-1] = 1

for i in range(N):
    if A[i] == 0:
        cnt += 1

print(cnt)

Submission status: Wrong Answer

Solution code:
n,m = map(int,input().split())
S = []
kisyutu = []
cnt = 0
for i in range(m):
    aa = list(input().split())
    S.append(aa[0:2])
#print(S)
for j in S:
    if j[0] not in kisyutu and j[1] not in kisyutu:
        kisyutu.append(j[0])
        kisyutu.append(j[1])
        cnt += 1
    if j[0] in kisyutu and j[1] not in kisyutu:
        kisyutu.append(j[1])
        cnt += 1
    if j[0] not in kisyutu and j[1] in kisyutu:
        kisyutu.append(j[0])
        cnt += 1
print(n-cnt)

Submission status: Wrong Answer

Solution code:
N, M = map(int, input().split())

items = []
ans = 0
visible = set()

for i in range(M):
    x, y, z = map(int, input().split())
    visible.add(x)
    visible.add(y)
    items.append((x, y, z))
unvisible = set([i for i in range(1, N + 1)]) - visible
ans += len(unvisible)


def f(num):
    know = set()
    cnt = 0
    for x, y, z in items:
        if x in know:
            # tmp = know[x]
            # if tmp + z % 2 == 0:
            #     know[y] = 2
            # else:
            #     know[x] = 1
            know.add(y)
            continue
        elif y in know:
            # tmp = know[y]
            # if tmp + z % 2 == 0:
            #     know[x] = 2
            # else:
            #     know[x] = 1
            know.add(x)
            continue
        else:
            cnt += 1
            know.add(x)
            know.add(y)
    if cnt <= num:
        return True
    else:
        return False


ok = N - ans
ng = -1

while abs(ok - ng) > 1:
    mid = (ok + ng) // 2
    if f(mid):
        ok = mid
    else:
        ng = mid
print(ans + ok)

Submission status: Wrong Answer

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time

sys.setrecursionlimit(10**7)
inf=10**20
mod=10**9+7

def LI(): return list(map(int,input().split()))
def II(): return int(input())
def LS(): return input().split()
def S(): return input()

def main():
  N,M=LI()
  l=[0]*N
  cnt=1
  for i in range(M):
    a,b,c=LI()
    x=l[a-1]
    y=l[b-1]
    if x==0:
      l[a-1]=cnt
      cnt+=1
    else:
      if x<y:
        for i in range(len(l)):
          if l[i]==y:
            l[i]=x

    if y==0:
      x=l[a-1]
      if x<=cnt:
        l[b-1]=x
    else:
      if y<x:
        for i in range(len(l)):
          if l[i]==x:
            l[i]=y


  print(cnt+l.count(0)-1)


main()
# print(main())

Submission status: Wrong Answer

Solution code:
N, M = map(int, input().split())

count = 0
ans = 0
flg = [False]*N
for _ in range(M):
    X, Y, Z = map(int, input().split())
    if flg[X-1] is False and flg[Y-1] is False:
        flg[X-1], flg[Y-1] = True, True
        count += 2
        ans += 1
    elif flg[X-1] is False and flg[Y-1] is True:
        flg[X-1] = True
        count += 1
    elif flg[X-1] is True and flg[Y-1] is False:
        flg[Y-1] = True
        count += 1

ans += N - count

print(ans)

Submission status: Wrong Answer

Solution code:
def solve(n, m, x):      #x = [[x1, y1], [x2, y2], ..., [xm, ym]]
    list1 = [0 for _ in range(n)]
    x.sort()
    
    cnt = 1
    list1[0] = cnt
    
    for i in range(m):
        a = list1[x[i][0]-1]
        b = list1[x[i][1]-1]
        if a != 0:
            if b != 0:
                mi = min(a, b)
                ma = max(a, b)
                for j in range(n):
                    if list1[j] == ma:
                        list1[j] = mi
            else:
                list1[x[i][1]-1] = a
        else:
            if b != 0:
                list1[x[i][0]-1] = b
            else:
                j = 0
                while j < x[i][0]-1:
                    if list1[j] == 0:
                        cnt += 1
                        list1[j] = cnt
                    j += 1
                
                cnt += 1
                list1[x[i][0]-1] = cnt
                list1[x[i][1]-1] = cnt
                
    for i in range(n):
        if list1[i] == 0:
            cnt += 1
            list1[i] = cnt
                
    return cnt

n, m = map(int, input().split())
x = []
for i in range(m):
    y = list(map(int, input().split()))
    x += [y[:2]]

print(solve(n, m, x))

Submission status: Wrong Answer

Solution code:
N, M = map(int, input().split())
countList = [0] * N
cost = 0
for i in range(M):
    x, y, z = map(int, input().split())
    if(countList[x-1] == 0):
        countList[x-1] = 1
        if(countList[y-1] == 0):
            countList[y-1] = 1
            cost += 1
    else:
        if(countList[y-1] == 0):
            countList[y-1] = 1
ans = cost + countList.count(0)
print(ans)

Submission status: Wrong Answer

Solution code:




N,M=[int(c) for c in input().split()]










graph_indexes=[i for i in range(N)] #それぞれの数は, どのグラフに含まれているのか
graphs=[[i] for i in range(N)] #実際のグラフ

for i in range(M):
	X,Y,Z=[int(c)-1 for c in input().split()]
	X_i=graph_indexes[X]
	Y_i=graph_indexes[Y]
	if(X_i!=Y_i):
		graphs[X_i].extend(graphs[Y_i].copy())
		graphs[Y_i]=[]
		graph_indexes[Y]=graph_indexes[X]
i=0
for g in graphs:
	if(g!=[]):
		i+=1
print(i)

Submission status: Wrong Answer

Solution code:
import numpy as np
N,M=map(int, input().split())
g = np.zeros(N).astype(int)
for m in range(M):
    x,y,z=map(int, input().split())
    x -= 1
    y -= 1
    if g[x] == 0 and g[y] == 0:
        g[x] = m+1
        g[y] = m+1
    elif g[x] == 0:
        g[x] = g[y]
    elif g[y] == 0:
        g[y] = g[x]
    elif g[x] == g[y]:
        pass
    else:
        t = g[x]
        g[np.where(g==g[y])] = t
cnt = np.zeros(M)
ans = 0
for mm in g:
    m = mm-1
    if m < 0:
        ans += 1
    if cnt[m] == 0:
        ans += 1
        cnt[m] = 1
print(ans)

Submission status: Wrong Answer

Solution code:
n, m = map(int,input().split())
l = []
l1 = []
count = 0
for i in range(m):
  a, b, c = map(int,input().split())
  if a not in l1:
    l1.append(a)
  if b not in l1:  
    l1.append(b)
  if a not in l and b not in l:
    count += 1
    l = []
    l.append(a)
    l.append(b)
  else:
    l.append(a)
    l.append(b)
num = n - len(l1)
print(count+num)

Submission status: Wrong Answer

Solution code:
n,m = map(int,input().split())
x=[]
y=[]
z=[]
for i in range(m):
    x1,y1,z1=map(int,input().split())
    x.append(x1)
    y.append(y1)
    z.append(z1)
cnt = 0
nlist = [1]*n
for i in range(m):
    if nlist[x[i]-1]==1 and nlist[y[i]-1]==1:
        cnt += 1
    nlist[x[i]-1] *= 0
    nlist[y[i]-1] *= 0
ans = sum(nlist)+cnt
print(ans)

Submission status: Wrong Answer

Solution code:
n, m = map(int, input().split(' '))
hints = []
for _ in range(m):
    x, y, z = map(int, input().split(' '))
    s = {x, y}
    processed = False
    for idx, hint in enumerate(hints):
        if len(hint & s) > 0:
            hints[idx] = hint | s
            processed = True

    if not processed:
        hints.append(s)

cost = len(hints)
cleared = sum(map(len, hints))
cost += n - cleared
print(cost)

Submission status: Wrong Answer

Solution code:
n, m = map(int, input().split())

info = set()

xyz = [list(map(int,input().split())) for _ in range(m)]
x, y, z = xyz[0]
info.add(x)
info.add(y)
cnt = 1

new = True
while new:
    new = False
    for i in range(1, m):
        x, y, z = xyz[i]
        if x not in info and y in info:
            cnt += 1
            info.add(x)
            new = True
        if y not in info and x in info:
            cnt += 1
            info.add(y)
            new = True

for i in range(1, m):
    x, y, z = xyz[i]
    if x not in info and y not in info:
        cnt += 1
        info.add(x)
        info.add(y)

new = True
while new:
    new = False
    for i in range(1, m):
        x, y, z = xyz[i]
        if x not in info and y in info:
            cnt += 1
            info.add(x)
            new = True
        if y not in info and x in info:
            cnt += 1
            info.add(y)
            new = True

print(n - cnt)

Submission status: Wrong Answer

Solution code:

N, M = map(int, input().split())
u = [0]*M
v = [0]*M
w = [0]*M

for i in range(M):
    u[i], v[i], w[i] = map(int, input().split())

ans = [1]*N
cost = 0

for i in range(M):
    if ans[u[i]-1] == 1 and ans[v[i]-1] == 1:
        cost += 1
        ans[u[i]-1] = 0
        ans[v[i]-1] = 0
    elif ans[u[i]-1] == 0 and ans[v[i]-1] == 0:
        cost += 0
    else:
        ans[u[i]-1] = 0
        ans[v[i]-1] = 0

for i in range(N):
    cost += ans[i]

print(cost)

Submission status: Wrong Answer

Solution code:
n, m = map(int, input().split())
edge = [0] *n
count =1
for _ in range(m):
    u, v, _ = map(int, input().split())
    if edge[u-1]==0 and edge[v-1]==0:
        edge[u-1] = count
        edge[v-1] = count
        count +=1
    elif edge[u-1]==0 and edge[v-1]!=0:
        edge[u-1] = edge[v-1]
    elif edge[u-1]!=0 and edge[v-1]==0:
        edge[v-1] = edge[u-1]
    else:
        mini = min(edge[u-1], edge[v-1]) 
        maxi = max(edge[u-1], edge[v-1]) 
        index = [i for i in range(len(edge)) if edge[i]==maxi]
        for i in index:
            edge[i] = mini
        count -=1
    
zero_count = edge.count(0)
if zero_count ==0:
    print(count-1)
else:
    print(count-1+zero_count)

Submission status: Wrong Answer

Solution code:
import numpy as np

n, m = list(map(int, input().split()))

known_dict = {}
search_count = 0
for i in range(m):
  w_ary = list(map(int, input().split()))
  if not (w_ary[0] in known_dict or w_ary[1] in known_dict) :
    search_count += 1
  known_dict[w_ary[0]] = "1"
  known_dict[w_ary[1]] = "1"

print(search_count + (n - len(known_dict)))

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

N,M = [int(i) for i in input().split()]
l = [[] for _ in range(N)]

for i in range(M):
    x,y,_ = [int(j) for j in input().split()]
    l[x-1].append(y-1)

print(l.count([]))

Submission status: Wrong Answer

Solution code:
from sys import stdin

class Card():
  def __init__(self,v):
    self.p=0
    self.v=v

  def set_p(self, p):
    if p.p == self.v:
      self.p = self.p
    elif p.p!=0:
      self.p = p.p
    else:
      self.p = p.v

n, m = [int(x) for x in stdin.readline().rstrip().split()]

list = []

for i in range(1,n+1):
  list.append(Card(i))

for i in range(m):
  x, y, z = [int(x) for x in stdin.readline().rstrip().split()]
  parent = min(x,y)
  child = max(x,y)
  if( list[child-1].p != 0 ):
    list[parent-1].set_p(list[child-1])
  else:
    list[child-1].set_p(list[parent-1])

ans=0
for i in range(0,n):
  #print(list[i].v, list[i].p)
  if( list[i].p==0):
    ans+=1

print(ans)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-

def readInts():
  return [int(s) for s in input().split(" ")]

def root(groups, n):
  while groups[n] != n:
    n = groups[n]
  return n

def main():
  N, M = readInts()
  groups = [i for i in range(N)]

  for i in range(M):
    X, Y, Z = readInts()
    n = min(groups[X-1], groups[Y-1])
    groups[X-1] = n
    groups[Y-1] = n

  knowns = set()
  for n in range(N):
    knowns.add(root(groups, n))
  print(len(knowns))

if __name__ == "__main__":
  main()

Submission status: Wrong Answer

Solution code:
from sys import stdin
input = stdin.readline
n,m=map(int,input().split())
a=[i for i in range(n)]
b=[]
for _ in range(m):
  x,y,z=map(int,input().split())
  b.append([x,y])
b.sort()
for i,j in b:a[i-1]=a[j-1]=min(a[i-1],a[j-1])
a.sort()
def ecount(X):
  ans=1
  for i in range(len(X)-1):
    if X[i]!=X[i+1]:ans+=1
  return ans
print(ecount(a))

Submission status: Wrong Answer

Solution code:
class UnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n+1)]
        self.rank = [0] * (n+1)

    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 union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    def same_check(self, x, y):
        return self.find(x) == self.find(y)
    def ans(self):
        return len(set(self.par))-1
n,m=map(int,input().split())
U=UnionFind(n)

for i in range(m):
  x,y,z=map(int,input().split())
  U.union(x,y)
print(U.ans())

Submission status: Wrong Answer

Solution code:
n, m = map(int, input().split())
data = [list(map(int, input().split())) for _ in range(m)]

indices = {}
for i in range(n):
    indices[i + 1] = -1

idx = 0
red = 0
for x, y, z in data:
    if indices[x] == -1 and indices[y] == -1:
        indices[x] = idx
        indices[y] = idx
        idx += 1
        red += 1
    elif indices[x] == -1:
        indices[x] = indices[y]
        red += 1
    elif indices[y] == -1:
        indices[y] = indices[x]
        red += 1
print(n - red)

Submission status: Wrong Answer

Solution code:
# 2019/05/19
# AtCoder Beginner Contest 126 - E

# Input
n, m = map(int,input().split())

# Table Init
wl = list()
for i in range(n):
    subl = list()
    subl.append(i)
    subl.append(0)
    subl.append(list())
    wl.append(subl)

for j in range(m):
    x, y, z = map(int,input().split())
    wl[x-1][2].append(y)
    wl[y-1][1] = -1

cnt = 0
for i in range(n):
    if wl[i][1] == 0:
        cnt += 1

# Output
print(cnt)

Submission status: Wrong Answer

Solution code:
num=[]
num=[int(i) for i in input().split()]

zyouken = []

for i in range(num[1]):
    zyouken.append(input())

count_arr = [0 for i in range(num[0])]

zyouken_2 = []
zyouken_3 =[]

for temp in zyouken:
    arr = temp.split()
    zyouken_2.append(int(arr[0]))
    zyouken_3.append(int(arr[1]))

for i,temp in enumerate(zyouken_3):
    if zyouken_2[i] != temp:
        count_arr[temp-1] = 1

print(count_arr.count(0))

Submission status: Wrong Answer

Solution code:
from collections import deque
import heapq        

N, M = map(int, input().split())
edges = {i: [] for i in range(N)}
for _ in range(M):
    x, y, _ = map(int, input().split())
    edges[x-1].append(y-1)

ans = 0
visited = [False]*N
for i in range(N):
    if visited[i]:
        continue
    stack = [i]
    while stack:
        v = stack.pop()
        for u in edges[v]:
            if not visited[u]:
                visited[u] = True
                stack.append(u)
    ans += 1
print(ans)

Submission status: Wrong Answer

Solution code:
# segtree

N, M = map(int, input().split())

parent = list(range(N + 1))

for _ in range(M):
    x, y, z = map(int, input().split())
    x_list = [x]
    parent[x] = y
    while x != parent[x]:
        x = parent[x]
        x_list.append(x)
    for a in x_list:
        parent[a] = x
    # print(x, x_list)

for i in range(N + 1):
    x = i
    x_list = [x]
    while x != parent[x]:
        x = parent[x]
        x_list.append(x)
    for a in x_list:
        parent[a] = x
    # print(x, x_list)

res = [0] * (N + 1)
res_c = 0
for i in range(1, N + 1):
    j = parent[i]
    if res[j] == 0:
        res_c += 1
    res[j] += 1

print(N - (sum(res) - res_c))

Submission status: Wrong Answer

Solution code:
N,M = map(int,input().split())
XYZ = [list(map(int,input().split())) for _ in range(M)]

nlist = [0] * N
for i in range(N):
    nlist[i] = i
    
for i in range(M):
    nlist[XYZ[i][1]-1] = nlist[XYZ[i][0]-1]

cnt = 0
for i in range(N):
    if nlist[i] == i: cnt += 1
    
print(cnt)

Submission status: Wrong Answer

Solution code:
# Union Find
# find the number of connected componnent
import sys
stdin = sys.stdin
 
sys.setrecursionlimit(10**5) 
 
def ii(): return int(stdin.readline())
def li(): return map(int, stdin.readline().split())
N, M = tuple(li())
prn = {i:i for i in range(1, N+1)}
def parent(node):
    if prn[node] == node:
        return node
    else:
        return parent(prn[node])
for _ in range(M):
    a, b, c = tuple(li())
    pa, pb = parent(a), parent(b)
    root = min(pa, pb)
    prn[a] = prn[b] = root


print(len(set(prn.values())))

Submission status: Wrong Answer

Solution code:

N, M = map(int, input().split())

ans = [False for _ in range(N)]
count = 0

for i in range(M):
    x, y, z = map(int, input().split())
    if ans[x - 1] == False and ans[y - 1] == False:
        ans[x - 1] = True
        ans[y - 1] = True
        count += 1
    elif ans[x - 1] == False:
        ans[x - 1] = True
        #count += 1
    elif ans[y - 1] == False:
        ans[y - 1] = True
        #count += 1
for j in ans:
    if j == False:
        count += 1
print(count)

Submission status: Wrong Answer

Solution code:
import sys
import re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from copy import copy


def input(): return sys.stdin.readline().strip()


def INT(): return int(input())


def MAP(): return map(int, input().split())


def LIST(): return list(map(int, input().split()))



sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7

n,m=MAP()

xyz = [LIST() for _ in range(m)]

lis = list(range(1,n+1))

for i, x in enumerate(xyz):
    if lis[x[0]-1] != lis[x[1]-1]:
        lis[x[1]-1] = lis[x[0]-1]

    
#print(lis)
p = set(lis)
#print(list(p))

print(len(p))

Submission status: Wrong Answer

Solution code:
n,m=map(int,input().split())
lst=[]
for i in range(m):
  x,y,z=map(int,input().split())
  lst.append((x,y))
l=[0]*n
ans=n-1
for i in range(m):
  a,b=lst[i]
  if l[a-1]==0 and l[b-1]==0:
    l[a-1]=1
    l[b-1]=1
  else:
    ans-=1
print(ans)

Submission status: Wrong Answer

Solution code:

from collections import defaultdict


def main():
    num, hinto = map(int, input().split())
    data_flg = [0 for i in range(num + 1)]
    ans = 0
    for i in range(hinto):
        x, y, z = map(int, input().split())
        if data_flg[x] == 0 and data_flg[y] == 0:
            ans += 1
        data_flg[x] = 1
        data_flg[y] = 1

    for i in range(1, num + 1):
        if data_flg[i] == 0:
            ans += 1

    print(ans)




if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:

# coding: utf-8

# In[20]:

import sys
import numpy as np
input = sys.stdin.readline
N, M = map(int, input().split())
hint = np.array([list(map(int, input().split())) for i in range(M)])


# In[21]:

#hint


# In[22]:

syugo = [set(hint[0][:2])]
for i in range(1, M):
    x_flag = False
    y_flag = False
    x, y = hint[i][:2]
    for i, s in enumerate(syugo):
        if x in s:
            x_flag = True
            x_i = i
        if y in s:
            y_flag = True
            y_i = i
    if x_flag and y_flag:
        syugo[x_i] = syugo[x_i] | syugo[y_i]
    elif x_flag:
        syugo[x_i] = syugo[x_i] | set([x, y])
    elif y_flag:
        syugo[y_i] = syugo[y_i] | set([x, y])
    else:
        syugo.append(set([x, y]))


# In[23]:

zen = set(range(1, N+1))
print(len(zen.difference(*syugo)) + len(syugo))


# In[ ]:

Submission status: Wrong Answer

Solution code:
N, M = map(int, input().split(" "))
group_list = list()
check = [False for i in range(N)]
for i in range(M):
    x, y, z = map(int, input().split(" "))
    if check[x-1]:
        for g in group_list:
            if x in g:
                g.add(y)
                check[y-1] = True
                break
    elif check[y-1]:
        for g in group_list:
            if y in g:
                g.add(x)
                check[x-1] = True
                break
    else:
        s = set()
        s.add(x)
        s.add(y)
        group_list.append(s)
        check[x-1] = True
        check[y-1] = True


count = 0
for g in group_list:
    count += len(g)

print(N - count + len(group_list))

Submission status: Wrong Answer

Solution code:
n,m = map(int,input().split())
x=[]
y=[]
z=[]
for i in range(m):
    x1,y1,z1=map(int,input().split())
    x.append(x1)
    y.append(y1)
    z.append(z1)
cnt = 0
nlist = [1]*n
for i in range(m):
    if nlist[x[i]-1]==1:
        nlist[x[i]-1] *= 0
        cnt += 1
    nlist[y[i]-1] *= 0
ans = sum(nlist)+cnt
print(ans)

Submission status: Wrong Answer

Solution code:
# segtree

N, M = map(int, input().split())

parent = list(range(N + 1))

for _ in range(M):
    x, y, _ = map(int, input().split())
    x_list = [x]
    parent[x] = y
    while x != parent[x]:
        x = parent[x]
        x_list.append(x)
    for a in x_list:
        parent[a] = x
    print(x, x_list)

for i in range(N + 1):
    x = i
    x_list = [x]
    while x != parent[x]:
        x = parent[x]
        x_list.append(x)
    for a in x_list:
        parent[a] = x
    print(x, x_list)

res = [0] * (N + 1)
res_c = 0
for i in range(1, N + 1):
    j = parent[i]
    if res[j] == 0:
        res_c += 1
    res[j] += 1

print(N - (sum(res) - res_c))

Submission status: Wrong Answer

Solution code:
n,m=[int(i) for i in input().split()]
ls=[]
for i in range(m):
    l=input().split()
    l.pop(2)
    ls.append(sorted([int(i) for i in l]))

from itertools import chain
count=len(set(range(n+1))-set(chain.from_iterable(ls))-{0})
sorted(ls)
while len(ls) != 0:
    ls = [i for i in ls if not (i.__contains__(ls[0][0]) or i.__contains__(ls[0][1]))]
    count+=1
print(count)

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-


def main():
    from collections import Counter

    n, m = map(int, input().split())
    numbers = list()
    ans = n

    for i in range(m):
        xi, yi, zi = map(int, input().split())
        numbers.append(xi)
        numbers.append(yi)

    for number, count in Counter(numbers).items():
        if count >= 2:
            ans -= 1

    if ans == n:
        ans -= m

    print(ans)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
n,m=map(int,input().split())
l=[list(map(int,input().split())) for i in range(m)]
L2={l[0][0],l[0][1]}
ct=1
for i in range(1,m):
  if l[i][0] in L2 or l[i][1] in L2:
    pass
  else:
    ct+=1
  L2.add(l[i][0])
  L2.add(l[i][1])

print(ct+n-len(L2))

Submission status: Wrong Answer

Solution code:
N, M = map(int, input().split())
box = set()
ans = 0
for _ in range(M):
    X, Y, Z = map(int, input().split())
    if X not in box and Y not in box:
        ans += 1
    box.add(X)
    box.add(Y)
for i in range(1,N+1):
    if i not in box:
        ans += 1
print(ans)

Submission status: Wrong Answer

Solution code:
n,m = map(int, input().split())

cards = [0] * n
ans = 0
for i in range(m):
      x,y,z = map(int, input().split())
      if cards[x-1] == 0 and cards[y-1] == 0:
            ans += 1
            cards[x-1] = 1
            cards[y-1] = 1
      elif cards[x-1] == 1 or cards[y-1] == 1:
            cards[x-1] = 1
            cards[y-1] = 1
print(ans+cards.count(0))

Submission status: Wrong Answer

Solution code:
num=[]
num=[int(i) for i in input().split()]

zyouken = []

for i in range(num[1]):
    zyouken.append(input())

count_arr = [0 for i in range(num[0])]

zyouken_2 = []
zyouken_3 =[]

for temp in zyouken:
    arr = temp.split()
    zyouken_2.append(int(arr[0]))
    zyouken_3.append(int(arr[1]))

for temp in zyouken_3:
    count_arr[temp-1] = 1

print(count_arr.count(0))

Submission status: Wrong Answer

Solution code:
# E問題
# X_i,Y_iで触れられていない数については魔法を使う必要がある.
# X_i、Y_iのペアのウチ、片方が分かればもう片方の偶奇も決定する.
# つまりグラフが何個に分割されているかが分かれば良い
n, m = map(int, input().split())
edge = {}
for i in range(m):
    x, y, z = map(int, input().split())
    if(x in edge.keys()):
        edge[x].append(y)
    else:
        edge[x] = [y]
    if(y in edge.keys()):
        edge[y].append(x)
    else:
        edge[y] = [x]
presence = {}
graph_count = 0
for key, nodes in edge.items():
    if(key not in presence.keys()):
        # 初出=>別グラフ.
        graph_count += 1
        presence[key] = 1
    for i in nodes:
        presence[i] = 1

print(graph_count + n - len(presence))

Submission status: Wrong Answer

Solution code:
from bisect import bisect_left, bisect_right
from collections import Counter, defaultdict, deque, OrderedDict
from copy import deepcopy
from fractions import gcd
from functools import lru_cache, reduce
from math import ceil, floor
from sys import setrecursionlimit

import heapq as hq
import itertools as its
import operator as op


# globals
inf = float('inf')
N = 0


def set_inputs():
    global N
    return


class UnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n+1)]
        self.rank = [0] * (n+1)

    # 検索
    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 union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    # 同じ集合に属するか判定
    def same_check(self, x, y):
        return self.find(x) == self.find(y)


def main():
    setrecursionlimit(100000)
    set_inputs()
    # ----------MAIN----------
    N, M = get_li()
    X, Y, Z = get_data(M, [int, int, int])
    uf = UnionFind(N)
    for x, y, _ in zip(X, Y, Z):
        uf.union(x, y)
    print(len(set(uf.par[1:])))
    return


def get_int():
    return int(input())


def get_float():
    return float(input())


def get_str():
    return input().strip()


def get_li():
    return [int(i) for i in input().split()]


def get_lf():
    return [float(f) for f in input().split()]


def get_lc():
    return list(input().strip())


def get_data(n, types, sep=None):
    if len(types) == 1:
        return [types[0](input().strip()) for _ in range(n)]
    return list(zip(*(
        [t(x) for t, x in zip(types, input().strip().split(sep=sep))]
        for _ in range(n)
    )))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from sys import stdin
input = stdin.readline
n,m=map(int,input().split())
a=[i for i in range(n)]
b=[]
for _ in range(m):
  x,y,z=map(int,input().split())
  b.append([x,y])
b.sort()
for i,j in b:a[i-1]=a[j-1]=min(a[i-1],a[j-1])
def ecount(X):
  ans=1
  for i in range(len(X)-1):
    if X[i]!=X[i+1]:ans+=1
  return ans
print(ecount(a))

Submission status: Wrong Answer

Solution code:
class UnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n+1)]
        self.rank = [0] * (n+1)

    # 検索
    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 union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    # 同じ集合に属するか判定
    def same_check(self, x, y):
        return self.find(x) == self.find(y)

n,m = map(int, input().split())

a = UnionFind(n)

for i in range(m):
    x,y,z = map(int, input().split())
    x-=1
    y-=1
    a.union(x,y)

print(len(set(a.par[:n])))

Submission status: Wrong Answer

Solution code:
import sys
input = sys.stdin.readline

n,m = map(int,input().split())
l = [False for i in range(n)]

for i in range(m):
    x, y, z = map(int, input().split())
    y -= 1
    if not l[y]:
        l[y] = True
    else:
        l[x] = True

sum = 0
for i in range(n):
    if not l[i]:
        sum += 1

print(sum)

Submission status: Wrong Answer

Solution code:
# グループに属するかの判定(find)や、グループ結合(union)に強い
class UnionFind:
    def __init__(self, n):
        self.par = [i for i in range(n+1)]
        self.rank = [0 for i in range(n+1)]
    
    # 検索
    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 union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        self.par[x] = y
    
    # 判定
    def judge(self,x,y):
        return self.find(x) == self.find(y)

if __name__ == "__main__":

    # unionfindを試す

    N, M = map(int,input().split())
    uf = UnionFind(N+1)
    for i in range(M):
        X,Y,Z = map(int,input().split())
        if not uf.judge(X,Y):
            uf.union(X,Y)
    print(len(set(uf.par[1:N+1])))

Submission status: Wrong Answer

Solution code:
n,m=map(int,input().split())
xyz=[list(map(int,input().split())) for _ in range(m)]
class UF:
    def __init__(self, n):
        self.par = [i for i in range(n+1)]
        self.rank = [0] * (n+1)
    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 union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1
    def same_check(self, x, y):
        return self.find(x) == self.find(y)
u=UF(n)
for i in range(m):
    xi = xyz[i][0]
    yi = xyz[i][1]
    u.union(xi,yi)
print(len(set(u.par))-1)