并查集
import java.math.BigInteger;
import java.time.Year;
import java.util.Arrays;
import java.util.Scanner;
public class Main
{
public static int x[], y[], z[];
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
while (sc.hasNext())
{
int a = sc.nextInt();
long b = sc.nextLong();
x = new int[500000];
y = new int[500000];
z = new int[500000];
for (int i = 1; i <= a; i++)
{
x[i] = i;
y[i] = 1;
}
long ff = 0;
while (b-- > 0)
{
int ez = sc.nextInt();
if (ez == 1)
{
int gg = find(sc.nextInt());
if (z[gg] == 0)
{
ff += y[gg];
z[gg] = 1;
}
} else
{
int o = sc.nextInt();
int k = sc.nextInt();
int oo = find(o);
int kk = find(k);
if (oo != kk)
{
if (z[oo] == 0 && z[kk] == 1)
{
ff += y[oo];
} else if(z[oo]==1 && z[kk]==0)
{
ff += y[kk];
z[kk] = 1;
}
y[kk] += y[oo];
x[oo] = kk;
}
}
System.out.println(ff);
}
}
}
public static int find(int i)
{
if (i != x[i])
{
i = find(x[i]);
}
return x[i];
}
}