Go: package main

import (
    "fmt"
    "bufio"
    "strconv"
    "os"
    "strings"
    "math"
)

var rdr = bufio.NewReaderSize(os.Stdin, 1000000)

func readLine() string {
    buf := make([]byte, 0, 1000000)
    for {
        l, p, e := rdr.ReadLine()
        if e != nil {
            panic(e)
        }
        buf = append(buf, l...)
        if !p {
            break
        }
    }
    return string(buf)
}

func toInt(str string) int  {
    n, _ := strconv.Atoi(str)
    return n
}

func abs(a int) int {
    return int(math.Abs(float64(a)))
}

func getPar(x int, parent[1000]int) int {
    if parent[x] == x {
        return x
    } else {
        parent[x] = getPar(parent[x], parent)
        return parent[x]
    }
}

func main() {
    nm := strings.Split(readLine(), " ")
    n := toInt(nm[0])
    m := toInt(nm[1])
    var parent [1000]int
    for i := 0;i < n; i++ {
        parent[i] = i
    }


    for i := 0; i < m; i++ {
        ab := strings.Split(readLine(), " ")
        pa := getPar(toInt(ab[0]) - 1, parent)
        pb := getPar(toInt(ab[1]) - 1, parent)
        parent[pb] = pa
    }

    cities := make(map[int]int)
    villageCnt := 0
    for i := 0;i < n; i ++ {
        pi := getPar(i, parent)
        if i != pi {
            cities[pi] = 1
        } else {
            villageCnt ++
        }
    }
    cityCnt := len(cities)
    fmt.Println(abs(cityCnt * 2 - villageCnt))
}

Python: [m,n] = map(int,input().split())

def find(v,cs):
    for c in cities:
        if v in c:
            return (True,c)
    return (False,set([v]))

cities = []
for _ in range(n):
    [a,b] = map(int,input().split())

    (ra,fa) = find(a,cities)
    (rb,fb) = find(b,cities)

    mg = fa | fb

    if ra:
        cities.remove(fa)
    else:
        m = m - 1
    if rb:
        if fa != fb:
            cities.remove(fb)
    else:
        m = m - 1
    cities.append(mg)

print(abs(m-len(cities)))

Python: n, m = map(int, input().split())
q = []
for _ in range(m):
    a, b = map(int, input().split())
    i, j = -1, -1
    for k in range(len(q)):
        if i == -1:
            if a in q[k]:
                i = k
        if j == -1:
            if b in q[k]:
                j = k
        if i >= 0 and j >= 0:
            break
    if i >= 0:
        if j >= 0:
            if i != j:
                q[i] |= q[j]
                q.pop(j)
        else:
            q[i].add(b)
    elif j >= 0:
        q[j].add(a)
    else:
        q.append(set([a, b]))
print(abs(n - sum([len(i) for i in q]) - len(q)))

Python: # AOJ 1576: Community Integration
# Python3 2018.7.13 bal4u

# UNION-FIND library
class UnionSet:
	def __init__(self, nmax):
		self.size = [1]*nmax
		self.id = [i for i in range(nmax+1)]
	def root(self, i):
		while i != self.id[i]:
			self.id[i] = self.id[self.id[i]]
			i = self.id[i]
		return i
	def connected(self, p, q): return self.root(p) == self.root(q)
	def unite(self, p, q):
		i, j = self.root(p), self.root(q)
		if i == j: return
		if self.size[i] < self.size[j]:
			self.id[i] = j
			self.size[j] += self.size[i]
		else:
			self.id[j] = i
			self.size[i] += self.size[j]
# UNION-FIND library

N, M = map(int, input().split())
u = UnionSet(N+1)
f = [0]*(N+1)
for i in range(M):
	a, b = map(int, input().split())
	u.unite(a, b)
for i in range(1, N+1): f[u.root(i)] += 1
a = b = 0
for i in range(1, N+1):
	if f[i] == 1: a += 1
	elif f[i] > 1: b += 1
print(abs(a-b))

Python: #!/usr/bin/env python3
# -*- coding: utf-8 -*-

import array


