-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCobweb.java
129 lines (97 loc) · 2.81 KB
/
Cobweb.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class Cobweb
{
public static class Edge {
private int first;
private int second;
public Edge(int a, int b) {
first = a;
second = b;
}
public int getFirst() {
return first;
}
public int getSecond() {
return second;
}
}
public static class DSU
{
int parent[];
int size[];
int count;
public DSU(int elems) {
parent = new int[elems+1];
size = new int[elems+1];
count = 0;
}
public int findSet(int n) {
if (parent[n] != n) {
parent[n] = findSet(parent[n]);
}
return parent[n];
}
public int count() {
return count;
}
public void unionSet(int a, int b) {
a = findSet(a);
b = findSet(b);
if (a == b)
return;
if (size[a] > size[b]) {
int tmp = a;
a = b;
b = tmp;
}
parent[a] = b;
size[b] += size[a];
count--;
}
public void makeSet(int n) {
if (parent[n] == 0) {
parent[n] = n;
size[n] = 1;
count++;
}
}
}
public static void main(String[] argv) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int nodes = in.nextInt();
int edges = in.nextInt();
DSU dsu = new DSU(nodes);
for (int i = 1; i <= nodes; i++)
dsu.makeSet(i);
Map<Integer, Edge> edgesList = new HashMap<>();
for (int i = 1; i <= edges; i++) {
int a = in.nextInt();
int b = in.nextInt();
edgesList.put(i, new Edge(a,b));
}
int forRemove = in.nextInt();
List<Edge> removedList = new ArrayList<>();
while(forRemove-- > 0) {
int k = in.nextInt();
removedList.add( edgesList.get(k) );
edgesList.remove(k);
}
for(Edge e: edgesList.values()) {
dsu.unionSet(e.getFirst(), e.getSecond());
}
Stack<Integer> stack = new Stack<>();
stack.push(dsu.count());
for (int i = removedList.size()-1 ; i > 0; i--) {
Edge e = removedList.get(i);
dsu.unionSet(e.getFirst(), e.getSecond());
stack.push(dsu.count());
}
while(stack.size() > 0) {
System.out.print(stack.pop()+" ");
}
System.out.println("");
}
}