class UnionFind(object):

    def __init__(self, number_of_nodes, typecode="L"):
        self.typecode = typecode
        self.par = array.array(typecode, range(number_of_nodes))
        self.rank = array.array(typecode, (0 for i in range(number_of_nodes)))

    def root(self, node):
        if self.par[node] == node:
            return node
        else:
            r = self.root(self.par[node])
            self.par[node] = r
            return r

    def in_the_same_set(self, node1, node2):
        return self.root(node1) == self.root(node2)

    def unite(self, node1, node2):
        x = self.root(node1)
        y = self.root(node2)
        if x == y:
            pass
        elif 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 main():
    n, m = map(int, input().split())
    uf = UnionFind(n, "I")
    for _ in range(m):
        a, b = map(lambda x: int(x) - 1, input().split())
        uf.unite(a, b)
    city_representatives = set()
    num_cities_and_villages = 0
    for i in range(n):
        rep = uf.root(i)
        if i == rep:
            num_cities_and_villages += 1
        else:
            city_representatives.add(rep)
    num_cities = len(city_representatives)
    answer = abs(num_cities_and_villages - 2 * num_cities)
    print(answer)


if __name__ == '__main__':
    main()

Python: n, m = map(int, input().split())
parent = [i for i in range(n)]

def get_par(x):
    if x == parent[x]:return x
    parent[x] = get_par(parent[x])
    return parent[x]

for _ in range(m):
    a, b = map(int, input().split())
    a -= 1
    b -= 1
    pa, pb = get_par(a), get_par(b)
    parent[pb] = pa

city_dic = set()
village_cnt = 0
for i in range(n):
    pi = get_par(i)
    if i == pi:village_cnt += 1
    else:city_dic.add(pi)

print(abs(2 * len(city_dic) - village_cnt))

Python: [m,n] = map(int,input().split())

def find(v,cs):
    for c in cities:
        if v in c:
            return (True,c)
    return (False,set([v]))

cities = []
for _ in range(n):
    [a,b] = map(int,input().split())

    (ra,fa) = find(a,cities)
    (rb,fb) = find(b,cities)

    mg = fa | fb

    print(fa)

    if ra:
        cities.remove(fa)
    else:
        m = m - 1
    if rb:
        if fa != fb:
            cities.remove(fb)
    else:
        m = m - 1
    cities.append(mg)

print(abs(m-len(cities)))

C++: #include<bits/stdc++.h>
using namespace std;
struct UnionFind{
  vector<int>parent,sizes;
  UnionFind(int n):parent(n),sizes(n,1){
    for(int i=0;i<n;++i)parent[i]=i;
  }
  int find(int x){
    if(x==parent[x])return x;
    return parent[x]=find(parent[x]);
  }
  void unite(int x,int y){
    x=find(x),y=find(y);
    if(x==y)return;
    if(sizes[x]>sizes[y])swap(x,y);
    parent[y]=x;
    sizes[x]+=sizes[y];
    sizes[y]=0;
  }
  bool same(int x,int y){
    return find(x)==find(y);
  }
  int size(int x){
    return sizes[find(x)];
  }
};
main(){
  int n,m,a,b,x=0,y=0;
  cin>>n>>m;
  UnionFind UF(n);
  for(int i=0;i++<m;UF.unite(--a,--b))cin>>a>>b;
  for(int i=0;i<n;++i)UF.sizes[i]>1?x++:UF.sizes[i]-1?:y++;
  cout<<abs(x-y)<<endl;
}

C++: #include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<map>
#include<set>
#include<utility>
#include<cmath>
#include<cstring>
#include<cstdio>
#define loop(i,a,b) for(int i=a;i<b;i++) 
#define rep(i,a) loop(i,0,a)
#define pb push_back
#define mp make_pair
#define all(in) in.begin(),in.end()
const double PI=acos(-1);
const double EPS=1e-10;
const int inf=1e8;
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef vector<vi> vvi;
int main(){
	int n,m;
	cin>>n>>m;
	vi in(n);
	rep(i,n)in[i]=i;
	while(m--){
		int a,b;
		cin>>a>>b;
		a--;b--;
		int d=in[b];
		in[b]=in[a];
		rep(i,n)if(d==in[i])in[i]=in[a];
	}
	vi q(n,0);
	rep(i,n)q[in[i]]++;
	int co1=0,co2=0;
	rep(i,n)if(q[i]==1)co1++;
	else if(q[i]>1)co2++;
	cout<<abs(co2-co1)<<endl;
}