exec_outcome
stringclasses 1
value | code_uid
stringlengths 32
32
| file_name
stringclasses 111
values | prob_desc_created_at
stringlengths 10
10
| prob_desc_description
stringlengths 63
3.8k
| prob_desc_memory_limit
stringclasses 18
values | source_code
stringlengths 117
65.5k
| lang_cluster
stringclasses 1
value | prob_desc_sample_inputs
stringlengths 2
802
| prob_desc_time_limit
stringclasses 27
values | prob_desc_sample_outputs
stringlengths 2
796
| prob_desc_notes
stringlengths 4
3k
⌀ | lang
stringclasses 5
values | prob_desc_input_from
stringclasses 3
values | tags
sequencelengths 0
11
| src_uid
stringlengths 32
32
| prob_desc_input_spec
stringlengths 28
2.37k
⌀ | difficulty
int64 -1
3.5k
⌀ | prob_desc_output_spec
stringlengths 17
1.47k
⌀ | prob_desc_output_to
stringclasses 3
values | hidden_unit_tests
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED | 6f75c58e3591a86f99ee5ed8a8fae1c7 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import static java.lang.Double.parseDouble;
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.System.in;
import static java.lang.System.out;
public class SolutionD extends Thread {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return parseInt(next());
}
long nextLong() {
return parseLong(next());
}
double nextDouble() {
return parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
private static final FastReader scanner = new FastReader();
private static final PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
new Thread(null, new SolutionD(), "Main", 1 << 28).start();
}
public void run() {
solve();
out.close();
}
private static void solve() {
int n = scanner.nextInt();
int d = scanner.nextInt();
DSU dsu = new DSU(n);
int amountSlackers = 0;
for (int i = 0; i < d; i++) {
int xi = scanner.nextInt()-1;
int yi = scanner.nextInt()-1;
int ans = 0;
if (dsu.find(xi) == dsu.find(yi)) {
amountSlackers++;
} else {
dsu.union(xi, yi);
}
List<Integer> groupSizes = new ArrayList<>();
for (int j = 0; j < n; j++) {
if (dsu.find(j) == j) {
groupSizes.add(dsu.size[j]);
}
}
Collections.sort(groupSizes);
for (int j = groupSizes.size()-1; j >= Math.max(0, groupSizes.size() - 1 - amountSlackers); j--) {
ans += groupSizes.get(j);
}
System.out.println(ans - 1);
}
}
static class DSU {
int[] leaders;
int[] rank;
int[] max;
int[] min;
int[] size;
public DSU(int n) {
this.leaders = new int[n];
this.rank = new int[n];
this.max = new int[n];
this.min = new int[n];
this.size = new int[n];
for (int i = 0; i < n; i++) {
leaders[i] = i;
max[i] = i;
min[i] = i;
size[i] = 1;
rank[i] = 0;
}
}
public void union(int a, int b) {
int aLeader = find(a);
int bLeader = find(b);
if (aLeader == bLeader) {
return;
}
if (rank[aLeader] == rank[bLeader]) {
rank[aLeader]++;
}
if (rank[aLeader] > rank[bLeader]) {
max[aLeader] = max(max[aLeader], max[bLeader]);
min[aLeader] = min(min[aLeader], min[bLeader]);
size[aLeader] += size[bLeader];
leaders[bLeader] = aLeader;
} else {
max[bLeader] = max(max[aLeader], max[bLeader]);
min[bLeader] = min(min[aLeader], min[bLeader]);
size[bLeader] += size[aLeader];
leaders[aLeader] = bLeader;
}
}
public int find(int u) {
Stack<Integer> s = new Stack<>();
int leader = u;
while (leaders[leader] != leader) {
s.push(leader);
leader = leaders[leader];
}
while (!s.isEmpty()) {
leaders[s.pop()] = leader;
}
return leader;
}
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 11 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 2e1e9e07b45a2989a9433beca4cd4566 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.*;
import java.util.*;
public class q4 {
public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// public static long mod = 1000000007;
public static int[] rank,par;
public static int find(int a){
if(par[a] == a) return a;
par[a] = find(par[a]);
return par[a];
}
public static boolean union(int a,int b){
int la = find(a),lb = find(b);
if(la != lb){
if(rank[la] > rank[lb]){
par[lb] = la;
rank[la] += rank[lb];
}else if(rank[la] < rank[lb]){
par[la] = lb;
rank[lb] += rank[la];
}else{
par[la] = lb;
rank[lb] += rank[la];
}
return true;
}
return false;
}
public static void solve() throws Exception {
String[] parts = br.readLine().split(" ");
int n = Integer.parseInt(parts[0]);
int q = Integer.parseInt(parts[1]);
par = new int[n];
rank = new int[n];
for(int i = 0;i < n;i++){
par[i] = i;
rank[i] = 1;
}
int extra = 0;
for(int i = 0;i < q;i++){
parts = br.readLine().split(" ");
int u = Integer.parseInt(parts[0]) - 1;
int v = Integer.parseInt(parts[1]) - 1;
if(!union(u,v)){
extra++;
}
boolean[] vis = new boolean[n];
ArrayList<Integer> val = new ArrayList<>();
for(int j = 0;j < n;j++) {
int lj = find(j);
if (vis[lj]) continue;
val.add(rank[lj]);
vis[lj] = true;
}
Collections.sort(val);
long ans = 0;
for(int j = val.size() - 1;j >= 0 && j >= val.size() - extra - 1;j--){
ans += val.get(j);
}
System.out.println(ans - 1);
}
}
public static void main(String[] args) throws Exception {
// int tests = Integer.parseInt(br.readLine());
// for (int test = 1; test <= tests; test++) {
solve();
// }
}
// public static void sort(int[] arr){
// ArrayList<Integer> temp = new ArrayList<>();
// for(int val : arr) temp.add(val);
//
// Collections.sort(temp);
//
// for(int i = 0;i < arr.length;i++) arr[i] = temp.get(i);
// }
// public static void sort(long[] arr){
// ArrayList<Long> temp = new ArrayList<>();
// for(long val : arr) temp.add(val);
//
// Collections.sort(temp);
//
// for(int i = 0;i < arr.length;i++) arr[i] = temp.get(i);
// }
//
// public static long power(long a,long b,long mod){
// if(b == 0) return 1;
//
// long p = power(a,b / 2,mod);
// p = (p * p) % mod;
//
// if(b % 2 == 1) return (p * a) % mod;
// return p;
// }
//
// public static int GCD(int a,int b){
// return b == 0 ? a : GCD(b,a % b);
// }
// public static long GCD(long a,long b){
// return b == 0 ? a : GCD(b,a % b);
// }
//
// public static int LCM(int a,int b){
// return a * b / GCD(a,b);
// }
// public static long LCM(long a,long b){
// return a * b / GCD(a,b);
// }
}
| Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 11 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 58d8e3450580af7bca80e9bd78e7bc52 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.util.*;
import java.io.*;
public class Deltix {
public static void main(String[] args) {
MyScanner sc = new MyScanner();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int t = 1;
while (t-- > 0) {
int n = sc.nextInt();
int d = sc.nextInt();
int [][] e = new int[d][2];
for (int i = 0; i < d; i++) {
e[i][0] = sc.nextInt() - 1;
e[i][1] = sc.nextInt() - 1;
}
for (int add = 1; add <= d; add++) {
UF dsu = new UF(n);
int free = 0;
for (int i = 0; i < add; i++) {
int x = e[i][0]; int y = e[i][1];
if (dsu.connected(x, y)) ++free;
else dsu.union(x, y);
}
Set<Integer> parents = new HashSet<>();
for (int i = 0; i < n; i++) {
parents.add(dsu.find(i));
}
ArrayList<Integer> sizes = new ArrayList<>();
for (Integer p: parents) {
sizes.add(dsu.size[p]);
}
Collections.sort(sizes, Comparator.reverseOrder());
int total = 0;
for (int i = 0; i <= free; i++) total += sizes.get(i);
out.println(total - 1);
}
}
out.close();
}
static class UF {
private int[] parent; // parent[i] = parent of i
private byte[] rank; // rank[i] = rank of subtree rooted at i (never more than 31)
private int count; // number of components
private int[] size;
public UF(int n) {
if (n < 0) throw new IllegalArgumentException();
count = n;
parent = new int[n];
rank = new byte[n];
size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 0;
size[i] = 1;
}
}
public int find(int p) {
while (p != parent[p]) {
parent[p] = parent[parent[p]]; // path compression by halving
p = parent[p];
}
return p;
}
public int count() {
return count;
}
public boolean connected(int p, int q) {
return find(p) == find(q);
}
public void union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) return;
// make root of smaller rank point to root of larger rank
if (rank[rootP] < rank[rootQ]) {
parent[rootP] = rootQ;
size[rootQ] = size[rootQ] + size[rootP];
}
else if (rank[rootP] > rank[rootQ]) {
parent[rootQ] = rootP;
size[rootP] = size[rootP] + size[rootQ];
}
else {
parent[rootQ] = rootP;
size[rootP] = size[rootP] + size[rootQ];
rank[rootP]++;
}
count--;
}
}
static void sort(int[] a) {
ArrayList<Integer> q = new ArrayList<>();
for (int i : a) q.add(i);
Collections.sort(q);
for (int i = 0; i < a.length; i++) a[i] = q.get(i);
}
static void sort(long[] a) {
ArrayList<Long> q = new ArrayList<>();
for (long i : a) q.add(i);
Collections.sort(q);
for (int i = 0; i < a.length; i++) a[i] = q.get(i);
}
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 11 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 1b61a493ab736b172cefb020acdf1f58 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args){
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solve(in, out);
out.close();
}
static String reverse(String s) {
return (new StringBuilder(s)).reverse().toString();
}
static void sieveOfEratosthenes(int n, int factors[], ArrayList<Integer> ar)
{
factors[1]=1;
int p;
for(p = 2; p*p <=n; p++)
{
if(factors[p] == 0)
{
ar.add(p);
factors[p]=p;
for(int i = p*p; i <= n; i += p)
if(factors[i]==0)
factors[i] = p;
}
}
for(;p<=n;p++){
if(factors[p] == 0)
{
factors[p] = p;
ar.add(p);
}
}
}
static void sort(int ar[]) {
int n = ar.length;
ArrayList<Integer> a = new ArrayList<>();
for (int i = 0; i < n; i++)
a.add(ar[i]);
Collections.sort(a);
for (int i = 0; i < n; i++)
ar[i] = a.get(i);
}
static void sort1(long ar[]) {
int n = ar.length;
ArrayList<Long> a = new ArrayList<>();
for (int i = 0; i < n; i++)
a.add(ar[i]);
Collections.sort(a);
for (int i = 0; i < n; i++)
ar[i] = a.get(i);
}
static void sort2(char ar[]) {
int n = ar.length;
ArrayList<Character> a = new ArrayList<>();
for (int i = 0; i < n; i++)
a.add(ar[i]);
Collections.sort(a);
for (int i = 0; i < n; i++)
ar[i] = a.get(i);
}
static long ncr(long n, long r, long mod) {
if (r == 0)
return 1;
long val = ncr(n - 1, r - 1, mod);
val = (n * val) % mod;
val = (val * modInverse(r, mod)) % mod;
return val;
}
static long max[];
static long lz[];
// static void build(long a[], int v, int tl, int tr) {
// if (tl == tr) {
// max[v] = a[tl];
// } else {
// int tm = (tl + tr) / 2;
// build(a, v*2, tl, tm);
// build(a, v*2+1, tm+1, tr);
// max[v] = max[v*2] + max[v*2+1];
// }
// }
// static void push(int v, int tl, int tr){
// if(tl==tr){
// lz[v] = 0;
// return;
// }
// max[2*v] += lz[v];
// // max[2*v] %= m;
// max[2*v+1] += lz[v];
// // max[2*v+1] %= m;
// lz[2*v] += lz[v];
// lz[2*v] %= m;
// lz[2*v+1] += lz[v];
// lz[2*v+1] %= m;
// lz[v] = 0;
// }
static void update(int v, int tl, int tr, int l, int r, long val) {
if(tl>r||tr<l)
return;
if(tl>=l&&tr<=r){
max[v] = Math.max(val, max[v]);
return;
}
int tm = ((tl + tr) >> 1);
update(v*2, tl, tm, l, r, val);
update(v*2+1, tm+1, tr, l, r, val);
max[v] = Math.max(max[2*v],max[2*v+1]);
}
static long get(int v, int tl, int tr, int l, int r) {
if(l>tr||r<tl)
return 0;
if (tl >= l && tr <= r) {
return max[v];
}
int tm = ((tl + tr) >> 1);
return Math.max(get(2*v, tl, tm, l, r), get(2*v+1, tm+1, tr, l, r));
}
// static int y = 0;
static int parent[];
static int rank[];
static long m = 0;
static int find_set(int v) {
if (v == parent[v])
return v;
return find_set(parent[v]);
}
static void make_set(int v) {
parent[v] = v;
rank[v] = 1;
}
static void union_sets(int a, int b) {
a = find_set(a);
b = find_set(b);
if (a != b) {
if (rank[a] < rank[b]){
int tmp = a;
a = b;
b = tmp;
}
parent[b] = a;
// if (rank[a] == rank[b])
// rank[a]++;
rank[a] += rank[b];
max1 = Math.max(max1,rank[a]);
// System.out.println(a+" "+b+" "+rank[a]+" "+rank[b]);
}
}
static int parent1[];
static int rank1[];
static int find_set1(int v) {
if (v == parent1[v])
return v;
return find_set1(parent1[v]);
}
static void make_set1(int v) {
parent1[v] = v;
rank1[v] = 1;
}
static void union_sets1(int a, int b) {
a = find_set1(a);
b = find_set1(b);
if (a != b) {
if (rank1[a] < rank1[b]){
int tmp = a;
a = b;
b = tmp;
}
parent1[b] = a;
// if (rank1[a] == rank1[b])
// rank1[a]++;
rank1[a] += rank1[b];
}
}
static long max1 = 0;
static int count = 0;
static int count1 = 0;
public static void solve(InputReader sc, PrintWriter pw){
int i, j = 0;
int t = 1;
long mod = 1000000007;
// int factors[] = new int[1000001];
// ArrayList<Integer> ar = new ArrayList<>();
// sieveOfEratosthenes(1000000, factors, ar);
// HashSet<Integer> set = new HashSet<>();
// for(int x:ar){
// set.add(x);
// }
// int t = sc.nextInt();
u: while (t-- > 0) {
int n = sc.nextInt();
int d = sc.nextInt();
parent = new int[n];
rank = new int[n];
ArrayList<Integer> p = new ArrayList<>();
for(i=0;i<n;i++){
parent[i] = i;
rank[i] = 1;
p.add(1);
}
max1 = 0;
int c = 1;
for(i=0;i<d;i++){
int x = sc.nextInt()-1;
int y = sc.nextInt()-1;
int px = find_set(x);
int py = find_set(y);
if(px!=py){
int y1 = rank[px];
int y2 = rank[py];
union_sets(x, y);
for(j=0;j<p.size();j++){
if(p.get(j)==y1){
p.remove(j);
break;
}
}
for(j=0;j<p.size();j++){
if(p.get(j)==y2){
p.remove(j);
break;
}
}
// p.remove(y1);
// p.remove(y2);
p.add(y1+y2);
Collections.sort(p);
}
else{
c++;
}
// for(j=0;j<p.size();j++){
// pw.print(p.get(j)+" ");
// }
// pw.println();
long val = 0;
for(j=p.size()-1;j>=0&&j>=p.size()-c;j--){
val += p.get(j);
}
pw.println(val-1);
}
}
}
static void KMPSearch(char pat[], char txt[], int pres[]){
int M = pat.length;
int N = txt.length;
int lps[] = new int[M];
int j = 0;
computeLPSArray(pat, M, lps);
int i = 0;
while (i < N) {
if (pat[j] == txt[i]) {
j++;
i++;
}
if (j == M) {
pres[i-1] = 1;
j = lps[j - 1];
}
else if (i < N && pat[j] != txt[i]) {
if (j != 0)
j = lps[j - 1];
else
i = i + 1;
}
}
}
static void computeLPSArray(char pat[], int M, int lps[])
{
int len = 0;
int i = 1;
lps[0] = 0;
while (i < M) {
if (pat[i] == pat[len]) {
len++;
lps[i] = len;
i++;
}
else
{
if (len != 0) {
len = lps[len - 1];
}
else
{
lps[i] = len;
i++;
}
}
}
}
static long[][] matrixMult(long a[][], long b[][], long mod){
int n = a.length;
int m = a[0].length;
int p = b[0].length;
long c[][] = new long[n][p];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
for(int k=0;k<p;k++){
c[i][k] += a[i][j]*b[j][k];
c[i][k] %= mod;
}
}
}
return c;
}
static long[][] exp(long mat[][], long b, long mod){
if(b==0){
int n = mat.length;
long res[][] = new long[n][n];
for(int i=0;i<n;i++){
res[i][i] = 1;
}
return res;
}
long half[][] = exp(mat, b/2, mod);
long res[][] = matrixMult(half, half, mod);
if(b%2==1){
res = matrixMult(res, mat, mod);
}
return res;
}
static void countPrimeFactors(int num, int a[], HashMap<Integer,Integer> pos){
for(int i=2;i*i<num;i++){
if(num%i==0){
int y = pos.get(i);
while(num%i==0){
a[y]++;
num/=i;
}
}
}
if(num>1){
int y = pos.get(num);
a[y]++;
}
}
static void assignAnc(ArrayList<Integer> ar[], int depth[], int sz[], int par[][] ,int curr, int parent, int d){
depth[curr] = d;
sz[curr] = 1;
par[curr][0] = parent;
for(int v:ar[curr]){
if(parent==v)
continue;
assignAnc(ar, depth, sz, par, v, curr, d+1);
sz[curr] += sz[v];
}
}
static int findLCA(int a, int b, int par[][], int depth[]){
if(depth[a]>depth[b]){
a = a^b;
b = a^b;
a = a^b;
}
int diff = depth[b] - depth[a];
for(int i=19;i>=0;i--){
if((diff&(1<<i))>0){
b = par[b][i];
}
}
if(a==b)
return a;
for(int i=19;i>=0;i--){
if(par[b][i]!=par[a][i]){
b = par[b][i];
a = par[a][i];
}
}
return par[a][0];
}
static void formArrayForBinaryLifting(int n, int par[][]){
for(int j=1;j<20;j++){
for(int i=0;i<n;i++){
if(par[i][j-1]==-1)
continue;
par[i][j] = par[par[i][j-1]][j-1];
}
}
}
static long lcm(int a, int b){
return a*b/gcd(a,b);
}
static class Pair1 {
long a;
long b;
Pair1(long a, long b) {
this.a = a;
this.b = b;
}
}
static class Pair implements Comparable<Pair> {
int a;
int b;
// int c;
Pair(int a, int b) {
this.a = a;
this.b = b;
// this.c = c;
}
public int compareTo(Pair p) {
if(a!=p.a)
return p.a-a;
return b-p.b;
}
}
static class Pair2 implements Comparable<Pair2> {
int a;
int b;
int c;
Pair2(int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
public int compareTo(Pair2 p) {
return a-p.a;
}
}
static boolean isPrime(int n) {
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static long fast_pow(long base, long n, long M) {
if (n == 0)
return 1;
if (n == 1)
return base % M;
long halfn = fast_pow(base, n / 2, M);
if (n % 2 == 0)
return (halfn * halfn) % M;
else
return (((halfn * halfn) % M) * base) % M;
}
static long modInverse(long n, long M) {
return fast_pow(n, M - 2, M);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 9992768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 11 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 87b135a3364d318b04e312a86e67b338 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Khater
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
DSocialNetwork solver = new DSocialNetwork();
solver.solve(1, in, out);
out.close();
}
static class DSocialNetwork {
public void solve(int testNumber, Scanner sc, PrintWriter pw) {
int t = 1;
// t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int d = sc.nextInt();
UnionFind dsu = new UnionFind(n);
int c = 0;
while (d-- > 0) {
int x = sc.nextInt() - 1;
int y = sc.nextInt() - 1;
if (dsu.isSameSet(x, y)) c++;
dsu.unionSet(x, y);
int ans = 0;
HashSet<Integer> hs = new HashSet<>();
ArrayList<Integer> arrl = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (!hs.contains(dsu.findSet(i))) {
hs.add(dsu.findSet(i));
arrl.add(dsu.sizeOfSet(i));
}
}
Collections.sort(arrl);
for (int i = arrl.size() - 1; i >= 0 && i >= arrl.size() - 1 - c; i--) ans += arrl.get(i);
pw.println(ans - 1);
}
}
}
public class UnionFind {
int[] p;
int[] rank;
int[] setSize;
int numSets;
public UnionFind(int N) {
p = new int[numSets = N];
rank = new int[N];
setSize = new int[N];
for (int i = 0; i < N; i++) {
p[i] = i;
setSize[i] = 1;
}
}
public int findSet(int i) {
return p[i] == i ? i : (p[i] = findSet(p[i]));
}
public boolean isSameSet(int i, int j) {
return findSet(i) == findSet(j);
}
public void unionSet(int i, int j) {
if (isSameSet(i, j))
return;
numSets--;
int x = findSet(i), y = findSet(j);
if (rank[x] > rank[y]) {
p[y] = x;
setSize[x] += setSize[y];
} else {
p[x] = y;
setSize[y] += setSize[x];
if (rank[x] == rank[y]) rank[y]++;
}
}
public int sizeOfSet(int i) {
return setSize[findSet(i)];
}
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 11 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 12f64070bf84d4aa562af52792426514 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.*;
import java.util.*;
public class CF1609D extends PrintWriter {
CF1609D() { super(System.out); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1609D o = new CF1609D(); o.main(); o.flush();
}
int[] ds;
int find(int i) {
return ds[i] < 0 ? i : (ds[i] = find(ds[i]));
}
boolean join(int i, int j) {
i = find(i);
j = find(j);
if (i == j)
return false;
if (ds[i] > ds[j]) {
int tmp = i; i = j; j = tmp;
}
ds[i] += ds[j];
ds[j] = i;
return true;
}
void main() {
int n = sc.nextInt();
int d = sc.nextInt();
int[] xx = new int[d];
int[] yy = new int[d];
for (int h = 0; h < d; h++) {
xx[h] = sc.nextInt() - 1;
yy[h] = sc.nextInt() - 1;
}
ds = new int[n];
int[] kk = new int[n];
for (int d_ = 1; d_ <= d; d_++) {
int k = 0;
Arrays.fill(ds, -1);
for (int h = 0; h < d_; h++)
if (!join(xx[h], yy[h]))
k++;
int[] qu = new int[n]; int cnt = 0;
for (int i = 0; i < n; i++)
if (ds[i] < 0)
qu[cnt++] = -ds[i];
Arrays.sort(qu, 0, cnt);
int s = 0;
while (k >= 0) {
s += qu[--cnt];
k--;
}
println(s - 1);
}
}
}
| Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 11 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | a046111c3e1e66544f7cbe9040ea45ca | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.util.*;
public class D {
public static final int MOD998 = 998244353;
public static final int MOD100 = 1000000007;
public static void main(String[] args) throws Exception {
ContestScanner sc = new ContestScanner();
ContestPrinter cp = new ContestPrinter();
int N = sc.nextInt();
int d = sc.nextInt();
DSU dsu = new DSU(N);
int groups = N;
for (int n = 0; n < d; n++) {
int x = sc.nextInt() - 1;
int y = sc.nextInt() - 1;
if (!dsu.same(x, y)) {
dsu.merge(x, y);
groups--;
}
ArrayList<ArrayList<Integer>> g = dsu.groups();
g.sort(Comparator.comparingInt(a -> -a.size()));
// n+1connection N-n-1
int ans = 0;
// System.out.println(groups - (N - n - 1));
for (int m = 0; m < groups - (N - n - 1) + 1; m++) {
ans += g.get(m).size();
}
cp.println(ans - 1);
}
cp.close();
}
//////////////////
// My Library //
//////////////////
public static int zeroOneBFS(int[][][] weighted_graph, int start, int goal) {
int[] dist = new int[weighted_graph.length];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[start] = 0;
LinkedList<Integer> queue = new LinkedList<>();
queue.add(start);
while (!queue.isEmpty()) {
int now = queue.poll();
if (now == goal) {
return dist[goal];
}
for (int[] info : weighted_graph[now]) {
if (dist[info[0]] > dist[now] + info[1]) {
dist[info[0]] = dist[now] + info[1];
if (info[1] == 0) {
queue.addFirst(info[0]);
} else {
queue.addLast(info[0]);
}
}
}
}
return -1;
}
public static int[] zeroOneBFSAll(int[][][] weighted_graph, int start) {
int[] dist = new int[weighted_graph.length];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[start] = 0;
LinkedList<Integer> queue = new LinkedList<>();
queue.add(start);
while (!queue.isEmpty()) {
int now = queue.poll();
for (int[] info : weighted_graph[now]) {
if (dist[info[0]] > dist[now] + info[1]) {
dist[info[0]] = dist[now] + info[1];
if (info[1] == 0) {
queue.addFirst(info[0]);
} else {
queue.addLast(info[0]);
}
}
}
}
return dist;
}
public static long dijkstra(int[][][] weighted_graph, int start, int goal) {
long[] dist = new long[weighted_graph.length];
Arrays.fill(dist, 0, dist.length, Long.MAX_VALUE);
dist[start] = 0;
PriorityQueue<Pair<Integer, Long>> unsettled = new PriorityQueue<>((u, v) -> (int) (u.cdr - v.cdr));
unsettled.offer(new Pair<Integer, Long>(start, 0L));
while (!unsettled.isEmpty()) {
Pair<Integer, Long> pair = unsettled.poll();
int now = pair.car;
if (now == goal) {
return dist[goal];
}
if (dist[now] < pair.cdr) {
continue;
}
for (int[] info : weighted_graph[now]) {
if (dist[info[0]] > dist[now] + info[1]) {
dist[info[0]] = dist[now] + info[1];
unsettled.offer(new Pair<Integer, Long>(info[0], dist[info[0]]));
}
}
}
return -1;
}
public static long[] dijkstraAll(int[][][] weighted_graph, int start) {
long[] dist = new long[weighted_graph.length];
Arrays.fill(dist, 0, dist.length, Long.MAX_VALUE);
dist[start] = 0;
PriorityQueue<Pair<Integer, Long>> unsettled = new PriorityQueue<>((u, v) -> (int) (u.cdr - v.cdr));
unsettled.offer(new Pair<Integer, Long>(start, 0L));
while (!unsettled.isEmpty()) {
Pair<Integer, Long> pair = unsettled.poll();
int now = pair.car;
if (dist[now] < pair.cdr) {
continue;
}
for (int[] info : weighted_graph[now]) {
if (dist[info[0]] > dist[now] + info[1]) {
dist[info[0]] = dist[now] + info[1];
unsettled.offer(new Pair<Integer, Long>(info[0], dist[info[0]]));
}
}
}
return dist;
}
public static class Pair<A, B> {
public final A car;
public final B cdr;
public Pair(A car_, B cdr_) {
car = car_;
cdr = cdr_;
}
private static boolean eq(Object o1, Object o2) {
return o1 == null ? o2 == null : o1.equals(o2);
}
private static int hc(Object o) {
return o == null ? 0 : o.hashCode();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Pair))
return false;
Pair<?, ?> rhs = (Pair<?, ?>) o;
return eq(car, rhs.car) && eq(cdr, rhs.cdr);
}
@Override
public int hashCode() {
return hc(car) ^ hc(cdr);
}
}
public static class Tuple1<A> extends Pair<A, Object> {
public Tuple1(A a) {
super(a, null);
}
}
public static class Tuple2<A, B> extends Pair<A, Tuple1<B>> {
public Tuple2(A a, B b) {
super(a, new Tuple1<>(b));
}
}
public static class Tuple3<A, B, C> extends Pair<A, Tuple2<B, C>> {
public Tuple3(A a, B b, C c) {
super(a, new Tuple2<>(b, c));
}
}
public static class Tuple4<A, B, C, D> extends Pair<A, Tuple3<B, C, D>> {
public Tuple4(A a, B b, C c, D d) {
super(a, new Tuple3<>(b, c, d));
}
}
public static class Tuple5<A, B, C, D, E> extends Pair<A, Tuple4<B, C, D, E>> {
public Tuple5(A a, B b, C c, D d, E e) {
super(a, new Tuple4<>(b, c, d, e));
}
}
public static class PriorityQueueLogTime<T> {
private PriorityQueue<T> queue;
private Multiset<T> total;
private int size = 0;
public PriorityQueueLogTime() {
queue = new PriorityQueue<>();
total = new Multiset<>();
}
public PriorityQueueLogTime(Comparator<T> c) {
queue = new PriorityQueue<>(c);
total = new Multiset<>();
}
public void clear() {
queue.clear();
total.clear();
size = 0;
}
public boolean contains(T e) {
return total.count(e) > 0;
}
public boolean isEmpty() {
return size == 0;
}
public boolean offer(T e) {
total.addOne(e);
size++;
return queue.offer(e);
}
public T peek() {
if (total.isEmpty()) {
return null;
}
simplify();
return queue.peek();
}
public T poll() {
if (total.isEmpty()) {
return null;
}
simplify();
size--;
T res = queue.poll();
total.removeOne(res);
return res;
}
public void remove(T e) {
total.removeOne(e);
size--;
}
public int size() {
return size;
}
private void simplify() {
while (total.count(queue.peek()) == 0) {
queue.poll();
}
}
}
static int[][] scanGraphOneIndexed(ContestScanner sc, int node, int edge, boolean undirected) {
int[][] arr = sc.nextIntArrayMulti(edge, 2);
for (int n = 0; n < edge; n++) {
arr[0][n]--;
arr[1][n]--;
}
return GraphBuilder.makeGraph(node, edge, arr[0], arr[1], undirected);
}
static int[][][] scanWeightedGraphOneIndexed(ContestScanner sc, int node, int edge, boolean undirected) {
int[][] arr = sc.nextIntArrayMulti(edge, 3);
for (int n = 0; n < edge; n++) {
arr[0][n]--;
arr[1][n]--;
}
return GraphBuilder.makeGraphWithWeight(node, edge, arr[0], arr[1], arr[2], undirected);
}
static class EdgeData {
private int capacity;
private int[] from, to, weight;
private int p = 0;
private boolean weighted;
public EdgeData(boolean weighted) {
this(weighted, 500000);
}
public EdgeData(boolean weighted, int initial_capacity) {
capacity = initial_capacity;
from = new int[capacity];
to = new int[capacity];
weight = new int[capacity];
this.weighted = weighted;
}
public void addEdge(int u, int v) {
if (weighted) {
System.err.println("The graph is weighted!");
return;
}
if (p == capacity) {
int[] newfrom = new int[capacity * 2];
int[] newto = new int[capacity * 2];
System.arraycopy(from, 0, newfrom, 0, capacity);
System.arraycopy(to, 0, newto, 0, capacity);
capacity *= 2;
}
from[p] = u;
to[p] = v;
p++;
}
public void addEdge(int u, int v, int w) {
if (!weighted) {
System.err.println("The graph is NOT weighted!");
return;
}
if (p == capacity) {
int[] newfrom = new int[capacity * 2];
int[] newto = new int[capacity * 2];
int[] newweight = new int[capacity * 2];
System.arraycopy(from, 0, newfrom, 0, capacity);
System.arraycopy(to, 0, newto, 0, capacity);
System.arraycopy(weight, 0, newweight, 0, capacity);
capacity *= 2;
}
from[p] = u;
to[p] = v;
weight[p] = w;
p++;
}
public int[] getFrom() {
int[] result = new int[p];
System.arraycopy(from, 0, result, 0, p);
return result;
}
public int[] getTo() {
int[] result = new int[p];
System.arraycopy(to, 0, result, 0, p);
return result;
}
public int[] getWeight() {
int[] result = new int[p];
System.arraycopy(weight, 0, result, 0, p);
return result;
}
public int size() {
return p;
}
}
////////////////////////////////
// Atcoder Library for Java //
////////////////////////////////
static class MathLib {
private static long safe_mod(long x, long m) {
x %= m;
if (x < 0)
x += m;
return x;
}
private static long[] inv_gcd(long a, long b) {
a = safe_mod(a, b);
if (a == 0)
return new long[] { b, 0 };
long s = b, t = a;
long m0 = 0, m1 = 1;
while (t > 0) {
long u = s / t;
s -= t * u;
m0 -= m1 * u;
long tmp = s;
s = t;
t = tmp;
tmp = m0;
m0 = m1;
m1 = tmp;
}
if (m0 < 0)
m0 += b / s;
return new long[] { s, m0 };
}
public static long gcd(long a, long b) {
a = java.lang.Math.abs(a);
b = java.lang.Math.abs(b);
return inv_gcd(a, b)[0];
}
public static long lcm(long a, long b) {
a = java.lang.Math.abs(a);
b = java.lang.Math.abs(b);
return a / gcd(a, b) * b;
}
public static long pow_mod(long x, long n, int m) {
assert n >= 0;
assert m >= 1;
if (m == 1)
return 0L;
x = safe_mod(x, m);
long ans = 1L;
while (n > 0) {
if ((n & 1) == 1)
ans = (ans * x) % m;
x = (x * x) % m;
n >>>= 1;
}
return ans;
}
public static long[] crt(long[] r, long[] m) {
assert (r.length == m.length);
int n = r.length;
long r0 = 0, m0 = 1;
for (int i = 0; i < n; i++) {
assert (1 <= m[i]);
long r1 = safe_mod(r[i], m[i]), m1 = m[i];
if (m0 < m1) {
long tmp = r0;
r0 = r1;
r1 = tmp;
tmp = m0;
m0 = m1;
m1 = tmp;
}
if (m0 % m1 == 0) {
if (r0 % m1 != r1)
return new long[] { 0, 0 };
continue;
}
long[] ig = inv_gcd(m0, m1);
long g = ig[0], im = ig[1];
long u1 = m1 / g;
if ((r1 - r0) % g != 0)
return new long[] { 0, 0 };
long x = (r1 - r0) / g % u1 * im % u1;
r0 += x * m0;
m0 *= u1;
if (r0 < 0)
r0 += m0;
// System.err.printf("%d %d\n", r0, m0);
}
return new long[] { r0, m0 };
}
public static long floor_sum(long n, long m, long a, long b) {
long ans = 0;
if (a >= m) {
ans += (n - 1) * n * (a / m) / 2;
a %= m;
}
if (b >= m) {
ans += n * (b / m);
b %= m;
}
long y_max = (a * n + b) / m;
long x_max = y_max * m - b;
if (y_max == 0)
return ans;
ans += (n - (x_max + a - 1) / a) * y_max;
ans += floor_sum(y_max, a, m, (a - x_max % a) % a);
return ans;
}
public static java.util.ArrayList<Long> divisors(long n) {
java.util.ArrayList<Long> divisors = new ArrayList<>();
java.util.ArrayList<Long> large = new ArrayList<>();
for (long i = 1; i * i <= n; i++)
if (n % i == 0) {
divisors.add(i);
if (i * i < n)
large.add(n / i);
}
for (int p = large.size() - 1; p >= 0; p--) {
divisors.add(large.get(p));
}
return divisors;
}
}
static class Multiset<T> extends java.util.TreeMap<T, Long> {
public Multiset() {
super();
}
public Multiset(java.util.List<T> list) {
super();
for (T e : list)
this.addOne(e);
}
public long count(Object elm) {
return getOrDefault(elm, 0L);
}
public void add(T elm, long amount) {
if (!this.containsKey(elm))
put(elm, amount);
else
replace(elm, get(elm) + amount);
if (this.count(elm) == 0)
this.remove(elm);
}
public void addOne(T elm) {
this.add(elm, 1);
}
public void removeOne(T elm) {
this.add(elm, -1);
}
public void removeAll(T elm) {
this.add(elm, -this.count(elm));
}
public static <T> Multiset<T> merge(Multiset<T> a, Multiset<T> b) {
Multiset<T> c = new Multiset<>();
for (T x : a.keySet())
c.add(x, a.count(x));
for (T y : b.keySet())
c.add(y, b.count(y));
return c;
}
}
static class GraphBuilder {
public static int[][] makeGraph(int NumberOfNodes, int NumberOfEdges, int[] from, int[] to,
boolean undirected) {
int[][] graph = new int[NumberOfNodes][];
int[] outdegree = new int[NumberOfNodes];
for (int i = 0; i < NumberOfEdges; i++) {
outdegree[from[i]]++;
if (undirected)
outdegree[to[i]]++;
}
for (int i = 0; i < NumberOfNodes; i++)
graph[i] = new int[outdegree[i]];
for (int i = 0; i < NumberOfEdges; i++) {
graph[from[i]][--outdegree[from[i]]] = to[i];
if (undirected)
graph[to[i]][--outdegree[to[i]]] = from[i];
}
return graph;
}
public static int[][][] makeGraphWithWeight(int NumberOfNodes, int NumberOfEdges, int[] from, int[] to,
int[] weight, boolean undirected) {
int[][][] graph = new int[NumberOfNodes][][];
int[] outdegree = new int[NumberOfNodes];
for (int i = 0; i < NumberOfEdges; i++) {
outdegree[from[i]]++;
if (undirected)
outdegree[to[i]]++;
}
for (int i = 0; i < NumberOfNodes; i++)
graph[i] = new int[outdegree[i]][];
for (int i = 0; i < NumberOfEdges; i++) {
graph[from[i]][--outdegree[from[i]]] = new int[] { to[i], weight[i] };
if (undirected)
graph[to[i]][--outdegree[to[i]]] = new int[] { from[i], weight[i] };
}
return graph;
}
public static int[][][] makeGraphWithEdgeInfo(int NumberOfNodes, int NumberOfEdges, int[] from, int[] to,
boolean undirected) {
int[][][] graph = new int[NumberOfNodes][][];
int[] outdegree = new int[NumberOfNodes];
for (int i = 0; i < NumberOfEdges; i++) {
outdegree[from[i]]++;
if (undirected)
outdegree[to[i]]++;
}
for (int i = 0; i < NumberOfNodes; i++)
graph[i] = new int[outdegree[i]][];
for (int i = 0; i < NumberOfEdges; i++) {
graph[from[i]][--outdegree[from[i]]] = new int[] { to[i], i, 0 };
if (undirected)
graph[to[i]][--outdegree[to[i]]] = new int[] { from[i], i, 1 };
}
return graph;
}
public static int[][][] makeGraphWithWeightAndEdgeInfo(int NumberOfNodes, int NumberOfEdges, int[] from,
int[] to, int[] weight, boolean undirected) {
int[][][] graph = new int[NumberOfNodes][][];
int[] outdegree = new int[NumberOfNodes];
for (int i = 0; i < NumberOfEdges; i++) {
outdegree[from[i]]++;
if (undirected)
outdegree[to[i]]++;
}
for (int i = 0; i < NumberOfNodes; i++)
graph[i] = new int[outdegree[i]][];
for (int i = 0; i < NumberOfEdges; i++) {
graph[from[i]][--outdegree[from[i]]] = new int[] { to[i], weight[i], i, 0 };
if (undirected)
graph[to[i]][--outdegree[to[i]]] = new int[] { from[i], weight[i], i, 1 };
}
return graph;
}
}
static class DSU {
private int n;
private int[] parentOrSize;
public DSU(int n) {
this.n = n;
this.parentOrSize = new int[n];
java.util.Arrays.fill(parentOrSize, -1);
}
int merge(int a, int b) {
if (!(0 <= a && a < n))
throw new IndexOutOfBoundsException("a=" + a);
if (!(0 <= b && b < n))
throw new IndexOutOfBoundsException("b=" + b);
int x = leader(a);
int y = leader(b);
if (x == y)
return x;
if (-parentOrSize[x] < -parentOrSize[y]) {
int tmp = x;
x = y;
y = tmp;
}
parentOrSize[x] += parentOrSize[y];
parentOrSize[y] = x;
return x;
}
boolean same(int a, int b) {
if (!(0 <= a && a < n))
throw new IndexOutOfBoundsException("a=" + a);
if (!(0 <= b && b < n))
throw new IndexOutOfBoundsException("b=" + b);
return leader(a) == leader(b);
}
int leader(int a) {
if (parentOrSize[a] < 0) {
return a;
} else {
parentOrSize[a] = leader(parentOrSize[a]);
return parentOrSize[a];
}
}
int size(int a) {
if (!(0 <= a && a < n))
throw new IndexOutOfBoundsException("" + a);
return -parentOrSize[leader(a)];
}
java.util.ArrayList<java.util.ArrayList<Integer>> groups() {
int[] leaderBuf = new int[n];
int[] groupSize = new int[n];
for (int i = 0; i < n; i++) {
leaderBuf[i] = leader(i);
groupSize[leaderBuf[i]]++;
}
java.util.ArrayList<java.util.ArrayList<Integer>> result = new java.util.ArrayList<>(n);
for (int i = 0; i < n; i++) {
result.add(new java.util.ArrayList<>(groupSize[i]));
}
for (int i = 0; i < n; i++) {
result.get(leaderBuf[i]).add(i);
}
result.removeIf(java.util.ArrayList::isEmpty);
return result;
}
}
static class ModIntFactory {
private final ModArithmetic ma;
private final int mod;
private final boolean usesMontgomery;
private final ModArithmetic.ModArithmeticMontgomery maMontgomery;
private ArrayList<Integer> factorial;
private ArrayList<Integer> factorial_inversion;
public ModIntFactory(int mod) {
this.ma = ModArithmetic.of(mod);
this.usesMontgomery = ma instanceof ModArithmetic.ModArithmeticMontgomery;
this.maMontgomery = usesMontgomery ? (ModArithmetic.ModArithmeticMontgomery) ma : null;
this.mod = mod;
this.factorial = new ArrayList<>();
this.factorial_inversion = new ArrayList<>();
}
public ModInt create(long value) {
if ((value %= mod) < 0)
value += mod;
if (usesMontgomery) {
return new ModInt(maMontgomery.generate(value));
} else {
return new ModInt((int) value);
}
}
private void prepareFactorial(int max) {
factorial.ensureCapacity(max + 1);
if (factorial.size() == 0)
factorial.add(1);
for (int i = factorial.size(); i <= max; i++) {
factorial.add(ma.mul(factorial.get(i - 1), i));
}
}
public ModInt factorial(int i) {
prepareFactorial(i);
return create(factorial.get(i));
}
public ModInt permutation(int n, int r) {
if (n < 0 || r < 0 || n < r)
return create(0);
prepareFactorial(n);
if (factorial_inversion.size() > n) {
return create(ma.mul(factorial.get(n), factorial_inversion.get(n - r)));
}
return create(ma.div(factorial.get(n), factorial.get(n - r)));
}
public ModInt combination(int n, int r) {
if (n < 0 || r < 0 || n < r)
return create(0);
prepareFactorial(n);
if (factorial_inversion.size() > n) {
return create(
ma.mul(factorial.get(n), ma.mul(factorial_inversion.get(n - r), factorial_inversion.get(r))));
}
return create(ma.div(factorial.get(n), ma.mul(factorial.get(r), factorial.get(n - r))));
}
public void prepareFactorialInv(int max) {
prepareFactorial(max);
factorial_inversion.ensureCapacity(max + 1);
for (int i = factorial_inversion.size(); i <= max; i++) {
factorial_inversion.add(ma.inv(factorial.get(i)));
}
}
public int getMod() {
return mod;
}
public class ModInt {
private int value;
private ModInt(int value) {
this.value = value;
}
public int mod() {
return mod;
}
public int value() {
if (ma instanceof ModArithmetic.ModArithmeticMontgomery) {
return ((ModArithmetic.ModArithmeticMontgomery) ma).reduce(value);
}
return value;
}
public ModInt add(ModInt mi) {
return new ModInt(ma.add(value, mi.value));
}
public ModInt add(ModInt mi1, ModInt mi2) {
return new ModInt(ma.add(value, mi1.value)).addAsg(mi2);
}
public ModInt add(ModInt mi1, ModInt mi2, ModInt mi3) {
return new ModInt(ma.add(value, mi1.value)).addAsg(mi2).addAsg(mi3);
}
public ModInt add(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) {
return new ModInt(ma.add(value, mi1.value)).addAsg(mi2).addAsg(mi3).addAsg(mi4);
}
public ModInt add(ModInt mi1, ModInt... mis) {
ModInt mi = add(mi1);
for (ModInt m : mis)
mi.addAsg(m);
return mi;
}
public ModInt add(long mi) {
return new ModInt(ma.add(value, ma.remainder(mi)));
}
public ModInt sub(ModInt mi) {
return new ModInt(ma.sub(value, mi.value));
}
public ModInt sub(long mi) {
return new ModInt(ma.sub(value, ma.remainder(mi)));
}
public ModInt mul(ModInt mi) {
return new ModInt(ma.mul(value, mi.value));
}
public ModInt mul(ModInt mi1, ModInt mi2) {
return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2);
}
public ModInt mul(ModInt mi1, ModInt mi2, ModInt mi3) {
return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2).mulAsg(mi3);
}
public ModInt mul(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) {
return new ModInt(ma.mul(value, mi1.value)).mulAsg(mi2).mulAsg(mi3).mulAsg(mi4);
}
public ModInt mul(ModInt mi1, ModInt... mis) {
ModInt mi = mul(mi1);
for (ModInt m : mis)
mi.mulAsg(m);
return mi;
}
public ModInt mul(long mi) {
return new ModInt(ma.mul(value, ma.remainder(mi)));
}
public ModInt div(ModInt mi) {
return new ModInt(ma.div(value, mi.value));
}
public ModInt div(long mi) {
return new ModInt(ma.div(value, ma.remainder(mi)));
}
public ModInt inv() {
return new ModInt(ma.inv(value));
}
public ModInt pow(long b) {
return new ModInt(ma.pow(value, b));
}
public ModInt addAsg(ModInt mi) {
this.value = ma.add(value, mi.value);
return this;
}
public ModInt addAsg(ModInt mi1, ModInt mi2) {
return addAsg(mi1).addAsg(mi2);
}
public ModInt addAsg(ModInt mi1, ModInt mi2, ModInt mi3) {
return addAsg(mi1).addAsg(mi2).addAsg(mi3);
}
public ModInt addAsg(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) {
return addAsg(mi1).addAsg(mi2).addAsg(mi3).addAsg(mi4);
}
public ModInt addAsg(ModInt... mis) {
for (ModInt m : mis)
addAsg(m);
return this;
}
public ModInt addAsg(long mi) {
this.value = ma.add(value, ma.remainder(mi));
return this;
}
public ModInt subAsg(ModInt mi) {
this.value = ma.sub(value, mi.value);
return this;
}
public ModInt subAsg(long mi) {
this.value = ma.sub(value, ma.remainder(mi));
return this;
}
public ModInt mulAsg(ModInt mi) {
this.value = ma.mul(value, mi.value);
return this;
}
public ModInt mulAsg(ModInt mi1, ModInt mi2) {
return mulAsg(mi1).mulAsg(mi2);
}
public ModInt mulAsg(ModInt mi1, ModInt mi2, ModInt mi3) {
return mulAsg(mi1).mulAsg(mi2).mulAsg(mi3);
}
public ModInt mulAsg(ModInt mi1, ModInt mi2, ModInt mi3, ModInt mi4) {
return mulAsg(mi1).mulAsg(mi2).mulAsg(mi3).mulAsg(mi4);
}
public ModInt mulAsg(ModInt... mis) {
for (ModInt m : mis)
mulAsg(m);
return this;
}
public ModInt mulAsg(long mi) {
this.value = ma.mul(value, ma.remainder(mi));
return this;
}
public ModInt divAsg(ModInt mi) {
this.value = ma.div(value, mi.value);
return this;
}
public ModInt divAsg(long mi) {
this.value = ma.div(value, ma.remainder(mi));
return this;
}
@Override
public String toString() {
return String.valueOf(value());
}
@Override
public boolean equals(Object o) {
if (o instanceof ModInt) {
ModInt mi = (ModInt) o;
return mod() == mi.mod() && value() == mi.value();
}
return false;
}
@Override
public int hashCode() {
return (1 * 37 + mod()) * 37 + value();
}
}
private static abstract class ModArithmetic {
abstract int mod();
abstract int remainder(long value);
abstract int add(int a, int b);
abstract int sub(int a, int b);
abstract int mul(int a, int b);
int div(int a, int b) {
return mul(a, inv(b));
}
int inv(int a) {
int b = mod();
if (b == 1)
return 0;
long u = 1, v = 0;
while (b >= 1) {
int t = a / b;
a -= t * b;
int tmp1 = a;
a = b;
b = tmp1;
u -= t * v;
long tmp2 = u;
u = v;
v = tmp2;
}
if (a != 1) {
throw new ArithmeticException("divide by zero");
}
return remainder(u);
}
int pow(int a, long b) {
if (b < 0)
throw new ArithmeticException("negative power");
int r = 1;
int x = a;
while (b > 0) {
if ((b & 1) == 1)
r = mul(r, x);
x = mul(x, x);
b >>= 1;
}
return r;
}
static ModArithmetic of(int mod) {
if (mod <= 0) {
throw new IllegalArgumentException();
} else if (mod == 1) {
return new ModArithmetic1();
} else if (mod == 2) {
return new ModArithmetic2();
} else if (mod == 998244353) {
return new ModArithmetic998244353();
} else if (mod == 1000000007) {
return new ModArithmetic1000000007();
} else if ((mod & 1) == 1) {
return new ModArithmeticMontgomery(mod);
} else {
return new ModArithmeticBarrett(mod);
}
}
private static final class ModArithmetic1 extends ModArithmetic {
int mod() {
return 1;
}
int remainder(long value) {
return 0;
}
int add(int a, int b) {
return 0;
}
int sub(int a, int b) {
return 0;
}
int mul(int a, int b) {
return 0;
}
int pow(int a, long b) {
return 0;
}
}
private static final class ModArithmetic2 extends ModArithmetic {
int mod() {
return 2;
}
int remainder(long value) {
return (int) (value & 1);
}
int add(int a, int b) {
return a ^ b;
}
int sub(int a, int b) {
return a ^ b;
}
int mul(int a, int b) {
return a & b;
}
}
private static final class ModArithmetic998244353 extends ModArithmetic {
private final int mod = 998244353;
int mod() {
return mod;
}
int remainder(long value) {
return (int) ((value %= mod) < 0 ? value + mod : value);
}
int add(int a, int b) {
int res = a + b;
return res >= mod ? res - mod : res;
}
int sub(int a, int b) {
int res = a - b;
return res < 0 ? res + mod : res;
}
int mul(int a, int b) {
return (int) (((long) a * b) % mod);
}
}
private static final class ModArithmetic1000000007 extends ModArithmetic {
private final int mod = 1000000007;
int mod() {
return mod;
}
int remainder(long value) {
return (int) ((value %= mod) < 0 ? value + mod : value);
}
int add(int a, int b) {
int res = a + b;
return res >= mod ? res - mod : res;
}
int sub(int a, int b) {
int res = a - b;
return res < 0 ? res + mod : res;
}
int mul(int a, int b) {
return (int) (((long) a * b) % mod);
}
}
private static final class ModArithmeticMontgomery extends ModArithmeticDynamic {
private final long negInv;
private final long r2;
private ModArithmeticMontgomery(int mod) {
super(mod);
long inv = 0;
long s = 1, t = 0;
for (int i = 0; i < 32; i++) {
if ((t & 1) == 0) {
t += mod;
inv += s;
}
t >>= 1;
s <<= 1;
}
long r = (1l << 32) % mod;
this.negInv = inv;
this.r2 = (r * r) % mod;
}
private int generate(long x) {
return reduce(x * r2);
}
private int reduce(long x) {
x = (x + ((x * negInv) & 0xffff_ffffl) * mod) >>> 32;
return (int) (x < mod ? x : x - mod);
}
@Override
int remainder(long value) {
return generate((value %= mod) < 0 ? value + mod : value);
}
@Override
int mul(int a, int b) {
return reduce((long) a * b);
}
@Override
int inv(int a) {
return super.inv(reduce(a));
}
@Override
int pow(int a, long b) {
return generate(super.pow(a, b));
}
}
private static final class ModArithmeticBarrett extends ModArithmeticDynamic {
private static final long mask = 0xffff_ffffl;
private final long mh;
private final long ml;
private ModArithmeticBarrett(int mod) {
super(mod);
/**
* m = floor(2^64/mod) 2^64 = p*mod + q, 2^32 = a*mod + b => (a*mod + b)^2 =
* p*mod + q => p = mod*a^2 + 2ab + floor(b^2/mod)
*/
long a = (1l << 32) / mod;
long b = (1l << 32) % mod;
long m = a * a * mod + 2 * a * b + (b * b) / mod;
mh = m >>> 32;
ml = m & mask;
}
private int reduce(long x) {
long z = (x & mask) * ml;
z = (x & mask) * mh + (x >>> 32) * ml + (z >>> 32);
z = (x >>> 32) * mh + (z >>> 32);
x -= z * mod;
return (int) (x < mod ? x : x - mod);
}
@Override
int remainder(long value) {
return (int) ((value %= mod) < 0 ? value + mod : value);
}
@Override
int mul(int a, int b) {
return reduce((long) a * b);
}
}
private static class ModArithmeticDynamic extends ModArithmetic {
final int mod;
ModArithmeticDynamic(int mod) {
this.mod = mod;
}
int mod() {
return mod;
}
int remainder(long value) {
return (int) ((value %= mod) < 0 ? value + mod : value);
}
int add(int a, int b) {
int sum = a + b;
return sum >= mod ? sum - mod : sum;
}
int sub(int a, int b) {
int sum = a - b;
return sum < 0 ? sum + mod : sum;
}
int mul(int a, int b) {
return (int) (((long) a * b) % mod);
}
}
}
}
static class Convolution {
/**
* Find a primitive root.
*
* @param m A prime number.
* @return Primitive root.
*/
private static int primitiveRoot(int m) {
if (m == 2)
return 1;
if (m == 167772161)
return 3;
if (m == 469762049)
return 3;
if (m == 754974721)
return 11;
if (m == 998244353)
return 3;
int[] divs = new int[20];
divs[0] = 2;
int cnt = 1;
int x = (m - 1) / 2;
while (x % 2 == 0)
x /= 2;
for (int i = 3; (long) (i) * i <= x; i += 2) {
if (x % i == 0) {
divs[cnt++] = i;
while (x % i == 0) {
x /= i;
}
}
}
if (x > 1) {
divs[cnt++] = x;
}
for (int g = 2;; g++) {
boolean ok = true;
for (int i = 0; i < cnt; i++) {
if (pow(g, (m - 1) / divs[i], m) == 1) {
ok = false;
break;
}
}
if (ok)
return g;
}
}
/**
* Power.
*
* @param x Parameter x.
* @param n Parameter n.
* @param m Mod.
* @return n-th power of x mod m.
*/
private static long pow(long x, long n, int m) {
if (m == 1)
return 0;
long r = 1;
long y = x % m;
while (n > 0) {
if ((n & 1) != 0)
r = (r * y) % m;
y = (y * y) % m;
n >>= 1;
}
return r;
}
/**
* Ceil of power 2.
*
* @param n Value.
* @return Ceil of power 2.
*/
private static int ceilPow2(int n) {
int x = 0;
while ((1L << x) < n)
x++;
return x;
}
/**
* Garner's algorithm.
*
* @param c Mod convolution results.
* @param mods Mods.
* @return Result.
*/
private static long garner(long[] c, int[] mods) {
int n = c.length + 1;
long[] cnst = new long[n];
long[] coef = new long[n];
java.util.Arrays.fill(coef, 1);
for (int i = 0; i < n - 1; i++) {
int m1 = mods[i];
long v = (c[i] - cnst[i] + m1) % m1;
v = v * pow(coef[i], m1 - 2, m1) % m1;
for (int j = i + 1; j < n; j++) {
long m2 = mods[j];
cnst[j] = (cnst[j] + coef[j] * v) % m2;
coef[j] = (coef[j] * m1) % m2;
}
}
return cnst[n - 1];
}
/**
* Pre-calculation for NTT.
*
* @param mod NTT Prime.
* @param g Primitive root of mod.
* @return Pre-calculation table.
*/
private static long[] sumE(int mod, int g) {
long[] sum_e = new long[30];
long[] es = new long[30];
long[] ies = new long[30];
int cnt2 = Integer.numberOfTrailingZeros(mod - 1);
long e = pow(g, (mod - 1) >> cnt2, mod);
long ie = pow(e, mod - 2, mod);
for (int i = cnt2; i >= 2; i--) {
es[i - 2] = e;
ies[i - 2] = ie;
e = e * e % mod;
ie = ie * ie % mod;
}
long now = 1;
for (int i = 0; i < cnt2 - 2; i++) {
sum_e[i] = es[i] * now % mod;
now = now * ies[i] % mod;
}
return sum_e;
}
/**
* Pre-calculation for inverse NTT.
*
* @param mod Mod.
* @param g Primitive root of mod.
* @return Pre-calculation table.
*/
private static long[] sumIE(int mod, int g) {
long[] sum_ie = new long[30];
long[] es = new long[30];
long[] ies = new long[30];
int cnt2 = Integer.numberOfTrailingZeros(mod - 1);
long e = pow(g, (mod - 1) >> cnt2, mod);
long ie = pow(e, mod - 2, mod);
for (int i = cnt2; i >= 2; i--) {
es[i - 2] = e;
ies[i - 2] = ie;
e = e * e % mod;
ie = ie * ie % mod;
}
long now = 1;
for (int i = 0; i < cnt2 - 2; i++) {
sum_ie[i] = ies[i] * now % mod;
now = now * es[i] % mod;
}
return sum_ie;
}
/**
* Inverse NTT.
*
* @param a Target array.
* @param sumIE Pre-calculation table.
* @param mod NTT Prime.
*/
private static void butterflyInv(long[] a, long[] sumIE, int mod) {
int n = a.length;
int h = ceilPow2(n);
for (int ph = h; ph >= 1; ph--) {
int w = 1 << (ph - 1), p = 1 << (h - ph);
long inow = 1;
for (int s = 0; s < w; s++) {
int offset = s << (h - ph + 1);
for (int i = 0; i < p; i++) {
long l = a[i + offset];
long r = a[i + offset + p];
a[i + offset] = (l + r) % mod;
a[i + offset + p] = (mod + l - r) * inow % mod;
}
int x = Integer.numberOfTrailingZeros(~s);
inow = inow * sumIE[x] % mod;
}
}
}
/**
* Inverse NTT.
*
* @param a Target array.
* @param sumE Pre-calculation table.
* @param mod NTT Prime.
*/
private static void butterfly(long[] a, long[] sumE, int mod) {
int n = a.length;
int h = ceilPow2(n);
for (int ph = 1; ph <= h; ph++) {
int w = 1 << (ph - 1), p = 1 << (h - ph);
long now = 1;
for (int s = 0; s < w; s++) {
int offset = s << (h - ph + 1);
for (int i = 0; i < p; i++) {
long l = a[i + offset];
long r = a[i + offset + p] * now % mod;
a[i + offset] = (l + r) % mod;
a[i + offset + p] = (l - r + mod) % mod;
}
int x = Integer.numberOfTrailingZeros(~s);
now = now * sumE[x] % mod;
}
}
}
/**
* Convolution.
*
* @param a Target array 1.
* @param b Target array 2.
* @param mod NTT Prime.
* @return Answer.
*/
public static long[] convolution(long[] a, long[] b, int mod) {
int n = a.length;
int m = b.length;
if (n == 0 || m == 0)
return new long[0];
int z = 1 << ceilPow2(n + m - 1);
{
long[] na = new long[z];
long[] nb = new long[z];
System.arraycopy(a, 0, na, 0, n);
System.arraycopy(b, 0, nb, 0, m);
a = na;
b = nb;
}
int g = primitiveRoot(mod);
long[] sume = sumE(mod, g);
long[] sumie = sumIE(mod, g);
butterfly(a, sume, mod);
butterfly(b, sume, mod);
for (int i = 0; i < z; i++) {
a[i] = a[i] * b[i] % mod;
}
butterflyInv(a, sumie, mod);
a = java.util.Arrays.copyOf(a, n + m - 1);
long iz = pow(z, mod - 2, mod);
for (int i = 0; i < n + m - 1; i++)
a[i] = a[i] * iz % mod;
return a;
}
/**
* Convolution.
*
* @param a Target array 1.
* @param b Target array 2.
* @param mod Any mod.
* @return Answer.
*/
public static long[] convolutionLL(long[] a, long[] b, int mod) {
int n = a.length;
int m = b.length;
if (n == 0 || m == 0)
return new long[0];
int mod1 = 754974721;
int mod2 = 167772161;
int mod3 = 469762049;
long[] c1 = convolution(a, b, mod1);
long[] c2 = convolution(a, b, mod2);
long[] c3 = convolution(a, b, mod3);
int retSize = c1.length;
long[] ret = new long[retSize];
int[] mods = { mod1, mod2, mod3, mod };
for (int i = 0; i < retSize; ++i) {
ret[i] = garner(new long[] { c1[i], c2[i], c3[i] }, mods);
}
return ret;
}
/**
* Convolution by ModInt.
*
* @param a Target array 1.
* @param b Target array 2.
* @return Answer.
*/
public static java.util.List<ModIntFactory.ModInt> convolution(java.util.List<ModIntFactory.ModInt> a,
java.util.List<ModIntFactory.ModInt> b) {
int mod = a.get(0).mod();
long[] va = a.stream().mapToLong(ModIntFactory.ModInt::value).toArray();
long[] vb = b.stream().mapToLong(ModIntFactory.ModInt::value).toArray();
long[] c = convolutionLL(va, vb, mod);
ModIntFactory factory = new ModIntFactory(mod);
return java.util.Arrays.stream(c).mapToObj(factory::create).collect(java.util.stream.Collectors.toList());
}
/**
* Naive convolution. (Complexity is O(N^2)!!)
*
* @param a Target array 1.
* @param b Target array 2.
* @param mod Mod.
* @return Answer.
*/
public static long[] convolutionNaive(long[] a, long[] b, int mod) {
int n = a.length;
int m = b.length;
int k = n + m - 1;
long[] ret = new long[k];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
ret[i + j] += a[i] * b[j] % mod;
ret[i + j] %= mod;
}
}
return ret;
}
}
static class ContestScanner {
private final java.io.InputStream in;
private final byte[] buffer = new byte[1024];
private int ptr = 0;
private int buflen = 0;
private static final long LONG_MAX_TENTHS = 922337203685477580L;
private static final int LONG_MAX_LAST_DIGIT = 7;
private static final int LONG_MIN_LAST_DIGIT = 8;
public ContestScanner(java.io.InputStream in) {
this.in = in;
}
public ContestScanner() {
this(System.in);
}
private boolean hasNextByte() {
if (ptr < buflen) {
return true;
} else {
ptr = 0;
try {
buflen = in.read(buffer);
} catch (java.io.IOException e) {
e.printStackTrace();
}
if (buflen <= 0) {
return false;
}
}
return true;
}
private int readByte() {
if (hasNextByte())
return buffer[ptr++];
else
return -1;
}
private static boolean isPrintableChar(int c) {
return 33 <= c && c <= 126;
}
public boolean hasNext() {
while (hasNextByte() && !isPrintableChar(buffer[ptr]))
ptr++;
return hasNextByte();
}
public String next() {
if (!hasNext())
throw new java.util.NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while (isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public long nextLong() {
if (!hasNext())
throw new java.util.NoSuchElementException();
long n = 0;
boolean minus = false;
int b = readByte();
if (b == '-') {
minus = true;
b = readByte();
}
if (b < '0' || '9' < b) {
throw new NumberFormatException();
}
while (true) {
if ('0' <= b && b <= '9') {
int digit = b - '0';
if (n >= LONG_MAX_TENTHS) {
if (n == LONG_MAX_TENTHS) {
if (minus) {
if (digit <= LONG_MIN_LAST_DIGIT) {
n = -n * 10 - digit;
b = readByte();
if (!isPrintableChar(b)) {
return n;
} else if (b < '0' || '9' < b) {
throw new NumberFormatException(
String.format("%d%s... is not number", n, Character.toString(b)));
}
}
} else {
if (digit <= LONG_MAX_LAST_DIGIT) {
n = n * 10 + digit;
b = readByte();
if (!isPrintableChar(b)) {
return n;
} else if (b < '0' || '9' < b) {
throw new NumberFormatException(
String.format("%d%s... is not number", n, Character.toString(b)));
}
}
}
}
throw new ArithmeticException(
String.format("%s%d%d... overflows long.", minus ? "-" : "", n, digit));
}
n = n * 10 + digit;
} else if (b == -1 || !isPrintableChar(b)) {
return minus ? -n : n;
} else {
throw new NumberFormatException();
}
b = readByte();
}
}
public int nextInt() {
long nl = nextLong();
if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE)
throw new NumberFormatException();
return (int) nl;
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long[] nextLongArray(int length) {
long[] array = new long[length];
for (int i = 0; i < length; i++)
array[i] = this.nextLong();
return array;
}
public long[] nextLongArray(int length, java.util.function.LongUnaryOperator map) {
long[] array = new long[length];
for (int i = 0; i < length; i++)
array[i] = map.applyAsLong(this.nextLong());
return array;
}
public int[] nextIntArray(int length) {
int[] array = new int[length];
for (int i = 0; i < length; i++)
array[i] = this.nextInt();
return array;
}
public int[][] nextIntArrayMulti(int length, int width) {
int[][] arrays = new int[width][length];
for (int i = 0; i < length; i++) {
for (int j = 0; j < width; j++)
arrays[j][i] = this.nextInt();
}
return arrays;
}
public int[] nextIntArray(int length, java.util.function.IntUnaryOperator map) {
int[] array = new int[length];
for (int i = 0; i < length; i++)
array[i] = map.applyAsInt(this.nextInt());
return array;
}
public double[] nextDoubleArray(int length) {
double[] array = new double[length];
for (int i = 0; i < length; i++)
array[i] = this.nextDouble();
return array;
}
public double[] nextDoubleArray(int length, java.util.function.DoubleUnaryOperator map) {
double[] array = new double[length];
for (int i = 0; i < length; i++)
array[i] = map.applyAsDouble(this.nextDouble());
return array;
}
public long[][] nextLongMatrix(int height, int width) {
long[][] mat = new long[height][width];
for (int h = 0; h < height; h++)
for (int w = 0; w < width; w++) {
mat[h][w] = this.nextLong();
}
return mat;
}
public int[][] nextIntMatrix(int height, int width) {
int[][] mat = new int[height][width];
for (int h = 0; h < height; h++)
for (int w = 0; w < width; w++) {
mat[h][w] = this.nextInt();
}
return mat;
}
public double[][] nextDoubleMatrix(int height, int width) {
double[][] mat = new double[height][width];
for (int h = 0; h < height; h++)
for (int w = 0; w < width; w++) {
mat[h][w] = this.nextDouble();
}
return mat;
}
public char[][] nextCharMatrix(int height, int width) {
char[][] mat = new char[height][width];
for (int h = 0; h < height; h++) {
String s = this.next();
for (int w = 0; w < width; w++) {
mat[h][w] = s.charAt(w);
}
}
return mat;
}
}
static class ContestPrinter extends java.io.PrintWriter {
public ContestPrinter(java.io.PrintStream stream) {
super(stream);
}
public ContestPrinter() {
super(System.out);
}
private static String dtos(double x, int n) {
StringBuilder sb = new StringBuilder();
if (x < 0) {
sb.append('-');
x = -x;
}
x += Math.pow(10, -n) / 2;
sb.append((long) x);
sb.append(".");
x -= (long) x;
for (int i = 0; i < n; i++) {
x *= 10;
sb.append((int) x);
x -= (int) x;
}
return sb.toString();
}
@Override
public void print(float f) {
super.print(dtos(f, 20));
}
@Override
public void println(float f) {
super.println(dtos(f, 20));
}
@Override
public void print(double d) {
super.print(dtos(d, 20));
}
@Override
public void println(double d) {
super.println(dtos(d, 20));
}
public void printArray(int[] array, String separator) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
super.print(array[i]);
super.print(separator);
}
super.println(array[n - 1]);
}
public void printArray(int[] array) {
this.printArray(array, " ");
}
public void printArray(int[] array, String separator, java.util.function.IntUnaryOperator map) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
super.print(map.applyAsInt(array[i]));
super.print(separator);
}
super.println(map.applyAsInt(array[n - 1]));
}
public void printArray(int[] array, java.util.function.IntUnaryOperator map) {
this.printArray(array, " ", map);
}
public void printArray(long[] array, String separator) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
super.print(array[i]);
super.print(separator);
}
super.println(array[n - 1]);
}
public void printArray(long[] array) {
this.printArray(array, " ");
}
public void printArray(long[] array, String separator, java.util.function.LongUnaryOperator map) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
super.print(map.applyAsLong(array[i]));
super.print(separator);
}
super.println(map.applyAsLong(array[n - 1]));
}
public void printArray(long[] array, java.util.function.LongUnaryOperator map) {
this.printArray(array, " ", map);
}
}
public static void safeSort(int[] array) {
Integer[] temp = new Integer[array.length];
for (int n = 0; n < array.length; n++) {
temp[n] = array[n];
}
Arrays.sort(temp);
for (int n = 0; n < array.length; n++) {
array[n] = temp[n];
}
}
public static void safeSort(long[] array) {
Long[] temp = new Long[array.length];
for (int n = 0; n < array.length; n++) {
temp[n] = array[n];
}
Arrays.sort(temp);
for (int n = 0; n < array.length; n++) {
array[n] = temp[n];
}
}
public static void safeSort(double[] array) {
Double[] temp = new Double[array.length];
for (int n = 0; n < array.length; n++) {
temp[n] = array[n];
}
Arrays.sort(temp);
for (int n = 0; n < array.length; n++) {
array[n] = temp[n];
}
}
}
| Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 11 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | bbfce0a8fa2d529b8ba0dbb6b61a2ed6 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.util.*;
import java.io.*;
public class D_1609 {
static TreeMap<Integer, Integer> map;
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt(), d = sc.nextInt();
int[] x = new int[d], y = new int[d];
for(int i = 0; i < d; i++) {
x[i] = sc.nextInt() - 1;
y[i] = sc.nextInt() - 1;
}
for(int i = 0; i < d; i++) {
map = new TreeMap<>();
DSU dsu = new DSU(n);
int rem = 1;
for(int j = 0; j <= i; j++) {
if(dsu.isSameSet(x[j], y[j]))
rem++;
else
dsu.union(x[j], y[j]);
}
int ans = 0;
while(rem-->0) {
Map.Entry<Integer, Integer> e = map.pollLastEntry();
ans += e.getKey();
if(e.getValue() == 1)
map.remove(e.getKey());
else
map.put(e.getKey(), e.getValue() - 1);
}
pw.println(ans - 1);
}
pw.flush();
}
public static class DSU {
int sets;
int[] parent, rank, size;
public DSU(int n) {
sets = n;
parent = new int[n];
rank = new int[n];
size = new int[n];
for(int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 1;
size[i] = 1;
int c = map.getOrDefault(size[i], 0) + 1;
map.put(size[i], c);
}
}
public int getParent(int u) {
return parent[u] == u ? u : (parent[u] = getParent(parent[u]));
}
public boolean isSameSet(int u, int v) {
return getParent(parent[u]) == getParent(parent[v]);
}
public void union(int u, int v) {
int x = getParent(u);
int y = getParent(v);
if(x == y)
return;
if(rank[x] >= rank[y]) {
parent[y] = x;
int c = map.get(size[x]) - 1;
if(c == 0)
map.remove(size[x]);
else
map.put(size[x], c);
c = map.get(size[y]) - 1;
if(c == 0)
map.remove(size[y]);
else
map.put(size[y], c);
size[x] += size[y];
size[y] = 0;
c = map.getOrDefault(size[x], 0) + 1;
map.put(size[x], c);
if(rank[x] == rank[y])
rank[x]++;
} else {
parent[x] = y;
int c = map.get(size[x]) - 1;
if(c == 0)
map.remove(size[x]);
else
map.put(size[x], c);
c = map.get(size[y]) - 1;
if(c == 0)
map.remove(size[y]);
else
map.put(size[y], c);
size[y] += size[x];
size[x] = 0;
c = map.getOrDefault(size[y], 0) + 1;
map.put(size[y], c);
}
sets--;
}
public int getSets() {
return sets;
}
public int getSetSize(int u) {
return size[getParent(u)];
}
}
public static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public int[] nextIntArray(int n) throws IOException {
int[] array = new int[n];
for (int i = 0; i < n; i++)
array[i] = nextInt();
return array;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] array = new Integer[n];
for (int i = 0; i < n; i++)
array[i] = new Integer(nextInt());
return array;
}
public long[] nextLongArray(int n) throws IOException {
long[] array = new long[n];
for (int i = 0; i < n; i++)
array[i] = nextLong();
return array;
}
public double[] nextDoubleArray(int n) throws IOException {
double[] array = new double[n];
for (int i = 0; i < n; i++)
array[i] = nextDouble();
return array;
}
public static int[] shuffle(int[] a) {
int n = a.length;
Random rand = new Random();
for (int i = 0; i < n; i++) {
int tmpIdx = rand.nextInt(n);
int tmp = a[i];
a[i] = a[tmpIdx];
a[tmpIdx] = tmp;
}
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
}
| Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 11 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 6491aa7076c4185a08ba0f1954be26e0 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
import java.util.stream.*;
public class D {
int get(int v, int[] p) {
return p[v] == v ? v : (p[v] = get(p[v], p));
}
void submit() {
int n = nextInt();
int d = nextInt();
int[] p = new int[n];
int[] sz = new int[n];
for (int i = 0; i < n; i++) {
p[i] = i;
sz[i] = 1;
}
int comps = n;
int free = 1;
while (d-- > 0) {
int v = nextInt() - 1;
int u = nextInt() - 1;
v = get(v, p);
u = get(u, p);
if (p[v] != p[u]) {
p[v] = u;
sz[u] += sz[v];
comps--;
} else {
free++;
}
int[] a = new int[n];
for (int i = 0, j = 0; i < n; i++) {
if (p[i] == i) {
a[j++] = sz[i];
}
}
Arrays.sort(a, 0, comps);
int ret = 0;
for (int i = comps - 1; i >= comps - free; i--) {
ret += a[i];
}
out.println(ret - 1);
}
}
void test() {
}
void stress() {
for (int tst = 0;; tst++) {
if (false) {
throw new AssertionError();
}
System.err.println(tst);
}
}
D() throws IOException {
is = System.in;
out = new PrintWriter(System.out);
submit();
// stress();
// test();
out.close();
}
static final Random rng = new Random();
static final int C = 5;
static int rand(int l, int r) {
return l + rng.nextInt(r - l + 1);
}
public static void main(String[] args) throws IOException {
new D();
}
private InputStream is;
PrintWriter out;
private byte[] buf = new byte[1 << 14];
private int bufSz = 0, bufPtr = 0;
private int readByte() {
if (bufSz == -1)
throw new RuntimeException("Reading past EOF");
if (bufPtr >= bufSz) {
bufPtr = 0;
try {
bufSz = is.read(buf);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (bufSz <= 0)
return -1;
}
return buf[bufPtr++];
}
private boolean isTrash(int c) {
return c < 33 || c > 126;
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isTrash(b))
;
return b;
}
String nextToken() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!isTrash(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
String nextString() {
int b = readByte();
StringBuilder sb = new StringBuilder();
while (!isTrash(b) || b == ' ') {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
char nextChar() {
return (char) skip();
}
int nextInt() {
int ret = 0;
int b = skip();
if (b != '-' && (b < '0' || b > '9')) {
throw new InputMismatchException();
}
boolean neg = false;
if (b == '-') {
neg = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
ret = ret * 10 + (b - '0');
} else {
if (b != -1 && !isTrash(b)) {
throw new InputMismatchException();
}
return neg ? -ret : ret;
}
b = readByte();
}
}
long nextLong() {
long ret = 0;
int b = skip();
if (b != '-' && (b < '0' || b > '9')) {
throw new InputMismatchException();
}
boolean neg = false;
if (b == '-') {
neg = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
ret = ret * 10 + (b - '0');
} else {
if (b != -1 && !isTrash(b)) {
throw new InputMismatchException();
}
return neg ? -ret : ret;
}
b = readByte();
}
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 11 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 0c2fb2a0c69938245b18b9c2c35762b9 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.math.BigInteger;
import java.util.*;
import java.io.*;
public class Balabizo {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt() , m = sc.nextInt();
UnionFind dsu = new UnionFind(n);
int cnt = 0;
for(int i=0; i<m ;i++){
int u = sc.nextInt() - 1 , v = sc.nextInt() - 1;
if(dsu.isSameSet(u , v))
cnt++;
dsu.unionSet(u , v);
HashSet<Integer> hs = new HashSet<>();
PriorityQueue<Integer> ts = new PriorityQueue<>(Collections.reverseOrder());
for(int j=0; j<n ;j++){
int x = dsu.findSet(j);
if(!hs.contains(x))
ts.add(dsu.sizeOfSet(x));
hs.add(x);
}
int ans = ts.poll();
for(int j=cnt; j>0 && !ts.isEmpty() ;j--)
ans += ts.poll();
pw.println(ans - 1);
}
pw.flush();
}
static class UnionFind {
int[] p, setSize;
int numSets;
public UnionFind(int N){
p = new int[numSets = N];
setSize = new int[N];
for (int i = 0; i < N; i++) {
p[i] = i;
setSize[i] = 1;
}
}
public int findSet(int i){
return p[i] == i ? i : (p[i] = findSet(p[i]));
}
public boolean isSameSet(int i, int j) {
return findSet(i) == findSet(j);
}
public void unionSet(int i, int j) {
if (isSameSet(i, j))
return;
int x = findSet(i), y = findSet(j);
if(setSize[x] < setSize[y]){
p[x] = y;
setSize[y] += setSize[x];
}else{
p[y] = x;
setSize[x] += setSize[y];
}
}
public int numDisjointSets() {
return numSets;
}
public int sizeOfSet(int i) {
return setSize[findSet(i)];
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String file) throws IOException {
br = new BufferedReader(new FileReader(file));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String readAllLines(BufferedReader reader) throws IOException {
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
content.append(line);
content.append(System.lineSeparator());
}
return content.toString();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public int[] nextCntArray(int n , int max) throws IOException {
int[] cnt = new int[max];
for(int i=0; i<n ;i++)
cnt[nextInt()]++;
return cnt;
}
public long[] nextlongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public Long[] nextLongArray(int n) throws IOException {
Long[] a = new Long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 6a9f4a2157d96f0cb2b7c51f3c537378 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main2 {
static Scanner sc;
static PrintWriter pw;
public static void main(String[] args) throws Exception {
pw = new PrintWriter(System.out);
sc = new Scanner(System.in);
int n = sc.nextInt(), m = sc.nextInt();
int[][] arr = new int[n][2];
DSU d = new DSU(n);
int c = 0;
for (int i = 0; i < m; i++) {
int x = sc.nextInt() - 1, y = sc.nextInt() - 1;
c += d.union(x, y);
HashSet<Integer> set = new HashSet<>();
PriorityQueue<Integer> ts = new PriorityQueue<>(Collections.reverseOrder());
for (int j = 0; j < n; j++) {
set.add(d.find(j));
}
for (int a : set) {
ts.add(d.size[a]);
}
int ans = ts.poll();
int v = c;
while (v > 0 && ts.size() > 0) {
ans += ts.poll();
v--;
}
pw.println(ans - 1);
}
pw.flush();
}
static class DSU {
int[] par, size;
DSU(int n) {
par = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
par[i] = i;
size[i] = 1;
}
}
public int find(int x) {
if (x == par[x])
return x;
return par[x] = find(par[x]);
}
public int union(int x, int y) {
int a = find(x), b = find(y);
if (a == b) {
return 1;
}
if (size[a] < size[b]) {
par[a] = b;
size[b] += size[a];
} else {
par[b] = a;
size[a] += size[b];
}
return 0;
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public String readAllLines(BufferedReader reader) throws IOException {
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
content.append(line);
content.append(System.lineSeparator());
}
return content.toString();
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public long[] nextlongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public Long[] nextLongArray(int n) throws IOException {
Long[] a = new Long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 1639078540a3c6976873c07295524d1d | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | //package codeforce.div2.deltix.Autumn2021;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import static java.lang.System.out;
import static java.util.stream.Collectors.joining;
/**
* @author pribic (Priyank Doshi)
* @see <a href="https://codeforces.com/contest/1609/problem/D" target="_top">https://codeforces.com/contest/1609/problem/D</a>
* @since 28/11/21 9:11 PM
*/
public class D {
static FastScanner sc = new FastScanner(System.in);
public static void main(String[] args) {
try (PrintWriter out = new PrintWriter(System.out)) {
int T = 1;//sc.nextInt();
for (int tt = 1; tt <= T; tt++) {
int n = sc.nextInt();
int d = sc.nextInt();
DSU dsu = new DSU(n);
List<int[]> queries = new ArrayList<>();
while (d-- > 0) {
int a = sc.nextInt();
int b = sc.nextInt();
queries.add(new int[]{a, b});
}
int pending = 1;
for (int[] q : queries) {
int a = q[0];
int b = q[1];
if (!dsu.union(a, b)) {
pending++;
}
int ans = 0;
//sum top pending sizes
int times = 0;
outer:
for (int key : dsu.sizes.descendingKeySet()) {
for (int i = 0; i < dsu.sizes.get(key); i++) {
ans += key;
times++;
if (times == pending)
break outer;
}
}
System.out.println(ans - 1);
}
}
}
}
static class DSU {
int[] parent;
int[] size;
TreeMap<Integer, Integer> sizes;
DSU(int n) {
parent = new int[n + 1];
size = new int[n + 1];
sizes = new TreeMap<>();
for (int i = 1; i <= n; i++) {
parent[i] = i;
size[i] = 1;
}
sizes.put(1, n);
}
boolean union(int a, int b) {
int pa = get(a);
int pb = get(b);
if (pa == pb)
return false;
int sa = size[pa];
int sb = size[pb];
if (sa < sb) {
//swap
int t = pa;
pa = pb;
pb = t;
}
remove(size[pb]);
remove(size[pa]);
parent[pb] = pa;
size[pa] += size[pb];
add(size[pa]);
return true;
}
private void add(int num) {
sizes.put(num, sizes.getOrDefault(num, 0) + 1);
}
private void remove(int num) {
sizes.put(num, sizes.get(num) - 1);
}
int get(int a) {
return parent[a] = (a == parent[a] ? a : get(parent[a]));
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f), 32768);
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | afc8eb540ddff1bc1d85bae1bd50573c | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | //package codeforce.div2.deltix.Autumn2021;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import static java.lang.System.out;
import static java.util.stream.Collectors.joining;
/**
* @author pribic (Priyank Doshi)
* @see <a href="https://codeforces.com/contest/1609/problem/D" target="_top">https://codeforces.com/contest/1609/problem/D</a>
* @since 28/11/21 9:11 PM
*/
public class D {
static FastScanner sc = new FastScanner(System.in);
public static void main(String[] args) {
try (PrintWriter out = new PrintWriter(System.out)) {
int T = 1;//sc.nextInt();
for (int tt = 1; tt <= T; tt++) {
int n = sc.nextInt();
int d = sc.nextInt();
DSU dsu = new DSU(n);
List<int[]> queries = new ArrayList<>();
while (d-- > 0) {
int a = sc.nextInt();
int b = sc.nextInt();
queries.add(new int[]{a, b});
}
int pending = 1;
for (int[] q : queries) {
int a = q[0];
int b = q[1];
if (!dsu.union(a, b)) {
pending++;
}
int ans = 0;
//sum top pending sizes
int times = 0;
outer:
for (int key : dsu.sizes.descendingKeySet()) {
for (int i = 0; i < dsu.sizes.get(key); i++) {
ans += key;
times++;
if (times == pending)
break outer;
}
}
System.out.println(ans - 1);
}
}
}
}
static class DSU {
int[] parent;
int[] size;
TreeMap<Integer, Integer> sizes;
DSU(int n) {
parent = new int[n + 1];
size = new int[n + 1];
sizes = new TreeMap<>();
for (int i = 1; i <= n; i++) {
parent[i] = i;
size[i] = 1;
}
sizes.put(1, n);
}
boolean union(int a, int b) {
int pa = get(a);
int pb = get(b);
if (pa == pb)
return false;
int sa = size[pa];
int sb = size[pb];
if (sa < sb) {
//swap
int t = sa;
sa = sb;
sb = t;
}
remove(size[pb]);
remove(size[pa]);
parent[pb] = pa;
size[pa] += size[pb];
add(size[pa]);
return true;
}
private void add(int num) {
sizes.put(num, sizes.getOrDefault(num, 0) + 1);
}
private void remove(int num) {
sizes.put(num, sizes.get(num) - 1);
}
int get(int a) {
return parent[a] = (a == parent[a] ? a : get(parent[a]));
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f), 32768);
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 360518ee7e7b247c4b2b22ba489acc0a | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | //package codeforce.div2.deltix.Autumn2021;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import static java.lang.System.out;
import static java.util.stream.Collectors.joining;
/**
* @author pribic (Priyank Doshi)
* @see <a href="https://codeforces.com/contest/1609/problem/D" target="_top">https://codeforces.com/contest/1609/problem/D</a>
* @since 28/11/21 9:11 PM
*/
public class D {
static FastScanner sc = new FastScanner(System.in);
public static void main(String[] args) {
try (PrintWriter out = new PrintWriter(System.out)) {
int T = 1;//sc.nextInt();
for (int tt = 1; tt <= T; tt++) {
int n = sc.nextInt();
int d = sc.nextInt();
DSU dsu = new DSU(n);
List<int[]> queries = new ArrayList<>();
while (d-- > 0) {
int a = sc.nextInt();
int b = sc.nextInt();
queries.add(new int[]{a, b});
}
int pending = 1;
for (int[] q : queries) {
int a = q[0];
int b = q[1];
if (!dsu.union(a, b)) {
pending++;
}
int ans = 0;
//sum top pending sizes
int times = 0;
outer:
for (int key : dsu.sizes.descendingKeySet()) {
for (int i = 0; i < dsu.sizes.get(key); i++) {
ans += key;
times++;
if (times == pending)
break outer;
}
}
System.out.println(ans - 1);
}
}
}
}
static class DSU {
int[] parent;
int[] size;
TreeMap<Integer, Integer> sizes;
DSU(int n) {
parent = new int[n + 1];
size = new int[n + 1];
sizes = new TreeMap<>();
for (int i = 1; i <= n; i++) {
parent[i] = i;
size[i] = 1;
}
sizes.put(1, n);
}
boolean union(int a, int b) {
int pa = get(a);
int pb = get(b);
if (pa == pb)
return false;
int sa = size[pa];
int sb = size[pb];
if (sa < sb) {
//swap
int t = sa;
sa = sb;
sb = t;
}
remove(size[pb]);
remove(size[pa]);
parent[pb] = pa;
size[pa] += size[pb];
add(size[pa]);
return true;
}
private void add(int num) {
if (sizes.containsKey(num))
sizes.put(num, sizes.get(num) + 1);
else
sizes.put(num, 1);
}
private void remove(int num) {
if (sizes.get(num) == 1)
sizes.remove(num);
else
sizes.put(num, sizes.get(num) - 1);
}
boolean areSame(int a, int b) {
return get(a) == get(b);
}
int get(int a) {
return parent[a] = (a == parent[a] ? a : get(parent[a]));
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f), 32768);
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | f90ec43cfe8d1b0b866e680ea9350f3d | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | //package codeforce.div2.deltix.Autumn2021;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import static java.lang.System.out;
import static java.util.stream.Collectors.joining;
/**
* @author pribic (Priyank Doshi)
* @see <a href="https://codeforces.com/contest/1609/problem/D" target="_top">https://codeforces.com/contest/1609/problem/D</a>
* @since 28/11/21 9:11 PM
*/
public class D {
static FastScanner sc = new FastScanner(System.in);
public static void main(String[] args) {
try (PrintWriter out = new PrintWriter(System.out)) {
int T = 1;//sc.nextInt();
for (int tt = 1; tt <= T; tt++) {
int n = sc.nextInt();
int d = sc.nextInt();
DSU dsu = new DSU(n);
List<int[]> queries = new ArrayList<>();
while (d-- > 0) {
int a = sc.nextInt();
int b = sc.nextInt();
queries.add(new int[]{a, b});
}
int pending = 1;
for (int[] q : queries) {
int a = q[0];
int b = q[1];
if (dsu.areSame(a, b)) {
pending++;
}
dsu.union(a, b);
int ans = 0;
//sum top pending sizes
int times = 0;
outer:
for (int key : dsu.sizes.descendingKeySet()) {
for (int i = 0; i < dsu.sizes.get(key); i++) {
ans += key;
times++;
if (times == pending)
break outer;
}
}
System.out.println(ans - 1);
}
}
}
}
static class DSU {
public int maxsize;
public int maxParent;
int[] parent;
int[] size;
Set<Integer> leaders;
TreeMap<Integer, Integer> sizes;
DSU(int n) {
parent = new int[n + 1];
size = new int[n + 1];
leaders = new HashSet<>();
sizes = new TreeMap<>();
maxsize = 1;
maxParent = 1;
for (int i = 1; i <= n; i++) {
parent[i] = i;
size[i] = 1;
leaders.add(i);
}
sizes.put(1, n);
}
boolean union(int a, int b) {
int pa = get(a);
int pb = get(b);
if (pa == pb)
return false;
int sa = size[pa];
int sb = size[pb];
if (sa < sb) {
//swap
int t = sa;
sa = sb;
sb = t;
}
remove(size[pb]);
remove(size[pa]);
parent[pb] = pa;
size[pa] += size[pb];
add(size[pa]);
leaders.remove(pb);
if (size[pa] > maxsize) {
maxsize = size[pa];
maxParent = pa;
}
return true;
}
private void add(int num) {
if (sizes.containsKey(num))
sizes.put(num, sizes.get(num) + 1);
else
sizes.put(num, 1);
}
private void remove(int num) {
if (sizes.get(num) == 1)
sizes.remove(num);
else
sizes.put(num, sizes.get(num) - 1);
}
boolean areSame(int a, int b) {
return get(a) == get(b);
}
//TODO iterative
int get(int a) {
return parent[a] = (a == parent[a] ? a : get(parent[a]));
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f), 32768);
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | d2a7d2edc92d6081434ba3dc7339c16f | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.*;
import java.util.*;
//1600: 18:22
public class social_network {
static int[] root;
public static void main(String[] args)throws IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int d = Integer.parseInt(st.nextToken());
root = new int[n];
for(int i=0; i<n; i++) root[i] = i;
int[]size = new int[n];
for(int i=0; i<n; i++)size[i] = 1;
int add = 1;
for(int i=0; i<d; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken())-1;
int b = Integer.parseInt(st.nextToken())-1;
int r1 = getRoot(a);
int r2 = getRoot(b);
if(r1!=r2) {
root[r2]= r1;
size[r1]+=size[r2];
size[r2]= 0;
}
else add++;
int ans = 0;
LinkedList<Integer> list = new LinkedList<>();
for(int j=0; j<n; j++) {
list.add(size[j]);
}
Collections.sort(list);
for(int j=0; j<add; j++)ans += list.removeLast();
out.write((Math.min(ans-1,n-1))+"\n");
}
out.flush();
out.close();
}
static int getRoot(int pos) {
if(root[pos]==pos)return pos;
return root[pos] = getRoot(root[pos]);
}
}
| Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 4a6dba5062eebbff9bfcda31656e625b | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.util.*;
import java.io.*;
public class s2 {
public static void main(String[] args) throws Exception {
FastScanner scan=new FastScanner(System.in);
PrintWriter out=new PrintWriter(System.out);
int T=1;
// int T=scan.nextInt();
while(T-->0) {
int n=scan.nextInt();
int d=scan.nextInt();
DSU dj=new DSU(n);
int extra=1;
while(d-->0) {
int x=scan.nextInt()-1,y=scan.nextInt()-1;
if(dj.isSameSet(x,y)) extra++;
else dj.union(x,y);
int best=0;
int left=extra;
for(Integer cur:sizes.keySet()) {
int amt=sizes.get(cur);
best+=Math.min(amt,left)*cur;
left-=Math.min(amt,left);
if(left==0) break;
}
out.println(Math.max(best-1,0));
}
} out.close();
}
static TreeMap<Integer,Integer> sizes;
static class DSU {
int[] p,rank,setSize;
int numSets;
public DSU(int N) {
p=new int[numSets=N];
rank=new int[N];
sizes=new TreeMap<>(Comparator.reverseOrder());
setSize=new int[N];
sizes.put(1,N);
for(int i=0;i<N;i++) {
p[i]=i;
setSize[i]=1;
}
}
public int findSet(int i) { return p[i] == i ? i : (p[i] = findSet(p[i])); }
public boolean isSameSet(int i, int j) { return findSet(i) == findSet(j); }
public void union(int i,int j) {
if (isSameSet(i, j)) return;
numSets--;
int x=findSet(i),y=findSet(j);
if(rank[x]>rank[y]) {
sizes.put(setSize[x],sizes.get(setSize[x])-1);
if(sizes.get(setSize[x])==0) sizes.remove(setSize[x]);
p[y] = x; setSize[x] += setSize[y];
sizes.put(setSize[x],sizes.getOrDefault(setSize[x],0)+1);
sizes.put(setSize[y],sizes.get(setSize[y])-1);
if(sizes.get(setSize[y])==0) sizes.remove(setSize[y]);
} else {
sizes.put(setSize[y],sizes.get(setSize[y])-1);
if(sizes.get(setSize[y])==0) sizes.remove(setSize[y]);
p[x] = y; setSize[y] += setSize[x];
sizes.put(setSize[y],sizes.getOrDefault(setSize[y],0)+1);
if(rank[x] == rank[y]) rank[y]++;
sizes.put(setSize[x],sizes.get(setSize[x])-1);
if(sizes.get(setSize[x])==0) sizes.remove(setSize[x]);
}
}
public int numDisjointSets() { return numSets; }
public int sizeOfSet(int i) { return setSize[findSet(i)]; }
}
}
class Pair {
Integer a,b;
Pair(int a,int b) {
this.a=a;
this.b=b;
}
}
class FastScanner {
private InputStream stream;
private byte[] buf=new byte[1024];
private int curChar;
private int numChars;
public FastScanner(InputStream stream) { this.stream=stream; }
int read() {
if(numChars==-1) throw new InputMismatchException();
if(curChar>=numChars) {
curChar=0;
try { numChars=stream.read(buf); }
catch(IOException e) { throw new InputMismatchException(); }
if(numChars<=0) return -1;
} return buf[curChar++];
}
boolean isSpaceChar(int c) { return c==' '||c=='\n'||c=='\r'||c=='\t'||c==-1; }
boolean isEndline(int c) { return c=='\n'||c=='\r'||c==-1; }
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble() { return Double.parseDouble(next()); }
String next() {
int c=read();
while(isSpaceChar(c)) c=read();
StringBuilder res=new StringBuilder();
do {
res.appendCodePoint(c);
c=read();
} while(!isSpaceChar(c));
return res.toString();
}
String nextLine() {
int c=read();
while(isEndline(c)) c=read();
StringBuilder res=new StringBuilder();
do {
res.appendCodePoint(c);
c=read();
} while(!isEndline(c));
return res.toString();
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 46b1a174ccac75bb28128e882235bc40 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.util.*;
import java.io.*;
public class D1609{
static int ans = 0;
static FastScanner fs = null;
public static void main(String[] args) {
fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = fs.nextInt();
int d = fs.nextInt();
int sz[] = new int[n+1];
int par[] = new int[n+1];
Arrays.fill(sz,1);
for(int i=0;i<=n;i++){
par[i] = i;
}
while(d-->0){
int x = fs.nextInt();
int y = fs.nextInt();
union(x,y,sz,par);
ArrayList<Integer> list = new ArrayList<>();
for(int i=1;i<=n;i++){
if(root(i,par)==i){
list.add(sz[i]);
}
}
Collections.sort(list,Collections.reverseOrder());
int ans2 = 0;
for(int i=0;i<list.size()&&i<=ans;i++){
ans2+=list.get(i);
}
out.println((ans2-1));
}
out.close();
}
static int root(int a,int par[]){
if(par[a]==a)
return a;
return root(par[a],par);
}
static void union(int a,int b,int sz[],int par[]){
int x = root(a,par);
int y = root(b,par);
if(x==y){
ans+=1;
return;
}
if(sz[x]>sz[y]){
par[y] = x;
sz[x]+=sz[y];
}
else{
par[x] = y;
sz[y]+=sz[x];
}
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | b0981f52c48e144a4162c2fa2c4b2ca8 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes |
import java.io.*;
import java.util.*;
import java.math.*;
import java.math.BigInteger;
public final class A
{
static PrintWriter out = new PrintWriter(System.out);
static StringBuilder ans=new StringBuilder();
static FastReader in=new FastReader();
static ArrayList<Integer> g[];
static long mod=(long) 998244353,INF=Long.MAX_VALUE;
static boolean set[];
static int par[],col[],D[];
static long A[];
public static void main(String args[])throws IOException
{
/*
* star,rope,TPST
* BS,LST,MS,MQ
*/
int N=i(),D=i();
int node[][]=new int[D][2];
for(int i=0; i<D; i++)node[i]=input(2);
for(int i=1; i<=D; i++)
{
par=new int[N+5];
Arrays.fill(par, -1);
int max=0;
int extra=1;
for(int j=0; j<i; j++)
{
int a=find(node[j][0]),b=find(node[j][1]);
if(a!=b)
{
union(a,b);
}
else
{
extra++;
}
}
int x=0;
ArrayList<Integer> temp=new ArrayList<>();
for(int j=1; j<=N; j++)
{
if(find(j)==j)
{
temp.add(par[j]);
}
}
Collections.sort(temp);
for(int j=0; j<Math.min(temp.size(), extra); j++)x+=(-1*temp.get(j));
max=x-1;
ans.append(max+"\n");
}
out.println(ans);
out.close();
}
static int compute(char X[],int i)
{
int N=X.length;
int c=0;
for(int j=i-2; j<=i+2; j++)
{
if(j>=0 && j+2<N)
{
if(X[j]=='a'&& X[j+1]=='b' && X[j+2]=='c')c++;
}
}
return c;
}
static boolean f(long X[],long V[],double m)
{
double l=0,r=1e18;
for(int i=0; i<X.length; i++)
{
double d=((double)(V[i]))*m;
double x=(double)X[i];
l=Math.max(l, x-d);
r=Math.min(r, x+d);
// System.out.println(l+" "+r);
}
return l<=r;
}
static int query(long a,TreeNode root)
{
long p=1L<<30;
TreeNode temp=root;
while(p!=0)
{
System.out.println(a+" "+p);
if((a&p)!=0)
{
temp=temp.right;
}
else temp=temp.left;
p>>=1;
}
return temp.index;
}
static void delete(long a,TreeNode root)
{
long p=1L<<30;
TreeNode temp=root;
while(p!=0)
{
if((a&p)!=0)
{
temp.right.cnt--;
temp=temp.right;
}
else
{
temp.left.cnt--;
temp=temp.left;
}
p>>=1;
}
}
static void insert(long a,TreeNode root,int i)
{
long p=1L<<30;
TreeNode temp=root;
while(p!=0)
{
if((a&p)!=0)
{
temp.right.cnt++;
temp=temp.right;
}
else
{
temp.left.cnt++;
temp=temp.left;
}
p>>=1;
}
temp.index=i;
}
static TreeNode create(int p)
{
TreeNode root=new TreeNode(0);
if(p!=0)
{
root.left=create(p-1);
root.right=create(p-1);
}
return root;
}
static boolean f(long A[],long m,int N)
{
long B[]=new long[N];
for(int i=0; i<N; i++)
{
B[i]=A[i];
}
for(int i=N-1; i>=0; i--)
{
if(B[i]<m)return false;
if(i>=2)
{
long extra=Math.min(B[i]-m, A[i]);
long x=extra/3L;
B[i-2]+=2L*x;
B[i-1]+=x;
}
}
return true;
}
static int f(int l,int r,long A[],long x)
{
while(r-l>1)
{
int m=(l+r)/2;
if(A[m]>=x)l=m;
else r=m;
}
return r;
}
static boolean f(long m,long H,long A[],int N)
{
long s=m;
for(int i=0; i<N-1;i++)
{
s+=Math.min(m, A[i+1]-A[i]);
}
return s>=H;
}
static boolean f(int i,int j,long last,boolean win[])
{
if(i>j)return false;
if(A[i]<=last && A[j]<=last)return false;
long a=A[i],b=A[j];
//System.out.println(a+" "+b);
if(a==b)
{
return win[i] | win[j];
}
else if(a>b)
{
boolean f=false;
if(b>last)f=!f(i,j-1,b,win);
return win[i] | f;
}
else
{
boolean f=false;
if(a>last)f=!f(i+1,j,a,win);
return win[j] | f;
}
}
static long ask(long l,long r)
{
System.out.println("? "+l+" "+r);
return l();
}
static long f(long N,long M)
{
long s=0;
if(N%3==0)
{
N/=3;
s=N*M;
}
else
{
long b=N%3;
N/=3;
N++;
s=N*M;
N--;
long a=N*M;
if(M%3==0)
{
M/=3;
a+=(b*M);
}
else
{
M/=3;
M++;
a+=(b*M);
}
s=Math.min(s, a);
}
return s;
}
static int ask(StringBuilder sb,int a)
{
System.out.println(sb+""+a);
return i();
}
static void swap(char X[],int i,int j)
{
char x=X[i];
X[i]=X[j];
X[j]=x;
}
static int min(int a,int b,int c)
{
return Math.min(Math.min(a, b), c);
}
static long and(int i,int j)
{
System.out.println("and "+i+" "+j);
return l();
}
static long or(int i,int j)
{
System.out.println("or "+i+" "+j);
return l();
}
static int len=0,number=0;
static void f(char X[],int i,int num,int l)
{
if(i==X.length)
{
if(num==0)return;
//update our num
if(isPrime(num))return;
if(l<len)
{
len=l;
number=num;
}
return;
}
int a=X[i]-'0';
f(X,i+1,num*10+a,l+1);
f(X,i+1,num,l);
}
static boolean is_Sorted(int A[])
{
int N=A.length;
for(int i=1; i<=N; i++)if(A[i-1]!=i)return false;
return true;
}
static boolean f(StringBuilder sb,String Y,String order)
{
StringBuilder res=new StringBuilder(sb.toString());
HashSet<Character> set=new HashSet<>();
for(char ch:order.toCharArray())
{
set.add(ch);
for(int i=0; i<sb.length(); i++)
{
char x=sb.charAt(i);
if(set.contains(x))continue;
res.append(x);
}
}
String str=res.toString();
return str.equals(Y);
}
static boolean all_Zero(int f[])
{
for(int a:f)if(a!=0)return false;
return true;
}
static long form(int a,int l)
{
long x=0;
while(l-->0)
{
x*=10;
x+=a;
}
return x;
}
static int count(String X)
{
HashSet<Integer> set=new HashSet<>();
for(char x:X.toCharArray())set.add(x-'0');
return set.size();
}
static int f(long K)
{
long l=0,r=K;
while(r-l>1)
{
long m=(l+r)/2;
if(m*m<K)l=m;
else r=m;
}
return (int)l;
}
// static void build(int v,int tl,int tr,long A[])
// {
// if(tl==tr)
// {
// seg[v]=A[tl];
// }
// else
// {
// int tm=(tl+tr)/2;
// build(v*2,tl,tm,A);
// build(v*2+1,tm+1,tr,A);
// seg[v]=Math.min(seg[v*2], seg[v*2+1]);
// }
// }
static int [] sub(int A[],int B[])
{
int N=A.length;
int f[]=new int[N];
for(int i=N-1; i>=0; i--)
{
if(B[i]<A[i])
{
B[i]+=26;
B[i-1]-=1;
}
f[i]=B[i]-A[i];
}
for(int i=0; i<N; i++)
{
if(f[i]%2!=0)f[i+1]+=26;
f[i]/=2;
}
return f;
}
static int[] f(int N)
{
char X[]=in.next().toCharArray();
int A[]=new int[N];
for(int i=0; i<N; i++)A[i]=X[i]-'a';
return A;
}
static int max(int a ,int b,int c,int d)
{
a=Math.max(a, b);
c=Math.max(c,d);
return Math.max(a, c);
}
static int min(int a ,int b,int c,int d)
{
a=Math.min(a, b);
c=Math.min(c,d);
return Math.min(a, c);
}
static HashMap<Integer,Integer> Hash(int A[])
{
HashMap<Integer,Integer> mp=new HashMap<>();
for(int a:A)
{
int f=mp.getOrDefault(a,0)+1;
mp.put(a, f);
}
return mp;
}
static long mul(long a, long b)
{
return ( a %mod * 1L * b%mod )%mod;
}
static void swap(int A[],int a,int b)
{
int t=A[a];
A[a]=A[b];
A[b]=t;
}
static int find(int a)
{
if(par[a]<0)return a;
return par[a]=find(par[a]);
}
static void union(int a,int b)
{
a=find(a);
b=find(b);
if(a!=b)
{
if(par[a]>par[b]) //this means size of a is less than that of b
{
int t=b;
b=a;
a=t;
}
par[a]+=par[b];
par[b]=a;
}
}
static boolean isSorted(int A[])
{
for(int i=1; i<A.length; i++)
{
if(A[i]<A[i-1])return false;
}
return true;
}
static boolean isDivisible(StringBuilder X,int i,long num)
{
long r=0;
for(; i<X.length(); i++)
{
r=r*10+(X.charAt(i)-'0');
r=r%num;
}
return r==0;
}
static int lower_Bound(int A[],int low,int high, int x)
{
if (low > high)
if (x >= A[high])
return A[high];
int mid = (low + high) / 2;
if (A[mid] == x)
return A[mid];
if (mid > 0 && A[mid - 1] <= x && x < A[mid])
return A[mid - 1];
if (x < A[mid])
return lower_Bound( A, low, mid - 1, x);
return lower_Bound(A, mid + 1, high, x);
}
static String f(String A)
{
String X="";
for(int i=A.length()-1; i>=0; i--)
{
int c=A.charAt(i)-'0';
X+=(c+1)%2;
}
return X;
}
static void sort(long[] a) //check for long
{
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static String swap(String X,int i,int j)
{
char ch[]=X.toCharArray();
char a=ch[i];
ch[i]=ch[j];
ch[j]=a;
return new String(ch);
}
static int sD(long n)
{
if (n % 2 == 0 )
return 2;
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0 )
return i;
}
return (int)n;
}
static void setGraph(int N)
{
par=new int[N+1];
D=new int[N+1];
g=new ArrayList[N+1];
set=new boolean[N+1];
col=new int[N+1];
for(int i=0; i<=N; i++)
{
col[i]=-1;
g[i]=new ArrayList<>();
D[i]=Integer.MAX_VALUE;
}
}
static long pow(long a,long b)
{
//long mod=1000000007;
long pow=1;
long x=a;
while(b!=0)
{
if((b&1)!=0)pow=(pow*x)%mod;
x=(x*x)%mod;
b/=2;
}
return pow;
}
static long toggleBits(long x)//one's complement || Toggle bits
{
int n=(int)(Math.floor(Math.log(x)/Math.log(2)))+1;
return ((1<<n)-1)^x;
}
static int countBits(long a)
{
return (int)(Math.log(a)/Math.log(2)+1);
}
static long fact(long N)
{
long n=2;
if(N<=1)return 1;
else
{
for(int i=3; i<=N; i++)n=(n*i)%mod;
}
return n;
}
static int kadane(int A[])
{
int lsum=A[0],gsum=A[0];
for(int i=1; i<A.length; i++)
{
lsum=Math.max(lsum+A[i],A[i]);
gsum=Math.max(gsum,lsum);
}
return gsum;
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static boolean isPrime(long N)
{
if (N<=1) return false;
if (N<=3) return true;
if (N%2 == 0 || N%3 == 0) return false;
for (int i=5; i*i<=N; i=i+6)
if (N%i == 0 || N%(i+2) == 0)
return false;
return true;
}
static void print(char A[])
{
for(char c:A)System.out.print(c+" ");
System.out.println();
}
static void print(boolean A[])
{
for(boolean c:A)System.out.print(c+" ");
System.out.println();
}
static void print(int A[])
{
for(int a:A)System.out.print(a+" ");
System.out.println();
}
static void print(long A[])
{
for(long i:A)System.out.print(i+ " ");
System.out.println();
}
static void print(boolean A[][])
{
for(boolean a[]:A)print(a);
}
static void print(long A[][])
{
for(long a[]:A)print(a);
}
static void print(int A[][])
{
for(int a[]:A)print(a);
}
static void print(ArrayList<Integer> A)
{
for(int a:A)System.out.print(a+" ");
System.out.println();
}
static int i()
{
return in.nextInt();
}
static long l()
{
return in.nextLong();
}
static int[] input(int N){
int A[]=new int[N];
for(int i=0; i<N; i++)
{
A[i]=in.nextInt();
}
return A;
}
static long[] inputLong(int N) {
long A[]=new long[N];
for(int i=0; i<A.length; i++)A[i]=in.nextLong();
return A;
}
static long GCD(long a,long b)
{
if(b==0)
{
return a;
}
else return GCD(b,a%b );
}
}
class pair implements Comparable<pair>
{
long a,l,r;
boolean left;
int index;
pair(long a,long l,int i)
{
this.a=a;
index=i;
this.l=l;
}
public int compareTo(pair x)
{
if(this.a==x.a)
{
if(this.l>x.l)return -1;
else if(x.l>this.l)return 1;
return 0;
}
if(this.a>x.a)return 1;
return -1;
}
}
class TreeNode
{
int cnt,index;
TreeNode left,right;
TreeNode(int c)
{
cnt=c;
index=-1;
}
TreeNode(int c,int index)
{
cnt=c;
this.index=index;
}
}
//Code For FastReader
//Code For FastReader
//Code For FastReader
//Code For FastReader
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br=new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while(st==null || !st.hasMoreElements())
{
try
{
st=new StringTokenizer(br.readLine());
}
catch(IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str="";
try
{
str=br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | ca8a774aecdf773d4ac41438bf1df833 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
int t;
//t = in.nextInt();
t = 1;
while (t > 0) {
solver.call(in,out);
t--;
}
out.close();
}
static class TaskA {
int[] parent;
public void call(InputReader in, PrintWriter out) {
int n, d, a, b, ans, c = 0;
n = in.nextInt();
d = in.nextInt();
parent = new int[n + 1];
Arrays.fill(parent, - 1);
ArrayList<Integer> arrayList;
for (int i = 0; i < d; i++) {
a = in.nextInt();
b = in.nextInt();
if(!union(a, b)){
c++;
}
arrayList = new ArrayList<>();
for (int j = 0; j <= n; j++) {
if(parent[j] < -1){
arrayList.add(parent[j]);
}
}
Collections.sort(arrayList);
a = 0;
ans = 0;
for(Integer j : arrayList){
ans += Math.abs(j);
a++;
if (a == c + 1) {
break;
}
}
if(a!=c+1) {
out.println(ans + c - a);
}
else{
out.println(ans - 1);
}
}
}
public boolean union(int a, int b){
int a1 = find(a);
int b1 = find(b);
int c;
if(a1!=b1){
if(Math.abs(a1) > Math.abs(b1)){
c = parent[b1];
parent[b1] = a1;
parent[a1] += c;
}
else{
c = parent[a1];
parent[a1] = b1;
parent[b1] += c;
}
return true;
}
return false;
}
public int find(int a){
if(parent[a] < 0){
return a;
}
return parent[a] = find(parent[a]);
}
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
static class answer implements Comparable<answer>{
int a, b;
public answer(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(answer o) {
return o.b - this.b;
}
}
static class arrayListClass {
ArrayList<Integer> arrayList2 ;
public arrayListClass(ArrayList<Integer> arrayList) {
this.arrayList2 = arrayList;
}
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static void sort(long[] a) {
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static final Random random=new Random();
static void shuffleSort(int[] a) {
int n = a.length;
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | b083b2c28f5866b343db2fb648c002f9 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
int t;
//t = in.nextInt();
t = 1;
while (t > 0) {
solver.call(in,out);
t--;
}
out.close();
}
static class TaskA {
int[] parent;
Map<Integer, Integer> map = new HashMap<>();
TreeSet<Integer> set = new TreeSet<>();
public void call(InputReader in, PrintWriter out) {
int n, d, a, b, ans, c = 0;
n = in.nextInt();
d = in.nextInt();
parent = new int[n + 1];
Arrays.fill(parent, - 1);
for (int i = 0; i < d; i++) {
a = in.nextInt();
b = in.nextInt();
if(!union(a, b)){
c++;
}
a = 0;
ans = 0;
for(Integer j : set){
for(int k = 0; k < map.get(j); k++) {
ans += Math.abs(j);
a++;
if (a == c + 1) {
break;
}
}
if (a == c + 1) {
break;
}
}
if(a!=c+1) {
out.println(ans + c - a);
}
else{
out.println(ans - 1);
}
}
}
public boolean union(int a, int b){
int a1 = find(a);
int b1 = find(b);
int c, d;
if(a1!=b1){
if(Math.abs(a1) > Math.abs(b1)){
c = parent[b1];
d = parent[a1];
parent[b1] = a1;
parent[a1] += c;
set.add(parent[a1]);
map.put(parent[a1], map.getOrDefault(parent[a1], 0)+1);
}
else{
c = parent[a1];
d = parent[b1];
parent[a1] = b1;
parent[b1] += c;
set.add(parent[b1]);
map.put(parent[b1], map.getOrDefault(parent[b1], 0)+1);
}
if(map.containsKey(c)){
map.put(c, map.get(c) - 1);
if(map.get(c)<=0){
set.remove(c);
}
}
if(map.containsKey(d)){
map.put(d, map.get(d) - 1);
if(map.get(d)<=0){
set.remove(d);
}
}
return true;
}
else{
return false;
}
}
public int find(int a){
if(parent[a] < 0){
return a;
}
return parent[a] = find(parent[a]);
}
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static int lcm(int a, int b)
{
return (a / gcd(a, b)) * b;
}
static class answer implements Comparable<answer>{
int a, b;
public answer(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(answer o) {
return o.b - this.b;
}
}
static class arrayListClass {
ArrayList<Integer> arrayList2 ;
public arrayListClass(ArrayList<Integer> arrayList) {
this.arrayList2 = arrayList;
}
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static void sort(long[] a) {
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static final Random random=new Random();
static void shuffleSort(int[] a) {
int n = a.length;
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 2f3d7f94065711a5900a3df40c691d3e | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.*;
import java.util.*;
public class A {
//--------------------------INPUT READER---------------------------------//
static class fs {
public BufferedReader br;
StringTokenizer st = new StringTokenizer("");
public fs() { this(System.in); }
public fs(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
String next() {
while (!st.hasMoreTokens()) {
try { st = new StringTokenizer(br.readLine()); }
catch (IOException e) { e.printStackTrace(); }
}
return st.nextToken();
}
int ni() { return Integer.parseInt(next()); }
long nl() { return Long.parseLong(next()); }
double nd() { return Double.parseDouble(next()); }
String ns() { return next(); }
int[] na(long nn) {
int n = (int) nn;
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
long[] nal(long nn) {
int n = (int) nn;
long[] l = new long[n];
for(int i = 0; i < n; i++) l[i] = nl();
return l;
}
}
//-----------------------------------------------------------------------//
//---------------------------PRINTER-------------------------------------//
static class Printer {
static PrintWriter w;
public Printer() {this(System.out);}
public Printer(OutputStream os) {
w = new PrintWriter(os);
}
public void p(int i) {w.println(i);}
public void p(long l) {w.println(l);}
public void p(double d) {w.println(d);}
public void p(String s) { w.println(s);}
public void pr(int i) {w.print(i);}
public void pr(long l) {w.print(l);}
public void pr(double d) {w.print(d);}
public void pr(String s) { w.print(s);}
public void pl() {w.println();}
public void close() {w.close();}
}
//-----------------------------------------------------------------------//
//--------------------------VARIABLES------------------------------------//
static fs sc = new fs();
static OutputStream outputStream = System.out;
static Printer w = new Printer(outputStream);
static long lma = Long.MAX_VALUE, lmi = Long.MIN_VALUE;
static long ima = Integer.MAX_VALUE, imi = Integer.MIN_VALUE;
static long mod = 1000000007;
//-----------------------------------------------------------------------//
//--------------------------ADMIN_MODE-----------------------------------//
private static void ADMIN_MODE() throws IOException {
if (System.getProperty("ONLINE_JUDGE") == null) {
w = new Printer(new FileOutputStream("output.txt"));
sc = new fs(new FileInputStream("input.txt"));
}
}
//-----------------------------------------------------------------------//
//----------------------------START--------------------------------------//
public static void main(String[] args)
throws IOException {
ADMIN_MODE();
//int t = sc.ni();while(t-->0)
solve();
w.close();
}
static List<List<Integer>> graph;
static int sz;
static void solve() throws IOException {
int n = sc.ni(); int d = sc.ni();
List<Integer> li = new ArrayList<>();
for(int i = 1; i <= n; i++) {
li.add(i);
}
UnionFind<Integer> uf = new UnionFind<>(li);
int ext = 0;
while(d-- > 0) {
int a = sc.ni(), b = sc.ni();
if(uf.connected(a, b)) {
ext++;
}
uf.unify(a,b);
int max = -1;
List<Integer> s = new ArrayList<>();
for(int i = 1; i <= n; i++) {
if(uf.isRoot(i)) {
s.add(uf.componentSize(i));
}
}
s.sort((x,y)->-1*Integer.compare(x,y));
int ans = 0;
for(int i = 0; i <= ext && i < s.size(); i++) {
ans += s.get(i);
}
w.p(ans-1);
}
}
static class UnionFind <T extends Comparable<T>> {
private int size;
private int[] sz;
private int[] id;
private int numComponents;
private Hashtable<T, Integer> ht;
public UnionFind(List<T> list) {
ht = new Hashtable<>(list.size());
for(int i = 0; i < list.size(); i++) ht.put(list.get(i), i);
this.size = numComponents = list.size();
sz = new int[list.size()];
id = new int[list.size()];
for(int i = 0; i < list.size(); i++) {
id[i] = i;
sz[i] = 1;
}
}
public boolean isRoot (T elem) {
int p = ht.get(elem);
return id[p] == p;
}
public int find (T elem) { // with path compression
int p = ht.get(elem);
int root = p;
while(id[root] != root) root = id[root];
while(p != root) {
int next = id[p];
id[p] = root;
p = next;
}
return root;
}
public boolean connected(T p, T q) { return find(p) == find(q); }
public int componentSize(T p) { return sz[find(p)]; }
public int size() { return size; }
public int components() { return numComponents; }
public void unify (T p, T q) {
int root1 = find(p);
int root2 = find(q);
if(root1 == root2) return;
if(sz[root1] < sz[root2]) {
sz[root2] += sz[root1];
id[root1] = root2;
} else {
sz[root1] += sz[root2];
id[root2] = root1;
}
numComponents--;
}
}
// endregion
}
| Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 4dc346b5ffd0756c1fba290001258446 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | /*==========================================================================
* AUTHOR: RonWonWon
* CREATED: 01.12.2021 14:44:14
/*==========================================================================*/
import java.io.*;
import java.util.*;
public class D {
public static void main(String[] args) throws IOException {
int n = in.nextInt(), d = in.nextInt();
int mx = 0;
parent = new int[n+1]; size = new int[n+1];
for(int i=1;i<=n;i++) make(i);
int extra = 0;
for(int i=0;i<d;i++){
int u = in.nextInt(), v = in.nextInt();
if(!union(u,v)) extra++;
int ans = 0;
int sz[] = new int[n+1];
for(int j=0;j<=n;j++) sz[j] = size[j];
ruffleSort(sz);
for(int j=n;j>=n-extra;j--){
ans += sz[j];
}
out.println(ans-1);
}
out.flush();
}
static int parent[], size[];
static void make(int v){
parent[v] = v; size[v] = 1;
}
static int find(int v){
if(parent[v]==v) return v;
else return parent[v] = find(parent[v]);
}
static boolean union(int u, int v){
int a = find(u), b = find(v);
if(a==b) return false;
if(size[a]<size[b]){
a = a+b; b = a-b; a = a-b;
}
parent[b] = a;
size[a] += size[b];
size[b] = 0;
return true;
}
static FastScanner in = new FastScanner();
static PrintWriter out = new PrintWriter(System.out);
static int oo = Integer.MAX_VALUE;
static long ooo = Long.MAX_VALUE;
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
void ini() throws FileNotFoundException {
br = new BufferedReader(new FileReader("input.txt"));
}
String next() {
while(!st.hasMoreTokens())
try { st = new StringTokenizer(br.readLine()); }
catch(IOException e) {}
return st.nextToken();
}
String nextLine(){
try{ return br.readLine(); }
catch(IOException e) { } return "";
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int a[] = new int[n];
for(int i=0;i<n;i++) a[i] = nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
long[] readArrayL(int n) {
long a[] = new long[n];
for(int i=0;i<n;i++) a[i] = nextLong();
return a;
}
double nextDouble() {
return Double.parseDouble(next());
}
double[] readArrayD(int n) {
double a[] = new double[n];
for(int i=0;i<n;i++) a[i] = nextDouble();
return a;
}
}
static final Random random = new Random();
static void ruffleSort(int[] a){
int n = a.length;
for(int i=0;i<n;i++){
int j = random.nextInt(n), temp = a[j];
a[j] = a[i]; a[i] = temp;
}
Arrays.sort(a);
}
static void ruffleSortL(long[] a){
int n = a.length;
for(int i=0;i<n;i++){
int j = random.nextInt(n);
long temp = a[j];
a[j] = a[i]; a[i] = temp;
}
Arrays.sort(a);
}
}
| Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 791f399c1d2113c09479e5002e10aca7 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.beans.DesignMode;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.CompletableFuture.AsynchronousCompletionTask;
import org.xml.sax.ErrorHandler;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.DataInputStream;
public class Solution {
//TEMPLATE -------------------------------------------------------------------------------------
public static boolean Local(){
try{
return System.getenv("LOCAL_SYS")!=null;
}catch(Exception e){
return false;
}
}
public static boolean LOCAL;
static class FastScanner {
BufferedReader br;
StringTokenizer st ;
FastScanner(){
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer("");
}
FastScanner(String file) {
try{
br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
st = new StringTokenizer("");
}catch(FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("file not found");
e.printStackTrace();
}
}
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
String readLine() throws IOException{
return br.readLine();
}
}
static class Pair<T,X> {
T first;
X second;
Pair(T first,X second){
this.first = first;
this.second = second;
}
@Override
public int hashCode(){
return Objects.hash(first,second);
}
@Override
public boolean equals(Object obj){
return obj.hashCode() == this.hashCode();
}
}
static PrintStream debug = null;
static long mod = (long)(Math.pow(10,9) + 7);
//TEMPLATE -------------------------------------------------------------------------------------END//
public static void main(String[] args) throws Exception {
FastScanner s = new FastScanner();
LOCAL = Local();
//PrintWriter pw = new PrintWriter(System.out);
if(LOCAL){
s = new FastScanner("src/input.txt");
PrintStream o = new PrintStream("src/sampleout.txt");
debug = new PrintStream("src/debug.txt");
System.setOut(o);
// pw = new PrintWriter(o);
} long mod = 1000000007;
int tcr = 1;//s.nextInt();
StringBuilder sb = new StringBuilder();
for(int tc=0;tc<tcr;tc++){
int n = s.nextInt();
int d = s.nextInt();
int parent[] = new int[n+1];
int size[] = new int[n+1];
for(int i=0;i<=n;i++){
parent[i] = i;
size[i] = 1;
}
int max = 0;
int extra = 1;
//Arrays.fill(max_s,1);
for(int i=0;i<d;i++){
int v1 = s.nextInt();
int v2 = s.nextInt();
int p1 = find(parent, v1);
int p2 = find(parent, v2);
if(p1 == p2){
extra++;
// sb.append(max-1);
// sb.append('\n');
}else{
if(size[p1] > size[p2]){
size[p1] += size[p2];
parent[p2] = p1;
if(size[p1] > max){
max = size[p1];
}
}else{
size[p2] += size[p1];
parent[p1] = p2;
if(size[p2] > max){
max = size[p2];
}
}
}
int ans = 0;
PriorityQueue<Integer> pq = new PriorityQueue<>();
Set<Integer> included = new HashSet<>();
for(int j=1;j<=n;j++){
int p = find(parent,j);
if(!included.add(p)){
continue;
}
if(pq.size() < extra){
pq.add(size[p]);
}else if(pq.peek() < size[p]){
pq.poll();
pq.add(size[p]);
}
}
while(!pq.isEmpty()){ans+=pq.poll();}
sb.append((ans - 1)+"\n");
}
}
print(sb.toString());
}
public static boolean check(char arr[],int index){
if(index - 2 >=0 && ((arr[index-2]=='a') && (arr[index-1]=='b') && (arr[index]=='c'))){
return true;
}
if((index - 1 >= 0) && (index + 1 < arr.length) && (arr[index-1]=='a') && (arr[index]=='b') && (arr[index+1]=='c')){
return true;
}
if((index + 2 < arr.length) && (arr[index]=='a') && (arr[index+1]=='b') && (arr[index+2] == 'c')){
return true;
}
return false;
}
public static List<int[]> print_prime_factors(int n){
List<int[]> list = new ArrayList<>();
for(int i=2;i<=(int)(Math.sqrt(n));i++){
if(n % i == 0){
int cnt = 0;
while( (n % i) == 0){
n = n/i;
cnt++;
}
list.add(new int[]{i,cnt});
}
}
if(n!=1){
list.add(new int[]{n,1});
}
return list;
}
public static List<int[]> prime_factors(int n,List<Integer> sieve){
List<int[]> list = new ArrayList<>();
int index = 0;
while(n > 1 && sieve.get(index) <= Math.sqrt(n)){
int curr = sieve.get(index);
int cnt = 0;
while((n % curr) == 0){
n = n/curr;
cnt++;
}
if(cnt >= 1){
list.add(new int[]{curr,cnt});
}
index++;
}
if(n > 1){
list.add(new int[]{n,1});
}
return list;
}
public static boolean inRange(int r1,int r2,int val){
return ((val >= r1) && (val <= r2));
}
static int len(long num){
return Long.toString(num).length();
}
static long mulmod(long a, long b,long mod)
{
long ans = 0l;
while(b > 0){
long curr = (b & 1l);
if(curr == 1l){
ans = ((ans % mod) + a) % mod;
}
a = (a + a) % mod;
b = b >> 1;
}
return ans;
}
public static void dbg(PrintStream ps,Object... o) throws Exception{
if(ps == null){
return;
}
Debug.dbg(ps,o);
}
public static long modpow(long num,long pow,long mod){
long val = num;
long ans = 1l;
while(pow > 0l){
long bit = pow & 1l;
if(bit == 1){
ans = (ans * (val%mod))%mod;
}
val = (val * val) % mod;
pow = pow >> 1;
}
return ans;
}
public static char get(int n){
return (char)('a' + n);
}
public static long[] sort(long arr[]){
List<Long> list = new ArrayList<>();
for(long n : arr){list.add(n);}
Collections.sort(list);
for(int i=0;i<arr.length;i++){
arr[i] = list.get(i);
}
return arr;
}
public static int[] sort(int arr[]){
List<Integer> list = new ArrayList<>();
for(int n : arr){list.add(n);}
Collections.sort(list);
for(int i=0;i<arr.length;i++){
arr[i] = list.get(i);
}
return arr;
}
// return the (index + 1)
// where index is the pos of just smaller element
// i.e count of elemets strictly less than num
public static int justSmaller(long arr[],long num){
// System.out.println(num+"@");
int st = 0;
int e = arr.length - 1;
int ans = -1;
while(st <= e){
int mid = (st + e)/2;
if(arr[mid] >= num){
e = mid - 1;
}else{
ans = mid;
st = mid + 1;
}
}
return ans + 1;
}
public static int justSmaller(int arr[],int num){
// System.out.println(num+"@");
int st = 0;
int e = arr.length - 1;
int ans = -1;
while(st <= e){
int mid = (st + e)/2;
if(arr[mid] >= num){
e = mid - 1;
}else{
ans = mid;
st = mid + 1;
}
}
return ans + 1;
}
//return (index of just greater element)
//count of elements smaller than or equal to num
public static int justGreater(long arr[],long num){
int st = 0;
int e = arr.length - 1;
int ans = arr.length;
while(st <= e){
int mid = (st + e)/2;
if(arr[mid] <= num){
st = mid + 1;
}else{
ans = mid;
e = mid - 1;
}
}
return ans;
}
public static int justGreater(int arr[],int num){
int st = 0;
int e = arr.length - 1;
int ans = arr.length;
while(st <= e){
int mid = (st + e)/2;
if(arr[mid] <= num){
st = mid + 1;
}else{
ans = mid;
e = mid - 1;
}
}
return ans;
}
public static void println(Object obj){
System.out.println(obj.toString());
}
public static void print(Object obj){
System.out.print(obj.toString());
}
public static int gcd(int a,int b){
if(b == 0){return a;}
return gcd(b,a%b);
}
public static long gcd(long a,long b){
if(b == 0l){
return a;
}
return gcd(b,a%b);
}
public static int find(int parent[],int v){
if(parent[v] == v){
return v;
}
return parent[v] = find(parent, parent[v]);
}
public static List<Integer> sieve(){
List<Integer> prime = new ArrayList<>();
int arr[] = new int[1000001];
Arrays.fill(arr,1);
arr[1] = 0;
arr[2] = 1;
for(int i=2;i<1000001;i++){
if(arr[i] == 1){
prime.add(i);
for(long j = (i*1l*i);j<1000001;j+=i){
arr[(int)j] = 0;
}
}
}
return prime;
}
static boolean isPower(long n,long a){
long log = (long)(Math.log(n)/Math.log(a));
long power = (long)Math.pow(a,log);
if(power == n){return true;}
return false;
}
private static int mergeAndCount(int[] arr, int l,int m, int r)
{
// Left subarray
int[] left = Arrays.copyOfRange(arr, l, m + 1);
// Right subarray
int[] right = Arrays.copyOfRange(arr, m + 1, r + 1);
int i = 0, j = 0, k = l, swaps = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j])
arr[k++] = left[i++];
else {
arr[k++] = right[j++];
swaps += (m + 1) - (l + i);
}
}
while (i < left.length)
arr[k++] = left[i++];
while (j < right.length)
arr[k++] = right[j++];
return swaps;
}
// Merge sort function
private static int mergeSortAndCount(int[] arr, int l,int r)
{
// Keeps track of the inversion count at a
// particular node of the recursion tree
int count = 0;
if (l < r) {
int m = (l + r) / 2;
// Total inversion count = left subarray count
// + right subarray count + merge count
// Left subarray count
count += mergeSortAndCount(arr, l, m);
// Right subarray count
count += mergeSortAndCount(arr, m + 1, r);
// Merge count
count += mergeAndCount(arr, l, m, r);
}
return count;
}
static class Debug{
//change to System.getProperty("ONLINE_JUDGE")==null; for CodeForces
public static final boolean LOCAL = System.getProperty("ONLINE_JUDGE")==null;
private static <T> String ts(T t) {
if(t==null) {
return "null";
}
try {
return ts((Iterable) t);
}catch(ClassCastException e) {
if(t instanceof int[]) {
String s = Arrays.toString((int[]) t);
return "{"+s.substring(1, s.length()-1)+"}\n";
}else if(t instanceof long[]) {
String s = Arrays.toString((long[]) t);
return "{"+s.substring(1, s.length()-1)+"}\n";
}else if(t instanceof char[]) {
String s = Arrays.toString((char[]) t);
return "{"+s.substring(1, s.length()-1)+"}\n";
}else if(t instanceof double[]) {
String s = Arrays.toString((double[]) t);
return "{"+s.substring(1, s.length()-1)+"}\n";
}else if(t instanceof boolean[]) {
String s = Arrays.toString((boolean[]) t);
return "{"+s.substring(1, s.length()-1)+"}\n";
}
try {
return ts((Object[]) t);
}catch(ClassCastException e1) {
return t.toString();
}
}
}
private static <T> String ts(T[] arr) {
StringBuilder ret = new StringBuilder();
ret.append("{");
boolean first = true;
for(T t: arr) {
if(!first) {
ret.append(", ");
}
first = false;
ret.append(ts(t));
}
ret.append("}");
return ret.toString();
}
private static <T> String ts(Iterable<T> iter) {
StringBuilder ret = new StringBuilder();
ret.append("{");
boolean first = true;
for(T t: iter) {
if(!first) {
ret.append(", ");
}
first = false;
ret.append(ts(t));
}
ret.append("}\n");
return ret.toString();
}
public static void dbg(PrintStream ps,Object... o) throws Exception {
if(LOCAL) {
System.setErr(ps);
System.err.print("Line #"+Thread.currentThread().getStackTrace()[2].getLineNumber()+": [\n");
for(int i = 0; i<o.length; i++) {
if(i!=0) {
System.err.print(", ");
}
System.err.print(ts(o[i]));
}
System.err.println("]");
}
}
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | ffdd67eaa8c4dcf2f3f50a77dbc549fb | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | //package codeforces.deltix_autumn;
import java.io.*;
import java.util.*;
import static java.lang.Math.*;
//Think through the entire logic before jump into coding!
//If you are out of ideas, take a guess! It is better than doing nothing!
//Read both C and D, it is possible that D is easier than C for you!
//Be aware of integer overflow!
//If you find an answer and want to return immediately, don't forget to flush before return!
public class D1 {
static InputReader in;
static PrintWriter out;
public static void main(String[] args) {
//initReaderPrinter(true);
initReaderPrinter(false);
//solve(in.nextInt());
solve(1);
}
static class UnionFind {
int[] id, sz;
UnionFind(int N) {
id = new int[N];
sz = new int[N];
for(int i = 0; i < N; i++) {
id[i] = i;
sz[i] = 1;
}
}
public boolean connected(int p, int q) {
return find(p) == find(q);
}
private int find(int p) {
if(p != id[p]) {
id[p] = find(id[p]);
}
return id[p];
}
public void union(int p, int q) {
int i = find(p);
int j = find(q);
if(i == j) {
return;
}
if(sz[i] < sz[j]) {
id[i] = j;
sz[j] += sz[i];
}
else {
id[j] = i;
sz[i] += sz[j];
}
}
}
static void solve(int testCnt) {
for (int testNumber = 0; testNumber < testCnt; testNumber++) {
int n = in.nextInt(), d = in.nextInt();
int[] x = new int[d], y = new int[d];
for(int i = 0; i < d; i++) {
x[i] = in.nextInt() - 1;
y[i] = in.nextInt() - 1;
}
for(int i = 0; i < d; i++) {
UnionFind uf = new UnionFind(n);
int cycle = 0;
for(int j = 0; j <= i; j++) {
if(uf.connected(x[j], y[j])) {
cycle++;
}
else {
uf.union(x[j], y[j]);
}
}
int[][] copy = new int[n][2];
for(int j = 0; j < n; j++) {
copy[j][0] = uf.id[j];
copy[j][1] = uf.sz[j];
}
Arrays.sort(copy, Comparator.comparingInt(e->-e[1]));
int ans = copy[0][1];
boolean[] used = new boolean[n];
used[copy[0][0]] = true;
for(int j = 1; j < n && cycle > 0; j++) {
int rj = uf.find(copy[j][0]);
if(used[rj]) continue;
ans += uf.sz[rj];
cycle--;
used[rj] = true;
}
out.println(ans - 1);
}
}
out.close();
}
static void initReaderPrinter(boolean test) {
if (test) {
try {
in = new InputReader(new FileInputStream("src/input.in"));
out = new PrintWriter(new FileOutputStream("src/output.out"));
} catch (IOException e) {
e.printStackTrace();
}
} else {
in = new InputReader(System.in);
out = new PrintWriter(System.out);
}
}
static class InputReader {
BufferedReader br;
StringTokenizer st;
InputReader(InputStream stream) {
try {
br = new BufferedReader(new InputStreamReader(stream), 32768);
} catch (Exception e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
Integer[] nextIntArray(int n) {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
int[] nextIntArrayPrimitive(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
int[] nextIntArrayPrimitiveOneIndexed(int n) {
int[] a = new int[n + 1];
for (int i = 1; i <= n; i++) a[i] = nextInt();
return a;
}
Long[] nextLongArray(int n) {
Long[] a = new Long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
long[] nextLongArrayPrimitive(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
long[] nextLongArrayPrimitiveOneIndexed(int n) {
long[] a = new long[n + 1];
for (int i = 1; i <= n; i++) a[i] = nextLong();
return a;
}
String[] nextStringArray(int n) {
String[] g = new String[n];
for (int i = 0; i < n; i++) g[i] = next();
return g;
}
List<Integer>[] readGraphOneIndexed(int n, int m) {
List<Integer>[] adj = new List[n + 1];
for (int i = 0; i <= n; i++) {
adj[i] = new ArrayList<>();
}
for (int i = 0; i < m; i++) {
int u = nextInt();
int v = nextInt();
adj[u].add(v);
adj[v].add(u);
}
return adj;
}
List<Integer>[] readGraphZeroIndexed(int n, int m) {
List<Integer>[] adj = new List[n];
for (int i = 0; i < n; i++) {
adj[i] = new ArrayList<>();
}
for (int i = 0; i < m; i++) {
int u = nextInt() - 1;
int v = nextInt() - 1;
adj[u].add(v);
adj[v].add(u);
}
return adj;
}
/*
A more efficient way of building a graph using int[] instead of ArrayList to store each node's neighboring nodes.
1-indexed.
*/
int[][] buildGraph(int nodeCnt, int edgeCnt) {
int[] end1 = new int[edgeCnt], end2 = new int[edgeCnt];
int[] edgeCntForEachNode = new int[nodeCnt + 1], idxForEachNode = new int[nodeCnt + 1];
for (int i = 0; i < edgeCnt; i++) {
int u = in.nextInt(), v = in.nextInt();
edgeCntForEachNode[u]++;
edgeCntForEachNode[v]++;
end1[i] = u;
end2[i] = v;
}
int[][] adj = new int[nodeCnt + 1][];
for (int i = 1; i <= nodeCnt; i++) {
adj[i] = new int[edgeCntForEachNode[i]];
}
for (int i = 0; i < edgeCnt; i++) {
adj[end1[i]][idxForEachNode[end1[i]]] = end2[i];
idxForEachNode[end1[i]]++;
adj[end2[i]][idxForEachNode[end2[i]]] = end1[i];
idxForEachNode[end2[i]]++;
}
return adj;
}
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 7c237392f2b290372d6a69ab3ad90dee | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | /**
* @author vivek
* programming is thinking, not typing
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class D {
private static void solveTC(int __) {
/* For Google */
// ans.append("Case #").append(__).append(": ");
//code start
int n = scn.nextInt();
int d = scn.nextInt();
ArrayList<HashSet<Integer>> gr = new ArrayList<>();
for (int i = 0; i < n; i++) {
HashSet<Integer> nn = new HashSet<>();
nn.add(i);
gr.add(nn);
}
for (int i = 1; i <= d; i++) {
int a = scn.nextInt() - 1;
int b = scn.nextInt() - 1;
gr = join(gr, a, b);
int left = i;
for (HashSet<Integer> ele : gr) {
left -= (ele.size() - 1);
}
Collections.sort(gr, new Comparator<HashSet<Integer>>() {
@Override
public int compare(HashSet<Integer> o1, HashSet<Integer> o2) {
return o2.size() - o1.size();
}
});
int ans = 0;
for (int j = 0; j <= left; j++) {
ans += gr.get(j).size();
}
print(ans - 1 + "\n");
}
//code end
print("\n");
}
private static ArrayList<HashSet<Integer>> join(ArrayList<HashSet<Integer>> gr, int a, int b) {
int aa = -1, bb = -1;
for (int i = 0; i < gr.size(); i++) {
if (gr.get(i).contains(a)) {
aa = i;
}
if (gr.get(i).contains(b)) {
bb = i;
}
}
if (aa == bb) {
return gr;
} else {
HashSet<Integer> newOne = gr.get(aa);
newOne.addAll(gr.get(bb));
ArrayList<HashSet<Integer>> newGr = new ArrayList<>(gr.size() - 1);
newGr.add(newOne);
for (int i = 0; i < gr.size(); i++) {
if (i != aa && i != bb) {
newGr.add(gr.get(i));
}
}
return newGr;
}
}
public static void main(String[] args) {
scn = new Scanner();
ans = new StringBuilder();
// int t = scn.nextInt();
int t = 1;
// int limit= ;
// sieve(limit);
/*
try {
System.setOut(new PrintStream(new File("file_i_o\\output.txt")));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
*/
for (int i = 1; i <= t; i++) {
solveTC(i);
}
System.out.print(ans);
}
//Stuff for prime start
/**
* sorting algos
*/
private static void sort(int[] arr) {
ArrayList<Integer> li = new ArrayList<>(arr.length);
for (int ele : arr) li.add(ele);
Collections.sort(li);
for (int i = 0; i < li.size(); i++) {
arr[i] = li.get(i);
}
}
private static void sort(long[] arr) {
ArrayList<Long> li = new ArrayList<>(arr.length);
for (long ele : arr) li.add(ele);
Collections.sort(li);
for (int i = 0; i < li.size(); i++) {
arr[i] = li.get(i);
}
}
private static void sort(float[] arr) {
ArrayList<Float> li = new ArrayList<>(arr.length);
for (float ele : arr) li.add(ele);
Collections.sort(li);
for (int i = 0; i < li.size(); i++) {
arr[i] = li.get(i);
}
}
private static void sort(double[] arr) {
ArrayList<Double> li = new ArrayList<>(arr.length);
for (double ele : arr) li.add(ele);
Collections.sort(li);
for (int i = 0; i < li.size(); i++) {
arr[i] = li.get(i);
}
}
/**
* List containing prime numbers <br>
* <b>i<sup>th</sup></b> position contains <b>i<sup>th</sup></b> prime number <br>
* 0th index is <b>null</b>
*/
private static ArrayList<Integer> listOfPrimes;
/**
* query <b>i<sup>th</sup></b> element to get if its prime of not
*/
private static boolean[] isPrime;
/**
* Performs Sieve of Erathosnesis and initialise isPrime array and listOfPrimes list
*
* @param limit the number till which sieve is to be performed
*/
private static void sieve(int limit) {
listOfPrimes = new ArrayList<>();
listOfPrimes.add(null);
boolean[] array = new boolean[limit + 1];
Arrays.fill(array, true);
array[0] = false;
array[1] = false;
for (int i = 2; i <= limit; i++) {
if (array[i]) {
for (int j = i * i; j <= limit; j += i) {
array[j] = false;
}
}
}
isPrime = array;
for (int i = 0; i <= limit; i++) {
if (array[i]) {
listOfPrimes.add(i);
}
}
}
//stuff for prime end
/**
* Calculates the Least Common Multiple of two numbers
*
* @param a First number
* @param b Second Number
* @return Least Common Multiple of <b>a</b> and <b>b</b>
*/
private static long lcm(long a, long b) {
return a * b / gcd(a, b);
}
/**
* Calculates the Greatest Common Divisor of two numbers
*
* @param a First number
* @param b Second Number
* @return Greatest Common Divisor of <b>a</b> and <b>b</b>
*/
private static long gcd(long a, long b) {
return (b == 0) ? a : gcd(b, a % b);
}
static void print(Object obj) {
ans.append(obj.toString());
}
static Scanner scn;
static StringBuilder ans;
//Fast Scanner
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() {
br = new BufferedReader(new
InputStreamReader(System.in));
/*
try {
br = new BufferedReader(new
InputStreamReader(new FileInputStream(new File("file_i_o\\input.txt"))));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
*/
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
Integer[] nextIntegerArray(int n) {
Integer[] array = new Integer[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
return array;
}
long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; i++) {
array[i] = nextLong();
}
return array;
}
String[] nextStringArray() {
return nextLine().split(" ");
}
String[] nextStringArray(int n) {
String[] array = new String[n];
for (int i = 0; i < n; i++) {
array[i] = next();
}
return array;
}
}
}
| Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 936e67d2547512dcd0e4699205f7ca8d | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | /**
* check out my youtube channel sh0rkyboy
* https://tinyurl.com/zdxe2y4z
* I do screencasts, solutions, and other fun stuff in the future
*/
import java.util.*;
import java.io.*;
import static java.lang.Math.min;
import static java.lang.Math.abs;
import static java.lang.Math.max;
public class EdA {
static long[] mods = {1000000007, 998244353, 1000000009};
static long mod = mods[0];
public static MyScanner sc;
public static PrintWriter out;
public static void main(String[] largewang) throws Exception{
// TODO Auto-generated method stub
sc = new MyScanner();
out = new PrintWriter(System.out);
int n = sc.nextInt();
int d = sc.nextInt();
UnionFind uf = new UnionFind(n);
PriorityQueue<Integer> sizes = new PriorityQueue<>();
for(int j = 0;j<d;j++){
int v1 = sc.nextInt();
int v2 = sc.nextInt();
uf.union(v1, v2);
ArrayList<Integer> siz = new ArrayList<>();
for(int k =1;k<=n;k++) {
if (uf.get(k) == k)
siz.add(uf.size[k]);
}
Collections.sort(siz);
Collections.reverse(siz);
int add = uf.numGroups - (n-j-1);
long sum = 0;
for(int k = 0;k<=min(siz.size() - 1, add);k++){
sum += siz.get(k);
}
out.println(min(sum - 1, n-1));
}
out.close();
}
static class UnionFind{
private int[] parent;
private int[] size;
private int numGroups;
private int maxSize;
public UnionFind(int n){
parent = new int[n+1];
size = new int[n+1];
numGroups = n;
for(int j = 1;j<=n;j++){
parent[j] = j;
size[j] = 1;
}
maxSize = 1;
}
public int get(int a){
if (a!= parent[a])
parent[a] = get(parent[a]);
return parent[a];
}
public boolean union(int a, int b){
int p1 = get(a);
int p2 = get(b);
if (p1 == p2)
return false;
if (size[p1] < size[p2]){
parent[p1] = p2;
size[p2]+=size[p1];
}
else{
parent[p2] = p1;
size[p1]+=size[p2];
}
numGroups--;
return true;
}
}
public static void sort(int[] array){
ArrayList<Integer> copy = new ArrayList<>();
for (int i : array)
copy.add(i);
Collections.sort(copy);
for(int i = 0;i<array.length;i++)
array[i] = copy.get(i);
}
static String[] readArrayString(int n){
String[] array = new String[n];
for(int j =0 ;j<n;j++)
array[j] = sc.next();
return array;
}
static int[] readArrayInt(int n){
int[] array = new int[n];
for(int j = 0;j<n;j++)
array[j] = sc.nextInt();
return array;
}
static int[] readArrayInt1(int n){
int[] array = new int[n+1];
for(int j = 1;j<=n;j++){
array[j] = sc.nextInt();
}
return array;
}
static long[] readArrayLong(int n){
long[] array = new long[n];
for(int j =0 ;j<n;j++)
array[j] = sc.nextLong();
return array;
}
static double[] readArrayDouble(int n){
double[] array = new double[n];
for(int j =0 ;j<n;j++)
array[j] = sc.nextDouble();
return array;
}
static int minIndex(int[] array){
int minValue = Integer.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static int minIndex(long[] array){
long minValue = Long.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static int minIndex(double[] array){
double minValue = Double.MAX_VALUE;
int minIndex = -1;
for(int j = 0;j<array.length;j++){
if (array[j] < minValue){
minValue = array[j];
minIndex = j;
}
}
return minIndex;
}
static long power(long x, long y){
if (y == 0)
return 1;
if (y%2 == 1)
return (x*power(x, y-1))%mod;
return power((x*x)%mod, y/2)%mod;
}
static void verdict(boolean a){
out.println(a ? "YES" : "NO");
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try{
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
//StringJoiner sj = new StringJoiner(" ");
//sj.add(strings)
//sj.toString() gives string of those stuff w spaces or whatever that sequence is | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 92d91e8399dfb4a1ff931b444826c432 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes |
import java.io.*;
import java.util.*;
public class Main {
//LinkedList implementation
//all sets are stored
static class DSU1{
int [] rep ;
LinkedList<Integer>[]arr ;
public DSU1(int n){
rep = new int[n];
arr = new LinkedList[n] ;
for(int i=0 ; i <n ;i++){
arr[i] = new LinkedList<>() ;
arr[i].add(i);
rep[i]=i ;
}
}
public int find(int a){
return rep[a] ;
}
public void union(int a, int b){
int x = rep[a];
int y = rep[b];
if(x==y)
return ;
if(arr[x].size()> arr[y].size()){
int tmp = x ;
x = y;
y = tmp;
}
while(!arr[x].isEmpty()){
int e = arr[x].poll();
rep[e]=y;
arr[y].add(e) ;
}
}
public boolean inSameSet(int a, int b){
return find(a)==find(b) ;
}
}
//tree idea and path compression
static class DSU2{
int [] par, size;
int cnt ;
public DSU2(int n){
par = new int[n];
size = new int [n] ;
for(int i=0 ; i<n ; i++){
par[i]=i;
size[i]=1;
}
cnt=1;
}
public int find(int a){
if(a == par[a])
return a ;
return par[a] = find(par[a]) ;
}
public void union(int a, int b){
int x = find(a), y = find(b) ;
if(x == y){
cnt++;
return ;
}
if(size[x]>size[y]){
int tmp = x;
x = y;
y = tmp;
}
par[x] = y;
size[y] += size[x] ;
}
public boolean inSameSet(int a, int b){
return find(a)==find(b) ;
}
public int solve(){
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()) ;
for(int i=0 ; i<size.length ; i++){
if(i==par[i])
pq.add(size[i]) ;
}
int num = 0;
int res = 0;
while(!pq.isEmpty() && num<cnt ){
res += pq.poll() ;
num++;
}
return (res-1);
}
}
//same as DSU2 but using rank instead of size
static class DSU3{
int [] par, rank;
public DSU3(int n){
par = new int[n];
rank = new int [n];
for(int i=0 ; i<n ; i++){
par[i]=i;
rank[i]=1;
}
}
public int find(int a){
if(a == par[a])
return a ;
return par[a] = find(par[a]) ;
}
public void union(int a, int b){
int x = find(a), y = find(b) ;
if(x == y)
return ;
if(rank[x]>=rank[y]){
par[y] = x ;
if(rank[x]==rank[y])
rank[x]++;
}
else{
par[x] = y;
}
}
public boolean inSameSet(int a, int b){
return find(a)==find(b) ;
}
}
public static void doJob() throws Exception{
//select between doJob and doJobT
int n = sc.nextInt();
int d = sc.nextInt();
DSU2 dsu = new DSU2(n);
while(d-- >0 ){
int u=sc.nextInt()-1;
int v=sc.nextInt()-1;
dsu.union(u, v);
pw.println(dsu.solve()) ;
}
}
public static void doJobT() throws Exception{
int t = sc.nextInt() ;
while(t-->0){
doJob() ;
}
}
public static void main(String[] args) throws Exception{
sc = new Scanner(System.in) ;
pw = new PrintWriter(System.out) ;
doJob() ;
//doJobT();
pw.flush();
pw.close();
}
/*-----------------------------------------Helpers--------------------------------------------*/
static Scanner sc;
static PrintWriter pw ;
static class Scanner{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String r) throws Exception {
br = new BufferedReader(new FileReader(new File(r)));
}
public String next() throws IOException{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException{
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if(x.charAt(0) == '-'){
neg = true;
start++;
}
for(int i = start; i < x.length(); i++)
if(x.charAt(i) == '.'){
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
}
else{
sb.append(x.charAt(i));
if(dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg?-1:1);
}
public Long[] nextLongArray(int n) throws IOException {
Long[] a = new Long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
}
//for descending order
static Comparator<PairI> cI = (p1,p2) -> (p1.x==p2.x)?p2.y-p1.y : p2.x-p1.x ;
static Comparator<PairL> cL =
(p1,p2) -> (p1.x==p2.x)? Long.compare(p2.y, p1.y) : Long.compare(p2.x, p1.x) ;
//ascending (by default)
static class PairI implements Comparable<PairI>{
int x;
int y;
public PairI(int xx, int yy){
x = xx;
y = yy;
}
public String toString(){
return "("+x + " " + y +")" ;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PairI other = (PairI) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
@Override
public int compareTo(PairI other) {
// TODO Auto-generated method stub
return (this.x==other.x)? this.y - other.y : this.x - other.x ;
}
}
static class PairL implements Comparable <PairL> {
long x;
long y;
public PairL(long x, long y) {
this.x = x;
this.y = y;
}
public String toString(){
return "("+x + " " + y +")" ;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (x ^ (x >>> 32));
result = prime * result + (int) (y ^ (y >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PairL other = (PairL) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
@Override
public int compareTo(PairL other) {
// TODO Auto-generated method stub
if (this.x == other.x) {
return Long.compare(this.y, other.y);
}
return Long.compare(this.x, other.x);
}
}
}
| Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | bd16b709965c9e8218b18a6d8ec99640 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes |
import java.io.*;
import java.util.*;
public class Main {
//LinkedList implementation
//all sets are stored
static class DSU1{
int [] rep ;
LinkedList<Integer>[]arr ;
public DSU1(int n){
rep = new int[n];
arr = new LinkedList[n] ;
for(int i=0 ; i <n ;i++){
arr[i] = new LinkedList<>() ;
arr[i].add(i);
rep[i]=i ;
}
}
public int find(int a){
return rep[a] ;
}
public void union(int a, int b){
int x = rep[a];
int y = rep[b];
if(x==y)
return ;
if(arr[x].size()> arr[y].size()){
int tmp = x ;
x = y;
y = tmp;
}
while(!arr[x].isEmpty()){
int e = arr[x].poll();
rep[e]=y;
arr[y].add(e) ;
}
}
public boolean inSameSet(int a, int b){
return find(a)==find(b) ;
}
}
//tree idea and path compression
static class DSU2{
int [] par, size;
int cnt ;
public DSU2(int n){
par = new int[n];
size = new int [n] ;
for(int i=0 ; i<n ; i++){
par[i]=i;
size[i]=1;
}
cnt=1;
}
public int find(int a){
if(a == par[a])
return a ;
return par[a] = find(par[a]) ;
}
public void union(int a, int b){
int x = find(a), y = find(b) ;
if(x == y){
cnt++;
return ;
}
if(size[x]>size[y]){
int tmp = x;
x = y;
y = tmp;
}
par[x] = y;
size[y] += size[x] ;
}
public boolean inSameSet(int a, int b){
return find(a)==find(b) ;
}
public int solve(){
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder()) ;
for(int i=0 ; i<size.length ; i++){
if(i==par[i])
pq.add(size[i]) ;
}
int num = 0;
int res = 0;
while(!pq.isEmpty() && num<cnt ){
res += pq.poll() ;
num++;
}
return (res-1);
}
}
//same as DSU2 but using rank instead of size
static class DSU3{
int [] par, rank;
public DSU3(int n){
par = new int[n];
rank = new int [n];
for(int i=0 ; i<n ; i++){
par[i]=i;
rank[i]=1;
}
}
public int find(int a){
if(a == par[a])
return a ;
return par[a] = find(par[a]) ;
}
public void union(int a, int b){
int x = find(a), y = find(b) ;
if(x == y)
return ;
if(rank[x]>=rank[y]){
par[y] = x ;
if(rank[x]==rank[y])
rank[x]++;
}
else{
par[x] = y;
}
}
public boolean inSameSet(int a, int b){
return find(a)==find(b) ;
}
}
public static void doJob() throws Exception{
//select between doJob and doJobT
int n = sc.nextInt();
int d = sc.nextInt();
DSU2 dsu = new DSU2(n);
while(d-- >0 ){
int u=sc.nextInt()-1;
int v=sc.nextInt()-1;
dsu.union(u, v);
pw.println(dsu.solve()) ;
}
}
public static void doJobT() throws Exception{
int t = sc.nextInt() ;
while(t-->0){
doJob() ;
}
}
public static void main(String[] args) throws Exception{
sc = new Scanner(System.in) ;
pw = new PrintWriter(System.out) ;
doJob() ;
//doJobT();
pw.flush();
pw.close();
}
/*-----------------------------------------Helpers--------------------------------------------*/
static Scanner sc;
static PrintWriter pw ;
static class Scanner{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String r) throws Exception {
br = new BufferedReader(new FileReader(new File(r)));
}
public String next() throws IOException{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException{
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if(x.charAt(0) == '-'){
neg = true;
start++;
}
for(int i = start; i < x.length(); i++)
if(x.charAt(i) == '.'){
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
}
else{
sb.append(x.charAt(i));
if(dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg?-1:1);
}
public Long[] nextLongArray(int n) throws IOException {
Long[] a = new Long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
}
//for descending order
static Comparator<PairI> cI = (p1,p2) -> (p1.x==p2.x)?p2.y-p1.y : p2.x-p1.x ;
static Comparator<PairL> cL =
(p1,p2) -> (p1.x==p2.x)? Long.compare(p2.y, p1.y) : Long.compare(p2.x, p1.x) ;
//ascending (by default)
static class PairI implements Comparable<PairI>{
int x;
int y;
public PairI(int xx, int yy){
x = xx;
y = yy;
}
public String toString(){
return "("+x + " " + y +")" ;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PairI other = (PairI) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
@Override
public int compareTo(PairI other) {
// TODO Auto-generated method stub
return (this.x==other.x)? this.y - other.y : this.x - other.x ;
}
}
static class PairL implements Comparable <PairL> {
long x;
long y;
public PairL(long x, long y) {
this.x = x;
this.y = y;
}
public String toString(){
return "("+x + " " + y +")" ;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (x ^ (x >>> 32));
result = prime * result + (int) (y ^ (y >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PairL other = (PairL) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
@Override
public int compareTo(PairL other) {
// TODO Auto-generated method stub
if (this.x == other.x) {
return Long.compare(this.y, other.y);
}
return Long.compare(this.x, other.x);
}
}
}
| Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | a9965b98aa7966e7bb4d2f67aed44575 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | //package kg.my_algorithms.Codeforces;
/*
Control
*/
import java.util.*;
import java.io.*;
public class Solution {
private static final FastReader fr = new FastReader();
public static void main(String[] args) throws IOException {
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
StringBuilder sb = new StringBuilder();
int n = fr.nextInt();
int d = fr.nextInt();
UnionFind unionFind = new UnionFind(n);
int dummyEdges = 0;
for(int q=0;q<d;q++){
int u = fr.nextInt()-1;
int v = fr.nextInt()-1;
if(!unionFind.union(u,v)) dummyEdges++;
List<Integer> list = unionFind.getSizesOfGroups();
list.sort(Collections.reverseOrder());
int res = list.get(0);
for(int de=1;de<=dummyEdges;de++) {
if(de==list.size()) break;
res += list.get(de);
}
sb.append(res-1).append("\n");
}
output.write(sb.toString());
output.flush();
}
}
class UnionFind{
int[] rank;
int[] root;
int[] sizes;
public UnionFind(int n){
this.root = new int[n];
this.rank = new int[n];
this.sizes = new int[n];
for(int i=0;i<n;i++){
root[i] = i;
rank[i] = 1;
sizes[i] = 1;
}
}
public int find(int v){
if(v == root[v]) return v;
return root[v] = find(root[v]);
}
public boolean isConnected(int x, int y){
return find(x) == find(y);
}
public boolean union(int x, int y){
int rootX = find(x);
int rootY = find(y);
if(rootX == rootY) return false;
if(rank[rootX] > rank[rootY]) {
root[rootY] = rootX;
sizes[rootX] += sizes[rootY];
}
else if(rank[rootY] > rank[rootX]) {
root[rootX] = rootY;
sizes[rootY] += sizes[rootX];
}
else{
rank[rootX]++;
root[rootY] = rootX;
sizes[rootX] += sizes[rootY];
}
return true;
}
public boolean onlyOneRoot(){
int root1 = find(0);
for(int i=1;i<root.length;i++) if(root1!=find(i)) return false;
return true;
}
public List<Integer> getSizesOfGroups(){
List<Integer> list = new ArrayList<>();
int[] counter = new int[root.length];
for(int i=0;i<counter.length;i++) counter[find(i)]++;
for(int c: counter) if(c>0) list.add(c);
return list;
}
}
//Fast Input
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
if(st.hasMoreTokens()){
str = st.nextToken("\n");
}
else{
str = br.readLine();
}
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | e67cf2b8933ce0a2356ef2b459838029 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.*;
import java.util.*;
public class SocialNetwork {
public static void solve(FastIO io) {
final int N = io.nextInt();
final int D = io.nextInt();
final int[] X = new int[D];
final int[] Y = new int[D];
for (int i = 0; i < D; ++i) {
X[i] = io.nextInt();
Y[i] = io.nextInt();
}
for (int d = 1; d <= D; ++d) {
io.println(compute(N, X, Y, d));
}
}
private static int compute(int N, int[] X, int[] Y, int D) {
DisjointSetMerge<Integer> djsm = new DisjointSetMerge<>(
N + 1,
1,
new DisjointSetMerge.Merger<Integer>() {
@Override
public Integer merge(Integer a, Integer b) {
return a + b;
}
}
);
CountMap<Integer> cm = new CountMap<>();
cm.increment(1, N);
int extraMerges = 0;
for (int i = 0; i < D; ++i) {
if (djsm.find(X[i]) == djsm.find(Y[i])) {
++extraMerges;
} else {
int xID = djsm.find(X[i]);
int yID = djsm.find(Y[i]);
int xPrev = djsm.getData(xID);
int yPrev = djsm.getData(yID);
cm.increment(xPrev, -1);
cm.increment(yPrev, -1);
djsm.union(X[i], Y[i]);
cm.increment(djsm.getData(X[i]), 1);
}
}
for (int i = 0; i < extraMerges; ++i) {
if (cm.totalCount < 2) {
break;
}
int top = cm.lastKey();
cm.increment(top, -1);
int secondTop = cm.lastKey();
cm.increment(secondTop, -1);
cm.increment(top + secondTop, 1);
}
return cm.lastKey() - 1;
}
public static class CountMap<T> extends TreeMap<T, Long> {
private static final long serialVersionUID = -4936106596428085337L;
public int totalCount;
public long getCount(T k) {
return getOrDefault(k, 0L);
}
public void increment(T k, int v) {
long next = getCount(k) + v;
if (next == 0) {
remove(k);
} else {
put(k, next);
}
totalCount += v;
}
}
public static class DisjointSetMerge<T> {
private int[] rank;
private int[] parent;
private ArrayList<T> data;
private Merger<T> merger;
public DisjointSetMerge(int n, Merger<T> m) {
this(n, null, m);
}
public DisjointSetMerge(int n, T defaultValue, Merger<T> m) {
this.rank = new int[n];
this.parent = new int[n];
this.data = new ArrayList<>();
while (this.data.size() < n) {
this.data.add(defaultValue);
}
this.merger = m;
for (int i = 0; i < n; ++i) {
parent[i] = i;
}
}
public T getData(int x) {
return data.get(find(x));
}
public void setData(int x, T d) {
data.set(find(x), d);
}
public int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
public boolean union(int x, int y) {
int xr = find(x);
int yr = find(y);
if (xr == yr) {
return false;
}
if (rank[xr] < rank[yr]) {
parent[xr] = yr;
} else if (rank[xr] > rank[yr]) {
parent[yr] = xr;
} else {
parent[xr] = yr;
++rank[yr];
}
data.set(find(xr), merger.merge(data.get(xr), data.get(yr)));
return true;
}
public static interface Merger<T> {
public T merge(T a, T b);
}
}
public static class FastIO {
private InputStream reader;
private PrintWriter writer;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastIO(InputStream r, OutputStream w) {
reader = r;
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(w)));
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = reader.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
// TODO: read this byte-by-byte like the other read functions.
public double nextDouble() {
return Double.parseDouble(nextString());
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
public int[] nextIntArray(int n, int off) {
int[] arr = new int[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
return nextLongArray(n, 0);
}
public long[] nextLongArray(int n, int off) {
long[] arr = new long[n + off];
for (int i = 0; i < n; i++) {
arr[i + off] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(arr[i]);
}
}
public void printlnArray(int[] arr) {
printArray(arr);
writer.println();
}
public void printlnArray(long[] arr) {
printArray(arr);
writer.println();
}
public void printf(String format, Object... args) {
print(String.format(format, args));
}
public void flush() {
writer.flush();
}
}
public static void main(String[] args) {
FastIO io = new FastIO(System.in, System.out);
solve(io);
io.flush();
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | ecfcec4539e95ab8ea7d29c703eceff0 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution {
static BufferedReader bf;
static PrintWriter out;
static Scanner sc;
static StringTokenizer st;
static long mod = (long)(1e9+7);
static long mod2 = 998244353;
static long fact[] = new long[1000001];
static long inverse[] = new long[1000001];
public static void main (String[] args)throws IOException {
bf = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
sc = new Scanner(System.in);
// fact[0] = 1;
// inverse[0] = 1;
// for(int i = 1;i<fact.length;i++){
// fact[i] = (fact[i-1] * i)%mod;
// // inverse[i] = binaryExpo(fact[i], mod-2);a
// }
// int t = nextInt();
// while(t-->0){
solve();
// }
}
static boolean ans;
public static void solve() throws IOException{
int n = nextInt();
int d = nextInt();
int[]parent = new int[n+1];
int[]rank = new int[n+1];
int[]comp = new int[n+1];
for(int i = 1;i<=n;i++){
parent[i] = i;
comp[i] = 1;
}
int extra = 0;
for(int i = 0;i<d;i++){
int u = nextInt();
int v = nextInt();
if(findP(u,parent) == findP(v,parent)){
extra++;
}
else{
union(u,v,parent,rank,comp);
}
PriorityQueue<Integer>pq = new PriorityQueue<>((a,b)->(b - a));
for(int j = 1;j<=n;j++){
pq.offer(comp[j]);
}
long sum = pq.poll();
for(int j = 0;j<extra;j++){
sum += pq.poll();
}
out.println(sum - 1);
}
out.flush();
}
public static int findP(int u,int []parent){
if(u == parent[u])return u;
return parent[u] = find(parent[u],parent);
}
public static void union(int u,int v,int[]parent,int []rank,int []comp){
int first = parent[u];
int second = parent[v];
if(rank[first] == rank[second]){
parent[first] = second;
rank[second]++;
comp[second] += comp[first];
comp[first] = 0;
}
else if(rank[first] > rank[second]){
parent[second] = first;
comp[first] += comp[second];
comp[second] = 0;
}
else{
parent[first] = second;
comp[second] += comp[first];
comp[first] = 0;
}
}
public static void h(long a, long b, long x,long A){
if(b <= x && (x - b)%a == 0 && (x <= A)){
ans = true;
return;
}
if(a == 0 || b == 0)return;
// println(x - a);
// println("A " + a);
if(a < b){
long temp = a;
a = b;
b = temp;
}
h(b , a % b ,x,a);
}
public static long nck(int n,int k){
return fact[n] * inverse[n-k] %mod * inverse[k]%mod;
}
public static void plus(int node,int low,int high,int tlow,int thigh,int[]tree){
if(low >= tlow && high <= thigh){
tree[node]++;
return;
}
if(high < tlow || low > thigh)return;
int mid = (low + high)/2;
plus(node*2,low,mid,tlow,thigh,tree);
plus(node*2 + 1 , mid + 1, high,tlow, thigh,tree);
}
public static boolean allEqual(int[]arr,int x){
for(int i = 0;i<arr.length;i++){
if(arr[i] != x)return false;
}
return true;
}
public static long helper(StringBuilder sb){
return Long.parseLong(sb.toString());
}
public static int min(int node,int low,int high,int tlow,int thigh,int[][]tree){
if(low >= tlow&& high <= thigh)return tree[node][0];
if(high < tlow || low > thigh)return Integer.MAX_VALUE;
int mid = (low + high)/2;
// println(low+" "+high+" "+tlow+" "+thigh);
return Math.min(min(node*2,low,mid,tlow,thigh,tree) ,min(node*2+1,mid+1,high,tlow,thigh,tree));
}
public static int max(int node,int low,int high,int tlow,int thigh,int[][]tree){
if(low >= tlow && high <= thigh)return tree[node][1];
if(high < tlow || low > thigh)return Integer.MIN_VALUE;
int mid = (low + high)/2;
return Math.max(max(node*2,low,mid,tlow,thigh,tree) ,max(node*2+1,mid+1,high,tlow,thigh,tree));
}
public static long[] help(List<List<Integer>>list,int[][]range,int cur){
List<Integer>temp = list.get(cur);
if(temp.size() == 0)return new long[]{range[cur][1],1};
long sum = 0;
long count = 0;
for(int i = 0;i<temp.size();i++){
long []arr = help(list,range,temp.get(i));
sum += arr[0];
count += arr[1];
}
if(sum < range[cur][0]){
count++;
sum = range[cur][1];
}
return new long[]{sum,count};
}
public static long findSum(int node,int low, int high,int tlow,int thigh,long[]tree,long mod){
if(low >= tlow && high <= thigh)return tree[node]%mod;
if(low > thigh || high < tlow)return 0;
int mid = (low + high)/2;
return((findSum(node*2,low,mid,tlow,thigh,tree,mod) % mod) + (findSum(node*2+1,mid+1,high,tlow,thigh,tree,mod)))%mod;
}
public static boolean allzero(long[]arr){
for(int i =0 ;i<arr.length;i++){
if(arr[i]!=0)return false;
}
return true;
}
public static long count(long[][]dp,int i,int[]arr,int drank,long sum){
if(i == arr.length)return 0;
if(dp[i][drank]!=-1 && arr[i]+sum >=0)return dp[i][drank];
if(sum + arr[i] >= 0){
long count1 = 1 + count(dp,i+1,arr,drank+1,sum+arr[i]);
long count2 = count(dp,i+1,arr,drank,sum);
return dp[i][drank] = Math.max(count1,count2);
}
return dp[i][drank] = count(dp,i+1,arr,drank,sum);
}
public static void help(int[]arr,char[]signs,int l,int r){
if( l < r){
int mid = (l+r)/2;
help(arr,signs,l,mid);
help(arr,signs,mid+1,r);
merge(arr,signs,l,mid,r);
}
}
public static void merge(int[]arr,char[]signs,int l,int mid,int r){
int n1 = mid - l + 1;
int n2 = r - mid;
int[]a = new int[n1];
int []b = new int[n2];
char[]asigns = new char[n1];
char[]bsigns = new char[n2];
for(int i = 0;i<n1;i++){
a[i] = arr[i+l];
asigns[i] = signs[i+l];
}
for(int i = 0;i<n2;i++){
b[i] = arr[i+mid+1];
bsigns[i] = signs[i+mid+1];
}
int i = 0;
int j = 0;
int k = l;
boolean opp = false;
while(i<n1 && j<n2){
if(a[i] <= b[j]){
arr[k] = a[i];
if(opp){
if(asigns[i] == 'R'){
signs[k] = 'L';
}
else{
signs[k] = 'R';
}
}
else{
signs[k] = asigns[i];
}
i++;
k++;
}
else{
arr[k] = b[j];
int times = n1 - i;
if(times%2 == 1){
if(bsigns[j] == 'R'){
signs[k] = 'L';
}
else{
signs[k] = 'R';
}
}
else{
signs[k] = bsigns[j];
}
j++;
opp = !opp;
k++;
}
}
while(i<n1){
arr[k] = a[i];
if(opp){
if(asigns[i] == 'R'){
signs[k] = 'L';
}
else{
signs[k] = 'R';
}
}
else{
signs[k] = asigns[i];
}
i++;
k++;
}
while(j<n2){
arr[k] = b[j];
signs[k] = bsigns[j];
j++;
k++;
}
}
public static long binaryExpo(long base,long expo){
if(expo == 0)return 1;
long val;
if(expo%2 == 1){
val = (binaryExpo(base, expo-1)*base)%mod;
}
else{
val = binaryExpo(base, expo/2);
val = (val*val)%mod;
}
return (val%mod);
}
public static boolean isSorted(int[]arr){
for(int i =1;i<arr.length;i++){
if(arr[i] < arr[i-1]){
return false;
}
}
return true;
}
//function to find the topological sort of the a DAG
public static boolean hasCycle(int[]indegree,List<List<Integer>>list,int n,List<Integer>topo){
Queue<Integer>q = new LinkedList<>();
for(int i =1;i<indegree.length;i++){
if(indegree[i] == 0){
q.add(i);
topo.add(i);
}
}
while(!q.isEmpty()){
int cur = q.poll();
List<Integer>l = list.get(cur);
for(int i = 0;i<l.size();i++){
indegree[l.get(i)]--;
if(indegree[l.get(i)] == 0){
q.add(l.get(i));
topo.add(l.get(i));
}
}
}
if(topo.size() == n)return false;
return true;
}
// function to find the parent of any given node with path compression in DSU
public static int find(int val,int[]parent){
if(val == parent[val])return val;
return parent[val] = find(parent[val],parent);
}
// function to connect two components
public static void union(int[]rank,int[]parent,int u,int v){
int a = find(u,parent);
int b= find(v,parent);
if(a == b)return;
if(rank[a] == rank[b]){
parent[b] = a;
rank[a]++;
}
else{
if(rank[a] > rank[b]){
parent[b] = a;
}
else{
parent[a] = b;
}
}
}
//
public static int findN(int n){
int num = 1;
while(num < n){
num *=2;
}
return num;
}
// code for input
public static void print(String s ){
System.out.print(s);
}
public static void print(int num ){
System.out.print(num);
}
public static void print(long num ){
System.out.print(num);
}
public static void println(String s){
System.out.println(s);
}
public static void println(int num){
System.out.println(num);
}
public static void println(long num){
System.out.println(num);
}
public static void println(){
System.out.println();
}
public static int Int(String s){
return Integer.parseInt(s);
}
public static long Long(String s){
return Long.parseLong(s);
}
public static String[] nextStringArray()throws IOException{
return bf.readLine().split(" ");
}
public static String nextString()throws IOException{
return bf.readLine();
}
public static long[] nextLongArray(int n)throws IOException{
String[]str = bf.readLine().split(" ");
long[]arr = new long[n];
for(int i =0;i<n;i++){
arr[i] = Long.parseLong(str[i]);
}
return arr;
}
public static int[][] newIntMatrix(int r,int c)throws IOException{
int[][]arr = new int[r][c];
for(int i =0;i<r;i++){
String[]str = bf.readLine().split(" ");
for(int j =0;j<c;j++){
arr[i][j] = Integer.parseInt(str[j]);
}
}
return arr;
}
public static long[][] newLongMatrix(int r,int c)throws IOException{
long[][]arr = new long[r][c];
for(int i =0;i<r;i++){
String[]str = bf.readLine().split(" ");
for(int j =0;j<c;j++){
arr[i][j] = Long.parseLong(str[j]);
}
}
return arr;
}
static class pair{
int one;
int two;
pair(int one,int two){
this.one = one ;
this.two =two;
}
}
public static long gcd(long a,long b){
if(b == 0)return a;
return gcd(b,a%b);
}
public static long lcm(long a,long b){
return (a*b)/(gcd(a,b));
}
public static boolean isPalindrome(String s){
int i = 0;
int j = s.length()-1;
while(i<=j){
if(s.charAt(i) != s.charAt(j)){
return false;
}
i++;
j--;
}
return true;
}
// these functions are to calculate the number of smaller elements after self
public static void sort(int[]arr,int l,int r){
if(l < r){
int mid = (l+r)/2;
sort(arr,l,mid);
sort(arr,mid+1,r);
smallerNumberAfterSelf(arr, l, mid, r);
}
}
public static void smallerNumberAfterSelf(int[]arr,int l,int mid,int r){
int n1 = mid - l +1;
int n2 = r - mid;
int []a = new int[n1];
int[]b = new int[n2];
for(int i = 0;i<n1;i++){
a[i] = arr[l+i];
}
for(int i =0;i<n2;i++){
b[i] = arr[mid+i+1];
}
int i = 0;
int j =0;
int k = l;
while(i<n1 && j < n2){
if(a[i] < b[j]){
arr[k++] = a[i++];
}
else{
arr[k++] = b[j++];
}
}
while(i<n1){
arr[k++] = a[i++];
}
while(j<n2){
arr[k++] = b[j++];
}
}
public static String next(){
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(bf.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
static int nextInt() {
return Integer.parseInt(next());
}
static long nextLong() {
return Long.parseLong(next());
}
static double nextDouble() {
return Double.parseDouble(next());
}
static String nextLine(){
String str = "";
try {
str = bf.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
// use some math tricks it might help
// sometimes just try to think in straightforward plan in A and B problems don't always complecate the questions with thinking too much differently
// always use long number to do 10^9+7 modulo
// if a problem is related to binary string it could also be related to parenthesis
// *****try to use binary search(it is a very beautiful thing it can work in some of the very unexpected problems ) in the question it might work******
// try sorting
// try to think in opposite direction of question it might work in your way
// if a problem is related to maths try to relate some of the continuous subarray with variables like - > a+b+c+d or a,b,c,d in general
// if the question is to much related to left and/or right side of any element in an array then try monotonic stack it could work.
// in range query sums try to do binary search it could work
// analyse the time complexity of program thoroughly
// anylyse the test cases properly
// if we divide any number by 2 till it gets 1 then there will be (number - 1) operation required
// try to do the opposite operation of what is given in the problem
//think about the base cases properly
//If a question is related to numbers try prime factorisation or something related to number theory
// keep in mind unique strings
//you can calculate the number of inversion in O(n log n)
// in a matrix you could sometimes think about row and cols indenpendentaly.
// Try to think in more constructive(means a way to look through various cases of a problem) way.
// observe the problem carefully the answer could be hidden in the given test cases itself. (A, B , C);
// when we have equations like (a+b = N) and we have to find the max of (a*b) then the values near to the N/2 must be chosen as (a and b);
// give emphasis to the number of occurences of elements it might help.
// if a number is even then we can find the pair for each and every number in that range whose bitwise AND is zero.
// if a you find a problem related to the graph make a graph | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 01aa95643d41d185bd910fcebe9459a5 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.*;
import java.util.*;
public class SocialNetwork{
static long mod = 1000000007L;
static MyScanner sc = new MyScanner();
static class Dsu{
int parent[];
int n;
Dsu(int n){
this.n = n;
parent = new int[n];
for(int i = 0;i<n;i++) parent[i] = i;
}
int find(int a){
if(a==parent[a]) return a;
else return find(parent[a]);
}
void union(int a,int b){
int x = find(a);
int y = find(b);
if(x!=y) parent[y] = x;
}
}
static void solve() {
int n = sc.nextInt();
Dsu dsu = new Dsu(n);
int m = sc.nextInt();
int size[] = new int[n];
Arrays.fill(size,1);
int extra = 0;
for(int i = 0;i<m;i++){
int a = sc.nextInt()-1;
int b = sc.nextInt()-1;
if(dsu.find(a)==dsu.find(b)){
extra++;
}else{
int c = size[dsu.find(a)] + size[dsu.find(b)];
dsu.union(a,b);
size[dsu.find(a)] = c;
}
ArrayList<Integer> ar = new ArrayList<>();
boolean vis[] = new boolean[n];
for(int j = 0;j<n;j++){
if(!vis[dsu.find(j)]){
vis[dsu.find(j)] = true;
ar.add(size[dsu.find(j)]);
}
}
Collections.sort(ar);
Collections.reverse(ar);
long ans = 0;
for(int j = 0;j<ar.size() && j<extra+1;j++){
ans += ar.get(j);
}
out.println(ans-1);
}
}
static long comb(int n,int k){
return factorial(n) * pow(factorial(k), mod-2) % mod * pow(factorial(n-k), mod-2) % mod;
}
static long factorial(int n){
long ret = 1;
while(n > 0){
ret = ret * n % mod;
n--;
}
return ret;
}
static class Pair implements Comparable<Pair>{
long a;
long b;
Pair(long aa,long bb){
a = aa;
b = bb;
}
public int compareTo(Pair p){
return Long.compare(this.b,p.b);
}
}
static void reverse(int arr[]){
int i = 0;int j = arr.length-1;
while(i<j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
static long pow(long a, long b) {
if (b == 0) return 1;
long res = pow(a, b / 2);
res = (res * res) % 1_000_000_007;
if (b % 2 == 1) {
res = (res * a) % 1_000_000_007;
}
return res;
}
static int lis(int arr[],int n){
int lis[] = new int[n];
lis[0] = 1;
for(int i = 1;i<n;i++){
lis[i] = 1;
for(int j = 0;j<i;j++){
if(arr[i]>arr[j]){
lis[i] = Math.max(lis[i],lis[j]+1);
}
}
}
int max = Integer.MIN_VALUE;
for(int i = 0;i<n;i++){
max = Math.max(lis[i],max);
}
return max;
}
static boolean isPali(String str){
int i = 0;
int j = str.length()-1;
while(i<j){
if(str.charAt(i)!=str.charAt(j)){
return false;
}
i++;
j--;
}
return true;
}
static long gcd(long a,long b){
if(b==0) return a;
return gcd(b,a%b);
}
static String reverse(String str){
char arr[] = str.toCharArray();
int i = 0;
int j = arr.length-1;
while(i<j){
char temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
String st = new String(arr);
return st;
}
static boolean isprime(int n){
if(n==1) return false;
if(n==3 || n==2) return true;
if(n%2==0 || n%3==0) return false;
for(int i = 5;i*i<=n;i+= 6){
if(n%i== 0 || n%(i+2)==0){
return false;
}
}
return true;
}
public static void main(String[] args) {
out = new PrintWriter(new BufferedOutputStream(System.out));
// int t = sc.nextInt();
int t= 1;
while(t-- >0){
solve();
// solve2();
// solve3();
}
// Stop writing your solution here. -------------------------------------
out.close();
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int[] readIntArray(int n){
int arr[] = new int[n];
for(int i = 0;i<n;i++){
arr[i] = Integer.parseInt(next());
}
return arr;
}
int[] reverse(int arr[]){
int n= arr.length;
int i = 0;
int j = n-1;
while(i<j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
j--;i++;
}
return arr;
}
long[] readLongArray(int n){
long arr[] = new long[n];
for(int i = 0;i<n;i++){
arr[i] = Long.parseLong(next());
}
return arr;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
private static void sort(int[] arr) {
List<Integer> list = new ArrayList<>();
for (int i=0; i<arr.length; i++){
list.add(arr[i]);
}
Collections.sort(list); // collections.sort uses nlogn in backend
for (int i = 0; i < arr.length; i++){
arr[i] = list.get(i);
}
}
private static void sort(long[] arr) {
List<Long> list = new ArrayList<>();
for (int i=0; i<arr.length; i++){
list.add(arr[i]);
}
Collections.sort(list); // collections.sort uses nlogn in backend
for (int i = 0; i < arr.length; i++){
arr[i] = list.get(i);
}
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | f49f412a827169827e520818106f763d | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main{
static Scanner sc = new Scanner(new BufferedInputStream(System.in));
static int sc(){return sc.nextInt();}
static long scl(){return sc.nextLong();}
static double scd(){return sc.nextDouble();};
static String scs(){return sc.next();};
static char scf(){return scs().charAt(0);}
static char[] carr(){return sc.next().toCharArray();};
static char[] chars(){
char[] s = carr();
char[] c = new char[s.length+1];
System.arraycopy(s,0,c,1,s.length);
return c;
}
static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
static void println (Object o) {out.println(o);}
static void println() {out.println();}
static void print(Object o) {out.print(o);}
static int[] dx = new int[]{-1,0,1,0},dy = new int[]{0,-1,0,1};
static final int N = (int)2e6+10,M = 2010,INF = 0x3f3f3f3f,P = 131,MOD = (int)1e9+7;
static int n;
// static int[] h = naew int[N],e = new int[N],ne = new int[N],w = new int[N];
// static int idx;
// static int[] a = new int[N];
static int[] p = new int[N],sum = new int[N];
static Integer[] num = new Integer[N];
static int find(int x){
return x == p[x]?p[x]:(p[x] = find(p[x]));
}
static D[] a = new D[N];
public static void main(String[] args) throws Exception{
n = sc();
int m = sc();
for(int i = 1;i<=n;i++) p[i] = i;
for(int i = 1;i<=m;i++){
for(int j = 1;j<=n;j++){
p[j] = j;
sum[j] = 1;
num[j] = j;
}
int cnt = 0;
a[i] = new D(sc(),sc());
int max = 1;
for(int j = 1;j<=i;j++){
int px = find(a[j].x),py = find(a[j].y);
if(px != py){
sum[py] += sum[px];
p[px] = py;
if(sum[max]<sum[py]) max = py;
}else cnt++;
}
Arrays.sort(num,1,n+1,(o1,o2)->sum[o2]-sum[o1]);
for(int j = 1;j<=n&&cnt>0;j++){
int px = find(num[j]);
if(px == max) continue;
sum[max]+=sum[px];
p[px] = max;
cnt--;
}
println(sum[max]-1);
}
out.close();
}
static class D{
int x,y; D(int x,int y){this.x = x;this.y = y;}
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | c47af13cc76627cb9ec31b62c6c29a5a | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.util.*;
public class SocialNetwork {
static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int n = scanner.nextInt();
int d = scanner.nextInt();
int[] set = new int[n];
TreeMap<Integer, Integer> tm = new TreeMap<>();
tm.put(1, n);
Arrays.fill(set, - 1);
int cnt = 0;
while (d -- > 0) {
int a = scanner.nextInt() - 1;
int b = scanner.nextInt() - 1;
boolean u = union(set, a, b, tm);
if (! u) {
cnt ++;
}
int temp = cnt + 1;
int ret = 0;
for (int k: tm.descendingKeySet()) {
int c = Math.min(tm.get(k), temp);
ret += k * c;
temp -= c;
if (temp == 0) {
break;
}
}
System.out.println(ret - 1);
}
}
static int find(int[] set, int a) {
if (set[a] < 0) {
return a;
}
return (set[a] = find(set, set[a]));
}
static boolean union(int[] set, int a, int b, TreeMap<Integer, Integer> tm) {
int rootA = find(set, a);
int rootB = find(set, b);
if (rootA == rootB) {
return false;
}
rm(tm, -set[rootA]);
rm(tm, -set[rootB]);
add(tm, -(set[rootA] + set[rootB]));
if (set[rootA] < set[rootB]) {
set[rootA] = set[rootA] + set[rootB];
set[rootB] = rootA;
} else {
set[rootB] = set[rootA] + set[rootB];
set[rootA] = rootB;
}
return true;
}
static void add(TreeMap<Integer, Integer> tm, int key) {
tm.put(key, tm.getOrDefault(key, 0) + 1);
}
static void rm(TreeMap<Integer, Integer> tm, int key) {
int o = tm.get(key);
if (o == 1) {
tm.remove(key);
} else {
tm.put(key, o - 1);
}
}
}
| Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | bafe12ba6e7459fd4c3566882ea28107 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | //package com.company;
import java.util.*;
import java.io.*;
public class SocialNetwork {
static boolean[] gT;
static int gC;
static void dfsG(ArrayList<ArrayList<Integer>> connections, int node) {
gT[node] = true; gC++;
for(int i : connections.get(node)) {
if(!gT[i]) {
dfsG(connections, i);
}
}
}
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken()); int d = Integer.parseInt(st.nextToken());
int[][] con = new int[d][2];
for(int i = 0; i < d; i++) {
st = new StringTokenizer(br.readLine());
con[i][0] = Integer.parseInt(st.nextToken()) - 1; con[i][1] = Integer.parseInt(st.nextToken()) - 1;
}
ArrayList<ArrayList<Integer>> connections = new ArrayList<>();
for(int i = 0; i < n; i++) {
connections.add(new ArrayList<>());
}
gT = new boolean[n]; gC = 0;
ArrayList<Integer> gCT = new ArrayList<>();
for(int i = 0; i < d; i++) {
connections.get(con[i][0]).add(con[i][1]);
connections.get(con[i][1]).add(con[i][0]);
int ans = 0; int mC = 0;
Arrays.fill(gT, false); gCT.clear();
for(int j = 0; j < n; j++) {
if(!gT[j]) {
gC = 0;
dfsG(connections, j);
mC += gC - 1; gCT.add(gC);
}
}
Collections.sort(gCT, Collections.reverseOrder());
for(int j = 0; j < i + 2 - mC; j++) {
ans += gCT.get(j);
}
System.out.println(ans - 1);
}
br.close();
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 98d673858df77ec9645fba3559261834 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.*;
import java.util.*;
public class SocialNetwork {
public static PrintWriter out;
public static void main(String[] args)throws IOException{
Scanner sc=new Scanner();
out=new PrintWriter(System.out);
int n=sc.nextInt();
int m=sc.nextInt();
DSU dsu=new DSU(n);
int extra=0;
for(int i=0;i<m;i++) {
int x=sc.nextInt()-1;
int y=sc.nextInt()-1;
if(!dsu.isSameSet(x, y)) {
dsu.union(x, y);
}else {
extra++;
}
int ans=0;
ArrayList<Integer>al=new ArrayList<>();
for(int j=0;j<n;j++) {
if(dsu.find(j)==j) {
al.add(dsu.sizeOfSet(j));
}
}
Collections.sort(al);
for(int j = al.size() - 1; j >= Math.max(al.size() - extra - 1, 0); j--) {
ans += al.get(j);
}
out.println(ans-1);
}
out.close();
}
static class DSU {
int[] parents;
int[] rank;
int[] setSize;
int numSets;
public DSU(int N) {
parents=new int[numSets=N];
rank=new int[N];
setSize=new int[N];
for(int i=0;i<N;i++) {
parents[i]=i;
setSize[i]=1;
}
}
public int find(int i) {
return parents[i] == i ? i : (parents[i] = find(parents[i]));
}
public boolean isSameSet(int i, int j) {
return find(i) == find(j);
}
public void union(int i,int j) {
if (isSameSet(i, j)) {
return;
}
numSets--;
int x=find(i);
int y=find(j);
if(rank[x]>rank[y]) {
parents[y] = x; setSize[x] += setSize[y];
}else {
parents[x] = y; setSize[y] += setSize[x];
if(rank[x] == rank[y]) rank[y]++;
}
}
public int numDisjointSets() {
return numSets;
}
public int sizeOfSet(int i) {
return setSize[find(i)];
}
}
public static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | b237b1f111bcc8ee20e21b77ee9876b9 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | //package AdvancedDSLab;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;
public class Social_Network {
static int INF = (int) 1e9;
static ArrayList<Integer>[] adjList;
public static void main(String[] args) throws IOException {
PrintWriter pw = new PrintWriter(System.out);
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), d = sc.nextInt();
UnionFind dsu = new UnionFind(n);
int postponeEdges = 0;
while(d-- > 0) {
int x = sc.nextInt() - 1, y = sc.nextInt() - 1 ;
if(dsu.isSameSet(x, y))
postponeEdges++;
else
dsu.unionSet(x, y);
ArrayList<Integer> setSizes = new ArrayList<>();
for(int i = 0 ; i < n ; i++)
if(i == dsu.findSet(i))
setSizes.add(dsu.sizeOfSet(i));
Collections.sort(setSizes, Collections.reverseOrder());
int ans = 0;
for(int i = 0 ; i <= postponeEdges ; i++)
ans += setSizes.get(i);
pw.println(ans - 1);
}
pw.flush();
}
static class UnionFind {
int[] p, rank, setSize, max;
int numSets;
public UnionFind(int N)
{
p = new int[numSets = N];
rank = new int[N];
max = new int[N];
setSize = new int[N];
for (int i = 0; i < N; i++) { p[i] = i; setSize[i] = 1; max[i] = i; }
}
public int findSet(int i) { return p[i] == i ? i : (p[i] = findSet(p[i])); }
public boolean isSameSet(int i, int j) { return findSet(i) == findSet(j); }
public void unionSet(int i, int j)
{
if (isSameSet(i, j))
return;
numSets--;
int x = findSet(i), y = findSet(j);
if(rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; max[x] = Math.max(max[x],max[y]); }
else
{ p[x] = y; setSize[y] += setSize[x];
if(rank[x] == rank[y]) rank[y]++;
max[y] = Math.max(max[x], max[y]);
}
}
public int getMax(int i) {
return max[this.findSet(i)];
}
public int numDisjointSets() { return numSets; }
public int sizeOfSet(int i) { return setSize[findSet(i)]; }
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
public static int gcd(int a, int b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
public static void shuffle(int[] a) {
int n = a.length;
for (int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
}
public static long square(long l) {
return l * l;
}
static long nCr(long n, long r) {
long[] dp = new long[(int) (r + 1)];
dp[0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = (int) Math.min(i, r); j > 0; j--)
dp[j] = dp[j] + dp[j - 1];
}
return dp[(int) r];
}
}
| Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 8987a60b307b8b948f9c48e163def08a | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class social_network {
public static void main(String[] agrs)
{
Scanner sc = new Scanner(System.in);
int N = sc.nextInt(), D = sc.nextInt();
int extra = 0;
DSU dsu = new DSU(N);
for(int _i = 0; _i < D; _i++)
{
int a = sc.nextInt(), b = sc.nextInt();
a--; b--;
if(!dsu.union(a, b)) extra++;
int me = 0;
List<Integer> l = new ArrayList<>();
for(int i = 0; i < N; i++)
if(dsu.get(i) == i)
l.add(dsu.size[i]);
Collections.sort(l);
for(int j = l.size() - 1; j >= Math.max(l.size() - extra - 1, 0); j--) me += l.get(j);
System.out.println(me - 1);
}
}
private static class DSU
{
int[] size, p;
int N;
public DSU(int _N)
{
N = _N;
size = new int[N];
p = new int[N];
for(int i = 0; i < N; i++)
{
p[i] = i;
size[i] = 1;
}
}
int get(int u)
{
return p[u] == u ? u :(p[u] = get(p[u]));
}
boolean union(int a, int b)
{
a = get(a);
b = get(b);
if(a == b) return false;
p[a] = b;
size[b] += size[a];
return true;
}
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | e0329e4ddb9c6c12a79c4f6ef46a0d68 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class social_network {
public static void main(String[] agrs)
{
Scanner sc = new Scanner(System.in);
int N = sc.nextInt(), D = sc.nextInt();
int extra = 0;
DSU dsu = new DSU(N);
for(int _i = 0; _i < D; _i++)
{
int a = sc.nextInt(), b = sc.nextInt();
a--; b--;
if(!dsu.union(a, b)) extra++;
int me = 0;
List<Integer> l = new ArrayList<>();
for(int i = 0; i < N; i++)
if(dsu.get(i) == i)
l.add(dsu.size[i]);
Collections.sort(l);
for(int j = l.size() - 1; j >= Math.max(l.size() - extra - 1, 0); j--) me += l.get(j);
System.out.println(me - 1);
}
}
private static class DSU
{
int[] size, p;
int N;
public DSU(int _N)
{
N = _N;
size = new int[N];
p = new int[N];
for(int i = 0; i < N; i++)
{
p[i] = i;
size[i] = 1;
}
}
int get(int u)
{
return p[u] == u ? u :(p[u] = get(p[u]));
}
boolean union(int a, int b)
{
a = get(a);
b = get(b);
if(a == b) return false;
p[a] = b;
size[b] += size[a];
return true;
}
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | c79b08fecf2532e6796923e1155b4419 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[])
{
FastReader input=new FastReader();
PrintWriter out=new PrintWriter(System.out);
int T=1;
while(T-->0)
{
int n=input.nextInt();
int d=input.nextInt();
int b[][]=new int[d][2];
for(int i=0;i<d;i++)
{
b[i][0]=input.nextInt();
b[i][1]=input.nextInt();
int c=0;
int arr[]=new int[n+1];
TreeSet<Pair> set=new TreeSet<>(new Comparator<Pair>() {
@Override
public int compare(Pair o1, Pair o2) {
if(o1.list.size()==o2.list.size())
{
return o1.k-o2.k;
}
else
{
return o2.list.size()-o1.list.size();
}
}
});
Pair a[]=new Pair[n+1];
for(int j=1;j<=n;j++)
{
Pair p=new Pair();
p.k=j;
p.list=new ArrayList<>();
p.list.add(j);
set.add(p);
arr[j]=j;
a[j]=p;
}
for(int l=0;l<=i;l++)
{
int u=b[l][0],v=b[l][1];
if(arr[u]==arr[v])
{
c++;
}
else
{
set.remove(a[arr[u]]);
set.remove(a[arr[v]]);
Pair p1=a[arr[u]];
Pair p2=a[arr[v]];
if(p2.list.size()<=p1.list.size())
{
for(int j=0;j<p2.list.size();j++)
{
int x=p2.list.get(j);
p1.list.add(x);
arr[x]=p1.k;
}
set.add(p1);
}
else
{
for(int j=0;j<p1.list.size();j++)
{
int x=p1.list.get(j);
p2.list.add(x);
arr[x]=p2.k;
}
set.add(p2);
}
}
}
while(set.size()>1 && c>0)
{
Pair p1=set.pollFirst();
Pair p2=set.pollFirst();
if(p2.list.size()<=p1.list.size())
{
for(int j=0;j<p2.list.size();j++)
{
int x=p2.list.get(j);
p1.list.add(x);
arr[x]=p1.k;
}
set.add(p1);
}
else
{
for(int j=0;j<p1.list.size();j++)
{
int x=p1.list.get(j);
p2.list.add(x);
arr[x]=p2.k;
}
set.add(p2);
}
c--;
}
out.println(set.first().list.size()-1);
}
}
out.close();
}
static class Pair
{
int k;
ArrayList<Integer> list;
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str="";
try
{
str=br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | dbdf72e28c358ffe0d484ae04be2e344 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.util.*;
import java.io.*;
public class ferrisWheel {
static PrintWriter pw;
static Scanner sc;
public static void main(String[] args) throws IOException, InterruptedException {
pw = new PrintWriter(System.out);
sc = new Scanner(System.in);
int n = sc.nextInt();
int q=sc.nextInt();
UnionFind dsu=new UnionFind(n);
int penalty=0;
int max=0;
for(int i=0;i<q;i++) {
int u=sc.nextInt(),v=sc.nextInt();
if(dsu.isSameSet(u, v))
penalty++;
else dsu.join(u, v);
int r=0;
TreeMap<Integer, TreeSet<Integer>> tm=dsu.query();
int x=penalty+1;
for(int j=0;j<x;) {
int k=tm.firstKey();
int s=tm.get(k).size();
r+=k*Math.min(s, x-j);
tm.remove(k);
j+=Math.min(s, x-j);
}
pw.println(r-1);
}
pw.flush();
}
static class UnionFind {
int[] parent, size;
int numSets;
int N;
public UnionFind(int n) {
parent = new int[n + 1];
size = new int[n + 1];
numSets=n;
N=n;
for (int i = 1; i <= n; i++) {
size[i] = 1;
parent[i] = i;
}
}
public TreeMap<Integer, TreeSet<Integer>> query(){
TreeMap<Integer,TreeSet<Integer>> r=new TreeMap<>((a,b)->b-a);
for(int i=1;i<=N;i++) {
int s=find(i);
if(r.containsKey(size[s])) {
r.get(size[s]).add(s);
}
else {
TreeSet<Integer> tt=new TreeSet<>();
tt.add(s);
r.put(size[s], tt);
}
}
return r;
}
public int find(int i) {
if (i == parent[i])
return i;
return parent[i] = find(parent[i]);
}
public boolean isSameSet(int x, int y) {
return find(x) == find(y);
}
public void join(int x, int y) {
int a = find(x), b = find(y);
if (a == b)
return;
numSets--;
if (size[a] > size[b]) {
parent[b] = a;
size[a] += size[b];
} else {
parent[a] = b;
size[b] += size[a];
}
}
}
static class pair implements Comparable<pair> {
// long x,y;
int x, y;
public pair(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return x + " " + y;
}
public boolean equals(Object o) {
if (o instanceof pair) {
pair p = (pair) o;
return p.x == x && p.y == y;
}
return false;
}
public int hashCode() {
return new Long(x).hashCode() * 31 + new Long(y).hashCode();
}
public int compareTo(pair other) {
if (this.x == other.x) {
return Long.compare(this.y, other.y);
}
return Long.compare(this.x, other.x);
}
}
static class tuble implements Comparable<tuble> {
int x;
int y;
int z;
public tuble(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public String toString() {
return x + " " + y + " " + z;
}
public int compareTo(tuble other) {
if (this.x == other.x) {
if (this.y == other.y) {
return this.z - other.z;
}
return this.y - other.y;
} else {
return this.x - other.x;
}
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String file) throws IOException {
br = new BufferedReader(new FileReader(file));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String readAllLines(BufferedReader reader) throws IOException {
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
content.append(line);
content.append(System.lineSeparator());
}
return content.toString();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public long[] nextlongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public Long[] nextLongArray(int n) throws IOException {
Long[] a = new Long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 0a652338c873c44d2223232d3c843e96 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
// For fast input output
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
try {
br = new BufferedReader(
new FileReader("input.txt"));
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
} catch (Exception e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
// end of fast i/o code
public static void main(String[] args) {
FastReader reader = new FastReader();
StringBuilder sb = new StringBuilder("");
int n = reader.nextInt();
int d = reader.nextInt();
int ans = 0;
TreeMap<Integer, Integer> tm = new TreeMap<>();
int parent[] = new int[n];
int rank[] = new int[n];
int area[] = new int[n];
for(int i=0; i<n; i++){
parent[i] = i;
area[i] = 1;
}
tm.put(1, n);
int extras = 0;
for(int i=0; i<d; i++){
int x = reader.nextInt()-1;
int y = reader.nextInt()-1;
int par_x = find_par(x, parent);
int par_y = find_par(y, parent);
if(par_x==par_y){
extras++;
}else{
combine(par_x, par_y, parent, rank, tm, area);
}
ans = compute(tm, extras)-1;
sb.append(ans + "\n");
}
System.out.println(sb);
}
static int compute(TreeMap<Integer, Integer> tm, int extras){
int ans = 0;
ArrayList<Integer> arr = new ArrayList<>();
extras++;
int size = 0;
while(extras-- > 0){
int last_key = tm.lastKey();
arr.add(last_key);
size++;
if(tm.get(last_key)==1){
tm.remove(last_key);
}else{
tm.put(last_key, tm.get(last_key)-1);
}
ans += last_key;
}
for(int i=0; i<size; i++){
tm.put(arr.get(i), tm.getOrDefault(arr.get(i), 0)+1);
}
return ans;
}
static void combine(int n1, int n2, int parent[], int rank[], TreeMap<Integer, Integer> tm, int area[]){
// System.out.println(area[n1]+" ,, "+area[n2]+" "+tm.get(area[n1])+" "+tm.get(area[n2]));
if(tm.get(area[n1])==1){
tm.remove(area[n1]);
// System.out.println("remove");
}else{
tm.put(area[n1], tm.get(area[n1])-1);
}
// System.out.println(area[n2]+" ,. "+tm.get(area[n2]));
if(tm.get(area[n2])==1){
tm.remove(area[n2]);
}else{
tm.put(area[n2], tm.get(area[n2])-1);
}
if(rank[n1]>=rank[n2]){
parent[n2] = n1;
rank[n1]++;
area[n1] = area[n1] + area[n2];
tm.put(area[n1], tm.getOrDefault(area[n1], 0)+1);
}else{
parent[n1] = n2;
rank[n2]++;
area[n2] = area[n1] + area[n2];
tm.put(area[n2], tm.getOrDefault(area[n2], 0)+1);
}
}
static int find_par(int node, int parent[]){
if(node==parent[node]){
return node;
}
parent[node] = find_par(parent[node], parent);
return parent[node];
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | c82e619e79faf3a0bcf225c12bf5d4e1 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution {
static class DSU {
private int[] parent;
private int[] size;
private int totalGroup;
public DSU(int n) {
parent = new int[n];
totalGroup = n;
for (int i = 0; i < n; i++) {
parent[i] = i;
}
size = new int[n];
Arrays.fill(size, 1);
}
public boolean union(int a, int b) {
int parentA = findParent(a);
int parentB = findParent(b);
if (parentA == parentB) {
return false;
}
totalGroup--;
if (parentA < parentB) {
this.parent[parentB] = parentA;
this.size[parentA] += this.size[parentB];
} else {
this.parent[parentA] = parentB;
this.size[parentB] += this.size[parentA];
}
return true;
}
public int findParent(int a) {
if (parent[a] != a) {
parent[a] = findParent(parent[a]);
}
return parent[a];
}
public int getGroupSize(int a) {
return this.size[findParent(a)];
}
public int getTotalGroup() {
return totalGroup;
}
}
public static void main(String[] args) throws Exception {
int tc = 1;
for (int i = 0; i < tc; i++) {
solve();
}
io.close();
}
private static void solve() throws Exception {
int n = io.nextInt();
int d = io.nextInt();
DSU dsu = new DSU(n);
int freeLot = 0;
for (int i = 0; i < d; i++) {
int a = io.nextInt() - 1;
int b = io.nextInt() - 1;
if (!dsu.union(a, b)) {
freeLot++;
}
List<Integer> sizes = new ArrayList<>();
for (int j = 0; j < n; j++) {
if (dsu.findParent(j) == j) {
sizes.add(dsu.getGroupSize(j));
}
}
int o = 0;
sizes.sort(Integer::compare);
for (int j = 0; j <= freeLot; j++) {
o += sizes.get(sizes.size() - 1 - j);
}
io.println(o - 1);
}
}
static void sort(int[] a) {
ArrayList<Integer> l = new ArrayList<>(a.length);
for (int i : a) l.add(i);
Collections.sort(l);
for (int i = 0; i < a.length; i++) a[i] = l.get(i);
}
//-----------PrintWriter for faster output---------------------------------
public static FastIO io = new FastIO();
//-----------MyScanner class for faster input----------
static class FastIO extends PrintWriter {
private InputStream stream;
private byte[] buf = new byte[1 << 16];
private int curChar, numChars;
// standard input
public FastIO() {
this(System.in, System.out);
}
public FastIO(InputStream i, OutputStream o) {
super(o);
stream = i;
}
// file input
public FastIO(String i, String o) throws IOException {
super(new FileWriter(o));
stream = new FileInputStream(i);
}
// throws InputMismatchException() if previously detected end of file
private int nextByte() {
if (numChars == -1) throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars == -1) return -1; // end of file
}
return buf[curChar++];
}
// to read in entire lines, replace c <= ' '
// with a function that checks whether c is a line break
public String next() {
int c;
do {
c = nextByte();
} while (c <= ' ');
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = nextByte();
} while (c > ' ');
return res.toString();
}
public String nextLine() {
int c;
do {
c = nextByte();
} while (c < '\n');
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = nextByte();
} while (c > '\n');
return res.toString();
}
public int nextInt() {
int c;
do {
c = nextByte();
} while (c <= ' ');
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nextByte();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10 * res + c - '0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
public long nextLong() {
int c;
do {
c = nextByte();
} while (c <= ' ');
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nextByte();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res = 10 * res + c - '0';
c = nextByte();
} while (c > ' ');
return res * sgn;
}
int[] nextInts(int n) {
int[] data = new int[n];
for (int i = 0; i < n; i++) {
data[i] = io.nextInt();
}
return data;
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
//--------------------------------------------------------
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 017d9ae2d985366e3e09cee70070739f | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | /*
* Everything is Hard
* Before Easy
* Jai Mata Dii
*/
import java.util.*;
import java.io.*;
public class Main {
static class FastReader{ BufferedReader br;StringTokenizer st;public FastReader(){br = new BufferedReader(new InputStreamReader(System.in));}String next(){while (st == null || !st.hasMoreElements()){try{st = new StringTokenizer(br.readLine());}catch (IOException e){e.printStackTrace();}}return st.nextToken();}int nextInt(){ return Integer.parseInt(next());}long nextLong(){return Long.parseLong(next());}double nextDouble(){return Double.parseDouble(next());}String nextLine(){String str = ""; try{str = br.readLine(); } catch (IOException e) {e.printStackTrace();} return str; }}
static long mod = (long)(1e9+7);
// static long mod = 998244353;
// static Scanner sc = new Scanner(System.in);
static FastReader sc = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
static int ans;
public static void main (String[] args) {
int ttt = 1;
// ttt = sc.nextInt();
z :for(int tc=1;tc<=ttt;tc++){
int n = sc.nextInt();
int d = sc.nextInt();
DSU dsu = new DSU(n+3);
int prev = 0;
for(int i=0;i<d;i++) {
int u = sc.nextInt();
int v = sc.nextInt();
boolean is = dsu.findPar(u) == dsu.findPar(v);
dsu.join(u, v);
if(is) prev++;
ArrayList<Integer> a = new ArrayList<>();
for(int j=1;j<=n;j++) {
if(dsu.findPar(j) == j) {
// if(i == 4) System.out.println(j+" "+dsu.size[j]);
a.add(dsu.size[j]);
}
}
Collections.sort(a);
int cans = a.get(a.size()-1)-1;
// if(i == 4) System.out.println(cans);
int cnt = 0;
for(int j=a.size()-2;j>=0&&cnt<prev;j--) {
// if(i == 4) System.out.println(a.get(j));
cans = cans + a.get(j);
cnt++;
}
// if(i == 4) System.out.println(cans);
out.write(cans+"\n");
}
}
out.close();
}
static long pow(long a, long b){long ret = 1;while(b>0){if(b%2 == 0){a = (a*a)%mod;b /= 2;}else{ret = (ret*a)%mod;b--;}}return ret%mod;}
static long gcd(long a,long b){if(b==0) return a; return gcd(b,a%b); }
private static void sort(int[] a) {List<Integer> k = new ArrayList<>();for(int val : a) k.add(val);Collections.sort(k);for(int i=0;i<a.length;i++) a[i] = k.get(i);}
private static void ini(List<Integer>[] tre2){for(int i=0;i<tre2.length;i++){tre2[i] = new ArrayList<>();}}
private static void init(List<int[]>[] tre2){for(int i=0;i<tre2.length;i++){tre2[i] = new ArrayList<>();}}
private static void sort(long[] a) {List<Long> k = new ArrayList<>();for(long val : a) k.add(val);Collections.sort(k);for(int i=0;i<a.length;i++) a[i] = k.get(i);}
}
class DSU {
int par[];
int size[];
int cans;
DSU(int n) {
par = new int[n];
size = new int[n];
Arrays.fill(size, 1);
for(int i=0;i<n;i++) par[i] = i;
cans = 0;
}
int findPar(int x) {
if(x == par[x]) return x;
return par[x] = findPar(par[x]);
}
boolean join(int u,int v) {
int fu = findPar(u);
int fv = findPar(v);
if(fu!=fv) {
if(size[fu]>size[fv]) {
par[fv] = fu;
size[fu] += size[fv];
cans = Math.max(cans, size[fu]);
}
else {
par[fu] = fv;
size[fv] += size[fu];
cans = Math.max(cans, size[fv]);
}
return true;
}
else return false;
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | dee328e1f5594ad732b62e61ea2692ac | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static FastScanner sc = new FastScanner(System.in);
static PrintWriter pw = new PrintWriter(System.out);
static StringBuilder sb = new StringBuilder();
static long mod = (long) 1e9 + 7;
public static void main(String[] args) throws Exception {
solve();
pw.flush();
}
public static void solve() {
int n = sc.nextInt();
int d = sc.nextInt();
DSU dsu = new DSU(n);
int rem = 0;
for(int i = 0; i < d; i++){
int a = sc.nextInt()-1;
int b = sc.nextInt()-1;
if(dsu.same(a,b)){
rem++;
}else{
dsu.merge(a,b);
}
ArrayList<ArrayList<Integer>> map = dsu.groups();
ArrayList<Integer> arr = new ArrayList<>();
for(ArrayList<Integer> m : map) arr.add(m.size());
Collections.sort(arr,Comparator.reverseOrder());
int max = Math.min(rem,arr.size()-1);
int tmp = 0;
for(int j = 0; j <= max; j++){
tmp += arr.get(j);
}
pw.println(tmp-1);
}
}
static class GeekInteger {
public static void save_sort(int[] array) {
shuffle(array);
Arrays.sort(array);
}
public static int[] shuffle(int[] array) {
int n = array.length;
Random random = new Random();
for (int i = 0, j; i < n; i++) {
j = i + random.nextInt(n - i);
int randomElement = array[j];
array[j] = array[i];
array[i] = randomElement;
}
return array;
}
public static void save_sort(long[] array) {
shuffle(array);
Arrays.sort(array);
}
public static long[] shuffle(long[] array) {
int n = array.length;
Random random = new Random();
for (int i = 0, j; i < n; i++) {
j = i + random.nextInt(n - i);
long randomElement = array[j];
array[j] = array[i];
array[i] = randomElement;
}
return array;
}
}
}
class DSU {
private int n;
private int[] parentOrSize;
private java.util.ArrayList<java.util.ArrayList<Integer>> map;
public DSU(int n) {
this.n = n;
this.map = new java.util.ArrayList<java.util.ArrayList<Integer>>();
for (int i = 0; i < n; i++) {
this.map.add(new java.util.ArrayList<Integer>());
this.map.get(i).add(i);
}
this.parentOrSize = new int[n];
java.util.Arrays.fill(parentOrSize, -1);
}
int merge(int a, int b) {
if (!(0 <= a && a < n))
throw new IndexOutOfBoundsException("a=" + a);
if (!(0 <= b && b < n))
throw new IndexOutOfBoundsException("b=" + b);
int x = leader(a);
int y = leader(b);
if (x == y)
return x;
if (-parentOrSize[x] < -parentOrSize[y]) {
int tmp = x;
x = y;
y = tmp;
}
parentOrSize[x] += parentOrSize[y];
parentOrSize[y] = x;
this.map.get(x).addAll(this.map.get(y));
return x;
}
boolean same(int a, int b) {
if (!(0 <= a && a < n))
throw new IndexOutOfBoundsException("a=" + a);
if (!(0 <= b && b < n))
throw new IndexOutOfBoundsException("b=" + b);
return leader(a) == leader(b);
}
int leader(int a) {
if (parentOrSize[a] < 0) {
return a;
} else {
parentOrSize[a] = leader(parentOrSize[a]);
return parentOrSize[a];
}
}
int size(int a) {
if (!(0 <= a && a < n))
throw new IndexOutOfBoundsException("" + a);
return -parentOrSize[leader(a)];
}
java.util.ArrayList<java.util.ArrayList<Integer>> groups() {
int[] leaderBuf = new int[n];
int[] groupSize = new int[n];
for (int i = 0; i < n; i++) {
leaderBuf[i] = leader(i);
groupSize[leaderBuf[i]]++;
}
java.util.ArrayList<java.util.ArrayList<Integer>> result = new java.util.ArrayList<>(n);
for (int i = 0; i < n; i++) {
result.add(new java.util.ArrayList<>(groupSize[i]));
}
for (int i = 0; i < n; i++) {
result.get(leaderBuf[i]).add(i);
}
result.removeIf(java.util.ArrayList::isEmpty);
return result;
}
java.util.ArrayList<Integer> getArray(int n) {
return this.map.get(n);
}
}
class FastScanner {
private BufferedReader reader = null;
private StringTokenizer tokenizer = null;
public FastScanner(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
tokenizer = null;
}
public FastScanner(FileReader in) {
reader = new BufferedReader(in);
tokenizer = null;
}
public String next() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken("\n");
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String[] nextArray(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++)
a[i] = next();
return a;
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
}
| Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 33662ceb625c21ff8f0e0d1825a0829b | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | /*
stream Butter!
eggyHide eggyVengeance
I need U
xiao rerun when
*/
import static java.lang.Math.*;
import java.util.*;
import java.io.*;
import java.math.*;
public class x1609D
{
public static void main(String hi[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
int D = Integer.parseInt(st.nextToken());
StringBuilder sb = new StringBuilder();
DSU union = new DSU(N);
int connections = 0;
for(int d=0; d < D; d++)
{
st = new StringTokenizer(infile.readLine());
int a = Integer.parseInt(st.nextToken())-1;
int b = Integer.parseInt(st.nextToken())-1;
if(union.find(a) != union.find(b))
{
union.merge(a, b);
connections++;
}
int turns = d+1-connections;
ArrayList<Integer> sizes = new ArrayList<Integer>();
for(int i=0; i < N; i++)
if(union.find(i) == i)
sizes.add(union.size[i]);
Collections.sort(sizes);
Collections.reverse(sizes);
int res = sizes.get(0);
for(int i=1; i < sizes.size(); i++)
{
if(turns == 0)
break;
turns--;
res += sizes.get(i);
}
res--;
sb.append(res+"\n");
}
System.out.print(sb);
}
}
class DSU
{
public int[] dsu;
public int[] size;
public DSU(int N)
{
dsu = new int[N+1];
size = new int[N+1];
for(int i=0; i <= N; i++)
{
dsu[i] = i;
size[i] = 1;
}
}
//with path compression, no find by rank
public int find(int x)
{
return dsu[x] == x ? x : (dsu[x] = find(dsu[x]));
}
public void merge(int x, int y)
{
if(x < y)
x = (x+y)-(y=x);
int fx = find(x);
int fy = find(y);
size[fy] += size[fx];
dsu[fx] = fy;
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | d8bb69c366eea0463ef11560107c7731 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes |
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class SocialNetwork {
static int find(int a, int[] par, int[] vis) {
vis[a] = 1;
if (par[a] < 0) {
return a;
}
return par[a] = find(par[a], par, vis);
}
static void union(int a, int b, int[] par, int[] r, int[] vis) {
int a1 = find(a, par, vis);
int b1 = find(b, par, vis);
if (a1 != b1) {
if (r[a1] > r[b1]) {
r[a1] += r[b1];
par[b1] = a1;
} else {
r[b1] += r[a1];
par[a1] = b1;
}
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int d = scan.nextInt();
int[] par = new int[n + 1];
int[] r = new int[n + 1];
for (int i = 0; i <= n; i++) {
par[i] = -1;
r[i] = 1;
}
int ex = 0;
int[] temp = new int[n + 1];
for (int i = 0; i < d; i++) {
int u = scan.nextInt();
int v = scan.nextInt();
if (find(u, par, temp) == find(v, par, temp)) {
++ex;
} else {
union(u, v, par, r, temp);
}
ArrayList<Integer> ar = new ArrayList<Integer>();
for (int j = 1; j <= n; j++) {
if (par[j] == -1) {
ar.add(r[j]);
}
}
Collections.sort(ar, Collections.reverseOrder());
long sum = 0;
for (int j = 0; j < ex + 1; j++) {
sum += ar.get(j);
}
System.out.println(sum - 1);
}
}
}
| Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | e4362e97e89ab6d00b96d21ab2fdc710 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.*;
import java.util.*;
public class a{
public static FastScanner fs;
public static int n,d,rank[],sz[],p[];
public static void main(String args[])
{
fs=new FastScanner();
n=fs.nextInt();
d=fs.nextInt();
rank=new int[n+1];
sz=new int[n+1];
p=new int[n+1];
for(int i=1;i<=n;i++)
{
p[i]=i;
rank[i]=0;
sz[i]=1;
}
int groupmergeoption=0;
for(int i=1;i<=d;i++)
{
int u=fs.nextInt();
int z=fs.nextInt();
if(f(u)!=f(z))
merge(u,z);
else
groupmergeoption++;
ArrayList<Integer>v=new ArrayList<>();
for(int j=1;j<=n;j++)
if(p[j]==j)
v.add(sz[j]);
Collections.sort(v,new Comparator<Integer>(){
@Override
public int compare(Integer a,Integer b)
{
return -a.compareTo(b);
}
});
// for(Integer it:v)
// System.out.print(it+" ");
// System.out.println("");
int tot=0;
for(int j=0;j<=Math.min(v.size()-1,groupmergeoption);j++)
tot += v.get(j);
System.out.println(tot-1);
}
}
public static int f(int x)
{
if(p[x]==x)
return x;
return p[x]=f(p[x]);
}
public static void merge(int x,int y)
{
x=f(x);
y=f(y);
if(rank[x]>rank[y])
{
// System.out.println("rank x greater than y");
p[y]=x;
sz[x] += sz[y];
}
else if(rank[x]<rank[y])
{
p[x]=y;
sz[y] += sz[x];
}
else{
p[y]=x;
sz[x] += sz[y];
rank[x]++;
}
}
static class FastScanner
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next()
{
while(!st.hasMoreTokens())
{
try{
st=new StringTokenizer(br.readLine());
}
catch(Exception e)
{
System.out.println("here");
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 517c049c53ea007ddcd95dc76dda990a | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.*;
import java.math.BigDecimal;
import java.util.*;
public class Main {
private static final int ma = (int) 1e3 + 10;
static int parent[] = new int[ma];
static int value[] = new int[ma];
static Integer a[] = new Integer[ma];
static int find(int x) {
if (x != parent[x])
return parent[x] = find(parent[x]);
return parent[x];
}
static class cmp implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
}
public static void main(String[] args) throws Exception {
initReader();
int n = nextInt();
int m = nextInt();
for (int i = 1; i <= n; i++) {
parent[i] = i;
value[i] = 1;
}
int x, y, fx, fy, ans, cnt = 1;
while (m-- != 0) {
x = nextInt();
y = nextInt();
fx = find(x);
fy = find(y);
if (fx == fy) cnt++;
else {
parent[fx] = fy;
value[fy] += value[fx];
}
int idx = 1;
for (int i = 1; i <= n; i++)
if (parent[i] == i)
a[idx++] = value[i];
Arrays.sort(a, 1, idx,new cmp());
ans=0;
for (int i = 1; i <= cnt; i++)
ans += a[i];
pw.println(ans-1);
}
pw.close();
}
/***************************************************************************************/
static BufferedReader reader;
static StringTokenizer tokenizer;
static PrintWriter pw;
public static void initReader() throws IOException {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = new StringTokenizer("");
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
// 从文件读写
// reader = new BufferedReader(new FileReader("test.in"));
// tokenizer = new StringTokenizer("");
// pw = new PrintWriter(new BufferedWriter(new FileWriter("test1.out")));
}
public static boolean hasNext() {
try {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
} catch (Exception e) {
return false;
}
return true;
}
public static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
public static String nextLine() {
try {
return reader.readLine();
} catch (Exception e) {
return null;
}
}
public static int nextInt() throws IOException {
return Integer.parseInt(next());
}
public static long nextLong() throws IOException {
return Long.parseLong(next());
}
public static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public static char nextChar() throws IOException {
return next().charAt(0);
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 4bb372cac830af90f949f1a7b5ea014b | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.*;
import java.util.*;
public class new1{
public static boolean isConnected(ArrayList<ArrayList<Integer>> aList, int u, int p, int f) {
if(u == f) return true;
boolean ret = false;
for(Integer x : aList.get(u)) {
if(x != p) {
ret = ret || isConnected(aList, x, u, f);
}
}
return ret;
}
public static int count(ArrayList<ArrayList<Integer>> aList, int u, int[] vis) {
vis[u] = 1;
int count = 1;
for(Integer x : aList.get(u)) {
if(vis[x] == 0) {
count = count + count(aList, x, vis);
}
}
return count;
}
public static void main(String[] args) throws IOException{
//long l1 = System.currentTimeMillis();
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
FastReader s = new FastReader();
int t = 1;//s.nextInt();
for(int z = 0; z < t; z++) {
int n = s.nextInt();
int d = s.nextInt();
ArrayList<ArrayList<Integer>> aList= new ArrayList<ArrayList<Integer>>(n + 1);
for(int i = 0; i <= n + 1; i++) {
ArrayList<Integer> a1 = new ArrayList<Integer>();
aList.add(a1);
}
int val = 0;
for(int i = 0; i < d; i++) {
int a = s.nextInt(); int b = s.nextInt();
if(!isConnected(aList, a, -1, b)) {
aList.get(a).add(b);
aList.get(b).add(a);
}
else {
val++;
}
ArrayList<Integer> gret = new ArrayList<Integer>();
int[] vis = new int[n + 1];
for(int j = 1; j <= n ; j++ ) {
if(vis[j] == 0) {
int aa = count(aList, j, vis);
gret.add(aa);
}
}
gret.sort(Collections.reverseOrder());
int sum = 0;
for(int j = 0; j < val + 1; j++) if(j < gret.size())sum = sum + gret.get(j);
System.out.println(sum - 1);
}
}
// output.flush();
}
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 024f1bc11189808b1866e466b174b562 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
/*
Challenge 1: Newbie to CM in 1year (Dec 2021 - Nov 2022) 🔥 5* Codechef
Challenge 2: CM to IM in 1 year (Dec 2022 - Nov 2023) 🔥🔥 6* Codechef
Challenge 3: IM to GM in 1 year (Dec 2023 - Nov 2024) 🔥🔥🔥 7* Codechef
Goal: Become better in CP!
Key: Consistency!
*/
public class Coder {
static StringBuffer str=new StringBuffer();
static int n, d;
static int a[];
static List<int []> q;
static int parent[];
static int rank[];
static int find(int i){
if(parent[i]!=i)
parent[i]=find(parent[i]);
return parent[i];
}
static void union(int u, int v){
if(rank[u] > rank[v]){
u=u+v;
v=u-v;
u=u-v;
}
parent[u]=v;
rank[v]+=rank[u];
}
static class Pair implements Comparable<Pair>{
int f,s;
Pair(){}
Pair(int f, int s){
this.f=f;this.s=s;
}
public int compareTo(Pair p){
if(this.f!=p.f) return this.f-p.f;
return this.s-p.s;
}
}
static void solve(){
List<Pair> com=new ArrayList<>();
int spare=0;
for(int i=0;i<d;i++){
int ans=0;
if(find(q.get(i)[0])!=find(q.get(i)[1])){
union(find(q.get(i)[0]), find(q.get(i)[1]));
}else spare++;
for(int j=1;j<=n;j++){
if(parent[j]==j) com.add(new Pair(rank[j], j));
}
Collections.sort(com);
for(int j=0, k=com.size()-1;k>=0 && j<=spare;j++, k--){
ans+=com.get(k).f;
// union(com.get(j).s, com.get(0).s);
}
str.append(ans-1).append("\n");
com.clear();
}
}
public static void main(String[] args) throws java.lang.Exception {
BufferedReader bf;
PrintWriter pw;
boolean lenv=false;
if(lenv){
bf = new BufferedReader(
new FileReader("input.txt"));
pw=new PrintWriter(new
BufferedWriter(new FileWriter("output.txt")));
}else{
bf = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new OutputStreamWriter(System.out));
}
// int t = Integer.parseInt(bf.readLine().trim());
// while (t-- > 0) {
String s[]=bf.readLine().trim().split("\\s+");
n=Integer.parseInt(s[0]);
d=Integer.parseInt(s[1]);
q=new ArrayList<>();
parent=new int[n+1];
rank=new int[n+1];
for(int i=0;i<d;i++){
s=bf.readLine().trim().split("\\s+");
q.add(new int[]{Integer.parseInt(s[0]), Integer.parseInt(s[1])});
}
for(int i=0;i<=n;i++){parent[i]=i;rank[i]=1;}
solve();
// }
pw.print(str);
pw.flush();
// System.out.print(str);
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 6b5c1a714dfa51270b2f83189cfa6d3e | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
/**
* @author Naitik
*
*/
public class Main
{
static FastReader sc=new FastReader();
static long dp[][][];
//static int v[][];
// static int mod=998244353;;
static int mod=1000000007;
static int max;
static int bit[];
// static int seg[];
//static long fact[];
// static long A[];
// static TreeMap<Integer,Integer> map;
//static StringBuffer sb=new StringBuffer("");
static HashMap<Integer,Integer> map;
static PrintWriter out=new PrintWriter(System.out);
static TreeSet<Long> set=new TreeSet<Long>();
public static void main(String[] args)
{
// StringBuffer sb=new StringBuffer("");
int ttt=1;
// ttt =i();
outer :while (ttt-- > 0)
{
int n=i()+1;
int m=i();
ArrayList<Integer> A[]=new ArrayList[n];
for(int i=0;i<A.length;i++) {
A[i]=new ArrayList<Integer>();
}
int B[][]=new int[n][n];
int C[]=new int[n];
for(int i=0;i<n;i++) {
C[i]=i;
}
boolean v[]=new boolean[n];
int tm=0;
for(int i=0;i<m;i++) {
int a=i();
int b=i();
A[a].add(b);
A[b].add(a);
int p1=find(C, a);
int p2=find(C, b);
if(p1==p2) {
tm++;
}
else {
C[p1]=p2;
}
int ans=1;
Arrays.fill(v, false);
ArrayList<Integer> l=new ArrayList<Integer>();
for(int j=1;j<n;j++) {
max=0;
if(!v[j]) {
dfs(A, j, v);
l.add(max);
}
}
l.sort(null);
int op1=l.get(l.size()-1);
int z=tm;
for(int j=l.size()-2;j>=0 && z>0;j--,z--) {
op1+=l.get(j);
}
ans=max(ans,op1-1);
System.out.println(ans);
}
}
//System.out.println(sb.toString());
out.close();
//CHECK FOR N=1 //CHECK FOR M=0
//CHECK FOR N=1 //CHECK FOR M=0
//CHECK FOR N=1
}
private static void dfs(ArrayList<Integer> [] A, int s, boolean[] v) {
v[s]=true;
max++;
for(int i=0;i<A[s].size();i++) {
int child=A[s].get(i);
if(!v[child]) {
dfs(A, child, v);
}
}
}
static class Pair implements Comparable<Pair>
{
int x;
int y;
int z;
Pair(int x,int y){
this.x=x;
this.y=y;
// this.z=z;
}
@Override
public int compareTo(Pair o) {
if(this.x>o.x)
return -1;
else if(this.x<o.x)
return 1;
else {
if(this.y>o.y)
return 1;
else if(this.y<o.y)
return -1;
else
return 0;
}
}
// public int hashCode()
// {
// final int temp = 14;
// int ans = 1;
// ans =x*31+y*13;
// return ans;
// }
// @Override
// public boolean equals(Object o)
// {
// if (this == o) {
// return true;
// }
// if (o == null) {
// return false;
// }
// if (this.getClass() != o.getClass()) {
// return false;
// }
// Pair other = (Pair)o;
// if (this.x != other.x || this.y!=other.y) {
// return false;
// }
// return true;
// }
//
/* FOR TREE MAP PAIR USE */
// public int compareTo(Pair o) {
// if (x > o.x) {
// return 1;
// }
// if (x < o.x) {
// return -1;
// }
// if (y > o.y) {
// return 1;
// }
// if (y < o.y) {
// return -1;
// }
// return 0;
// }
}
static int find(int A[],int a) {
if(A[a]==a)
return a;
return A[a]=find(A, A[a]);
}
//static int find(int A[],int a) {
// if(A[a]==a)
// return a;
// return find(A, A[a]);
//}
//FENWICK TREE
static void update(int i, int x){
for(; i < bit.length; i += (i&-i))
bit[i] += x;
}
static int sum(int i){
int ans = 0;
for(; i > 0; i -= (i&-i))
ans += bit[i];
return ans;
}
//END
static void add(int v) {
if(!map.containsKey(v)) {
map.put(v, 1);
}
else {
map.put(v, map.get(v)+1);
}
}
static void remove(int v) {
if(map.containsKey(v)) {
map.put(v, map.get(v)-1);
if(map.get(v)==0)
map.remove(v);
}
}
public static int upper(int A[],int k,int si,int ei)
{
int l=si;
int u=ei;
int ans=-1;
while(l<=u) {
int mid=(l+u)/2;
if(A[mid]<=k) {
ans=mid;
l=mid+1;
}
else {
u=mid-1;
}
}
return ans;
}
public static int lower(int A[],int k,int si,int ei)
{
int l=si;
int u=ei;
int ans=-1;
while(l<=u) {
int mid=(l+u)/2;
if(A[mid]<=k) {
l=mid+1;
}
else {
ans=mid;
u=mid-1;
}
}
return ans;
}
static int[] copy(int A[]) {
int B[]=new int[A.length];
for(int i=0;i<A.length;i++) {
B[i]=A[i];
}
return B;
}
static long[] copy(long A[]) {
long B[]=new long[A.length];
for(int i=0;i<A.length;i++) {
B[i]=A[i];
}
return B;
}
static int[] input(int n) {
int A[]=new int[n];
for(int i=0;i<n;i++) {
A[i]=sc.nextInt();
}
return A;
}
static long[] inputL(int n) {
long A[]=new long[n];
for(int i=0;i<n;i++) {
A[i]=sc.nextLong();
}
return A;
}
static String[] inputS(int n) {
String A[]=new String[n];
for(int i=0;i<n;i++) {
A[i]=sc.next();
}
return A;
}
static long sum(int A[]) {
long sum=0;
for(int i : A) {
sum+=i;
}
return sum;
}
static long sum(long A[]) {
long sum=0;
for(long i : A) {
sum+=i;
}
return sum;
}
static void reverse(long A[]) {
int n=A.length;
long B[]=new long[n];
for(int i=0;i<n;i++) {
B[i]=A[n-i-1];
}
for(int i=0;i<n;i++)
A[i]=B[i];
}
static void reverse(int A[]) {
int n=A.length;
int B[]=new int[n];
for(int i=0;i<n;i++) {
B[i]=A[n-i-1];
}
for(int i=0;i<n;i++)
A[i]=B[i];
}
static void input(int A[],int B[]) {
for(int i=0;i<A.length;i++) {
A[i]=sc.nextInt();
B[i]=sc.nextInt();
}
}
static int[][] input(int n,int m){
int A[][]=new int[n][m];
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
A[i][j]=i();
}
}
return A;
}
static char[][] charinput(int n,int m){
char A[][]=new char[n][m];
for(int i=0;i<n;i++) {
String s=s();
for(int j=0;j<m;j++) {
A[i][j]=s.charAt(j);
}
}
return A;
}
static int nextPowerOf2(int n)
{
n--;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n++;
return n;
}
static int highestPowerof2(int x)
{
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x ^ (x >> 1);
}
static long highestPowerof2(long x)
{
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x ^ (x >> 1);
}
static int max(int A[]) {
int max=Integer.MIN_VALUE;
for(int i=0;i<A.length;i++) {
max=Math.max(max, A[i]);
}
return max;
}
static int min(int A[]) {
int min=Integer.MAX_VALUE;
for(int i=0;i<A.length;i++) {
min=Math.min(min, A[i]);
}
return min;
}
static long max(long A[]) {
long max=Long.MIN_VALUE;
for(int i=0;i<A.length;i++) {
max=Math.max(max, A[i]);
}
return max;
}
static long min(long A[]) {
long min=Long.MAX_VALUE;
for(int i=0;i<A.length;i++) {
min=Math.min(min, A[i]);
}
return min;
}
static long [] prefix(long A[]) {
long p[]=new long[A.length];
p[0]=A[0];
for(int i=1;i<A.length;i++)
p[i]=p[i-1]+A[i];
return p;
}
static long [] prefix(int A[]) {
long p[]=new long[A.length];
p[0]=A[0];
for(int i=1;i<A.length;i++)
p[i]=p[i-1]+A[i];
return p;
}
static long [] suffix(long A[]) {
long p[]=new long[A.length];
p[A.length-1]=A[A.length-1];
for(int i=A.length-2;i>=0;i--)
p[i]=p[i+1]+A[i];
return p;
}
static long [] suffix(int A[]) {
long p[]=new long[A.length];
p[A.length-1]=A[A.length-1];
for(int i=A.length-2;i>=0;i--)
p[i]=p[i+1]+A[i];
return p;
}
static void fill(int dp[]) {
Arrays.fill(dp, -1);
}
static void fill(int dp[][]) {
for(int i=0;i<dp.length;i++)
Arrays.fill(dp[i], -1);
}
static void fill(int dp[][][]) {
for(int i=0;i<dp.length;i++) {
for(int j=0;j<dp[0].length;j++) {
Arrays.fill(dp[i][j],-1);
}
}
}
static void fill(int dp[][][][]) {
for(int i=0;i<dp.length;i++) {
for(int j=0;j<dp[0].length;j++) {
for(int k=0;k<dp[0][0].length;k++) {
Arrays.fill(dp[i][j][k],-1);
}
}
}
}
static void fill(long dp[]) {
Arrays.fill(dp, -1);
}
static void fill(long dp[][]) {
for(int i=0;i<dp.length;i++)
Arrays.fill(dp[i], -1);
}
static void fill(long dp[][][]) {
for(int i=0;i<dp.length;i++) {
for(int j=0;j<dp[0].length;j++) {
Arrays.fill(dp[i][j],-1);
}
}
}
static void fill(long dp[][][][]) {
for(int i=0;i<dp.length;i++) {
for(int j=0;j<dp[0].length;j++) {
for(int k=0;k<dp[0][0].length;k++) {
Arrays.fill(dp[i][j][k],-1);
}
}
}
}
static int min(int a,int b) {
return Math.min(a, b);
}
static int min(int a,int b,int c) {
return Math.min(a, Math.min(b, c));
}
static int min(int a,int b,int c,int d) {
return Math.min(a, Math.min(b, Math.min(c, d)));
}
static int max(int a,int b) {
return Math.max(a, b);
}
static int max(int a,int b,int c) {
return Math.max(a, Math.max(b, c));
}
static int max(int a,int b,int c,int d) {
return Math.max(a, Math.max(b, Math.max(c, d)));
}
static long min(long a,long b) {
return Math.min(a, b);
}
static long min(long a,long b,long c) {
return Math.min(a, Math.min(b, c));
}
static long min(long a,long b,long c,long d) {
return Math.min(a, Math.min(b, Math.min(c, d)));
}
static long max(long a,long b) {
return Math.max(a, b);
}
static long max(long a,long b,long c) {
return Math.max(a, Math.max(b, c));
}
static long max(long a,long b,long c,long d) {
return Math.max(a, Math.max(b, Math.max(c, d)));
}
static long power(long x, long y, long p)
{
if(y==0)
return 1;
if(x==0)
return 0;
long res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static long power(long x, long y)
{
if(y==0)
return 1;
if(x==0)
return 0;
long res = 1;
while (y > 0) {
if (y % 2 == 1)
res = (res * x);
y = y >> 1;
x = (x * x);
}
return res;
}
static void print(int A[]) {
for(int i : A) {
System.out.print(i+" ");
}
System.out.println();
}
static void print(long A[]) {
for(long i : A) {
System.out.print(i+" ");
}
System.out.println();
}
static long mod(long x) {
return ((x%mod + mod)%mod);
}
static String reverse(String s) {
StringBuffer p=new StringBuffer(s);
p.reverse();
return p.toString();
}
static int i() {
return sc.nextInt();
}
static String s() {
return sc.next();
}
static long l() {
return sc.nextLong();
}
static void sort(int[] A){
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i){
int tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
static void sort(long[] A){
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i){
long tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
static String sort(String s) {
Character ch[]=new Character[s.length()];
for(int i=0;i<s.length();i++) {
ch[i]=s.charAt(i);
}
Arrays.sort(ch);
StringBuffer st=new StringBuffer("");
for(int i=0;i<s.length();i++) {
st.append(ch[i]);
}
return st.toString();
}
static HashMap<Integer,Integer> hash(int A[]){
HashMap<Integer,Integer> map=new HashMap<Integer, Integer>();
for(int i : A) {
if(map.containsKey(i)) {
map.put(i, map.get(i)+1);
}
else {
map.put(i, 1);
}
}
return map;
}
static HashMap<Long,Integer> hash(long A[]){
HashMap<Long,Integer> map=new HashMap<Long, Integer>();
for(long i : A) {
if(map.containsKey(i)) {
map.put(i, map.get(i)+1);
}
else {
map.put(i, 1);
}
}
return map;
}
static TreeMap<Integer,Integer> tree(int A[]){
TreeMap<Integer,Integer> map=new TreeMap<Integer, Integer>();
for(int i : A) {
if(map.containsKey(i)) {
map.put(i, map.get(i)+1);
}
else {
map.put(i, 1);
}
}
return map;
}
static TreeMap<Long,Integer> tree(long A[]){
TreeMap<Long,Integer> map=new TreeMap<Long, Integer>();
for(long i : A) {
if(map.containsKey(i)) {
map.put(i, map.get(i)+1);
}
else {
map.put(i, 1);
}
}
return map;
}
static boolean prime(int n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static boolean prime(long n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
| Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 455b5ee76ac7a4e978aacb5143b90dc8 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.*;
import java.util.*;
public class D {
public static void main(String[] args) {
//for (int t = IO.nextInt(), i = 0; i < t; i++)
new SolD().solve();
IO.close();
}
}
class SolD {
int n, d;
int[] par, cnt;
Map<Integer, Integer> hash;
int e;
SolD() {
n = IO.nextInt();
d = IO.nextInt();
par = new int[n+1];
cnt = new int[n+1];
for (int i = 1; i <= n; i++) {
par[i] = i;
cnt[i] = 1;
}
hash = new TreeMap<>((k1, k2) -> Integer.compare(k2, k1));
hash.put(1, n);
}
void solve() {
for (int i = 0; i < d; i++) {
int a = IO.nextInt();
int b = IO.nextInt();
dsu(a, b);
IO.writer.println(calc()-1);
}
}
void dsu(int a, int b) {
int pa = getPar(a), pb = getPar(b);
if (pa == pb) {
e++;
return;
}
par[pb] = pa;
par[b] = pa;
updateHash(cnt[pa]);
updateHash(cnt[pb]);
cnt[pa] += cnt[pb];
hash.put(cnt[pa], hash.getOrDefault(cnt[pa], 0) + 1);
}
void updateHash(int v) {
int c = hash.get(v);
if (c == 1)
hash.remove(v);
else
hash.put(v, c-1);
}
int getPar(int a) {
if (par[a] == a)
return a;
int p = getPar(par[a]);
par[a] = p;
return p;
}
int calc() {
int ans = 0;
List<Integer> lst = new ArrayList<>(hash.keySet());
for (int i = 0, cur = e+1; cur > 0; i++) {
int v = lst.get(i);
int c = Integer.min(hash.get(v), cur);
ans += c * v;
cur -= c;
}
return ans;
}
}
class IO {
static final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
static final PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
private static StringTokenizer tokens;
static String readLine() {
try {
return reader.readLine();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
static void initializeTokens() {
while (null == tokens || !tokens.hasMoreTokens())
tokens = new StringTokenizer(readLine());
}
static String next() {
initializeTokens();
return tokens.nextToken();
}
static String next(String delim) {
initializeTokens();
return tokens.nextToken(delim);
}
static int nextInt() {
return Integer.parseInt(next());
}
static long nextLong() {
return Long.parseLong(next());
}
static void close() {
try {
reader.close();
writer.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 7bf5a1846dd169e306f28d009504cc45 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.util.*;
import java.io.*;
////***************************************************************************
/* public class E_Gardener_and_Tree implements Runnable{
public static void main(String[] args) throws Exception {
new Thread(null, new E_Gardener_and_Tree(), "E_Gardener_and_Tree", 1<<28).start();
}
public void run(){
WRITE YOUR CODE HERE!!!!
JUST WRITE EVERYTHING HERE WHICH YOU WRITE IN MAIN!!!
}
}
*/
/////**************************************************************************
public class D_Social_Network{
public static void main(String[] args) {
FastScanner s= new FastScanner();
//PrintWriter out=new PrintWriter(System.out);
//end of program
//out.println(answer);
//out.close();
StringBuilder res = new StringBuilder();
int n=s.nextInt();
int d=s.nextInt();
long array1[]= new long[d];
long array2[]= new long[d];
for(int i=0;i<d;i++){
long a=s.nextLong();
long b=s.nextLong();
array1[i]=a;
array2[i]=b;
}
for(int i=0;i<d;i++){
//System.out.println("hello");
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>(n+3);
for(int j=0;j<=n;j++){
ArrayList<Integer> obj = new ArrayList<Integer>();
list.add(obj);
}
for(int j=0;j<=i;j++){
list.get((int)array1[j]).add((int)array2[j]);
list.get((int)array2[j]).add((int)array1[j]);
}
long well=0;
int visited[]= new int[n+1];
ArrayList<Long> nice = new ArrayList<Long>();
for(int k=1;k<=n;k++){
if(visited[k]==0){
long count[]= new long[1];
dfs(list,visited,k,count);
// ans=Math.max(ans,(count[0]-1));
// System.out.println(count[0]+" kk");
nice.add(count[0]);
well+=(count[0]-1);
}
}
long remain=(i+1)-well;
Collections.sort(nice,Collections.reverseOrder());
remain++;
long end=Math.min(remain,nice.size());
long ans=0;
for(int k=0;k<end;k++){
ans+=nice.get(k);
}
ans--;
res.append(ans+" \n");
}
System.out.println(res);
}
private static void dfs(ArrayList<ArrayList<Integer>> list, int[] visited, int i, long[] count) {
// System.out.println(i+" i");
count[0]++;
visited[i]=1;
for(int j=0;j<list.get(i).size();j++){
int num=list.get(i).get(j);
if(visited[num]==0){
dfs(list,visited,num,count);
}
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | cc1e388fd742af60ad39c24848bbf6d9 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class social_network {
public static void main(String[] agrs)
{
Scanner sc = new Scanner(System.in);
int N = sc.nextInt(), D = sc.nextInt();
int extra = 0;
DSU dsu = new DSU(N);
for(int _i = 0; _i < D; _i++)
{
int a = sc.nextInt(), b = sc.nextInt();
a--; b--;
if(!dsu.union(a, b)) extra++;
int me = 0;
List<Integer> l = new ArrayList<>();
for(int i = 0; i < N; i++)
if(dsu.get(i) == i)
l.add(dsu.size[i]);
Collections.sort(l);
for(int j = l.size() - 1; j >= Math.max(l.size() - extra - 1, 0); j--) me += l.get(j);
System.out.println(me - 1);
}
}
private static class DSU
{
int[] size, p;
int N;
public DSU(int _N)
{
N = _N;
size = new int[N];
p = new int[N];
for(int i = 0; i < N; i++)
{
p[i] = i;
size[i] = 1;
}
}
int get(int u)
{
return p[u] == u ? u :(p[u] = get(p[u]));
}
boolean union(int a, int b)
{
a = get(a);
b = get(b);
if(a == b) return false;
p[a] = b;
size[b] += size[a];
return true;
}
}
}
| Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | aad6f2c0ebd7e0ff8953d8246a6bdb2e | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes |
import java.io.*;
import java.util.*;
public class D {
public static void main(String[] hi) {
FastIO io = new FastIO();
int n = io.nextInt(), q = io.nextInt();
DSU dsu = new DSU(n);
int extra = 0;
while (q --> 0) {
int x = io.nextInt()-1, y = io.nextInt()-1;
int a = dsu.get(x), b = dsu.get(y);
int answer = 0;
if (a != b) {
dsu.merge(a,b);
}
else {
extra++;
}
DSU dsu2 = new DSU(n, dsu.parent, dsu.rank, dsu.size);
for (int k=0; k<extra; k++) {
int max1 = 0, max2 = 0, in1 = 0, in2 = 0;
for (int i=0; i<n; i++) {
if (dsu2.size[i] > max1) {
max2 = max1;
in2 = in1;
max1 = dsu2.size[i];
in1 = i;
}
else if (dsu2.size[i] > max2) {
max2 = dsu2.size[i];
in2 = i;
}
}
dsu2.merge(in1, in2);
}
for (int i=0; i<n; i++) {
answer = Math.max(answer, dsu2.size[i]);
}
io.println(answer-1);
}
io.close();
}
static class FastIO extends PrintWriter {
BufferedReader br;
StringTokenizer st;
public FastIO() {
super(System.out);
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next() {
try {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
catch (Exception e) {
return null;
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public void close() {
try {
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
super.close();
}
}
}
class DSU {
int[] rank, parent, size;
int n;
public DSU(int n) {
this.n = n;
rank = new int[n];
parent = new int[n];
size = new int[n];
for (int i=0; i<n; i++) {
parent[i] = i;
size[i]++;
}
}
public DSU(int n, int[] p, int[] r, int[] s) {
rank = new int[n];
parent = new int[n];
size = new int[n];
for (int i=0; i<n; i++) {
rank[i] = r[i];
parent[i] = p[i];
size[i] = s[i];
}
}
int get(int x) {
if (parent[x] != x) {
parent[x] = get(parent[x]); //path compression
return parent[x];
}
else {
return x;
}
}
void merge(int x, int y) {
int a = get(x), b = get(y);
if (a == b) {
return;
}
if (rank[a] < rank[b]) {
parent[a] = b;
size[b] += size[a];
size[a] = 0;
}
else if (rank[b] > rank[a]) {
parent[b] = a;
size[a] += size[b];
size[b] = 0;
}
else {
parent[a] = b;
rank[b]++;
size[b] += size[a];
size[a] = 0;
}
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 968b838021fb1b34aca8712952bb7ff3 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static long startTime = System.currentTimeMillis();
// for global initializations and methods starts here
static class DSU {
int[] rank, parent, node;
int n, count, size;
public DSU(int n) {
rank = new int[n];
parent = new int[n];
node = new int[n];
this.n = n;
count = 0;
size = n;
makeSet();
}
void makeSet() {
for (int i = 0; i < n; i++) {
parent[i] = i;
rank[i] = 1;
node[i] = 0;
}
}
int find(int x) {
if (x == parent[x]) return x;
return parent[x] = find(parent[x]);
}
void union(int x, int y) {
int a = find(x);
int b = find(y);
if (a == b) count++;
else {
if (rank[a] < rank[b]) {
a ^= b;
b ^= a;
a ^= b;
}
parent[b] = a;
rank[a] += rank[b];
node[a] += node[b];
}
node[a]++;
}
}
// global initialisations and methods end here
static void run() {
boolean tc = false;
AdityaFastIO r = new AdityaFastIO();
//FastReader r = new FastReader();
try (OutputStream out = new BufferedOutputStream(System.out)) {
//long startTime = System.currentTimeMillis();
int testcases = tc ? r.ni() : 1;
int tcCounter = 1;
// Hold Here Sparky------------------->>>
// Solution Starts Here
start:
while (testcases-- > 0) {
int n = r.ni();
int d = r.ni();
int[] x = new int[n];
int[] y = new int[n];
for (int i = 0; i < d; i++) {
x[i] = r.ni() - 1;
y[i] = r.ni() - 1;
}
for (int i = 0; i < d; i++) {
DSU dsu = new DSU(n);
for (int j = 0; j <= i; j++) {
dsu.union(x[j], y[j]);
}
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
for (int j = 0; j < dsu.size; j++) {
if (j == dsu.parent[j]) {
pq.add(dsu.rank[j]);
}
}
while (pq.size() > 1 && dsu.count > 0) {
int a = pq.poll();
int b = pq.poll();
pq.add(a + b);
dsu.count--;
}
//out.write((pq.size() + " ").getBytes());
out.write((pq.peek() - 1 + " ").getBytes());
out.write(("\n").getBytes());
}
}
// Solution Ends Here
} catch (IOException e) {
e.printStackTrace();
}
}
static class AdityaFastIO {
final private int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
public BufferedReader br;
public StringTokenizer st;
public AdityaFastIO() {
br = new BufferedReader(new InputStreamReader(System.in));
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public AdityaFastIO(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String word() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public String line() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public String readLine() throws IOException {
byte[] buf = new byte[100000001]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int ni() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public long nl() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg) return -ret;
return ret;
}
public double nd() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') c = read();
boolean neg = (c == '-');
if (neg) c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') while ((c = read()) >= '0' && c <= '9') ret += (c - '0') / (div *= 10);
if (neg) return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null) return;
din.close();
}
}
public static void main(String[] args) throws Exception {
run();
}
static long mod = 998244353;
static long modInv(long base, long e) {
long result = 1;
base %= mod;
while (e > 0) {
if ((e & 1) > 0) result = result * base % mod;
base = base * base % mod;
e >>= 1;
}
return result;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String word() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
String line() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int ni() {
return Integer.parseInt(word());
}
long nl() {
return Long.parseLong(word());
}
double nd() {
return Double.parseDouble(word());
}
}
static int MOD = (int) (1e9 + 7);
static long powerLL(long x, long n) {
long result = 1;
while (n > 0) {
if (n % 2 == 1) result = result * x % MOD;
n = n / 2;
x = x * x % MOD;
}
return result;
}
static long powerStrings(int i1, int i2) {
String sa = String.valueOf(i1);
String sb = String.valueOf(i2);
long a = 0, b = 0;
for (int i = 0; i < sa.length(); i++) a = (a * 10 + (sa.charAt(i) - '0')) % MOD;
for (int i = 0; i < sb.length(); i++) b = (b * 10 + (sb.charAt(i) - '0')) % (MOD - 1);
return powerLL(a, b);
}
static long gcd(long a, long b) {
if (a == 0) return b;
else return gcd(b % a, a);
}
static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
static long lower_bound(int[] arr, int x) {
int l = -1, r = arr.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (arr[m] >= x) r = m;
else l = m;
}
return r;
}
static int upper_bound(int[] arr, int x) {
int l = -1, r = arr.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (arr[m] <= x) l = m;
else r = m;
}
return l + 1;
}
static void addEdge(ArrayList<ArrayList<Integer>> graph, int edge1, int edge2) {
graph.get(edge1).add(edge2);
graph.get(edge2).add(edge1);
}
public static class Pair implements Comparable<Pair> {
int first;
int second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
public String toString() {
return "(" + first + "," + second + ")";
}
public int compareTo(Pair o) {
// TODO Auto-generated method stub
if (this.first != o.first)
return (int) (this.first - o.first);
else return (int) (this.second - o.second);
}
}
public static class PairC<X, Y> implements Comparable<PairC> {
X first;
Y second;
public PairC(X first, Y second) {
this.first = first;
this.second = second;
}
public String toString() {
return "(" + first + "," + second + ")";
}
public int compareTo(PairC o) {
// TODO Auto-generated method stub
return o.compareTo((PairC) first);
}
}
static boolean isCollectionsSorted(List<Long> list) {
if (list.size() == 0 || list.size() == 1) return true;
for (int i = 1; i < list.size(); i++) if (list.get(i) <= list.get(i - 1)) return false;
return true;
}
static boolean isCollectionsSortedReverseOrder(List<Long> list) {
if (list.size() == 0 || list.size() == 1) return true;
for (int i = 1; i < list.size(); i++) if (list.get(i) >= list.get(i - 1)) return false;
return true;
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | d40701bcfabc39b7c0936c367bf03572 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.util.*;
public class D {
static int find(int v, int[] parent) {
if (parent[v] == v) {
return v;
}
int res = find(parent[v], parent);
parent[v] = res;
return res;
}
static int getSizesSum(PriorityQueue<Integer> q, int count) {
int res = 0;
List<Integer> polled = new LinkedList<>();
for (int i = 0; i < count; i++) {
int size = q.poll();
polled.add(size);
res += size;
}
for (int size : polled) {
q.add(size);
}
return res;
}
public static void main(String[] args) {
PriorityQueue<Integer> sizes = new PriorityQueue<>((o1, o2) -> o2 - o1);
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int d = sc.nextInt();
int[] parent = new int[n];
int[] size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
sizes.add(1);
}
int extra = 0;
for (int i = 0; i < d; i++) {
int x = sc.nextInt() - 1;
int y = sc.nextInt() - 1;
if (find(x, parent) == find(y, parent)) {
extra += 1;
} else {
union(find(x, parent), find(y, parent), parent, size, sizes);
}
System.out.println(getSizesSum(sizes, 1 + extra) - 1);
}
}
private static void union(int par1, int par2, int[] parent, int[] size, PriorityQueue<Integer> sizes) {
int size1 = size[par1];
int size2 = size[par2];
parent[par1] = par2;
size[par2] = size1 + size2;
size[par1] = 0;
sizes.remove(size1);
sizes.remove(size2);
sizes.add(size1 + size2);
}
}
| Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 2efd2205609bb6986f9c6b2202d08f36 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
ConsoleIO io = new ConsoleIO(new InputStreamReader(System.in), new PrintWriter(System.out));
// String fileName = "C-large-practice";
// ConsoleIO io = new ConsoleIO(new FileReader("D:\\Dropbox\\code\\practice\\jb\\src\\" + fileName + ".in"), new PrintWriter(new File("D:\\Dropbox\\code\\practice\\jb\\src\\" + fileName + ".out")));
new Main(io).solve();
// new Main(io).solveLocal();
io.close();
}
ConsoleIO io;
Main(ConsoleIO io) {
this.io = io;
}
ConsoleIO opt;
Main(ConsoleIO io, ConsoleIO opt) {
this.io = io;
this.opt = opt;
}
List<List<Integer>> gr = new ArrayList<>();
//long MOD = 1_000_000_007;
class Point {
public Point(long x, long y){
this.x = x;
this.y = y;
}
public long x;
public long y;
public long prod(Point p){
return x*p.y - y*p.x;
}
}
int[] rank, size, parent, count;
int maxSize = 1;
int find(int x)
{
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
boolean union(int x, int y) {
int rx = find(x), ry = find(y);
if (rx == ry)
return true;
if (rank[rx] < rank[ry]) {
parent[rx] = ry;
count[size[ry]]--;
size[ry] += size[rx];
count[size[rx]]--;
count[size[ry]]++;
maxSize = Math.max(maxSize, size[ry]);
}
else if (rank[ry] < rank[rx]) {
parent[ry] = rx;
count[size[rx]]--;
size[rx] += size[ry];
count[size[ry]]--;
count[size[rx]]++;
maxSize = Math.max(maxSize, size[rx]);
}
else {
parent[ry] = rx;
count[size[rx]]--;
size[rx] += size[ry];
rank[rx] = rank[rx] + 1;
count[size[ry]]--;
count[size[rx]]++;
maxSize = Math.max(maxSize, size[rx]);
}
return false;
}
public void solve() {
int n = io.ri();
int d = io.ri();
parent = new int[n];
size = new int[n];
rank = new int[n];
count = new int[n+1];
for(int i = 0;i<n;i++) {
parent[i] = i;
size[i] = 1;
}
count[1] = n;
int take = 1;
for(int i = 0 ; i < d; i++) {
int x = io.ri() - 1;
int y = io.ri() - 1;
if(union(x,y)) {
take++;
}
int res = 0;
int cur = take;
for(int j = maxSize;j>=0 && cur > 0;j--){
res += j * Math.min(count[j], cur);
cur -= count[j];
}
io.writeLine(Long.toString(res - 1));
}
}
public boolean good(char[] s, int p){
char v = s[p];
if(v=='a' && p < s.length-2 && s[p+1] == 'b' && s[p+2] == 'c') {
return true;
}
if(v=='b' && p < s.length-1 && p > 0 && s[p-1] == 'a' && s[p+1] == 'c') {
return true;
}
if(v=='c' && p > 1 && s[p-2] == 'a' && s[p-1] == 'b') {
return true;
}
return false;
}
public long choose4(long v){
if(v<4)
return 0;
return v * (v-1) * (v-2) * (v-3) / 24;
}
public long choose3(long v){
if(v<3)
return 0;
return v * (v-1) * (v-2) / 6;
}
}
class ConsoleIO {
BufferedReader br;
PrintWriter out;
public ConsoleIO(Reader reader, PrintWriter writer){br = new BufferedReader(reader);out = writer;}
public void flush(){this.out.flush();}
public void close(){this.out.close();}
public void writeLine(String s) {this.out.println(s);}
public void writeInt(int a) {this.out.print(a);this.out.print(' ');}
public void writeWord(String s){
this.out.print(s);
}
public void writeIntArray(int[] a, int k, String separator) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < k; i++) {
if (i > 0) sb.append(separator);
sb.append(a[i]);
}
this.writeLine(sb.toString());
}
public void writeLongArray(long[] a, int k, String separator) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < k; i++) {
if (i > 0) sb.append(separator);
sb.append(a[i]);
}
this.writeLine(sb.toString());
}
public int read(char[] buf, int len){try {return br.read(buf,0,len);}catch (Exception ex){ return -1; }}
public String readLine() {try {return br.readLine();}catch (Exception ex){ return "";}}
public long[] readLongArray() {
String[]n=this.readLine().trim().split("\\s+");long[]r=new long[n.length];
for(int i=0;i<n.length;i++)r[i]=Long.parseLong(n[i]);
return r;
}
public int[] readIntArray() {
String[]n=this.readLine().trim().split("\\s+");int[]r=new int[n.length];
for(int i=0;i<n.length;i++)r[i]=Integer.parseInt(n[i]);
return r;
}
public int[] readIntArray(int n) {
int[] res = new int[n];
char[] all = this.readLine().toCharArray();
int cur = 0;boolean have = false;
int k = 0;
boolean neg = false;
for(int i = 0;i<all.length;i++){
if(all[i]>='0' && all[i]<='9'){
cur = cur*10+all[i]-'0';
have = true;
}else if(all[i]=='-') {
neg = true;
}
else if(have){
res[k++] = neg?-cur:cur;
cur = 0;
have = false;
neg = false;
}
}
if(have)res[k++] = neg?-cur:cur;
return res;
}
public int ri() {
try {
int r = 0;
boolean start = false;
boolean neg = false;
while (true) {
int c = br.read();
if (c >= '0' && c <= '9') {
r = r * 10 + c - '0';
start = true;
} else if (!start && c == '-') {
start = true;
neg = true;
} else if (start || c == -1) return neg ? -r : r;
}
} catch (Exception ex) {
return -1;
}
}
public long readLong() {
try {
long r = 0;
boolean start = false;
boolean neg = false;
while (true) {
int c = br.read();
if (c >= '0' && c <= '9') {
r = r * 10 + c - '0';
start = true;
} else if (!start && c == '-') {
start = true;
neg = true;
} else if (start || c == -1) return neg ? -r : r;
}
} catch (Exception ex) {
return -1;
}
}
public String readWord() {
try {
boolean start = false;
StringBuilder sb = new StringBuilder();
while (true) {
int c = br.read();
if (c!= ' ' && c!= '\r' && c!='\n' && c!='\t') {
sb.append((char)c);
start = true;
} else if (start || c == -1) return sb.toString();
}
} catch (Exception ex) {
return "";
}
}
public char readSymbol() {
try {
while (true) {
int c = br.read();
if (c != ' ' && c != '\r' && c != '\n' && c != '\t') {
return (char) c;
}
}
} catch (Exception ex) {
return 0;
}
}
//public char readChar(){try {return (char)br.read();}catch (Exception ex){ return 0; }}
}
class Pair {
public Pair(int a, int b) {this.a = a;this.b = b;}
public int a;
public int b;
}
class PairLL {
public PairLL(long a, long b) {this.a = a;this.b = b;}
public long a;
public long b;
}
class Triple {
public Triple(int a, int b, int c) {this.a = a;this.b = b;this.c = c;}
public int a;
public int b;
public int c;
}
class TripleLL {
public TripleLL(long a, long b, long c) {this.a = a;this.b = b;this.c = c;}
public long a;
public long b;
public long c;
}
| Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 9d3ff033966832271cec189b4a79b68d | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class d {
public static void main(String[] args) {
FastScanner scan=new FastScanner();
PrintWriter out=new PrintWriter(System.out);
int n=scan.nextInt(), m=scan.nextInt();
DSU d=new DSU(n);
int adv=0;
for(int i=0;i<m;i++) {
int u=scan.nextInt()-1, v=scan.nextInt()-1;
if(d.unite(u,v)) {
//already united
adv++;
}
boolean[] seen=new boolean[n];
PriorityQueue<Integer> big=new PriorityQueue<>(Collections.reverseOrder());
for(int j=0;j<n;j++) {
int root=d.findRoot(j);
if(seen[root]) continue;
big.offer(d.size[root]);
seen[root]=true;
}
big.poll();
int res=d.maxcompsize-1;
for(int x=0;x<adv;x++) {
if(big.isEmpty()) break;
res+=big.poll();
}
out.println(res);
}
out.close();
}
static class DSU {
int n;
int[] parent, size;
int maxcompsize;
int comps;
int edges;
public DSU(int v) {
n = v;
parent = new int[n];
size = new int[n];
for(int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
maxcompsize=1;
comps=n;
edges=0;
}
public int findRoot(int curr) {
if(curr == parent[curr]) return curr;
return parent[curr] = findRoot(parent[curr]);
}
public boolean unite(int a, int b) {
int rootA = findRoot(a);
int rootB = findRoot(b);
if(rootA == rootB) return true;
if(size[rootA] > size[rootB]) {
parent[rootB] = rootA;
size[rootA] += size[rootB];
maxcompsize=Math.max(maxcompsize,size[rootA]);
}
else {
parent[rootA] = rootB;
size[rootB] += size[rootA];
maxcompsize=Math.max(maxcompsize,size[rootB]);
}
comps--;
edges++;
return false;
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e){e.printStackTrace();}
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception e) {e.printStackTrace();}
return st.nextToken();
}
public int nextInt() {return Integer.parseInt(next());}
public long nextLong() {return Long.parseLong(next());}
public double nextDouble() {return Double.parseDouble(next());}
public String nextLine() {
String line = "";
if(st.hasMoreTokens()) line = st.nextToken();
else try {return br.readLine();}catch(IOException e){e.printStackTrace();}
while(st.hasMoreTokens()) line += " "+st.nextToken();
return line;
}
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | e644aa065bce74079eefc8b2bf9691b1 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes |
import java.io.*;
import java.util.*;
public final class Main {
static PrintWriter out = new PrintWriter(System.out);
static FastReader in = new FastReader();
static Pair[] moves = new Pair[]{new Pair(-1, 0), new Pair(0, 1), new Pair(1, 0), new Pair(0, -1)};
static int mod = (int) (1e9 + 7);
static int mod2 = 998244353;
public static void main(String[] args) {
int tt = 1;
while (tt-- > 0) {
solve();
}
out.flush();
}
public static void solve() {
int n = i();
int d = i();
DSU dsu = new DSU(n);
for (int i = 0; i < d; i++) {
int u = i() - 1;
int v = i() - 1;
dsu.union(u, v);
out.println(Math.min(i + 1, dsu.getAns() - 1));
}
}
static class DSU {
int[] p;
int[] c;
int[] cc;
int fail;
public DSU(int n) {
p = new int[n];
c = new int[n];
for (int i = 0; i < n; i++) {
p[i] = i;
c[i] = 1;
}
cc = new int[n + 1];
cc[1] = n;
}
public int find(int x) {
return (p[x] == x) ? (x) : (p[x] = find(p[x]));
}
public boolean union(int u, int v) {
u = find(u);
v = find(v);
if (u == v) {
fail++;
return false;
}
if (u > v) {
p[u] = v;
cc[c[u]]--;
cc[c[v]]--;
cc[c[u] + c[v]]++;
c[v] += c[u];
} else {
p[v] = u;
cc[c[u]]--;
cc[c[v]]--;
cc[c[u] + c[v]]++;
c[u] += c[v];
}
return true;
}
public int getAns(){
int ans = 0;
int cost = fail + 1;
for (int i = cc.length - 1; i >= 1; i--) {
if (cost >= cc[i]) {
cost -= cc[i];
ans += cc[i] * i;
} else {
ans += cost * i;
cost = 0;
}
if (cost == 0) {
break;
}
}
return ans;
}
public boolean isSameUnion(int u, int v) {
return find(u) == find(v);
}
}
static long[] pre(int[] a) {
long[] pre = new long[a.length + 1];
pre[0] = 0;
for (int i = 0; i < a.length; i++) {
pre[i + 1] = pre[i] + a[i];
}
return pre;
}
static long[] pre(long[] a) {
long[] pre = new long[a.length + 1];
pre[0] = 0;
for (int i = 0; i < a.length; i++) {
pre[i + 1] = pre[i] + a[i];
}
return pre;
}
static void print(char A[]) {
for (char c : A) {
out.print(c);
}
out.println();
}
static void print(boolean A[]) {
for (boolean c : A) {
out.print(c + " ");
}
out.println();
}
static void print(int A[]) {
for (int c : A) {
out.print(c + " ");
}
out.println();
}
static void print(long A[]) {
for (long i : A) {
out.print(i + " ");
}
out.println();
}
static void print(List<Integer> A) {
for (int a : A) {
out.print(a + " ");
}
}
static int i() {
return in.nextInt();
}
static long l() {
return in.nextLong();
}
static double d() {
return in.nextDouble();
}
static String s() {
return in.nextLine();
}
static String c() {
return in.next();
}
static int[][] inputWithIdx(int N) {
int A[][] = new int[N][2];
for (int i = 0; i < N; i++) {
A[i] = new int[]{i, in.nextInt()};
}
return A;
}
static int[] input(int N) {
int A[] = new int[N];
for (int i = 0; i < N; i++) {
A[i] = in.nextInt();
}
return A;
}
static long[] inputLong(int N) {
long A[] = new long[N];
for (int i = 0; i < A.length; i++) {
A[i] = in.nextLong();
}
return A;
}
static int GCD(int a, int b) {
if (b == 0) {
return a;
} else {
return GCD(b, a % b);
}
}
static long GCD(long a, long b) {
if (b == 0) {
return a;
} else {
return GCD(b, a % b);
}
}
static long LCM(int a, int b) {
return (long) a / GCD(a, b) * b;
}
static long LCM(long a, long b) {
return a / GCD(a, b) * b;
}
static void shuffleAndSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
int rand = (int) (Math.random() * arr.length);
int temp = arr[rand];
arr[rand] = arr[i];
arr[i] = temp;
}
Arrays.sort(arr);
}
static void shuffleAndSort(int[][] arr, Comparator<? super int[]> comparator) {
for (int i = 0; i < arr.length; i++) {
int rand = (int) (Math.random() * arr.length);
int[] temp = arr[rand];
arr[rand] = arr[i];
arr[i] = temp;
}
Arrays.sort(arr, comparator);
}
static void shuffleAndSort(long[] arr) {
for (int i = 0; i < arr.length; i++) {
int rand = (int) (Math.random() * arr.length);
long temp = arr[rand];
arr[rand] = arr[i];
arr[i] = temp;
}
Arrays.sort(arr);
}
static boolean isPerfectSquare(double number) {
double sqrt = Math.sqrt(number);
return ((sqrt - Math.floor(sqrt)) == 0);
}
static void swap(int A[], int a, int b) {
int t = A[a];
A[a] = A[b];
A[b] = t;
}
static void swap(char A[], int a, int b) {
char t = A[a];
A[a] = A[b];
A[b] = t;
}
static long pow(long a, long b, int mod) {
long pow = 1;
long x = a;
while (b != 0) {
if ((b & 1) != 0) {
pow = (pow * x) % mod;
}
x = (x * x) % mod;
b /= 2;
}
return pow;
}
static long pow(long a, long b) {
long pow = 1;
long x = a;
while (b != 0) {
if ((b & 1) != 0) {
pow *= x;
}
x = x * x;
b /= 2;
}
return pow;
}
static long modInverse(long x, int mod) {
return pow(x, mod - 2, mod);
}
static boolean isPrime(long N) {
if (N <= 1) {
return false;
}
if (N <= 3) {
return true;
}
if (N % 2 == 0 || N % 3 == 0) {
return false;
}
for (int i = 5; i * i <= N; i = i + 6) {
if (N % i == 0 || N % (i + 2) == 0) {
return false;
}
}
return true;
}
public static String reverse(String str) {
if (str == null) {
return null;
}
return new StringBuilder(str).reverse().toString();
}
public static void reverse(int[] arr) {
for (int i = 0; i < arr.length / 2; i++) {
int tmp = arr[i];
arr[arr.length - 1 - i] = tmp;
arr[i] = arr[arr.length - 1 - i];
}
}
public static String repeat(char ch, int repeat) {
if (repeat <= 0) {
return "";
}
final char[] buf = new char[repeat];
for (int i = repeat - 1; i >= 0; i--) {
buf[i] = ch;
}
return new String(buf);
}
public static int[] manacher(String s) {
char[] chars = s.toCharArray();
int n = s.length();
int[] d1 = new int[n];
for (int i = 0, l = 0, r = -1; i < n; i++) {
int k = (i > r) ? 1 : Math.min(d1[l + r - i], r - i + 1);
while (0 <= i - k && i + k < n && chars[i - k] == chars[i + k]) {
k++;
}
d1[i] = k--;
if (i + k > r) {
l = i - k;
r = i + k;
}
}
return d1;
}
public static int[] kmp(String s) {
int n = s.length();
int[] res = new int[n];
for (int i = 1; i < n; ++i) {
int j = res[i - 1];
while (j > 0 && s.charAt(i) != s.charAt(j)) {
j = res[j - 1];
}
if (s.charAt(i) == s.charAt(j)) {
++j;
}
res[i] = j;
}
return res;
}
}
class Pair {
int i;
int j;
Pair(int i, int j) {
this.i = i;
this.j = j;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Pair pair = (Pair) o;
return i == pair.i && j == pair.j;
}
@Override
public int hashCode() {
return Objects.hash(i, j);
}
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
class Node {
int val;
public Node(int val) {
this.val = val;
}
}
class ST {
int n;
Node[] st;
ST(int n) {
this.n = n;
st = new Node[4 * Integer.highestOneBit(n)];
}
void build(Node[] nodes) {
build(0, 0, n - 1, nodes);
}
private void build(int id, int l, int r, Node[] nodes) {
if (l == r) {
st[id] = nodes[l];
return;
}
int mid = (l + r) >> 1;
build((id << 1) + 1, l, mid, nodes);
build((id << 1) + 2, mid + 1, r, nodes);
st[id] = comb(st[(id << 1) + 1], st[(id << 1) + 2]);
}
void update(int i, Node node) {
update(0, 0, n - 1, i, node);
}
private void update(int id, int l, int r, int i, Node node) {
if (i < l || r < i) {
return;
}
if (l == r) {
st[id] = node;
return;
}
int mid = (l + r) >> 1;
update((id << 1) + 1, l, mid, i, node);
update((id << 1) + 2, mid + 1, r, i, node);
st[id] = comb(st[(id << 1) + 1], st[(id << 1) + 2]);
}
Node get(int x, int y) {
return get(0, 0, n - 1, x, y);
}
private Node get(int id, int l, int r, int x, int y) {
if (x > r || y < l) {
return new Node(0);
}
if (x <= l && r <= y) {
return st[id];
}
int mid = (l + r) >> 1;
return comb(get((id << 1) + 1, l, mid, x, y), get((id << 1) + 2, mid + 1, r, x, y));
}
Node comb(Node a, Node b) {
if (a == null) {
return b;
}
if (b == null) {
return a;
}
return new Node(a.val | b.val);
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 5e6a274e1d5052632e52341c6212bd52 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class D{
public static class dsu {
int[] p;
public dsu(int n) {
p = new int[n];
for (int i = 0; i < n; i++) {
p[i] = i;
}
}
int find(int a) {return a == p[a] ? a: (p[a] = find(p[a]));}
void merge(int a, int b) {p[find(a)] = find(b);}
boolean check(int a, int b) {return find(a) == find(b);}
}
public static void main(String[] args) throws IOException{
// br = new BufferedReader(new FileReader(".in"));
// out = new PrintWriter(new FileWriter(".out"));
// new Thread(null, new (), "fisa balls", 1<<28).start();
int n =readInt(), d = readInt();
dsu dsu = new dsu(n);
boolean[] added = new boolean[n];
int freeEdges = 0;
for (int i = 0; i < d; i++) {
int u =readInt()-1, v = readInt()-1;
if (added[u] && added[v] && dsu.check(u,v)) freeEdges++;
added[u]=added[v]=true;
dsu.merge(u, v);
Integer[] cnt = new Integer[n];
Arrays.fill(cnt, 0);
for (int j = 0; j < n; j++) cnt[dsu.find(j)]++;
Arrays.sort(cnt,Collections.reverseOrder());
int max = 0;
for (int j = 0; j < freeEdges+1; j++) max+=cnt[j];
out.println(max-1);
}
out.close();
}
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
static StringTokenizer st = new StringTokenizer("");
static String read() throws IOException{
while (!st.hasMoreElements()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public static int readInt() throws IOException{return Integer.parseInt(read());}
public static long readLong() throws IOException{return Long.parseLong(read());}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 0560bd848ff0099e5ff1ff61ad5a6d1f | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
DSotsialnayaSet solver = new DSotsialnayaSet();
solver.solve(1, in, out);
out.close();
}
static class DSotsialnayaSet {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
DSU d = new DSU(n);
int[] a = new int[n];
int left = 0;
for (int i = 0; i < m; i++) {
int from = in.nextInt() - 1;
int to = in.nextInt() - 1;
if (d.findSet(from) == d.findSet(to)) {
left++;
} else {
d.unionSets(from, to);
}
Arrays.fill(a, 0);
for (int h = 0; h < n; h++) {
a[d.findSet(h)]++;
}
long mmax = 0;
Arrays.sort(a);
for (int h = 0; h < left + 1; h++) {
mmax += a[n - 1 - h];
}
out.println(mmax - 1);
}
}
}
static class InputReader {
private static final int BUFFER_LENGTH = 1 << 10;
private InputStream stream;
private byte[] buf = new byte[BUFFER_LENGTH];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int nextC() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = skipWhileSpace();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nextC();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = nextC();
} while (!isSpaceChar(c));
return res * sgn;
}
public int skipWhileSpace() {
int c = nextC();
while (isSpaceChar(c)) {
c = nextC();
}
return c;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
static class DSU {
int[] parent;
int[] size;
public DSU(int n) {
this.parent = new int[n];
this.size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
}
int findSet(int v) {
if (v == parent[v]) {
return v;
}
parent[v] = findSet(parent[v]);
return parent[v];
}
void unionSets(int a, int b) {
a = findSet(a);
b = findSet(b);
if (a != b) {
if (size[a] < size[b]) {
int z = a;
a = b;
b = z;
}
parent[b] = a;
size[a] += size[b];
}
}
}
}
| Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 18b427733c7f456670fc0883fd767c01 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.*;import java.util.*;import java.math.*;import static java.lang.Math.*;import static java.
util.Map.*;import static java.util.Arrays.*;import static java.util.Collections.*;
import static java.lang.System.*;
public class Main
{
public void tq()throws Exception
{
st=new StringTokenizer(bq.readLine());
int tq=1;
sb=new StringBuilder(2000000);
boolean s[]=si(1000000);
o:
while(tq-->0)
{
int n=i();
int m=i();
int ar[][]=ari(m,2);
int d[]=new int[n];
for(int x=0;x<n;x++)d[x]=-1;
int i=-1;
int ee=0;
for(int e[]:ar)
{
i++;
int a=e[0]-1;
int b=e[1]-1;
int pa=p(a,d);
int pb=p(b,d);
if(pa!=pb)
{
if(d[pa]<=d[pb])
{
d[pa]+=d[pb];
d[pb]=pa;
}
else
{
d[pb]+=d[pa];
d[pa]=pb;
}
}
else ee++;
int c=0;
PriorityQueue<Integer> p=new PriorityQueue<>(n,reverseOrder());
for(int x:d)
{
if(x<-1)
{
int v=((-x));
p.add(v);
}
}
int vv=ee;
c=p.poll()-1;
if(vv<=p.size())
{
while(vv-->0)c+=p.poll();
}
else
{
vv-=p.size();
while(p.size()>0)c+=p.poll();
c+=vv;
}
sl(c);
}
}
p(sb);
}
int p(int i,int d[])
{
if(d[i]<0)return i;
return d[i]=p(d[i],d);
}
void f(){out.flush();}
int di[][]={{-1,0},{1,0},{0,-1},{0,1}};
int de[][]={{-1,0},{1,0},{0,-1},{0,1},{-1,-1},{1,1},{-1,1},{1,-1}};
long mod=1000000007l;int max=Integer.MAX_VALUE,min=Integer.MIN_VALUE;long maxl=Long.MAX_VALUE, minl=Long.
MIN_VALUE;BufferedReader bq=new BufferedReader(new InputStreamReader(in));StringTokenizer st;
StringBuilder sb;public static void main(String[] a)throws Exception{new Main().tq();}int[] so(int ar[])
{Integer r[]=new Integer[ar.length];for(int x=0;x<ar.length;x++)r[x]=ar[x];sort(r);for(int x=0;x<ar.length;
x++)ar[x]=r[x];return ar;}long[] so(long ar[]){Long r[]=new Long[ar.length];for(int x=0;x<ar.length;x++)
r[x]=ar[x];sort(r);for(int x=0;x<ar.length;x++)ar[x]=r[x];return ar;}
char[] so(char ar[]) {Character
r[]=new Character[ar.length];for(int x=0;x<ar.length;x++)r[x]=ar[x];sort(r);for(int x=0;x<ar.length;x++)
ar[x]=r[x];return ar;}void s(String s){sb.append(s);}void s(int s){sb.append(s);}void s(long s){sb.
append(s);}void s(char s){sb.append(s);}void s(double s){sb.append(s);}void ss(){sb.append(' ');}void sl
(String s){sb.append(s);sb.append("\n");}void sl(int s){sb.append(s);sb.append("\n");}void sl(long s){sb
.append(s);sb.append("\n");}void sl(char s) {sb.append(s);sb.append("\n");}void sl(double s){sb.append(s)
;sb.append("\n");}void sl(){sb.append("\n");}int l(int v){return 31-Integer.numberOfLeadingZeros(v);}
long l(long v){return 63-Long.numberOfLeadingZeros(v);}int sq(int a){return (int)sqrt(a);}long sq(long a)
{return (long)sqrt(a);}long gcd(long a,long b){while(b>0l){long c=a%b;a=b;b=c;}return a;}int gcd(int a,int b)
{while(b>0){int c=a%b;a=b;b=c;}return a;}boolean pa(String s,int i,int j){while(i<j)if(s.charAt(i++)!=
s.charAt(j--))return false;return true;}boolean[] si(int n) {boolean bo[]=new boolean[n+1];bo[0]=true;bo[1]
=true;for(int x=4;x<=n;x+=2)bo[x]=true;for(int x=3;x*x<=n;x+=2){if(!bo[x]){int vv=(x<<1);for(int y=x*x;y<=n;
y+=vv)bo[y]=true;}}return bo;}long mul(long a,long b,long m) {long r=1l;a%=m;while(b>0){if((b&1)==1)
r=(r*a)%m;b>>=1;a=(a*a)%m;}return r;}int i()throws IOException{if(!st.hasMoreTokens())st=new
StringTokenizer(bq.readLine());return Integer.parseInt(st.nextToken());}long l()throws IOException
{if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine());return Long.parseLong(st.nextToken());}String
s()throws IOException {if (!st.hasMoreTokens())st=new StringTokenizer(bq.readLine());return st.nextToken();}
double d()throws IOException{if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine());return Double.
parseDouble(st.nextToken());}void p(Object p){out.print(p);}void p(String p){out.print(p);}void p(int p)
{out.print(p);}void p(double p){out.print(p);}void p(long p){out.print(p);}void p(char p){out.print(p);}void
p(boolean p){out.print(p);}void pl(Object p){out.println(p);}void pl(String p){out.println(p);}void pl(int p)
{out.println(p);}void pl(char p){out.println(p);}void pl(double p){out.println(p);}void pl(long p){out.
println(p);}void pl(boolean p)
{out.println(p);}void pl(){out.println();}void s(int a[]){for(int e:a)
{sb.append(e);sb.append(' ');}sb.append("\n");}
void s(long a[])
{for(long e:a){sb.append(e);sb.append(' ')
;}sb.append("\n");}void s(int ar[][]){for(int a[]:ar){for(int e:a){sb.append(e);sb.append(' ');}sb.append
("\n");}}
void s(char a[])
{for(char e:a){sb.append(e);sb.append(' ');}sb.append("\n");}void s(char ar[][])
{for(char a[]:ar){for(char e:a){sb.append(e);sb.append(' ');}sb.append("\n");}}int[] ari(int n)throws
IOException {int ar[]=new int[n];if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine());for(int x=0;
x<n;x++)ar[x]=Integer.parseInt(st.nextToken());return ar;}int[][] ari(int n,int m)throws
IOException {int ar[][]=new int[n][m];for(int x=0;x<n;x++){if (!st.hasMoreTokens())st=new StringTokenizer
(bq.readLine());for(int y=0;y<m;y++)ar[x][y]=Integer.parseInt(st.nextToken());}return ar;}long[] arl
(int n)throws IOException {long ar[]=new long[n];if(!st.hasMoreTokens()) st=new StringTokenizer(bq.readLine())
;for(int x=0;x<n;x++)ar[x]=Long.parseLong(st.nextToken());return ar;}long[][] arl(int n,int m)throws
IOException {long ar[][]=new long[n][m];for(int x=0;x<n;x++) {if(!st.hasMoreTokens()) st=new
StringTokenizer(bq.readLine());for(int y=0;y<m;y++)ar[x][y]=Long.parseLong(st.nextToken());}return ar;}
String[] ars(int n)throws IOException {String ar[] =new String[n];if(!st.hasMoreTokens())st=new
StringTokenizer(bq.readLine());for(int x=0;x<n;x++)ar[x]=st.nextToken();return ar;}double[] ard
(int n)throws IOException {double ar[] =new double[n];if(!st.hasMoreTokens())st=new StringTokenizer
(bq.readLine());for(int x=0;x<n;x++)ar[x]=Double.parseDouble(st.nextToken());return ar;}double[][] ard
(int n,int m)throws IOException{double ar[][]=new double[n][m];for(int x=0;x<n;x++) {if(!st.hasMoreTokens())
st=new StringTokenizer(bq.readLine());for(int y=0;y<m;y++) ar[x][y]=Double.parseDouble(st.nextToken());}
return ar;}char[] arc(int n)throws IOException{char ar[]=new char[n];if(!st.hasMoreTokens())st=new
StringTokenizer(bq.readLine());for(int x=0;x<n;x++)ar[x]=st.nextToken().charAt(0);return ar;}char[][]
arc(int n,int m)throws IOException {char ar[][]=new char[n][m];for(int x=0;x<n;x++){String s=bq.readLine();
for(int y=0;y<m;y++)ar[x][y]=s.charAt(y);}return ar;}void p(int ar[])
{StringBuilder sb=new StringBuilder
(2*ar.length);for(int a:ar){sb.append(a);sb.append(' ');}out.println(sb);}void p(int ar[][])
{StringBuilder sb=new StringBuilder(2*ar.length*ar[0].length);for(int a[]:ar){for(int aa:a){sb.append(aa);
sb.append(' ');}sb.append("\n");}p(sb);}void p(long ar[]){StringBuilder sb=new StringBuilder
(2*ar.length);for(long a:ar){ sb.append(a);sb.append(' ');}out.println(sb);}
void p(long ar[][])
{StringBuilder sb=new StringBuilder(2*ar.length*ar[0].length);for(long a[]:ar){for(long aa:a){sb.append(aa);
sb.append(' ');}sb.append("\n");}p(sb);}void p(String ar[]){int c=0;for(String s:ar)c+=s.length()+1;
StringBuilder sb=new StringBuilder(c);for(String a:ar){sb.append(a);sb.append(' ');}out.println(sb);}
void p(double ar[])
{StringBuilder sb=new StringBuilder(2*ar.length);for(double a:ar){sb.append(a);
sb.append(' ');}out.println(sb);}void p
(double ar[][]){StringBuilder sb=new StringBuilder(2*
ar.length*ar[0].length);for(double a[]:ar){for(double aa:a){sb.append(aa);sb.append(' ');}sb.append("\n")
;}p(sb);}void p(char ar[])
{StringBuilder sb=new StringBuilder(2*ar.length);for(char aa:ar){sb.append(aa);
sb.append(' ');}out.println(sb);}void p(char ar[][]){StringBuilder sb=new StringBuilder(2*ar.length*ar[0]
.length);for(char a[]:ar){for(char aa:a){sb.append(aa);sb.append(' ');}sb.append("\n");}p(sb);}void pl
(int... ar){for(int e:ar)p(e+" ");pl();}void pl(long... ar){for(long e:ar)p(e+" ");pl();}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | e410346fdd86ec06f95a83d42a20aa82 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
/**
* @author Naitik
*
*/
public class Main
{
static FastReader sc=new FastReader();
static long dp[][][];
//static int v[][];
// static int mod=998244353;;
static int mod=1000000007;
static int max;
static int bit[];
// static int seg[];
//static long fact[];
// static long A[];
// static TreeMap<Integer,Integer> map;
//static StringBuffer sb=new StringBuffer("");
static HashMap<Integer,Integer> map;
static PrintWriter out=new PrintWriter(System.out);
static TreeSet<Long> set=new TreeSet<Long>();
public static void main(String[] args)
{
// StringBuffer sb=new StringBuffer("");
int ttt=1;
// ttt =i();
outer :while (ttt-- > 0)
{
int n=i()+1;
int m=i();
ArrayList<Integer> A[]=new ArrayList[n];
for(int i=0;i<A.length;i++) {
A[i]=new ArrayList<Integer>();
}
int B[][]=new int[n][n];
int C[]=new int[n];
for(int i=0;i<n;i++) {
C[i]=i;
}
boolean v[]=new boolean[n];
int tm=0;
for(int i=0;i<m;i++) {
int a=i();
int b=i();
A[a].add(b);
A[b].add(a);
int p1=find(C, a);
int p2=find(C, b);
if(p1==p2) {
tm++;
}
else {
C[p1]=p2;
}
int ans=1;
Arrays.fill(v, false);
ArrayList<Integer> l=new ArrayList<Integer>();
for(int j=1;j<n;j++) {
max=0;
if(!v[j]) {
dfs(A, j, v);
l.add(max);
}
}
l.sort(null);
int op1=l.get(l.size()-1);
int z=tm;
for(int j=l.size()-2;j>=0 && z>0;j--,z--) {
op1+=l.get(j);
}
ans=max(ans,op1-1);
System.out.println(ans);
}
}
//System.out.println(sb.toString());
out.close();
//CHECK FOR N=1 //CHECK FOR M=0
//CHECK FOR N=1 //CHECK FOR M=0
//CHECK FOR N=1
}
private static void dfs(ArrayList<Integer> [] A, int s, boolean[] v) {
v[s]=true;
max++;
for(int i=0;i<A[s].size();i++) {
int child=A[s].get(i);
if(!v[child]) {
dfs(A, child, v);
}
}
}
static class Pair implements Comparable<Pair>
{
int x;
int y;
int z;
Pair(int x,int y){
this.x=x;
this.y=y;
// this.z=z;
}
@Override
public int compareTo(Pair o) {
if(this.x>o.x)
return -1;
else if(this.x<o.x)
return 1;
else {
if(this.y>o.y)
return 1;
else if(this.y<o.y)
return -1;
else
return 0;
}
}
// public int hashCode()
// {
// final int temp = 14;
// int ans = 1;
// ans =x*31+y*13;
// return ans;
// }
// @Override
// public boolean equals(Object o)
// {
// if (this == o) {
// return true;
// }
// if (o == null) {
// return false;
// }
// if (this.getClass() != o.getClass()) {
// return false;
// }
// Pair other = (Pair)o;
// if (this.x != other.x || this.y!=other.y) {
// return false;
// }
// return true;
// }
//
/* FOR TREE MAP PAIR USE */
// public int compareTo(Pair o) {
// if (x > o.x) {
// return 1;
// }
// if (x < o.x) {
// return -1;
// }
// if (y > o.y) {
// return 1;
// }
// if (y < o.y) {
// return -1;
// }
// return 0;
// }
}
static int find(int A[],int a) {
if(A[a]==a)
return a;
return A[a]=find(A, A[a]);
}
//static int find(int A[],int a) {
// if(A[a]==a)
// return a;
// return find(A, A[a]);
//}
//FENWICK TREE
static void update(int i, int x){
for(; i < bit.length; i += (i&-i))
bit[i] += x;
}
static int sum(int i){
int ans = 0;
for(; i > 0; i -= (i&-i))
ans += bit[i];
return ans;
}
//END
static void add(int v) {
if(!map.containsKey(v)) {
map.put(v, 1);
}
else {
map.put(v, map.get(v)+1);
}
}
static void remove(int v) {
if(map.containsKey(v)) {
map.put(v, map.get(v)-1);
if(map.get(v)==0)
map.remove(v);
}
}
public static int upper(int A[],int k,int si,int ei)
{
int l=si;
int u=ei;
int ans=-1;
while(l<=u) {
int mid=(l+u)/2;
if(A[mid]<=k) {
ans=mid;
l=mid+1;
}
else {
u=mid-1;
}
}
return ans;
}
public static int lower(int A[],int k,int si,int ei)
{
int l=si;
int u=ei;
int ans=-1;
while(l<=u) {
int mid=(l+u)/2;
if(A[mid]<=k) {
l=mid+1;
}
else {
ans=mid;
u=mid-1;
}
}
return ans;
}
static int[] copy(int A[]) {
int B[]=new int[A.length];
for(int i=0;i<A.length;i++) {
B[i]=A[i];
}
return B;
}
static long[] copy(long A[]) {
long B[]=new long[A.length];
for(int i=0;i<A.length;i++) {
B[i]=A[i];
}
return B;
}
static int[] input(int n) {
int A[]=new int[n];
for(int i=0;i<n;i++) {
A[i]=sc.nextInt();
}
return A;
}
static long[] inputL(int n) {
long A[]=new long[n];
for(int i=0;i<n;i++) {
A[i]=sc.nextLong();
}
return A;
}
static String[] inputS(int n) {
String A[]=new String[n];
for(int i=0;i<n;i++) {
A[i]=sc.next();
}
return A;
}
static long sum(int A[]) {
long sum=0;
for(int i : A) {
sum+=i;
}
return sum;
}
static long sum(long A[]) {
long sum=0;
for(long i : A) {
sum+=i;
}
return sum;
}
static void reverse(long A[]) {
int n=A.length;
long B[]=new long[n];
for(int i=0;i<n;i++) {
B[i]=A[n-i-1];
}
for(int i=0;i<n;i++)
A[i]=B[i];
}
static void reverse(int A[]) {
int n=A.length;
int B[]=new int[n];
for(int i=0;i<n;i++) {
B[i]=A[n-i-1];
}
for(int i=0;i<n;i++)
A[i]=B[i];
}
static void input(int A[],int B[]) {
for(int i=0;i<A.length;i++) {
A[i]=sc.nextInt();
B[i]=sc.nextInt();
}
}
static int[][] input(int n,int m){
int A[][]=new int[n][m];
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
A[i][j]=i();
}
}
return A;
}
static char[][] charinput(int n,int m){
char A[][]=new char[n][m];
for(int i=0;i<n;i++) {
String s=s();
for(int j=0;j<m;j++) {
A[i][j]=s.charAt(j);
}
}
return A;
}
static int nextPowerOf2(int n)
{
n--;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n++;
return n;
}
static int highestPowerof2(int x)
{
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x ^ (x >> 1);
}
static long highestPowerof2(long x)
{
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x ^ (x >> 1);
}
static int max(int A[]) {
int max=Integer.MIN_VALUE;
for(int i=0;i<A.length;i++) {
max=Math.max(max, A[i]);
}
return max;
}
static int min(int A[]) {
int min=Integer.MAX_VALUE;
for(int i=0;i<A.length;i++) {
min=Math.min(min, A[i]);
}
return min;
}
static long max(long A[]) {
long max=Long.MIN_VALUE;
for(int i=0;i<A.length;i++) {
max=Math.max(max, A[i]);
}
return max;
}
static long min(long A[]) {
long min=Long.MAX_VALUE;
for(int i=0;i<A.length;i++) {
min=Math.min(min, A[i]);
}
return min;
}
static long [] prefix(long A[]) {
long p[]=new long[A.length];
p[0]=A[0];
for(int i=1;i<A.length;i++)
p[i]=p[i-1]+A[i];
return p;
}
static long [] prefix(int A[]) {
long p[]=new long[A.length];
p[0]=A[0];
for(int i=1;i<A.length;i++)
p[i]=p[i-1]+A[i];
return p;
}
static long [] suffix(long A[]) {
long p[]=new long[A.length];
p[A.length-1]=A[A.length-1];
for(int i=A.length-2;i>=0;i--)
p[i]=p[i+1]+A[i];
return p;
}
static long [] suffix(int A[]) {
long p[]=new long[A.length];
p[A.length-1]=A[A.length-1];
for(int i=A.length-2;i>=0;i--)
p[i]=p[i+1]+A[i];
return p;
}
static void fill(int dp[]) {
Arrays.fill(dp, -1);
}
static void fill(int dp[][]) {
for(int i=0;i<dp.length;i++)
Arrays.fill(dp[i], -1);
}
static void fill(int dp[][][]) {
for(int i=0;i<dp.length;i++) {
for(int j=0;j<dp[0].length;j++) {
Arrays.fill(dp[i][j],-1);
}
}
}
static void fill(int dp[][][][]) {
for(int i=0;i<dp.length;i++) {
for(int j=0;j<dp[0].length;j++) {
for(int k=0;k<dp[0][0].length;k++) {
Arrays.fill(dp[i][j][k],-1);
}
}
}
}
static void fill(long dp[]) {
Arrays.fill(dp, -1);
}
static void fill(long dp[][]) {
for(int i=0;i<dp.length;i++)
Arrays.fill(dp[i], -1);
}
static void fill(long dp[][][]) {
for(int i=0;i<dp.length;i++) {
for(int j=0;j<dp[0].length;j++) {
Arrays.fill(dp[i][j],-1);
}
}
}
static void fill(long dp[][][][]) {
for(int i=0;i<dp.length;i++) {
for(int j=0;j<dp[0].length;j++) {
for(int k=0;k<dp[0][0].length;k++) {
Arrays.fill(dp[i][j][k],-1);
}
}
}
}
static int min(int a,int b) {
return Math.min(a, b);
}
static int min(int a,int b,int c) {
return Math.min(a, Math.min(b, c));
}
static int min(int a,int b,int c,int d) {
return Math.min(a, Math.min(b, Math.min(c, d)));
}
static int max(int a,int b) {
return Math.max(a, b);
}
static int max(int a,int b,int c) {
return Math.max(a, Math.max(b, c));
}
static int max(int a,int b,int c,int d) {
return Math.max(a, Math.max(b, Math.max(c, d)));
}
static long min(long a,long b) {
return Math.min(a, b);
}
static long min(long a,long b,long c) {
return Math.min(a, Math.min(b, c));
}
static long min(long a,long b,long c,long d) {
return Math.min(a, Math.min(b, Math.min(c, d)));
}
static long max(long a,long b) {
return Math.max(a, b);
}
static long max(long a,long b,long c) {
return Math.max(a, Math.max(b, c));
}
static long max(long a,long b,long c,long d) {
return Math.max(a, Math.max(b, Math.max(c, d)));
}
static long power(long x, long y, long p)
{
if(y==0)
return 1;
if(x==0)
return 0;
long res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static long power(long x, long y)
{
if(y==0)
return 1;
if(x==0)
return 0;
long res = 1;
while (y > 0) {
if (y % 2 == 1)
res = (res * x);
y = y >> 1;
x = (x * x);
}
return res;
}
static void print(int A[]) {
for(int i : A) {
System.out.print(i+" ");
}
System.out.println();
}
static void print(long A[]) {
for(long i : A) {
System.out.print(i+" ");
}
System.out.println();
}
static long mod(long x) {
return ((x%mod + mod)%mod);
}
static String reverse(String s) {
StringBuffer p=new StringBuffer(s);
p.reverse();
return p.toString();
}
static int i() {
return sc.nextInt();
}
static String s() {
return sc.next();
}
static long l() {
return sc.nextLong();
}
static void sort(int[] A){
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i){
int tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
static void sort(long[] A){
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i){
long tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
static String sort(String s) {
Character ch[]=new Character[s.length()];
for(int i=0;i<s.length();i++) {
ch[i]=s.charAt(i);
}
Arrays.sort(ch);
StringBuffer st=new StringBuffer("");
for(int i=0;i<s.length();i++) {
st.append(ch[i]);
}
return st.toString();
}
static HashMap<Integer,Integer> hash(int A[]){
HashMap<Integer,Integer> map=new HashMap<Integer, Integer>();
for(int i : A) {
if(map.containsKey(i)) {
map.put(i, map.get(i)+1);
}
else {
map.put(i, 1);
}
}
return map;
}
static HashMap<Long,Integer> hash(long A[]){
HashMap<Long,Integer> map=new HashMap<Long, Integer>();
for(long i : A) {
if(map.containsKey(i)) {
map.put(i, map.get(i)+1);
}
else {
map.put(i, 1);
}
}
return map;
}
static TreeMap<Integer,Integer> tree(int A[]){
TreeMap<Integer,Integer> map=new TreeMap<Integer, Integer>();
for(int i : A) {
if(map.containsKey(i)) {
map.put(i, map.get(i)+1);
}
else {
map.put(i, 1);
}
}
return map;
}
static TreeMap<Long,Integer> tree(long A[]){
TreeMap<Long,Integer> map=new TreeMap<Long, Integer>();
for(long i : A) {
if(map.containsKey(i)) {
map.put(i, map.get(i)+1);
}
else {
map.put(i, 1);
}
}
return map;
}
static boolean prime(int n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static boolean prime(long n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
| Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 42f3de4394dd26b4ab67e5998fc90881 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.util.Arrays;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.InputStreamReader;
import java.io.Writer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Nipuna Samarasekara
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, FastScanner in, FastPrinter out) {
int n = in.nextInt(), d = in.nextInt();
int[] a = new int[d];
int[] b = new int[d];
DisjointSetUnion dsu = new DisjointSetUnion(n + 1);
int free = 0;
for (int i = 0; i < d; i++) {
a[i] = in.nextInt();
b[i] = in.nextInt();
if (!dsu.union(a[i], b[i])) {
free++;
}
int[] counts = new int[n];
for (int j = 0; j < n; j++) {
counts[j] = dsu.getCount(j + 1);
}
Arrays.sort(counts);
int ans = 0;
for (int j = n - 1; j >= Math.max(0, n - 1 - free); j--) {
ans += counts[j];
}
out.println(ans - 1);
}
}
}
static class DisjointSetUnion {
int[] p;
int[] count;
public DisjointSetUnion(int n) {
p = new int[n];
count = new int[n];
for (int i = 0; i < n; i++) {
count[i] = 1;
}
clear();
}
public void clear() {
for (int i = 0; i < p.length; i++) {
p[i] = i;
}
}
public int get(int x) {
return x != p[x] ? p[x] = get(p[x]) : x;
}
public int getCount(int x) {
return count[x];
}
public boolean union(int a, int b) {
a = get(a);
b = get(b);
p[a] = b;
if (a != b) {
count[b] += count[a];
count[a] = 0;
}
return a != b;
}
}
static class FastPrinter extends PrintWriter {
public FastPrinter(OutputStream out) {
super(out);
}
public FastPrinter(Writer out) {
super(out);
}
}
static class FastScanner extends BufferedReader {
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try {
int ret = super.read();
// if (isEOF && ret < 0) {
// throw new InputMismatchException();
// }
// isEOF = ret == -1;
return ret;
} catch (IOException e) {
throw new InputMismatchException();
}
}
static boolean isWhiteSpace(int c) {
return c >= 0 && c <= 32;
}
public int nextInt() {
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int ret = 0;
while (c >= 0 && !isWhiteSpace(c)) {
if (c < '0' || c > '9') {
throw new NumberFormatException("digit expected " + (char) c + " found");
}
ret = ret * 10 + c - '0';
c = read();
}
return ret * sgn;
}
public String readLine() {
try {
return super.readLine();
} catch (IOException e) {
return null;
}
}
}
}
| Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | bbc5b64cfc9834e5a923c273de0a9ee4 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.*;
import java.util.*;
/*
*/
public class D{
static FastReader sc=null;
public static void main(String[] args) {
sc=new FastReader();
int n=sc.nextInt(),m=sc.nextInt();
DU du=new DU(n);
int extra=0;
for(int i=0;i<m;i++) {
int v=sc.nextInt()-1,w=sc.nextInt()-1;
if(du.connected(v, w))extra++;
else du.unify(v, w);
ArrayList<Integer> comps=new ArrayList<>();
boolean used[]=new boolean[n];
for(int j=0;j<n;j++) {
int root=du.find(j);
if(!used[root]) {
comps.add(du.compsize(root));
used[root]=true;
}
}
Collections.sort(comps);
int ans=0;
int sz=comps.size();
int min=Math.min(extra+1, sz);
for(int j=0;j<min;j++)ans+=comps.get(sz-j-1);
System.out.println(ans-1);
}
}
static class DU{
int sz[];
int par[];
int comp;
int n;
DU(int n){
this.n=n;
sz=new int[n];
Arrays.fill(sz, 1);
par=new int[n];
for(int i=0;i<n;i++)par[i]=i;
comp=n;
}
int find(int p) {
if(par[p]==p)return p;
return par[p]=find(par[p]);
}
void unify(int p,int q) {
int r1=find(p),r2=find(q);
if(r1==r2)return;
if(sz[r1]<sz[r2]) {
int temp=r1;
r1=r2;
r2=temp;
}
sz[r1]+=sz[r2];
par[r2]=r1;
comp--;
}
int compsize(int p) {
int root=find(p);
return sz[root];
}
boolean connected(int p,int q) {
return find(p)==find(q);
}
}
static int[] ruffleSort(int a[]) {
ArrayList<Integer> al=new ArrayList<>();
for(int i:a)al.add(i);
Collections.sort(al);
for(int i=0;i<a.length;i++)a[i]=al.get(i);
return a;
}
static void print(int a[]) {
for(int e:a) {
System.out.print(e+" ");
}
System.out.println();
}
static class FastReader{
StringTokenizer st=new StringTokenizer("");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String next() {
while(!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
}
catch(IOException e){
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
int[] readArray(int n) {
int a[]=new int[n];
for(int i=0;i<n;i++)a[i]=sc.nextInt();
return a;
}
}
}
| Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 0412d27778f0a5ee80a1bd0403ea75ef | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static PrintWriter pr = new PrintWriter(System.out);
static String readLine() throws IOException {
return br.readLine();
}
static String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(readLine());
return st.nextToken();
}
static int readInt() throws IOException {
return Integer.parseInt(next());
}
static long readLong() throws IOException {
return Long.parseLong(next());
}
static double readDouble() throws IOException {
return Double.parseDouble(next());
}
static char readChar() throws IOException {
return next().charAt(0);
}
static class Pair implements Comparable<Pair> {
int f, s;
Pair(int f, int s) {
this.f = f; this.s = s;
}
public int compareTo(Pair other) {
if (this.f != other.f) return this.f - other.f;
return this.s - other.s;
}
}
static int dsu[], size[];
static int find(int v) {
return dsu[v] == v ? v : (dsu[v] = find(dsu[v]));
}
static void solve() throws IOException {
int n = readInt(), m = readInt();
dsu = new int[n + 1];
size = new int[n + 1];
for (int i = 1; i <= n; ++i) {
dsu[i] = i;
size[i] = 1;
}
List<Pair> list = new ArrayList();
for (int k = 1, spare = 0; k <= m; ++k) {
int u = readInt(), v = readInt();
u = find(u);
v = find(v);
if (u != v) {
if (size[u] > size[v]) { int tmp = u; u = v; v = tmp; }
dsu[u] = v;
size[v] += size[u];
} else ++spare;
for (int i = 1; i <= n; ++i)
if (dsu[i] == i) list.add(new Pair(size[i], i));
Collections.sort(list);
int ans = 0;
for (int i = list.size() - 1, j = 0; i >= 0 && j <= spare; --i, ++j) ans += list.get(i).f;
list.clear();
pr.println(ans - 1);
}
}
public static void main(String[] args) throws IOException {
solve();
//for (int t = readInt(); t > 0; --t) solve();
pr.close();
}
}
| Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | d49bc398c85f8614ee7c3db042df0dde | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class D {
public static void main(String[] args) throws IOException {
/**/
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
/*/
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("src/d.in"))));
/**/
int n = sc.nextInt();
int d = sc.nextInt();
int[] which = new int[n];
ArrayList<ArrayList<Integer>> ch = new ArrayList<>();
for (int i = 0; i < n; ++i) {
ch.add(new ArrayList<>());
ch.get(i).add(i);
which[i] = i;
}
int free = 0;
for (int i = 0; i < d; ++i) {
int u = which[sc.nextInt()-1];
int v = which[sc.nextInt()-1];
if (u==v) {
++free;
} else {
for (int v2 : ch.get(v)) {
which[v2] = u;
ch.get(u).add(v2);
}
}
ArrayList<Integer> cts = new ArrayList<>();
for (int j = 0; j < n; ++j) {
if (which[j]==j)
cts.add(ch.get(j).size());
}
Collections.sort(cts);
int ans = 0;
for (int j = 0; j <= free; ++j) {
ans += cts.get(cts.size()-j-1);
}
System.out.println(ans-1);
}
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | d8a36c8307b4b4443be3f0a9823c2879 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD1 solver = new TaskD1();
solver.solve(1, in, out);
out.close();
}
static class TaskD1 {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
int d = in.nextInt();
DSU dsu = new DSU(n);
int[] compSizes = new int[n];
int spareEdges = 0;
for (int step = 0; step < d; step++) {
int a = in.nextInt() - 1;
int b = in.nextInt() - 1;
if (dsu.findComp(a) == dsu.findComp(b)) {
++spareEdges;
} else {
dsu.merge(a, b);
}
Arrays.fill(compSizes, 0);
for (int i = 0; i < n; i++) {
++compSizes[dsu.findComp(i)];
}
Arrays.sort(compSizes);
int ans = -1;
for (int i = n - 1; i >= 0 && i >= n - 1 - spareEdges; i--) {
ans += compSizes[i];
}
out.println(ans);
}
}
class DSU {
int[] f;
int numComps;
DSU(int n) {
f = new int[n];
for (int i = 0; i < f.length; i++) {
f[i] = i;
}
numComps = f.length;
}
int findComp(int x) {
int r;
int saved;
saved = x;
while (x != f[x]) {
x = f[x];
}
r = x;
x = saved;
while (x != r) {
saved = f[x];
f[x] = r;
x = saved;
}
return r;
}
void merge(int p0, int q0) {
int p1 = f[p0];
int q1 = f[q0];
while (p1 != q1) {
if (p1 > q1) {
if (p0 == p1) {
--numComps;
}
f[p0] = q1;
p0 = p1;
p1 = f[p1];
} else {
if (q0 == q1) {
--numComps;
}
f[q0] = p1;
q0 = q1;
q1 = f[q1];
}
}
}
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
try {
in = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
} catch (Exception e) {
throw new AssertionError();
}
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
String rl = in.readLine();
if (rl == null) {
return null;
}
st = new StringTokenizer(rl);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 4c607d35c9643209f827983f6d620277 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.io.*;
import java.util.*;
public class D {
FastScanner in;
PrintWriter out;
boolean systemIO = true;
public int sum(int x, int y) {
if (x + y >= mod) {
return x + y - mod;
}
return x + y;
}
public int diff(int x, int y) {
if (x >= y) {
return x - y;
}
return x - y + mod;
}
public int mult(int x, int y) {
return (int) (x * 1L * y % mod);
}
public int div(int x, int y) {
return (int) (x * 1L * modInv(y) % mod);
}
public class Pair implements Comparable<Pair> {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return x + " " + y;
}
@Override
public int compareTo(Pair o) {
if (x > o.x) {
return 1;
}
if (x < o.x) {
return -1;
}
if (y > o.y) {
return 1;
}
if (y < o.y) {
return -1;
}
return 0;
}
}
public class Fenvik {
int[] sum;
public Fenvik(int n) {
sum = new int[n];
}
public void add(int x, int d) {
for (int i = x; i < sum.length; i = (i | (i + 1))) {
sum[i] += d;
}
}
public int sum(int r) {
int ans = 0;
for (int i = r; i >= 0; i = (i & (i + 1)) - 1) {
ans += sum[i];
}
return ans;
}
public int sum(int l, int r) {
if (l > r) {
return 0;
}
return sum(r) - sum(l - 1);
}
}
public long gcd(long x, long y) {
if (y == 0) {
return x;
}
if (x == 0) {
return y;
}
return gcd(y, x % y);
}
public long[][] pow(long[][] x, long p) {
if (p == 0) {
long[][] ans = new long[x.length][x.length];
for (int i = 0; i < ans.length; i++) {
ans[i][i] = 1;
}
return ans;
}
long[][] t = pow(x, p / 2);
t = multiply(t, t);
if (p % 2 == 1) {
t = multiply(t, x);
}
return t;
}
public long[][] multiply(long[][] a, long[][] b) {
long[][] ans = new long[a.length][b[0].length];
for (int i = 0; i < ans.length; i++) {
for (int j = 0; j < ans[0].length; j++) {
for (int k = 0; k < b.length; k++) {
ans[i][j] += a[i][k] * b[k][j];
ans[i][j] %= mod;
}
}
}
return ans;
}
public int pow(int x, int p) {
if (p == 0) {
return 1;
}
int t = pow(x, p / 2);
t = mult(t, t);
if (p % 2 == 1) {
t = mult(t, x);
}
return t;
}
public int modInv(int x) {
return pow(x, mod - 2);
}
int mod = 1000000007;
Random random = new Random(566);
public class DSU {
int[] sz;
int[] p;
public DSU(int n) {
sz = new int[n];
p = new int[n];
for (int i = 0; i < p.length; i++) {
p[i] = i;
sz[i] = 1;
}
}
public int get(int x) {
if (x == p[x]) {
return x;
}
int par = get(p[x]);
p[x] = par;
return par;
}
public boolean unite(int a, int b) {
int pa = get(a);
int pb = get(b);
if (pa == pb) {
return false;
}
if (sz[pa] < sz[pb]) {
p[pa] = pb;
sz[pb] += sz[pa];
} else {
p[pb] = pa;
sz[pa] += sz[pb];
}
return true;
}
}
public void solve() {
int n = in.nextInt();
// int n = 1000;
DSU dsu = new DSU(n);
int d = in.nextInt();
// int d = 1000 - 1;
int free = 0;
for (int i = 0; i < d; i++) {
if (!dsu.unite(in.nextInt() - 1, in.nextInt() - 1)) {
free++;
}
// if (!dsu.unite(random.nextInt(n), random.nextInt(n))) {
// free++;
// }
TreeSet<Pair> set = new TreeSet<>();
for (int j = 0; j < n; j++) {
set.add(new Pair(dsu.sz[dsu.get(j)], dsu.get(j)));
}
int ans = 0;
for (int j = 0; j < free + 1; j++) {
ans += set.pollLast().x;
}
out.println(ans - 1);
}
}
public void run() {
try {
if (systemIO) {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
} else {
in = new FastScanner(new File("input.txt"));
out = new PrintWriter(new File("output.txt"));
}
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
return null;
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
// AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
public static void main(String[] arg) {
long time = System.currentTimeMillis();
new D().run();
System.err.println(System.currentTimeMillis() - time);
}
} | Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 8 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 8276613ecc226327e2130a26dc0fb6a6 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes | import java.util.*;
import java.util.function.*;
import java.io.*;
// you can compare with output.txt and expected out
public class RoundDeltixAutumn2021D {
MyPrintWriter out;
MyScanner in;
// final static long FIXED_RANDOM;
// static {
// FIXED_RANDOM = System.currentTimeMillis();
// }
final static String IMPOSSIBLE = "IMPOSSIBLE";
final static String POSSIBLE = "POSSIBLE";
final static String YES = "YES";
final static String NO = "NO";
private void initIO(boolean isFileIO) {
if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) {
try{
in = new MyScanner(new FileInputStream("input.txt"));
out = new MyPrintWriter(new FileOutputStream("output.txt"));
}
catch(FileNotFoundException e){
e.printStackTrace();
}
}
else{
in = new MyScanner(System.in);
out = new MyPrintWriter(new BufferedOutputStream(System.out));
}
}
public static void main(String[] args){
// Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
// the code for the deep recursion (more than 100k or 3~400k or so)
// Thread t = new Thread(null, new RoundEdu130F(), "threadName", 1<<28);
// t.start();
// t.join();
RoundDeltixAutumn2021D sol = new RoundDeltixAutumn2021D();
sol.run();
}
private void run() {
boolean isDebug = false;
boolean isFileIO = true;
boolean hasMultipleTests = false;
initIO(isFileIO);
int t = hasMultipleTests? in.nextInt() : 1;
for (int i = 1; i <= t; ++i) {
if(isDebug){
out.printf("Test %d\n", i);
}
getInput();
solve();
printOutput();
}
in.close();
out.close();
}
// use suitable one between matrix(2, n), matrix(n, 2), transposedMatrix(2, n) for graph edges, pairs, ...
int n, d;
int[] x, y;
void getInput() {
n = in.nextInt();
d = in.nextInt();
int[][] xy = in.nextTransposedMatrix(d, 2, -1);
x = xy[0];
y = xy[1];
}
void printOutput() {
out.printlnAns(ans);
}
int[] ans;
void solve(){
ans = new int[d];
DSU dsu = new DSU(n);
candidates = new TreeMap<>();
candidates.put(1, n);
best = new TreeMap<>();
bestSum = 0;
for(int i=0; i<d; i++) {
int sizeX = dsu.size[dsu.find(x[i])];
int sizeY = dsu.size[dsu.find(y[i])];
if(!dsu.union(x[i], y[i])) {
int val = candidates.lastKey();
del(candidates, val);
add(best, val);
bestSum += val;
}
else {
int cnt = 0;
if(candidates.containsKey(sizeX))
del(candidates, sizeX);
else {
del(best, sizeX);
bestSum -= sizeX;
cnt++;
}
if(candidates.containsKey(sizeY))
del(candidates, sizeY);
else {
del(best, sizeY);
bestSum -= sizeY;
cnt++;
}
if(cnt == 0 && !best.isEmpty()){
cnt++;
int val = best.firstKey();
del(best, val);
add(candidates, val);
bestSum -= val;
}
add(candidates, sizeX+sizeY);
while(cnt > 0) {
int val = candidates.lastKey();
del(candidates, val);
add(best, val);
bestSum += val;
cnt--;
}
}
ans[i] = candidates.lastKey() + bestSum - 1;
}
}
int bestSum;
TreeMap<Integer, Integer> best;
TreeMap<Integer, Integer> candidates;
void add(TreeMap<Integer, Integer> map, int val) {
map.merge(val, 1, (x, y) -> x+y);
}
void del(TreeMap<Integer, Integer> map, int val) {
int cnt = map.get(val) - 1;
if(cnt == 0)
map.remove(val);
else
map.put(val, cnt);
}
public class DSU {
int[] size;
int[] parents;
public DSU(int max) {
parents = new int[max];
size = new int[max];
Arrays.fill(parents, -1);
Arrays.fill(size, 1);
}
public boolean union(int v, int u) {
int head1 = find(v);
int head2 = find(u);
if(head1 == head2)
return false;
int smaller, larger;
if(size[head1] > size[head2]) {
smaller = head2;
larger = head1;
}
else {
smaller = head1;
larger = head2;
}
parents[smaller] = larger;
size[larger] += size[smaller];
return true;
}
public int find(int v) {
if(parents[v] == -1)
return v;
int head = find(parents[v]);
parents[v] = head;
return head;
}
}
// Optional<T> solve()
// return Optional.empty();
static class Pair implements Comparable<Pair>{
final static long FIXED_RANDOM = System.currentTimeMillis();
int first, second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
@Override
public int hashCode() {
// http://xorshift.di.unimi.it/splitmix64.c
long x = first;
x <<= 32;
x += second;
x += FIXED_RANDOM;
x += 0x9e3779b97f4a7c15l;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9l;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebl;
return (int)(x ^ (x >> 31));
}
@Override
public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
Pair other = (Pair) obj;
return first == other.first && second == other.second;
}
@Override
public String toString() {
return "[" + first + "," + second + "]";
}
@Override
public int compareTo(Pair o) {
int cmp = Integer.compare(first, o.first);
return cmp != 0? cmp: Integer.compare(second, o.second);
}
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
// 32768?
public MyScanner(InputStream is, int bufferSize) {
br = new BufferedReader(new InputStreamReader(is), bufferSize);
}
public MyScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
// br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
}
public void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[][] nextMatrix(int n, int m) {
return nextMatrix(n, m, 0);
}
int[][] nextMatrix(int n, int m, int offset) {
int[][] mat = new int[n][m];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
mat[i][j] = nextInt()+offset;
}
}
return mat;
}
int[][] nextTransposedMatrix(int n, int m){
return nextTransposedMatrix(n, m, 0);
}
int[][] nextTransposedMatrix(int n, int m, int offset){
int[][] mat = new int[m][n];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
mat[j][i] = nextInt()+offset;
}
}
return mat;
}
int[] nextIntArray(int len) {
return nextIntArray(len, 0);
}
int[] nextIntArray(int len, int offset){
int[] a = new int[len];
for(int j=0; j<len; j++)
a[j] = nextInt()+offset;
return a;
}
long[] nextLongArray(int len) {
return nextLongArray(len, 0);
}
long[] nextLongArray(int len, int offset){
long[] a = new long[len];
for(int j=0; j<len; j++)
a[j] = nextLong()+offset;
return a;
}
String[] nextStringArray(int len) {
String[] s = new String[len];
for(int i=0; i<len; i++)
s[i] = next();
return s;
}
}
public static class MyPrintWriter extends PrintWriter{
public MyPrintWriter(OutputStream os) {
super(os);
}
// public <T> void printlnAns(Optional<T> ans) {
// if(ans.isEmpty())
// println(-1);
// else
// printlnAns(ans.get());
// }
public void printlnAns(OptionalInt ans) {
println(ans.orElse(-1));
}
public void printlnAns(long ans) {
println(ans);
}
public void printlnAns(int ans) {
println(ans);
}
public void printlnAns(boolean ans) {
if(ans)
println(YES);
else
println(NO);
}
public void printAns(long[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(long[] arr){
printAns(arr);
println();
}
public void printAns(int[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(int[] arr){
printAns(arr);
println();
}
public <T> void printAns(ArrayList<T> arr){
if(arr != null && arr.size() > 0){
print(arr.get(0));
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i));
}
}
}
public <T> void printlnAns(ArrayList<T> arr){
printAns(arr);
println();
}
public void printAns(int[] arr, int add){
if(arr != null && arr.length > 0){
print(arr[0]+add);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]+add);
}
}
}
public void printlnAns(int[] arr, int add){
printAns(arr, add);
println();
}
public void printAns(ArrayList<Integer> arr, int add) {
if(arr != null && arr.size() > 0){
print(arr.get(0)+add);
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i)+add);
}
}
}
public void printlnAns(ArrayList<Integer> arr, int add){
printAns(arr, add);
println();
}
public void printlnAnsSplit(long[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public void printlnAnsSplit(int[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public <T> void printlnAnsSplit(ArrayList<T> arr, int split){
if(arr != null && !arr.isEmpty()){
for(int i=0; i<arr.size(); i+=split){
print(arr.get(i));
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr.get(j));
}
println();
}
}
}
}
static private void permutateAndSort(long[] a) {
int n = a.length;
Random R = new Random(System.currentTimeMillis());
for(int i=0; i<n; i++) {
int t = R.nextInt(n-i);
long temp = a[n-1-i];
a[n-1-i] = a[t];
a[t] = temp;
}
Arrays.sort(a);
}
static private void permutateAndSort(int[] a) {
int n = a.length;
Random R = new Random(System.currentTimeMillis());
for(int i=0; i<n; i++) {
int t = R.nextInt(n-i);
int temp = a[n-1-i];
a[n-1-i] = a[t];
a[t] = temp;
}
Arrays.sort(a);
}
static private int[][] constructChildren(int n, int[] parent, int parentRoot){
int[][] childrens = new int[n][];
int[] numChildren = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
numChildren[parent[i]]++;
}
for(int i=0; i<n; i++) {
childrens[i] = new int[numChildren[i]];
}
int[] idx = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
childrens[parent[i]][idx[parent[i]]++] = i;
}
return childrens;
}
static private int[][][] constructDirectedNeighborhood(int n, int[][] e){
int[] inDegree = new int[n];
int[] outDegree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outDegree[u]++;
inDegree[v]++;
}
int[][] inNeighbors = new int[n][];
int[][] outNeighbors = new int[n][];
for(int i=0; i<n; i++) {
inNeighbors[i] = new int[inDegree[i]];
outNeighbors[i] = new int[outDegree[i]];
}
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outNeighbors[u][--outDegree[u]] = v;
inNeighbors[v][--inDegree[v]] = u;
}
return new int[][][] {inNeighbors, outNeighbors};
}
static private int[][] constructNeighborhood(int n, int[][] e) {
int[] degree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
degree[u]++;
degree[v]++;
}
int[][] neighbors = new int[n][];
for(int i=0; i<n; i++)
neighbors[i] = new int[degree[i]];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
neighbors[u][--degree[u]] = v;
neighbors[v][--degree[v]] = u;
}
return neighbors;
}
static private void drawGraph(int[][] e) {
makeDotUndirected(e);
try {
final Process process = new ProcessBuilder("dot", "-Tpng", "graph.dot")
.redirectOutput(new File("graph.png"))
.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
static private void makeDotUndirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict graph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "--" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
static private void makeDotDirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict digraph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "->" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
}
| Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 17 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | 194340a1604677c413079ed08f174229 | train_110.jsonl | 1638110100 | William arrived at a conference dedicated to cryptocurrencies. Networking, meeting new people, and using friends' connections are essential to stay up to date with the latest news from the world of cryptocurrencies.The conference has $$$n$$$ participants, who are initially unfamiliar with each other. William can introduce any two people, $$$a$$$ and $$$b$$$, who were not familiar before, to each other. William has $$$d$$$ conditions, $$$i$$$'th of which requires person $$$x_i$$$ to have a connection to person $$$y_i$$$. Formally, two people $$$x$$$ and $$$y$$$ have a connection if there is such a chain $$$p_1=x, p_2, p_3, \dots, p_k=y$$$ for which for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$ it's true that two people with numbers $$$p_i$$$ and $$$p_{i + 1}$$$ know each other.For every $$$i$$$ ($$$1 \le i \le d$$$) William wants you to calculate the maximal number of acquaintances one person can have, assuming that William satisfied all conditions from $$$1$$$ and up to and including $$$i$$$ and performed exactly $$$i$$$ introductions. The conditions are being checked after William performed $$$i$$$ introductions. The answer for each $$$i$$$ must be calculated independently. It means that when you compute an answer for $$$i$$$, you should assume that no two people have been introduced to each other yet. | 256 megabytes |
import java.util.*;
import java.io.*;
public class A {
static class Set{
int id;
int count;
Set parent;
Set(int id){
this.id = id;
this.count = 1;
this.parent = this;
}
public void union(Set a, Set b){
Set pa = a.getParent();
Set pb = b.getParent();
if(pa.count > pb.count){
pb.parent = pa;
pa.count += pb.count;
}
else{
pa.parent = pb;
pb.count += pa.count;
}
}
public Set getParent(){
if(this.parent == this){
return this;
}
this.parent = this.parent.getParent();
return this.parent;
}
}
public static void main(String[] args) throws IOException {
Soumit sc = new Soumit();
int n = sc.nextInt();
int q = sc.nextInt();
StringBuilder sb = new StringBuilder();
Set[] sets = new Set[n];
for(int i=0;i<n;i++)
sets[i] = new Set(i);
int[][] conditions = new int[q][2];
for(int i=0;i<q;i++){
conditions[i][0] = sc.nextInt()-1;
conditions[i][1] = sc.nextInt()-1;
}
int extra_ops = 1;
for(int i=0;i<q;i++){
int u = conditions[i][0];
int v = conditions[i][1];
if(sets[u].getParent() != sets[v].getParent()){
sets[u].union(sets[u], sets[v]);
}
else{
extra_ops++;
}
List<Integer> list = new ArrayList<>();
for(int j=0;j<n;j++){
if(sets[j].getParent() != sets[j])
continue;
int c = sets[j].count;
list.add(c);
}
list.sort(Collections.reverseOrder());
int total_nodes = 0;
for(int j=0;j<Math.min(list.size(), extra_ops);j++){
total_nodes += list.get(j);
}
sb.append(total_nodes-1).append("\n");
}
System.out.println(sb);
sc.close();
}
static class Soumit {
final private int BUFFER_SIZE = 1 << 18;
final private DataInputStream din;
final private byte[] buffer;
private PrintWriter pw;
private int bufferPointer, bytesRead;
StringTokenizer st;
public Soumit() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Soumit(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public void streamOutput(String file) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
pw = new PrintWriter(bw);
}
public void println(String a) {
pw.println(a);
}
public void print(String a) {
pw.print(a);
}
public String readLine() throws IOException {
byte[] buf = new byte[3000064]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public void sort(int[] arr) {
ArrayList<Integer> arlist = new ArrayList<>();
for (int i : arr)
arlist.add(i);
Collections.sort(arlist);
for (int i = 0; i < arr.length; i++)
arr[i] = arlist.get(i);
}
public void sort(long[] arr) {
ArrayList<Long> arlist = new ArrayList<>();
for (long i : arr)
arlist.add(i);
Collections.sort(arlist);
for (int i = 0; i < arr.length; i++)
arr[i] = arlist.get(i);
}
public int[] nextIntArray(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
public double[] nextDoubleArray(int n) throws IOException {
double[] arr = new double[n];
for (int i = 0; i < n; i++) {
arr[i] = nextDouble();
}
return arr;
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
/*if (din == null)
return;*/
if (din != null) din.close();
if (pw != null) pw.close();
}
}
}
| Java | ["7 6\n1 2\n3 4\n2 4\n7 6\n6 5\n1 7", "10 8\n1 2\n2 3\n3 4\n1 4\n6 7\n8 9\n8 10\n1 4"] | 2 seconds | ["1\n1\n3\n3\n3\n6", "1\n2\n3\n4\n5\n5\n6\n8"] | NoteThe explanation for the first test case:In this explanation, the circles and the numbers in them denote a person with the corresponding number. The line denotes that William introduced two connected people. The person marked with red has the most acquaintances. These are not the only correct ways to introduce people. | Java 17 | standard input | [
"dsu",
"graphs",
"greedy",
"implementation",
"trees"
] | 29bc7a22baa3dc6bb508b00048e50114 | The first line contains two integers $$$n$$$ and $$$d$$$ ($$$2 \le n \le 10^3, 1 \le d \le n - 1$$$), the number of people, and number of conditions, respectively. Each of the next $$$d$$$ lines each contain two integers $$$x_i$$$ and $$$y_i$$$ ($$$1 \le x_i, y_i \le n, x_i \neq y_i$$$), the numbers of people which must have a connection according to condition $$$i$$$. | 1,600 | Output $$$d$$$ integers. $$$i$$$th number must equal the number of acquaintances the person with the maximal possible acquaintances will have, if William performed $$$i$$$ introductions and satisfied the first $$$i$$$ conditions. | standard output | |
PASSED | c60340443961ebf8acc68f684760016a | train_110.jsonl | 1638110100 | Before becoming a successful trader William got a university degree. During his education an interesting situation happened, after which William started to listen to homework assignments much more attentively. What follows is a formal description of the homework assignment as William heard it:You are given a string $$$s$$$ of length $$$n$$$ only consisting of characters "a", "b" and "c". There are $$$q$$$ queries of format ($$$pos, c$$$), meaning replacing the element of string $$$s$$$ at position $$$pos$$$ with character $$$c$$$. After each query you must output the minimal number of characters in the string, which have to be replaced, so that the string doesn't contain string "abc" as a subsequence. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is said to be a subsequence of string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deleting some characters without changing the ordering of the remaining characters. | 256 megabytes | import java.util.*;
import java.util.function.*;
import java.io.*;
// you can compare with output.txt and expected out
public class RoundDeltixAutumn2021E {
MyPrintWriter out;
MyScanner in;
// final static long FIXED_RANDOM;
// static {
// FIXED_RANDOM = System.currentTimeMillis();
// }
final static String IMPOSSIBLE = "IMPOSSIBLE";
final static String POSSIBLE = "POSSIBLE";
final static String YES = "YES";
final static String NO = "NO";
private void initIO(boolean isFileIO) {
if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) {
try{
in = new MyScanner(new FileInputStream("input.txt"));
out = new MyPrintWriter(new FileOutputStream("output.txt"));
}
catch(FileNotFoundException e){
e.printStackTrace();
}
}
else{
in = new MyScanner(System.in);
out = new MyPrintWriter(new BufferedOutputStream(System.out));
}
}
public static void main(String[] args){
// Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
// the code for the deep recursion (more than 100k or 3~400k or so)
// Thread t = new Thread(null, new RoundEdu130F(), "threadName", 1<<28);
// t.start();
// t.join();
RoundDeltixAutumn2021E sol = new RoundDeltixAutumn2021E();
sol.run();
}
private void run() {
boolean isDebug = false;
boolean isFileIO = true;
boolean hasMultipleTests = false;
initIO(isFileIO);
int t = hasMultipleTests? in.nextInt() : 1;
for (int i = 1; i <= t; ++i) {
if(isDebug){
out.printf("Test %d\n", i);
}
getInput();
solve();
printOutput();
}
in.close();
out.close();
}
// use suitable one between matrix(2, n), matrix(n, 2), transposedMatrix(2, n) for graph edges, pairs, ...
int n, q;
char[] s;
int[] pos;
char[] ch;
void getInput() {
n = in.nextInt();
q = in.nextInt();
s = in.next().toCharArray();
pos = new int[q];
ch = new char[q];
for(int i=0; i<q; i++) {
pos[i] = in.nextInt()-1;
ch[i] = in.next().charAt(0);
}
}
void printOutput() {
out.printlnAns(ans);
}
int[] ans;
void solve(){
// for each b
// all a that appear before
// or all c that appear after
// or b itself should be removed
// --> there exist cut points u, v
// s.t. remove all a in [0, u), remove all b in [u, v), and remove all c in [v, n)
// minimize prefixA[u-1] + prefixB[v-1] - prefixB[u-1] + prefixC[n-1] - prefixC[v-1]
// minimize prefix(A-B)[u-1] + prefix(B-C)[v-1]
// minimize each prefix
// suppose v < u
// prefix(A-B)[u-2] >= prefix(A-B)[u-1]
// so s[u-1] = B or C
// prefix(B-C)[v] <= prefix(B-C)[v+1]
// so s[v+1] = A or B
// so s(v..u) = all B
// this is not a useful argument
// minimize prefix(A-B)[u-1] + prefix(B-C)[v-1], u <= v
// when u = 0, find best v
// then when u++, v can only move to rightward
// -> O(n)
// don't need to increment u one by one?
// u = 0, find best v
// then find best u left to v
// u = v+1, find best v
// bbbbbbbbbbbb
// introduce prefix(A-C)
// but stil insufficient
// no abc
// remove all a in [0, u), remove all b in [u, v), and remove all c in [v, n)
// part 1 -> part 2 -> part 3
// (b + c) -> (a + c) -> (a + b)
// for each u, there are 6 states
// 1) contains only part 1
// 2) contains only part 2
// 3) contains only part 3
// 4) contains part1 + part2
// 5) contains part2 + part3
// 6) contains part1 + part2 + part3
// 90 mins until here
ans = new int[q];
SegmentTree sumTree = new SegmentTree(s);
for(int i=0; i<q; i++) {
s[pos[i]] = ch[i];
sumTree.update(pos[i], ch[i]);
ans[i] = sumTree.query();
}
}
class SegmentTree {
int n;
int[] tree1, tree2, tree3, tree12, tree23, tree123;
public SegmentTree(char[] arr){
this.n = arr.length;
int m = n<=1? 8: Integer.highestOneBit(n-1)*4;
tree1 = new int[m];
tree2 = new int[m];
tree3 = new int[m];
tree12 = new int[m];
tree23 = new int[m];
tree123 = new int[m];
build(arr, 1, 0, n-1);
}
private void recalculate(int treeIdx) {
int left = treeIdx<<1;
int right = (treeIdx<<1)+1;
tree1[treeIdx] = tree1[left] + tree1[right];
tree2[treeIdx] = tree2[left] + tree2[right];
tree3[treeIdx] = tree3[left] + tree3[right];
tree12[treeIdx] = Math.min(tree1[left] + tree2[right], tree1[left] + tree12[right]);
tree12[treeIdx] = Math.min(tree12[treeIdx], tree12[left] + tree2[right]);
tree23[treeIdx] = Math.min(tree2[left] + tree3[right], tree2[left] + tree23[right]);
tree23[treeIdx] = Math.min(tree23[treeIdx], tree23[left] + tree3[right]);
tree123[treeIdx] = Math.min(tree1[left] + tree23[right], tree12[left] + tree3[right]);
tree123[treeIdx] = Math.min(tree123[treeIdx], tree123[left] + tree3[right]);
tree123[treeIdx] = Math.min(tree123[treeIdx], tree1[left] + tree123[right]);
tree123[treeIdx] = Math.min(tree123[treeIdx], tree1[left] + tree3[right]);
tree123[treeIdx] = Math.min(tree123[treeIdx], tree12[left] + tree23[right]);
}
private void build(char[] arr, int treeIdx, int left, int right) {
if(left == right) {
// part 1 -> part 2 -> part 3
// (b + c) -> (a + c) -> (a + b)
switch(arr[left]) {
case 'a':
tree1[treeIdx] = 1;
break;
case 'b':
tree2[treeIdx] = 1;
break;
case 'c':
tree3[treeIdx] = 1;
break;
}
return;
}
int mid = (left+right)>>1;
int treeIdxLeftMid = treeIdx<<1;
int treeIdxMidRight = (treeIdx<<1)+1;
build(arr, treeIdxLeftMid, left, mid);
build(arr, treeIdxMidRight, mid+1, right);
recalculate(treeIdx);
}
public void update(int idx, char val){
update(idx, val, 1, 0, n-1);
}
private void update(int idx, char val, int treeIdx, int left, int right) {
// no need to update, not containing idx
if(left > idx || idx > right)
return;
// base case
if(left == right){
switch(val) {
case 'a':
tree1[treeIdx] = 1;
tree2[treeIdx] = 0;
tree3[treeIdx] = 0;
break;
case 'b':
tree1[treeIdx] = 0;
tree2[treeIdx] = 1;
tree3[treeIdx] = 0;
break;
case 'c':
tree1[treeIdx] = 0;
tree2[treeIdx] = 0;
tree3[treeIdx] = 1;
break;
}
return;
}
// update [left, right] containing idx
int mid = (left+right)>>1;
update(idx, val, treeIdx<<1, left, mid);
update(idx, val, (treeIdx<<1) + 1, mid+1, right);
recalculate(treeIdx);
}
public int query() {
int res = Math.min(tree1[1], tree2[1]);
res = Math.min(res, tree3[1]);
res = Math.min(res, tree12[1]);
res = Math.min(res, tree23[1]);
res = Math.min(res, tree123[1]);
return res;
}
}
// Optional<T> solve()
// return Optional.empty();
static class Pair implements Comparable<Pair>{
final static long FIXED_RANDOM = System.currentTimeMillis();
int first, second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
@Override
public int hashCode() {
// http://xorshift.di.unimi.it/splitmix64.c
long x = first;
x <<= 32;
x += second;
x += FIXED_RANDOM;
x += 0x9e3779b97f4a7c15l;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9l;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebl;
return (int)(x ^ (x >> 31));
}
@Override
public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
Pair other = (Pair) obj;
return first == other.first && second == other.second;
}
@Override
public String toString() {
return "[" + first + "," + second + "]";
}
@Override
public int compareTo(Pair o) {
int cmp = Integer.compare(first, o.first);
return cmp != 0? cmp: Integer.compare(second, o.second);
}
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
// 32768?
public MyScanner(InputStream is, int bufferSize) {
br = new BufferedReader(new InputStreamReader(is), bufferSize);
}
public MyScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
// br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
}
public void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[][] nextMatrix(int n, int m) {
return nextMatrix(n, m, 0);
}
int[][] nextMatrix(int n, int m, int offset) {
int[][] mat = new int[n][m];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
mat[i][j] = nextInt()+offset;
}
}
return mat;
}
int[][] nextTransposedMatrix(int n, int m){
return nextTransposedMatrix(n, m, 0);
}
int[][] nextTransposedMatrix(int n, int m, int offset){
int[][] mat = new int[m][n];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
mat[j][i] = nextInt()+offset;
}
}
return mat;
}
int[] nextIntArray(int len) {
return nextIntArray(len, 0);
}
int[] nextIntArray(int len, int offset){
int[] a = new int[len];
for(int j=0; j<len; j++)
a[j] = nextInt()+offset;
return a;
}
long[] nextLongArray(int len) {
return nextLongArray(len, 0);
}
long[] nextLongArray(int len, int offset){
long[] a = new long[len];
for(int j=0; j<len; j++)
a[j] = nextLong()+offset;
return a;
}
String[] nextStringArray(int len) {
String[] s = new String[len];
for(int i=0; i<len; i++)
s[i] = next();
return s;
}
}
public static class MyPrintWriter extends PrintWriter{
public MyPrintWriter(OutputStream os) {
super(os);
}
// public <T> void printlnAns(Optional<T> ans) {
// if(ans.isEmpty())
// println(-1);
// else
// printlnAns(ans.get());
// }
public void printlnAns(OptionalInt ans) {
println(ans.orElse(-1));
}
public void printlnAns(long ans) {
println(ans);
}
public void printlnAns(int ans) {
println(ans);
}
public void printlnAns(boolean ans) {
if(ans)
println(YES);
else
println(NO);
}
public void printAns(long[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(long[] arr){
printAns(arr);
println();
}
public void printAns(int[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(int[] arr){
printAns(arr);
println();
}
public <T> void printAns(ArrayList<T> arr){
if(arr != null && arr.size() > 0){
print(arr.get(0));
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i));
}
}
}
public <T> void printlnAns(ArrayList<T> arr){
printAns(arr);
println();
}
public void printAns(int[] arr, int add){
if(arr != null && arr.length > 0){
print(arr[0]+add);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]+add);
}
}
}
public void printlnAns(int[] arr, int add){
printAns(arr, add);
println();
}
public void printAns(ArrayList<Integer> arr, int add) {
if(arr != null && arr.size() > 0){
print(arr.get(0)+add);
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i)+add);
}
}
}
public void printlnAns(ArrayList<Integer> arr, int add){
printAns(arr, add);
println();
}
public void printlnAnsSplit(long[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public void printlnAnsSplit(int[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public <T> void printlnAnsSplit(ArrayList<T> arr, int split){
if(arr != null && !arr.isEmpty()){
for(int i=0; i<arr.size(); i+=split){
print(arr.get(i));
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr.get(j));
}
println();
}
}
}
}
static private void permutateAndSort(long[] a) {
int n = a.length;
Random R = new Random(System.currentTimeMillis());
for(int i=0; i<n; i++) {
int t = R.nextInt(n-i);
long temp = a[n-1-i];
a[n-1-i] = a[t];
a[t] = temp;
}
Arrays.sort(a);
}
static private void permutateAndSort(int[] a) {
int n = a.length;
Random R = new Random(System.currentTimeMillis());
for(int i=0; i<n; i++) {
int t = R.nextInt(n-i);
int temp = a[n-1-i];
a[n-1-i] = a[t];
a[t] = temp;
}
Arrays.sort(a);
}
static private int[][] constructChildren(int n, int[] parent, int parentRoot){
int[][] childrens = new int[n][];
int[] numChildren = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
numChildren[parent[i]]++;
}
for(int i=0; i<n; i++) {
childrens[i] = new int[numChildren[i]];
}
int[] idx = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
childrens[parent[i]][idx[parent[i]]++] = i;
}
return childrens;
}
static private int[][][] constructDirectedNeighborhood(int n, int[][] e){
int[] inDegree = new int[n];
int[] outDegree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outDegree[u]++;
inDegree[v]++;
}
int[][] inNeighbors = new int[n][];
int[][] outNeighbors = new int[n][];
for(int i=0; i<n; i++) {
inNeighbors[i] = new int[inDegree[i]];
outNeighbors[i] = new int[outDegree[i]];
}
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outNeighbors[u][--outDegree[u]] = v;
inNeighbors[v][--inDegree[v]] = u;
}
return new int[][][] {inNeighbors, outNeighbors};
}
static private int[][] constructNeighborhood(int n, int[][] e) {
int[] degree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
degree[u]++;
degree[v]++;
}
int[][] neighbors = new int[n][];
for(int i=0; i<n; i++)
neighbors[i] = new int[degree[i]];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
neighbors[u][--degree[u]] = v;
neighbors[v][--degree[v]] = u;
}
return neighbors;
}
static private void drawGraph(int[][] e) {
makeDotUndirected(e);
try {
final Process process = new ProcessBuilder("dot", "-Tpng", "graph.dot")
.redirectOutput(new File("graph.png"))
.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
static private void makeDotUndirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict graph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "--" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
static private void makeDotDirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict digraph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "->" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
}
| Java | ["9 12\naaabccccc\n4 a\n4 b\n2 b\n5 a\n1 b\n6 b\n5 c\n2 a\n1 a\n5 a\n6 b\n7 b"] | 3 seconds | ["0\n1\n2\n2\n1\n2\n1\n2\n2\n2\n2\n2"] | NoteLet's consider the state of the string after each query: $$$s = $$$"aaaaccccc". In this case the string does not contain "abc" as a subsequence and no replacements are needed. $$$s = $$$"aaabccccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"aaaaccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"ababccccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$aaaaccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"ababacccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaaaacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbabacccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"bbacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"bbacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbabcbccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"bbcbcbccc". This string does not contain "abc" as a subsequence. $$$s = $$$"baabcbccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"bbbbcbccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaabcbccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababbcc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaababbbb". This string does not contain "abc" as a subsequence. | Java 17 | standard input | [
"bitmasks",
"data structures",
"dp",
"matrices"
] | b431e4af99eb78e2c6e53d5d08bb0bc4 | The first line contains two integers $$$n$$$ and $$$q$$$ $$$(1 \le n, q \le 10^5)$$$, the length of the string and the number of queries, respectively. The second line contains the string $$$s$$$, consisting of characters "a", "b" and "c". Each of the next $$$q$$$ lines contains an integer $$$i$$$ and character $$$c$$$ $$$(1 \le i \le n)$$$, index and the value of the new item in the string, respectively. It is guaranteed that character's $$$c$$$ value is "a", "b" or "c". | 2,400 | For each query output the minimal number of characters that would have to be replaced so that the string doesn't contain "abc" as a subsequence. | standard output | |
PASSED | 50b779e70b4ba94d67cfa2b9af61e9dd | train_110.jsonl | 1638110100 | Before becoming a successful trader William got a university degree. During his education an interesting situation happened, after which William started to listen to homework assignments much more attentively. What follows is a formal description of the homework assignment as William heard it:You are given a string $$$s$$$ of length $$$n$$$ only consisting of characters "a", "b" and "c". There are $$$q$$$ queries of format ($$$pos, c$$$), meaning replacing the element of string $$$s$$$ at position $$$pos$$$ with character $$$c$$$. After each query you must output the minimal number of characters in the string, which have to be replaced, so that the string doesn't contain string "abc" as a subsequence. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is said to be a subsequence of string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deleting some characters without changing the ordering of the remaining characters. | 256 megabytes | // package c1609;
import java.io.File;
import java.lang.invoke.MethodHandles;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
//
// Deltix Round, Autumn 2021 (open for everyone, rated, Div. 1 + Div. 2) 2021-11-28 06:35
// E. William The Oblivious
// https://codeforces.com/contest/1609/problem/E
// time limit per test 3 seconds; memory limit per test 256 megabytes
//
// Before becoming a successful trader William got a university degree. During his education an
// interesting situation happened, after which William started to listen to homework assignments
// much more attentively. What follows is a formal description of the homework assignment as William
// heard it:
//
// You are given a string s of length n only consisting of characters "", "" and "". There are q
// queries of format (pos, c), meaning replacing the element of string s at position pos with
// character c. After each query you must output the minimal number of characters in the string,
// which have to be replaced, so that the string doesn't contain string "" as a . A valid
// replacement of a character is replacing it with "", "" or "".
//
// A string x is said to be a subsequence of string y if x can be obtained from y by deleting some
// characters without changing the ordering of the remaining characters.
//
// Input
//
// The first line contains two integers n and q (1 <= n, q <= 10^5), the length of the string and
// the number of queries, respectively.
//
// The second line contains the string s, consisting of characters "", "" and "".
//
// Each of the next q lines contains an integer i and character c (1 <= i <= n), index and the value
// of the new item in the string, respectively. It is guaranteed that character's c value is "", ""
// or "".
//
// Output
//
// For each query output the minimal number of characters that would have to be replaced so that the
// string doesn't contain "" as a subsequence.
//
// Example
/*
input:
9 12
aaabccccc
4 a
4 b
2 b
5 a
1 b
6 b
5 c
2 a
1 a
5 a
6 b
7 b
output:
0
1
2
2
1
2
1
2
2
2
2
2
*/
// Note
//
// Let's consider the state of the string after each query:
// 1. s = "". In this case the string does not contain "" as a subsequence and no replacements are
// needed.
// 2. s = "". In this case 1 replacements can be performed to get, for instance, string s = "".
// This string does not contain "" as a subsequence.
// 3. s = "". In this case 2 replacements can be performed to get, for instance, string s = ". This
// string does not contain "" as a subsequence.
// 4. s = "". In this case 2 replacements can be performed to get, for instance, string s = "".
// This string does not contain "" as a subsequence.
// 5. s = "". In this case 1 replacements can be performed to get, for instance, string s = "".
// This string does not contain "" as a subsequence.
// 6. s = "". In this case 2 replacements can be performed to get, for instance, string s = "".
// This string does not contain "" as a subsequence.
// 7. s = "". In this case 1 replacements can be performed to get, for instance, string s = "".
// This string does not contain "" as a subsequence.
// 8. s = "". In this case 2 replacements can be performed to get, for instance, string s = "".
// This string does not contain "" as a subsequence.
// 9. s = "". In this case 2 replacements can be performed to get, for instance, string s = "".
// This string does not contain "" as a subsequence.
// 10. s = "". In this case 2 replacements can be performed to get, for instance, string s = "".
// This string does not contain "" as a subsequence.
// 11. s = "". In this case 2 replacements can be performed to get, for instance, string s = "".
// This string does not contain "" as a subsequence.
// 12. s = "". In this case 2 replacements can be performed to get, for instance, string s = "".
// This string does not contain "" as a subsequence.
//
public class C1609E {
static final int MOD = (int)1e9+7;
static final Random RAND = new Random();
// Based on https://codeforces.com/contest/1609/submission/137364266
static int[] solve(String s, int[] pos, char[] val) {
int n = s.length();
SegTree st = new SegTree(n);
for (int i = 0; i < s.length(); i++) {
st.set(i, s.charAt(i));
}
int q = pos.length;
int[] ans = new int[q];
for (int i = 0; i < q; i++) {
st.set(pos[i], val[i]);
ans[i] = st.get();
}
return ans;
}
static class Node {
int a;
int b;
int c;
// Minimal number of characters to replace to NOT contain "ab".
int ab;
// Minimal number of characters to replace to NOT contain "bc".
int bc;
// Minimal number of characters to replace to NOT contain "abc".
int abc;
Node() {
}
Node(char ch) {
if (ch == 'a') {
a = 1;
} else if (ch == 'b') {
b = 1;
} else if (ch == 'c') {
c = 1;
}
}
}
static class SegTree {
Node[] data;
int size;
SegTree(int n) {
size = 1;
while (size < n) {
size *= 2;
}
data = new Node[2 * size];
for (int i = 0; i < data.length; i++) {
data[i] = new Node();
}
}
void set(int pos, char c) {
set(pos, c, 0, 0, size);
}
// [lx, rx), pos represents location in array
private void set(int idx, char c, int pos, int lx, int rx) {
if (rx - lx == 1) {
Node node = new Node(c);
data[pos] = node;
return;
}
int mid = (lx + rx) / 2;
if (idx < mid) {
set(idx, c, 2 * pos + 1, lx, mid);
} else {
set(idx, c, 2 * pos + 2, mid, rx);
}
data[pos] = merge(data[pos * 2 + 1], data[2 * pos + 2]);
}
int get() {
return data[0].abc;
}
private Node merge(Node one, Node other) {
Node node = new Node();
node.a = one.a + other.a;
node.b = one.b + other.b;
node.c = one.c + other.c;
node.ab = Math.min(one.a + other.ab, one.ab + other.b);
node.bc = Math.min(one.b + other.bc, one.bc + other.c);
node.abc = Math.min(one.a + other.abc, Math.min(one.ab + other.bc, one.abc + other.c));
return node;
}
}
static void doTest() {
long t0 = System.currentTimeMillis();
int n = 100000;
int q = 32;
char[] ca = new char[n];
for (int i = 0; i < n; i++) {
char c = (char) ('a' + (i % 3));
ca[i] = c;
}
int[] pos = new int[q];
char[] val = new char[q];
String s = new String(ca);
System.out.println(s);
for (int i = 0; i < q; i++) {
pos[i] = RAND.nextInt(n);
char c = (char) ('a' + RAND.nextInt(3));
val[i] = c;
ca[pos[i]] = c;
}
int[] ans = solve(s, pos, val);
String str = Arrays.toString(ans);
System.out.println(str.substring(0, Math.min(512, str.length())));
System.out.format("%d msec\n", System.currentTimeMillis() - t0);
System.exit(0);
}
public static void main(String[] args) {
// doTest();
Scanner in = getInputScanner();
int n = in.nextInt();
int q = in.nextInt();
String s = in.next();
// Read pos as 0-based
int[] pos = new int[q];
char[] val = new char[q];
for (int i = 0; i < q; i++) {
pos[i] = in.nextInt() - 1;
val[i] = in.next().charAt(0);
}
int[] ans = solve(s, pos, val);
System.out.println(trace(ans));
in.close();
}
static Scanner getInputScanner() {
try {
final String USERDIR = System.getProperty("user.dir");
final String CNAME = MethodHandles.lookup().lookupClass().getSimpleName();
final File fin = new File(USERDIR + "/io/c" + CNAME.substring(1,5) + "/" + CNAME + ".in");
return fin.exists() ? new Scanner(fin) : new Scanner(System.in);
} catch (Exception e) {
return new Scanner(System.in);
}
}
static String trace(int[] arr) {
StringBuilder sb = new StringBuilder();
for (int v : arr) {
sb.append(v);
sb.append('\n');
}
return sb.toString();
}
}
| Java | ["9 12\naaabccccc\n4 a\n4 b\n2 b\n5 a\n1 b\n6 b\n5 c\n2 a\n1 a\n5 a\n6 b\n7 b"] | 3 seconds | ["0\n1\n2\n2\n1\n2\n1\n2\n2\n2\n2\n2"] | NoteLet's consider the state of the string after each query: $$$s = $$$"aaaaccccc". In this case the string does not contain "abc" as a subsequence and no replacements are needed. $$$s = $$$"aaabccccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"aaaaccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"ababccccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$aaaaccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"ababacccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaaaacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbabacccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"bbacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"bbacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbabcbccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"bbcbcbccc". This string does not contain "abc" as a subsequence. $$$s = $$$"baabcbccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"bbbbcbccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaabcbccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababbcc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaababbbb". This string does not contain "abc" as a subsequence. | Java 11 | standard input | [
"bitmasks",
"data structures",
"dp",
"matrices"
] | b431e4af99eb78e2c6e53d5d08bb0bc4 | The first line contains two integers $$$n$$$ and $$$q$$$ $$$(1 \le n, q \le 10^5)$$$, the length of the string and the number of queries, respectively. The second line contains the string $$$s$$$, consisting of characters "a", "b" and "c". Each of the next $$$q$$$ lines contains an integer $$$i$$$ and character $$$c$$$ $$$(1 \le i \le n)$$$, index and the value of the new item in the string, respectively. It is guaranteed that character's $$$c$$$ value is "a", "b" or "c". | 2,400 | For each query output the minimal number of characters that would have to be replaced so that the string doesn't contain "abc" as a subsequence. | standard output | |
PASSED | 92daa903e718a55dbab29e747deb64a7 | train_110.jsonl | 1638110100 | Before becoming a successful trader William got a university degree. During his education an interesting situation happened, after which William started to listen to homework assignments much more attentively. What follows is a formal description of the homework assignment as William heard it:You are given a string $$$s$$$ of length $$$n$$$ only consisting of characters "a", "b" and "c". There are $$$q$$$ queries of format ($$$pos, c$$$), meaning replacing the element of string $$$s$$$ at position $$$pos$$$ with character $$$c$$$. After each query you must output the minimal number of characters in the string, which have to be replaced, so that the string doesn't contain string "abc" as a subsequence. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is said to be a subsequence of string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deleting some characters without changing the ordering of the remaining characters. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Arrays;
import java.util.Random;
import java.io.FileWriter;
import java.io.PrintWriter;
/*
Solution Created: 12:02:09 01/12/2021
Custom Competitive programming helper.
*/
public class Main {
public static void solve() {
int n = in.nextInt(), m = in.nextInt();
char[] a = in.nca();
SegmentTree st = new SegmentTree(a);
for(int i = 0; i<m; i++) {
st.update(in.nextInt()-1, in.next().toCharArray()[0]);
out.println(st.getAns());
}
}
static class Node{
int a,b,c,ab,bc,abc;
public Node(char type) {
update(type);
}
public void update(char type) {
this.a = this.b = this.c = this.ab = this.bc = 0;
if(type == 'a') a++;
if(type == 'b') b++;
if(type == 'c') c++;
}
public Node() {
this.a = this.b = this.c = this.ab = this.bc = 0;
}
}
static class SegmentTree{
int dummyValue = 0;
public int getAns() {
return tree[0].abc;
}
public void merge(Node toPass, Node a, Node b){
toPass.a = a.a + b.a;
toPass.b = a.b + b.b;
toPass.c = a.c + b.c;
toPass.ab = Math.min(a.a + b.ab, a.ab + b.b);
toPass.bc = Math.min(a.b + b.bc, a.bc + b.c);
toPass.abc = Math.min(a.a + b.abc, Math.min(a.ab+b.bc, a.abc + b.c));
}
private Node[] tree;
int n;
public SegmentTree(char[] a) {
this.n = a.length;
this.tree = new Node[4*n];
build(0, 0, n-1, a);
}
public SegmentTree(int n) {
this.n = n;
this.tree = new Node[4*n];
}
private void build(int idx, int l, int r, char[] a) {
if(l==r) tree[idx] = new Node(a[l]);
else {
int m = (l+r)/2;
build(2*idx+1, l, m, a);
build(2*idx+2,m+1,r, a);
tree[idx] = new Node();
merge(tree[idx], tree[2*idx+1], tree[2*idx+2]);
}
}
public void update(int idx, char type) {
updateUtil(0, 0, n-1, idx, type);
}
private void updateUtil(int idx ,int l, int r, int i, char type) {
if(l==r) tree[idx].update(type);
else {
int md = (l+r)/2;
if(i<=md) updateUtil(2*idx+1, l, md, i, type);
else updateUtil(2*idx+2, md+1, r, i, type);
merge(tree[idx], tree[2*idx+1], tree[2*idx+2]);
}
}
}
public static void main(String[] args) {
in = new Reader();
out = new Writer();
int t = 1;
while(t-->0) solve();
out.exit();
}
static Reader in; static Writer out;
static class Reader {
static BufferedReader br;
static StringTokenizer st;
public Reader() {
this.br = new BufferedReader(new InputStreamReader(System.in));
}
public Reader(String f){
try {
this.br = new BufferedReader(new FileReader(f));
} catch (IOException e) {
e.printStackTrace();
}
}
public int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public double[] nd(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++) a[i] = nextDouble();
return a;
}
public long[] nl(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
public char[] nca() {
return next().toCharArray();
}
public String[] ns(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++) a[i] = next();
return a;
}
public int nextInt() {
ensureNext();
return Integer.parseInt(st.nextToken());
}
public double nextDouble() {
ensureNext();
return Double.parseDouble(st.nextToken());
}
public Long nextLong() {
ensureNext();
return Long.parseLong(st.nextToken());
}
public String next() {
ensureNext();
return st.nextToken();
}
public String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private void ensureNext() {
if (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
static class Util{
private static Random random = new Random();
static long[] fact;
public static void initFactorial(int n, long mod) {
fact = new long[n+1];
fact[0] = 1;
for (int i = 1; i < n+1; i++) fact[i] = (fact[i - 1] * i) % mod;
}
public static long modInverse(long a, long MOD) {
long[] gcdE = gcdExtended(a, MOD);
if (gcdE[0] != 1) return -1; // Inverted doesn't exist
long x = gcdE[1];
return (x % MOD + MOD) % MOD;
}
public static long[] gcdExtended(long p, long q) {
if (q == 0) return new long[] { p, 1, 0 };
long[] vals = gcdExtended(q, p % q);
long tmp = vals[2];
vals[2] = vals[1] - (p / q) * vals[2];
vals[1] = tmp;
return vals;
}
public static long nCr(int n, int r, long MOD) {
if (r == 0) return 1;
return (fact[n] * modInverse(fact[r], MOD) % MOD * modInverse(fact[n - r], MOD) % MOD) % MOD;
}
public static long nCr(int n, int r) {
return (fact[n]/fact[r])/fact[n-r];
}
public static long nPr(int n, int r, long MOD) {
if (r == 0) return 1;
return (fact[n] * modInverse(fact[n - r], MOD) % MOD) % MOD;
}
public static long nPr(int n, int r) {
return fact[n]/fact[n-r];
}
public static boolean isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static boolean[] getSieve(int n) {
boolean[] isPrime = new boolean[n+1];
for (int i = 2; i <= n; i++) isPrime[i] = true;
for (int i = 2; i*i <= n; i++) if (isPrime[i])
for (int j = i; i*j <= n; j++) isPrime[i*j] = false;
return isPrime;
}
static long pow(long x, long pow, long mod){
long res = 1;
x = x % mod;
if (x == 0) return 0;
while (pow > 0){
if ((pow & 1) != 0) res = (res * x) % mod;
pow >>= 1;
x = (x * x) % mod;
}
return res;
}
public static int gcd(int a, int b) {
int tmp = 0;
while(b != 0) {
tmp = b;
b = a%b;
a = tmp;
}
return a;
}
public static long gcd(long a, long b) {
long tmp = 0;
while(b != 0) {
tmp = b;
b = a%b;
a = tmp;
}
return a;
}
public static int random(int min, int max) {
return random.nextInt(max-min+1)+min;
}
public static void dbg(Object... o) {
System.out.println(Arrays.deepToString(o));
}
public static void reverse(int[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
int tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(int[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(long[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
long tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(long[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(float[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
float tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(float[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(double[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
double tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(double[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(char[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
char tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(char[] s) {
reverse(s, 0, s.length-1);
}
public static <T> void reverse(T[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
T tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static <T> void reverse(T[] s) {
reverse(s, 0, s.length-1);
}
public static void shuffle(int[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
int t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(long[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
long t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(float[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
float t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(double[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
double t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(char[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
char t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static <T> void shuffle(T[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
T t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void sortArray(int[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(long[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(float[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(double[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(char[] a) {
shuffle(a);
Arrays.sort(a);
}
public static <T extends Comparable<T>> void sortArray(T[] a) {
Arrays.sort(a);
}
}
static class Writer {
private PrintWriter pw;
public Writer(){
pw = new PrintWriter(System.out);
}
public Writer(String f){
try {
pw = new PrintWriter(new FileWriter(f));
} catch (IOException e) {
e.printStackTrace();
}
}
public void yesNo(boolean condition) {
println(condition?"YES":"NO");
}
public void printArray(int[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
}
public void printlnArray(int[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
pw.println();
}
public void printArray(long[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
}
public void printlnArray(long[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
pw.println();
}
public void print(Object o) {
pw.print(o.toString());
}
public void println(Object o) {
pw.println(o.toString());
}
public void println() {
pw.println();
}
public void flush() {
pw.flush();
}
public void exit() {
pw.close();
}
}
}
| Java | ["9 12\naaabccccc\n4 a\n4 b\n2 b\n5 a\n1 b\n6 b\n5 c\n2 a\n1 a\n5 a\n6 b\n7 b"] | 3 seconds | ["0\n1\n2\n2\n1\n2\n1\n2\n2\n2\n2\n2"] | NoteLet's consider the state of the string after each query: $$$s = $$$"aaaaccccc". In this case the string does not contain "abc" as a subsequence and no replacements are needed. $$$s = $$$"aaabccccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"aaaaccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"ababccccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$aaaaccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"ababacccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaaaacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbabacccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"bbacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"bbacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbabcbccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"bbcbcbccc". This string does not contain "abc" as a subsequence. $$$s = $$$"baabcbccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"bbbbcbccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaabcbccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababbcc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaababbbb". This string does not contain "abc" as a subsequence. | Java 11 | standard input | [
"bitmasks",
"data structures",
"dp",
"matrices"
] | b431e4af99eb78e2c6e53d5d08bb0bc4 | The first line contains two integers $$$n$$$ and $$$q$$$ $$$(1 \le n, q \le 10^5)$$$, the length of the string and the number of queries, respectively. The second line contains the string $$$s$$$, consisting of characters "a", "b" and "c". Each of the next $$$q$$$ lines contains an integer $$$i$$$ and character $$$c$$$ $$$(1 \le i \le n)$$$, index and the value of the new item in the string, respectively. It is guaranteed that character's $$$c$$$ value is "a", "b" or "c". | 2,400 | For each query output the minimal number of characters that would have to be replaced so that the string doesn't contain "abc" as a subsequence. | standard output | |
PASSED | 60ecf04b4616a6f5849d5df1b9d7d310 | train_110.jsonl | 1638110100 | Before becoming a successful trader William got a university degree. During his education an interesting situation happened, after which William started to listen to homework assignments much more attentively. What follows is a formal description of the homework assignment as William heard it:You are given a string $$$s$$$ of length $$$n$$$ only consisting of characters "a", "b" and "c". There are $$$q$$$ queries of format ($$$pos, c$$$), meaning replacing the element of string $$$s$$$ at position $$$pos$$$ with character $$$c$$$. After each query you must output the minimal number of characters in the string, which have to be replaced, so that the string doesn't contain string "abc" as a subsequence. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is said to be a subsequence of string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deleting some characters without changing the ordering of the remaining characters. | 256 megabytes | // upsolve with kaiboy, coached by rainboy
import java.io.*;
import java.util.*;
public class CF1609E extends PrintWriter {
CF1609E() { super(System.out); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1609E o = new CF1609E(); o.main(); o.flush();
}
static final int INF = 0x3f3f3f3f;
int[][][] st; int n_;
void put(int i, byte c) {
int[][] aa = st[i];
// 0:
// 1: a
// 2: ab
if (c == 'a') {
aa[0][0] = 1; aa[0][1] = 0; aa[0][2] = INF;
aa[1][1] = 0; aa[1][2] = INF;
aa[2][2] = 0;
} else if (c == 'b') {
aa[0][0] = 0; aa[0][1] = INF; aa[0][2] = INF;
aa[1][1] = 1; aa[1][2] = 0;
aa[2][2] = 0;
} else {
aa[0][0] = 0; aa[0][1] = INF; aa[0][2] = INF;
aa[1][1] = 0; aa[1][2] = INF;
aa[2][2] = 1;
}
}
void pul(int i) {
int l = i << 1, r = l | 1;
int[][] aa = st[l], bb = st[r], cc = st[i];
for (int u = 0; u < 3; u++)
for (int v = u; v < 3; v++) {
int x = INF;
for (int w = u; w <= v; w++)
x = Math.min(x, aa[u][w] + bb[w][v]);
cc[u][v] = x;
}
}
void build(byte[] cc, int n) {
n_ = 1;
while (n_ < n)
n_ <<= 1;
st = new int[n_ * 2][3][3];
for (int i = 0; i < n; i++)
put(n_ + i, cc[i]);
for (int i = n_ - 1; i > 0; i--)
pul(i);
}
void update(int i, byte c) {
put(i += n_, c);
while (i > 1)
pul(i >>= 1);
}
int query() {
int x = INF;
for (int v = 0; v < 3; v++)
x = Math.min(x, st[1][0][v]);
return x;
}
void main() {
int n = sc.nextInt();
int q = sc.nextInt();
byte[] cc = sc.next().getBytes();
build(cc, n);
while (q-- > 0) {
int i = sc.nextInt() - 1;
byte c = (byte) sc.next().charAt(0);
update(i, c);
println(query());
}
}
}
| Java | ["9 12\naaabccccc\n4 a\n4 b\n2 b\n5 a\n1 b\n6 b\n5 c\n2 a\n1 a\n5 a\n6 b\n7 b"] | 3 seconds | ["0\n1\n2\n2\n1\n2\n1\n2\n2\n2\n2\n2"] | NoteLet's consider the state of the string after each query: $$$s = $$$"aaaaccccc". In this case the string does not contain "abc" as a subsequence and no replacements are needed. $$$s = $$$"aaabccccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"aaaaccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"ababccccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$aaaaccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"ababacccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaaaacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbabacccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"bbacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"bbacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbabcbccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"bbcbcbccc". This string does not contain "abc" as a subsequence. $$$s = $$$"baabcbccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"bbbbcbccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaabcbccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababbcc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaababbbb". This string does not contain "abc" as a subsequence. | Java 11 | standard input | [
"bitmasks",
"data structures",
"dp",
"matrices"
] | b431e4af99eb78e2c6e53d5d08bb0bc4 | The first line contains two integers $$$n$$$ and $$$q$$$ $$$(1 \le n, q \le 10^5)$$$, the length of the string and the number of queries, respectively. The second line contains the string $$$s$$$, consisting of characters "a", "b" and "c". Each of the next $$$q$$$ lines contains an integer $$$i$$$ and character $$$c$$$ $$$(1 \le i \le n)$$$, index and the value of the new item in the string, respectively. It is guaranteed that character's $$$c$$$ value is "a", "b" or "c". | 2,400 | For each query output the minimal number of characters that would have to be replaced so that the string doesn't contain "abc" as a subsequence. | standard output | |
PASSED | e6c9702b52e841e40a1182e87ddd7f65 | train_110.jsonl | 1638110100 | Before becoming a successful trader William got a university degree. During his education an interesting situation happened, after which William started to listen to homework assignments much more attentively. What follows is a formal description of the homework assignment as William heard it:You are given a string $$$s$$$ of length $$$n$$$ only consisting of characters "a", "b" and "c". There are $$$q$$$ queries of format ($$$pos, c$$$), meaning replacing the element of string $$$s$$$ at position $$$pos$$$ with character $$$c$$$. After each query you must output the minimal number of characters in the string, which have to be replaced, so that the string doesn't contain string "abc" as a subsequence. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is said to be a subsequence of string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deleting some characters without changing the ordering of the remaining characters. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
import java.util.stream.*;
public class E {
// This is an implementation of add to segment/set or add to point/query max on segment/query point.
static class SegTree {
Node root;
int n;
public SegTree(int n, int[] s) {
Node.initS = s;
this.n = n;
root = new Node(0, n);
}
public void setPoint(int idx, int val) {
Node.ql = idx;
Node.delta = val;
root.setPoint(0, n);
}
static class Node {
static int ql;
static int delta;
static int[] initS;
Node left, right;
int v012, v01, v12, v0, v1, v2;
void initChar(int c) {
v012 = v01 = v12 = 0;
v0 = c == 0 ? 1 : 0;
v1 = c == 1 ? 1 : 0;
v2 = c == 2 ? 1 : 0;
}
void combine() {
v0 = left.v0 + right.v0;
v1 = left.v1 + right.v1;
v2 = left.v2 + right.v2;
v01 = Math.min(left.v01 + right.v1, left.v0 + right.v01);
v12 = Math.min(left.v12 + right.v2, left.v1 + right.v12);
v012 = Math.min(Math.min(left.v0 + right.v012, left.v012 + right.v2), left.v01 + right.v12);
}
public Node(int l, int r) {
if (r - l > 1) {
int m = (l + r) >> 1;
left = new Node(l, m);
right = new Node(m, r);
combine();
} else {
initChar(initS[l]);
}
}
void setPoint(int l, int r) {
if (r - l == 1) {
initChar(Node.delta);
return;
}
int m = (l + r) >> 1;
if (ql < m) {
left.setPoint(l, m);
} else {
right.setPoint(m, r);
}
combine();
}
}
}
void submit() {
int n = nextInt();
int q = nextInt();
int[] a = new int[n];
String s = nextToken();
for (int i = 0; i < n; i++) {
a[i] = s.charAt(i) - 'a';
}
SegTree st = new SegTree(n, a);
while (q-- > 0) {
int idx = nextInt() - 1;
int val = nextChar() - 'a';
st.setPoint(idx, val);
out.println(st.root.v012);
}
}
void test() {
}
void stress() {
for (int tst = 0;; tst++) {
if (false) {
throw new AssertionError();
}
System.err.println(tst);
}
}
E() throws IOException {
is = System.in;
out = new PrintWriter(System.out);
submit();
// stress();
// test();
out.close();
}
static final Random rng = new Random();
static final int C = 5;
static int rand(int l, int r) {
return l + rng.nextInt(r - l + 1);
}
public static void main(String[] args) throws IOException {
new E();
}
private InputStream is;
PrintWriter out;
private byte[] buf = new byte[1 << 14];
private int bufSz = 0, bufPtr = 0;
private int readByte() {
if (bufSz == -1)
throw new RuntimeException("Reading past EOF");
if (bufPtr >= bufSz) {
bufPtr = 0;
try {
bufSz = is.read(buf);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (bufSz <= 0)
return -1;
}
return buf[bufPtr++];
}
private boolean isTrash(int c) {
return c < 33 || c > 126;
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isTrash(b))
;
return b;
}
String nextToken() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!isTrash(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
String nextString() {
int b = readByte();
StringBuilder sb = new StringBuilder();
while (!isTrash(b) || b == ' ') {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
char nextChar() {
return (char) skip();
}
int nextInt() {
int ret = 0;
int b = skip();
if (b != '-' && (b < '0' || b > '9')) {
throw new InputMismatchException();
}
boolean neg = false;
if (b == '-') {
neg = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
ret = ret * 10 + (b - '0');
} else {
if (b != -1 && !isTrash(b)) {
throw new InputMismatchException();
}
return neg ? -ret : ret;
}
b = readByte();
}
}
long nextLong() {
long ret = 0;
int b = skip();
if (b != '-' && (b < '0' || b > '9')) {
throw new InputMismatchException();
}
boolean neg = false;
if (b == '-') {
neg = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
ret = ret * 10 + (b - '0');
} else {
if (b != -1 && !isTrash(b)) {
throw new InputMismatchException();
}
return neg ? -ret : ret;
}
b = readByte();
}
}
} | Java | ["9 12\naaabccccc\n4 a\n4 b\n2 b\n5 a\n1 b\n6 b\n5 c\n2 a\n1 a\n5 a\n6 b\n7 b"] | 3 seconds | ["0\n1\n2\n2\n1\n2\n1\n2\n2\n2\n2\n2"] | NoteLet's consider the state of the string after each query: $$$s = $$$"aaaaccccc". In this case the string does not contain "abc" as a subsequence and no replacements are needed. $$$s = $$$"aaabccccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"aaaaccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"ababccccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$aaaaccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"ababacccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaaaacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbabacccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"bbacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"bbacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbabcbccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"bbcbcbccc". This string does not contain "abc" as a subsequence. $$$s = $$$"baabcbccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"bbbbcbccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaabcbccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababbcc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaababbbb". This string does not contain "abc" as a subsequence. | Java 11 | standard input | [
"bitmasks",
"data structures",
"dp",
"matrices"
] | b431e4af99eb78e2c6e53d5d08bb0bc4 | The first line contains two integers $$$n$$$ and $$$q$$$ $$$(1 \le n, q \le 10^5)$$$, the length of the string and the number of queries, respectively. The second line contains the string $$$s$$$, consisting of characters "a", "b" and "c". Each of the next $$$q$$$ lines contains an integer $$$i$$$ and character $$$c$$$ $$$(1 \le i \le n)$$$, index and the value of the new item in the string, respectively. It is guaranteed that character's $$$c$$$ value is "a", "b" or "c". | 2,400 | For each query output the minimal number of characters that would have to be replaced so that the string doesn't contain "abc" as a subsequence. | standard output | |
PASSED | 6a2149382706f3423142503469872fd9 | train_110.jsonl | 1638110100 | Before becoming a successful trader William got a university degree. During his education an interesting situation happened, after which William started to listen to homework assignments much more attentively. What follows is a formal description of the homework assignment as William heard it:You are given a string $$$s$$$ of length $$$n$$$ only consisting of characters "a", "b" and "c". There are $$$q$$$ queries of format ($$$pos, c$$$), meaning replacing the element of string $$$s$$$ at position $$$pos$$$ with character $$$c$$$. After each query you must output the minimal number of characters in the string, which have to be replaced, so that the string doesn't contain string "abc" as a subsequence. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is said to be a subsequence of string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deleting some characters without changing the ordering of the remaining characters. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
private static void update(int[][][] stree, int node, int left, int right,
int idx, char ch) {
if (left == right) {
for (int i=0; i<3; i++) {
for (int j=i; j<3; j++) {
stree[node][i][j] = 0;
}
}
stree[node][ch-'a'][ch-'a'] = 1;
return;
}
int mid = (left+right)/2;
if (idx <= mid) {update(stree, node*2, left, mid, idx, ch);}
else {update(stree, node*2+1, mid+1, right, idx, ch);}
for (int i=0; i<3; i++) {
for (int j=i; j<3; j++) {
stree[node][i][j] = Integer.MAX_VALUE;
for (int split=i; split<=j; split++) {
stree[node][i][j] = Math.min(stree[node][i][j],
stree[node*2][i][split] + stree[node*2+1][split][j]);
}
}
}
}
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
String[] line = in.readLine().split(" ");
int N = Integer.parseInt(line[0]);
int Q = Integer.parseInt(line[1]);
char[] S = in.readLine().toCharArray();
int[][][] stree = new int[N*20][3][3];
for (int idx=0; idx<N; idx++) {
update(stree, 1, 0, S.length-1, idx, S[idx]);
}
for (int q=1; q<=Q; q++) {
line = in.readLine().split(" ");
int idx = Integer.parseInt(line[0]);
char ch = line[1].charAt(0);
update(stree, 1, 0, S.length-1, idx-1, ch);
out.write(stree[1][0][2] + "\n");
}
//out.write(S);
in.close();
out.close();
}
} | Java | ["9 12\naaabccccc\n4 a\n4 b\n2 b\n5 a\n1 b\n6 b\n5 c\n2 a\n1 a\n5 a\n6 b\n7 b"] | 3 seconds | ["0\n1\n2\n2\n1\n2\n1\n2\n2\n2\n2\n2"] | NoteLet's consider the state of the string after each query: $$$s = $$$"aaaaccccc". In this case the string does not contain "abc" as a subsequence and no replacements are needed. $$$s = $$$"aaabccccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"aaaaccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"ababccccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$aaaaccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"ababacccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaaaacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbabacccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"bbacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"bbacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbabcbccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"bbcbcbccc". This string does not contain "abc" as a subsequence. $$$s = $$$"baabcbccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"bbbbcbccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaabcbccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababbcc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaababbbb". This string does not contain "abc" as a subsequence. | Java 8 | standard input | [
"bitmasks",
"data structures",
"dp",
"matrices"
] | b431e4af99eb78e2c6e53d5d08bb0bc4 | The first line contains two integers $$$n$$$ and $$$q$$$ $$$(1 \le n, q \le 10^5)$$$, the length of the string and the number of queries, respectively. The second line contains the string $$$s$$$, consisting of characters "a", "b" and "c". Each of the next $$$q$$$ lines contains an integer $$$i$$$ and character $$$c$$$ $$$(1 \le i \le n)$$$, index and the value of the new item in the string, respectively. It is guaranteed that character's $$$c$$$ value is "a", "b" or "c". | 2,400 | For each query output the minimal number of characters that would have to be replaced so that the string doesn't contain "abc" as a subsequence. | standard output | |
PASSED | 3e71cc7e7126e574c4e93121e89cb037 | train_110.jsonl | 1638110100 | Before becoming a successful trader William got a university degree. During his education an interesting situation happened, after which William started to listen to homework assignments much more attentively. What follows is a formal description of the homework assignment as William heard it:You are given a string $$$s$$$ of length $$$n$$$ only consisting of characters "a", "b" and "c". There are $$$q$$$ queries of format ($$$pos, c$$$), meaning replacing the element of string $$$s$$$ at position $$$pos$$$ with character $$$c$$$. After each query you must output the minimal number of characters in the string, which have to be replaced, so that the string doesn't contain string "abc" as a subsequence. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is said to be a subsequence of string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deleting some characters without changing the ordering of the remaining characters. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
private static void update(int[][][] stree, int node, int left, int right,
int idx, char ch) {
if (left == right) {
for (int i=0; i<3; i++) {
for (int j=i; j<3; j++) {
stree[node][i][j] = 0;
}
}
if (ch == 'a') {
stree[node][0][0] = 1;
} else if (ch == 'b') {
stree[node][1][1] = 1;
} else {
stree[node][2][2] = 1;
}
return;
}
int mid = (left+right)/2;
if (idx <= mid) {update(stree, node*2, left, mid, idx, ch);}
else {update(stree, node*2+1, mid+1, right, idx, ch);}
for (int i=0; i<3; i++) {
for (int j=i; j<3; j++) {
stree[node][i][j] = Integer.MAX_VALUE;
for (int split=i; split<=j; split++) {
stree[node][i][j] = Math.min(stree[node][i][j],
stree[node*2][i][split] + stree[node*2+1][split][j]);
}
}
}
}
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
String[] line = in.readLine().split(" ");
int N = Integer.parseInt(line[0]);
int Q = Integer.parseInt(line[1]);
char[] S = in.readLine().toCharArray();
int[][][] stree = new int[N*20][3][3];
for (int idx=0; idx<N; idx++) {
update(stree, 1, 0, S.length-1, idx, S[idx]);
}
for (int q=1; q<=Q; q++) {
line = in.readLine().split(" ");
int idx = Integer.parseInt(line[0]);
char ch = line[1].charAt(0);
update(stree, 1, 0, S.length-1, idx-1, ch);
out.write(stree[1][0][2] + "\n");
}
//out.write(S);
in.close();
out.close();
}
} | Java | ["9 12\naaabccccc\n4 a\n4 b\n2 b\n5 a\n1 b\n6 b\n5 c\n2 a\n1 a\n5 a\n6 b\n7 b"] | 3 seconds | ["0\n1\n2\n2\n1\n2\n1\n2\n2\n2\n2\n2"] | NoteLet's consider the state of the string after each query: $$$s = $$$"aaaaccccc". In this case the string does not contain "abc" as a subsequence and no replacements are needed. $$$s = $$$"aaabccccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"aaaaccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"ababccccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$aaaaccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"ababacccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaaaacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbabacccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"bbacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"bbacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbabcbccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"bbcbcbccc". This string does not contain "abc" as a subsequence. $$$s = $$$"baabcbccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"bbbbcbccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaabcbccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababbcc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaababbbb". This string does not contain "abc" as a subsequence. | Java 8 | standard input | [
"bitmasks",
"data structures",
"dp",
"matrices"
] | b431e4af99eb78e2c6e53d5d08bb0bc4 | The first line contains two integers $$$n$$$ and $$$q$$$ $$$(1 \le n, q \le 10^5)$$$, the length of the string and the number of queries, respectively. The second line contains the string $$$s$$$, consisting of characters "a", "b" and "c". Each of the next $$$q$$$ lines contains an integer $$$i$$$ and character $$$c$$$ $$$(1 \le i \le n)$$$, index and the value of the new item in the string, respectively. It is guaranteed that character's $$$c$$$ value is "a", "b" or "c". | 2,400 | For each query output the minimal number of characters that would have to be replaced so that the string doesn't contain "abc" as a subsequence. | standard output | |
PASSED | 6eb582aea4fe92cc3664148dde4e9f90 | train_110.jsonl | 1638110100 | Before becoming a successful trader William got a university degree. During his education an interesting situation happened, after which William started to listen to homework assignments much more attentively. What follows is a formal description of the homework assignment as William heard it:You are given a string $$$s$$$ of length $$$n$$$ only consisting of characters "a", "b" and "c". There are $$$q$$$ queries of format ($$$pos, c$$$), meaning replacing the element of string $$$s$$$ at position $$$pos$$$ with character $$$c$$$. After each query you must output the minimal number of characters in the string, which have to be replaced, so that the string doesn't contain string "abc" as a subsequence. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is said to be a subsequence of string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deleting some characters without changing the ordering of the remaining characters. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
private static void update(int[][][] stree, int node, int left, int right,
int idx, char ch) {
if (left == right) {
for (int i=0; i<3; i++) {
for (int j=i; j<3; j++) {
stree[node][i][j] = 0;
}
}
if (ch == 'a') {
stree[node][0][0] = 1;
} else if (ch == 'b') {
stree[node][1][1] = 1;
} else {
stree[node][2][2] = 1;
}
return;
}
int mid = (left+right)/2;
if (idx <= mid) {update(stree, node*2, left, mid, idx, ch);}
else {update(stree, node*2+1, mid+1, right, idx, ch);}
for (int i=0; i<3; i++) {
for (int j=i; j<3; j++) {
stree[node][i][j] = Integer.MAX_VALUE;
for (int split=i; split<=j; split++) {
stree[node][i][j] = Math.min(stree[node][i][j],
stree[node*2][i][split] + stree[node*2+1][split][j]);
}
}
}
}
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
String[] line = in.readLine().split(" ");
int N = Integer.parseInt(line[0]);
int Q = Integer.parseInt(line[1]);
char[] S = in.readLine().toCharArray();
int[][][] stree = new int[N*20][3][3];
for (int idx=0; idx<N; idx++) {
update(stree, 1, 0, S.length-1, idx, S[idx]);
}
for (int q=1; q<=Q; q++) {
line = in.readLine().split(" ");
int idx = Integer.parseInt(line[0]);
char ch = line[1].charAt(0);
update(stree, 1, 0, S.length-1, idx-1, ch);
int res = Integer.MAX_VALUE;
for (int i=0; i<3; i++) {
for (int j=i; j<3; j++) {
res = Math.min(res, stree[1][i][j]);
}
}
out.write(stree[1][0][2] + "\n");
}
//out.write(S);
in.close();
out.close();
}
} | Java | ["9 12\naaabccccc\n4 a\n4 b\n2 b\n5 a\n1 b\n6 b\n5 c\n2 a\n1 a\n5 a\n6 b\n7 b"] | 3 seconds | ["0\n1\n2\n2\n1\n2\n1\n2\n2\n2\n2\n2"] | NoteLet's consider the state of the string after each query: $$$s = $$$"aaaaccccc". In this case the string does not contain "abc" as a subsequence and no replacements are needed. $$$s = $$$"aaabccccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"aaaaccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"ababccccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$aaaaccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"ababacccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaaaacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbabacccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"bbacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"bbacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbabcbccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"bbcbcbccc". This string does not contain "abc" as a subsequence. $$$s = $$$"baabcbccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"bbbbcbccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaabcbccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababbcc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaababbbb". This string does not contain "abc" as a subsequence. | Java 8 | standard input | [
"bitmasks",
"data structures",
"dp",
"matrices"
] | b431e4af99eb78e2c6e53d5d08bb0bc4 | The first line contains two integers $$$n$$$ and $$$q$$$ $$$(1 \le n, q \le 10^5)$$$, the length of the string and the number of queries, respectively. The second line contains the string $$$s$$$, consisting of characters "a", "b" and "c". Each of the next $$$q$$$ lines contains an integer $$$i$$$ and character $$$c$$$ $$$(1 \le i \le n)$$$, index and the value of the new item in the string, respectively. It is guaranteed that character's $$$c$$$ value is "a", "b" or "c". | 2,400 | For each query output the minimal number of characters that would have to be replaced so that the string doesn't contain "abc" as a subsequence. | standard output | |
PASSED | f8e5773c4be9c048b314649f0a37fb47 | train_110.jsonl | 1638110100 | Before becoming a successful trader William got a university degree. During his education an interesting situation happened, after which William started to listen to homework assignments much more attentively. What follows is a formal description of the homework assignment as William heard it:You are given a string $$$s$$$ of length $$$n$$$ only consisting of characters "a", "b" and "c". There are $$$q$$$ queries of format ($$$pos, c$$$), meaning replacing the element of string $$$s$$$ at position $$$pos$$$ with character $$$c$$$. After each query you must output the minimal number of characters in the string, which have to be replaced, so that the string doesn't contain string "abc" as a subsequence. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is said to be a subsequence of string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deleting some characters without changing the ordering of the remaining characters. | 256 megabytes | //package codeforce.practice;
import org.w3c.dom.Node;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import static java.lang.Math.min;
import static java.lang.System.out;
import static java.util.stream.Collectors.joining;
/**
* @author pribic (Priyank Doshi)
* @see <a href="https://codeforces.com/contest/1609/problem/E" target="_top">https://codeforces.com/contest/1609/problem/E</a>
* @since 29/11/21 10:37 PM
*/
public class p1609_William_The_Oblivious {
static FastScanner sc = new FastScanner(System.in);
public static void main(String[] args) {
try (PrintWriter out = new PrintWriter(System.out)) {
int T = 1;//sc.nextInt();
for (int tt = 1; tt <= T; tt++) {
int n = sc.nextInt();
int q = sc.nextInt();
String s = sc.next();
SegTree st = new SegTree(n);
for (int i = 0; i < s.length(); i++)
st.set(i, s.charAt(i));
StringBuilder sb = new StringBuilder();
while (q-- > 0) {
int pos = sc.nextInt() - 1;
char c = sc.next().charAt(0);
st.set(pos, c);
sb.append(st.get()).append("\n");
}
System.out.println(sb);
}
}
}
static class Node {
int a, b, c, ab, bc, abc;
Node() {
}
Node(char ch) {
if (ch == 'a')
a = 1;
else if (ch == 'b')
b = 1;
else if (ch == 'c')
c = 1;
}
}
static class SegTree {
Node[] data;
int size;
SegTree(int n) {
size = 1;
while (size < n) size *= 2;
data = new Node[2 * size];
for (int i = 0; i < data.length; i++)
data[i] = new Node();
}
void set(int pos, char c) {
set(pos, c, 0, 0, size);
}
private void set(int idx, char c, int pos, int lx, int rx) { // [lx, rx), pos represents location in array
if (rx - lx == 1) {
Node node = new Node(c);
data[pos] = node;
return;
}
int mid = (lx + rx) / 2;
if (idx < mid)
set(idx, c, 2 * pos + 1, lx, mid);
else
set(idx, c, 2 * pos + 2, mid, rx);
data[pos] = merge(data[pos * 2 + 1], data[2 * pos + 2]);
}
int get() {
return data[0].abc;
}
private Node merge(Node one, Node other) {
Node node = new Node();
node.a = one.a + other.a;
node.b = one.b + other.b;
node.c = one.c + other.c;
node.ab = min(one.a + other.ab, one.ab + other.b);
node.bc = min(one.b + other.bc, one.bc + other.c);
node.abc = min(one.a + other.abc, min(one.ab + other.bc, one.abc + other.c));
return node;
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f), 32768);
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["9 12\naaabccccc\n4 a\n4 b\n2 b\n5 a\n1 b\n6 b\n5 c\n2 a\n1 a\n5 a\n6 b\n7 b"] | 3 seconds | ["0\n1\n2\n2\n1\n2\n1\n2\n2\n2\n2\n2"] | NoteLet's consider the state of the string after each query: $$$s = $$$"aaaaccccc". In this case the string does not contain "abc" as a subsequence and no replacements are needed. $$$s = $$$"aaabccccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"aaaaccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"ababccccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$aaaaccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"ababacccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaaaacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbabacccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"bbacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"bbacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbabcbccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"bbcbcbccc". This string does not contain "abc" as a subsequence. $$$s = $$$"baabcbccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"bbbbcbccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaabcbccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababbcc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaababbbb". This string does not contain "abc" as a subsequence. | Java 8 | standard input | [
"bitmasks",
"data structures",
"dp",
"matrices"
] | b431e4af99eb78e2c6e53d5d08bb0bc4 | The first line contains two integers $$$n$$$ and $$$q$$$ $$$(1 \le n, q \le 10^5)$$$, the length of the string and the number of queries, respectively. The second line contains the string $$$s$$$, consisting of characters "a", "b" and "c". Each of the next $$$q$$$ lines contains an integer $$$i$$$ and character $$$c$$$ $$$(1 \le i \le n)$$$, index and the value of the new item in the string, respectively. It is guaranteed that character's $$$c$$$ value is "a", "b" or "c". | 2,400 | For each query output the minimal number of characters that would have to be replaced so that the string doesn't contain "abc" as a subsequence. | standard output | |
PASSED | a72eb3aacfa961e44b3b2f022b6a8d22 | train_110.jsonl | 1638110100 | Before becoming a successful trader William got a university degree. During his education an interesting situation happened, after which William started to listen to homework assignments much more attentively. What follows is a formal description of the homework assignment as William heard it:You are given a string $$$s$$$ of length $$$n$$$ only consisting of characters "a", "b" and "c". There are $$$q$$$ queries of format ($$$pos, c$$$), meaning replacing the element of string $$$s$$$ at position $$$pos$$$ with character $$$c$$$. After each query you must output the minimal number of characters in the string, which have to be replaced, so that the string doesn't contain string "abc" as a subsequence. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is said to be a subsequence of string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deleting some characters without changing the ordering of the remaining characters. | 256 megabytes | //package codeforce.practice;
import org.w3c.dom.Node;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import static java.lang.Math.min;
import static java.lang.System.out;
import static java.util.stream.Collectors.joining;
/**
* @author pribic (Priyank Doshi)
* @see <a href="https://codeforces.com/contest/1609/problem/E" target="_top">https://codeforces.com/contest/1609/problem/E</a>
* @since 29/11/21 10:37 PM
*/
public class p1609_William_The_Oblivious {
static FastScanner sc = new FastScanner(System.in);
public static void main(String[] args) {
try (PrintWriter out = new PrintWriter(System.out)) {
int T = 1;//sc.nextInt();
for (int tt = 1; tt <= T; tt++) {
int n = sc.nextInt();
int q = sc.nextInt();
String s = sc.next();
SegTree st = new SegTree(n);
for (int i = 0; i < s.length(); i++)
st.set(i, s.charAt(i));
while (q-- > 0) {
int pos = sc.nextInt() - 1;
char c = sc.next().charAt(0);
st.set(pos, c);
System.out.println(st.get());
}
}
}
}
static class Node {
int a, b, c, ab, bc, abc;
Node() {
}
Node(char ch) {
if (ch == 'a')
a = 1;
else if (ch == 'b')
b = 1;
else if (ch == 'c')
c = 1;
}
}
static class SegTree {
Node[] data;
int size;
SegTree(int n) {
size = 1;
while (size < n) size *= 2;
data = new Node[2 * size];
for (int i = 0; i < data.length; i++)
data[i] = new Node();
}
void set(int pos, char c) {
set(pos, c, 0, 0, size);
}
private void set(int idx, char c, int pos, int lx, int rx) { // [lx, rx), pos represents location in array
if (rx - lx == 1) {
Node node = new Node(c);
data[pos] = node;
return;
}
int mid = (lx + rx) / 2;
if (idx < mid)
set(idx, c, 2 * pos + 1, lx, mid);
else
set(idx, c, 2 * pos + 2, mid, rx);
data[pos] = merge(data[pos * 2 + 1], data[2 * pos + 2]);
}
int get() {
return data[0].abc;
}
private Node merge(Node one, Node other) {
Node node = new Node();
node.a = one.a + other.a;
node.b = one.b + other.b;
node.c = one.c + other.c;
node.ab = min(one.a + other.ab, one.ab + other.b);
node.bc = min(one.b + other.bc, one.bc + other.c);
node.abc = min(one.a + other.abc, min(one.ab + other.bc, one.abc + other.c));
return node;
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f), 32768);
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["9 12\naaabccccc\n4 a\n4 b\n2 b\n5 a\n1 b\n6 b\n5 c\n2 a\n1 a\n5 a\n6 b\n7 b"] | 3 seconds | ["0\n1\n2\n2\n1\n2\n1\n2\n2\n2\n2\n2"] | NoteLet's consider the state of the string after each query: $$$s = $$$"aaaaccccc". In this case the string does not contain "abc" as a subsequence and no replacements are needed. $$$s = $$$"aaabccccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"aaaaccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"ababccccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$aaaaccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"ababacccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaaaacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbabacccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"bbacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"bbacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbabcbccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"bbcbcbccc". This string does not contain "abc" as a subsequence. $$$s = $$$"baabcbccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"bbbbcbccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaabcbccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababbcc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaababbbb". This string does not contain "abc" as a subsequence. | Java 8 | standard input | [
"bitmasks",
"data structures",
"dp",
"matrices"
] | b431e4af99eb78e2c6e53d5d08bb0bc4 | The first line contains two integers $$$n$$$ and $$$q$$$ $$$(1 \le n, q \le 10^5)$$$, the length of the string and the number of queries, respectively. The second line contains the string $$$s$$$, consisting of characters "a", "b" and "c". Each of the next $$$q$$$ lines contains an integer $$$i$$$ and character $$$c$$$ $$$(1 \le i \le n)$$$, index and the value of the new item in the string, respectively. It is guaranteed that character's $$$c$$$ value is "a", "b" or "c". | 2,400 | For each query output the minimal number of characters that would have to be replaced so that the string doesn't contain "abc" as a subsequence. | standard output | |
PASSED | 215bd17ec7c1e76105e6ae07a9053800 | train_110.jsonl | 1638110100 | Before becoming a successful trader William got a university degree. During his education an interesting situation happened, after which William started to listen to homework assignments much more attentively. What follows is a formal description of the homework assignment as William heard it:You are given a string $$$s$$$ of length $$$n$$$ only consisting of characters "a", "b" and "c". There are $$$q$$$ queries of format ($$$pos, c$$$), meaning replacing the element of string $$$s$$$ at position $$$pos$$$ with character $$$c$$$. After each query you must output the minimal number of characters in the string, which have to be replaced, so that the string doesn't contain string "abc" as a subsequence. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is said to be a subsequence of string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deleting some characters without changing the ordering of the remaining characters. | 256 megabytes | /*
stream Butter!
eggyHide eggyVengeance
I need U
xiao rerun when
*/
import static java.lang.Math.*;
import java.util.*;
import java.io.*;
import java.math.*;
public class x1609E
{
static int N;
public static void main(String hi[]) throws Exception
{
Node[] templates = new Node[3];
templates[0] = new Node(1, 0, 0, 0, 0, 0);
templates[1] = new Node(0, 0, 0, 0, 1, 0);
templates[2] = new Node(0, 0, 0, 0, 0, 1);
segtree = new Node[1<<19];
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
N = Integer.parseInt(st.nextToken());
int Q = Integer.parseInt(st.nextToken());
char[] arr = infile.readLine().toCharArray();
for(int i=0; i < N; i++)
update(i, templates[arr[i]-'a']);
StringBuilder sb = new StringBuilder();
while(Q-->0)
{
st = new StringTokenizer(infile.readLine());
int dex = Integer.parseInt(st.nextToken())-1;
char tag = st.nextToken().charAt(0);
update(dex, templates[tag-'a']);
sb.append(segtree[1].abc+"\n");
}
System.out.print(sb);
}
static Node[] segtree;
public static void update(int dex, Node updated)
{
updateHelper(1, 0, N-1, dex, updated);
}
public static void updateHelper(int id, int L, int R, int dex, Node updated)
{
if(R < dex || dex < L)
return;
if(L == R)
{
segtree[id] = updated;
return;
}
int mid = (L+R)/2;
updateHelper(id*2, L, mid, dex, updated);
updateHelper(id*2+1, mid+1, R, dex, updated);
segtree[id] = merge(segtree[id*2], segtree[id*2+1]);
}
public static Node merge(Node left, Node right)
{
if(left == null)
return right;
if(right == null)
return left;
int a = left.a+right.a;
int b = left.b+right.b;
int c = left.c+right.c;
int ab = min(left.ab+right.b, left.a+right.ab);
int bc = min(left.bc+right.c, left.b+right.bc);
int abc = min(left.a+right.abc, left.abc+right.c);
abc = min(abc, left.ab+right.bc);
return new Node(a, ab, abc, bc, b, c);
}
}
class Node
{
public int a;
public int ab;
public int abc;
public int bc;
public int b;
public int c;
public Node(int q, int w, int e, int r, int t, int y)
{
a = q;
ab = w;
abc = e;
bc = r;
b = t;
c = y;
ab = min(ab, min(a,b));
bc = min(bc, min(b, c));
abc = min(abc, min(ab, bc));
}
}
/*
minimum # of characters to delete to ensure these don't appear in node:
"a"
"ab"
"abc"
"c"
"bc"
*/ | Java | ["9 12\naaabccccc\n4 a\n4 b\n2 b\n5 a\n1 b\n6 b\n5 c\n2 a\n1 a\n5 a\n6 b\n7 b"] | 3 seconds | ["0\n1\n2\n2\n1\n2\n1\n2\n2\n2\n2\n2"] | NoteLet's consider the state of the string after each query: $$$s = $$$"aaaaccccc". In this case the string does not contain "abc" as a subsequence and no replacements are needed. $$$s = $$$"aaabccccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"aaaaccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"ababccccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$aaaaccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"ababacccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaaaacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbabacccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"bbacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"bbacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbabcbccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"bbcbcbccc". This string does not contain "abc" as a subsequence. $$$s = $$$"baabcbccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"bbbbcbccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaabcbccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababbcc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaababbbb". This string does not contain "abc" as a subsequence. | Java 8 | standard input | [
"bitmasks",
"data structures",
"dp",
"matrices"
] | b431e4af99eb78e2c6e53d5d08bb0bc4 | The first line contains two integers $$$n$$$ and $$$q$$$ $$$(1 \le n, q \le 10^5)$$$, the length of the string and the number of queries, respectively. The second line contains the string $$$s$$$, consisting of characters "a", "b" and "c". Each of the next $$$q$$$ lines contains an integer $$$i$$$ and character $$$c$$$ $$$(1 \le i \le n)$$$, index and the value of the new item in the string, respectively. It is guaranteed that character's $$$c$$$ value is "a", "b" or "c". | 2,400 | For each query output the minimal number of characters that would have to be replaced so that the string doesn't contain "abc" as a subsequence. | standard output | |
PASSED | eea084c9cbe4d7bd2bbd1d57a547ca52 | train_110.jsonl | 1638110100 | Before becoming a successful trader William got a university degree. During his education an interesting situation happened, after which William started to listen to homework assignments much more attentively. What follows is a formal description of the homework assignment as William heard it:You are given a string $$$s$$$ of length $$$n$$$ only consisting of characters "a", "b" and "c". There are $$$q$$$ queries of format ($$$pos, c$$$), meaning replacing the element of string $$$s$$$ at position $$$pos$$$ with character $$$c$$$. After each query you must output the minimal number of characters in the string, which have to be replaced, so that the string doesn't contain string "abc" as a subsequence. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is said to be a subsequence of string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deleting some characters without changing the ordering of the remaining characters. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class e {
public static void main(String[] args) {
FastScanner scan=new FastScanner();
PrintWriter out=new PrintWriter(System.out);
/*
in our segment tree we store the answer for all substrings [i,j]
to merge two segments X and Y together we consider three cases:
1. X has no subsequence a, and Y has no subsequence abc
2. X has no subsequence ab, and Y has no subsequence bc
3. X has no subsequence abc, and Y has no subsequence c
we take the best of these three.
so in each node of the segment tree we store the number of characters we need to change
to ensure that there is no substring: a, b, c, ab, bc, abc
*/
int n=scan.nextInt(), q=scan.nextInt();
str=scan.next().toCharArray();
segtree tree=new segtree(n);
for(int i=0;i<n;i++) {
tree.updateChar(i,str[i]);
}
// out.println(Arrays.toString(tree.lo));
// out.println(Arrays.toString(tree.hi));
// out.println();
// out.println(Arrays.toString(tree.changeA));
// out.println(Arrays.toString(tree.changeB));
// out.println(Arrays.toString(tree.changeC));
// out.println(Arrays.toString(tree.changeAB));
// out.println(Arrays.toString(tree.changeBC));
// out.println(Arrays.toString(tree.changeABC));
for(int i=0;i<q;i++) {
int p=scan.nextInt()-1;
char c=scan.next().charAt(0);
str[p]=c;
tree.updateChar(p,c);
out.println(tree.changeABC[1]);
// out.println(Arrays.toString(tree.changeA));
// out.println(Arrays.toString(tree.changeB));
// out.println(Arrays.toString(tree.changeC));
// out.println(Arrays.toString(tree.changeAB));
// out.println(Arrays.toString(tree.changeBC));
// out.println(Arrays.toString(tree.changeABC));
}
out.close();
}
static char[] str;
static class segtree {
int n;
int[] lo, hi, changeA, changeB, changeC, changeAB, changeBC, changeABC;
segtree(int n) {
this.n=n;
lo=new int[4*n+1];//low end of range for each node
hi=new int[4*n+1];//high end of range for each node
changeA=new int[4*n+1];
changeB=new int[4*n+1];
changeC=new int[4*n+1];
changeAB=new int[4*n+1];
changeBC=new int[4*n+1];
changeABC=new int[4*n+1];
init(1,0,n-1);//init for root node and it is the entire range
}
void init(int i, int a, int b) {
lo[i]=a;
hi[i]=b;
if(a==b) {
return;//you are at a leaf
}
int m=(a+b)/2;
init(2*i,a,m);//recur for left child
init(2*i+1,m+1,b);//recur for right child
}
void updateChar(int p, char c) {
updateChar(1,p,c);
}
void updateChar(int i, int p, char c) {
if(hi[i]<p||lo[i]>p) return;//no cover
if(lo[i]==hi[i]&&lo[i]==p) {//full cover
if(str[p]=='a') {
changeA[i]=1;
changeB[i]=changeC[i]=0;
}
if(str[p]=='b') {
changeB[i]=1;
changeA[i]=changeC[i]=0;
}
if(str[p]=='c') {
changeC[i]=1;
changeA[i]=changeB[i]=0;
}
return;
}
updateChar(2*i,p,c);
updateChar(2*i+1,p,c);
update(i);
}
void update(int i) {
changeA[i]=changeA[2*i]+changeA[2*i+1];
changeB[i]=changeB[2*i]+changeB[2*i+1];
changeC[i]=changeC[2*i]+changeC[2*i+1];
changeAB[i]=Math.min(changeA[2*i]+changeAB[2*i+1],changeAB[2*i]+changeB[2*i+1]);
changeBC[i]=Math.min(changeB[2*i]+changeBC[2*i+1],changeBC[2*i]+changeC[2*i+1]);
int optimal=Integer.MAX_VALUE;
optimal=Math.min(optimal,changeA[2*i]+changeABC[2*i+1]);
optimal=Math.min(optimal,changeAB[2*i]+changeBC[2*i+1]);
optimal=Math.min(optimal,changeABC[2*i]+changeC[2*i+1]);
changeABC[i]=optimal;
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e){e.printStackTrace();}
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception e) {e.printStackTrace();}
return st.nextToken();
}
public int nextInt() {return Integer.parseInt(next());}
public long nextLong() {return Long.parseLong(next());}
public double nextDouble() {return Double.parseDouble(next());}
public String nextLine() {
String line = "";
if(st.hasMoreTokens()) line = st.nextToken();
else try {return br.readLine();}catch(IOException e){e.printStackTrace();}
while(st.hasMoreTokens()) line += " "+st.nextToken();
return line;
}
}
} | Java | ["9 12\naaabccccc\n4 a\n4 b\n2 b\n5 a\n1 b\n6 b\n5 c\n2 a\n1 a\n5 a\n6 b\n7 b"] | 3 seconds | ["0\n1\n2\n2\n1\n2\n1\n2\n2\n2\n2\n2"] | NoteLet's consider the state of the string after each query: $$$s = $$$"aaaaccccc". In this case the string does not contain "abc" as a subsequence and no replacements are needed. $$$s = $$$"aaabccccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"aaaaccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"ababccccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$aaaaccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"ababacccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaaaacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbabacccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"bbacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"bbacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"bbabcbccc". In this case 1 replacements can be performed to get, for instance, string $$$s = $$$"bbcbcbccc". This string does not contain "abc" as a subsequence. $$$s = $$$"baabcbccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"bbbbcbccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaabcbccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacccccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababccc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaacacccc". This string does not contain "abc" as a subsequence. $$$s = $$$"aaababbcc". In this case 2 replacements can be performed to get, for instance, string $$$s = $$$"aaababbbb". This string does not contain "abc" as a subsequence. | Java 8 | standard input | [
"bitmasks",
"data structures",
"dp",
"matrices"
] | b431e4af99eb78e2c6e53d5d08bb0bc4 | The first line contains two integers $$$n$$$ and $$$q$$$ $$$(1 \le n, q \le 10^5)$$$, the length of the string and the number of queries, respectively. The second line contains the string $$$s$$$, consisting of characters "a", "b" and "c". Each of the next $$$q$$$ lines contains an integer $$$i$$$ and character $$$c$$$ $$$(1 \le i \le n)$$$, index and the value of the new item in the string, respectively. It is guaranteed that character's $$$c$$$ value is "a", "b" or "c". | 2,400 | For each query output the minimal number of characters that would have to be replaced so that the string doesn't contain "abc" as a subsequence. | standard output | |
PASSED | 8517a642b61eeae413e1ca0553a2b6e7 | train_110.jsonl | 1638110100 | William has an array of non-negative numbers $$$a_1, a_2, \dots, a_n$$$. He wants you to find out how many segments $$$l \le r$$$ pass the check. The check is performed in the following manner: The minimum and maximum numbers are found on the segment of the array starting at $$$l$$$ and ending at $$$r$$$. The check is considered to be passed if the binary representation of the minimum and maximum numbers have the same number of bits equal to 1. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
import java.util.stream.*;
public class F_fenwick {
void submit() {
int n = nextInt();
// int n = 1_000_000;
long[] a = new long[n];
int[] b = new int[n];
boolean[] check = new boolean[62];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
// a[i] = i & 15;
// a[i] = i ^ (i >> 1);
b[i] = Long.bitCount(a[i]);
check[b[i]] = true;
}
int[] a0 = new int[n];
int[] a1 = new int[n];
int[] b0 = new int[n];
int[] b1 = new int[n];
int[] min = new int[n + 1];
int[] max = new int[n + 1];
min[0] = max[0] = -1;
long ret = 0;
int szMin = 1, szMax = 1;
int CUR_VAL = 0;
for (int bit = 0; bit < 62; bit++) {
if (!check[bit]) {
continue;
}
for (int j = 0; j < n; j++) {
long x = a[j];
// min
while (szMin > 1 && a[min[szMin - 1]] >= x) {
if (b[min[szMin - 1]] == bit) {
int low = min[szMin - 2];
int high = min[szMin - 1];
for (int i = high; i >= 0; i = (i & (i + 1)) - 1) {
CUR_VAL -= b1[i] * high + b0[i];
}
for (int i = low; i >= 0; i = (i & (i + 1)) - 1) {
CUR_VAL += b1[i] * low + b0[i];
}
for (int i = low + 1; i < n; i |= i + 1) {
a0[i] += low;
a1[i]--;
}
for (int i = high; i < n; i |= i + 1) {
a0[i] -= high;
a1[i]++;
}
// st.modifySegm(min[szMin - 2] + 1, min[szMin - 1] + 1, -1);
}
--szMin;
}
if (b[j] == bit) {
int low = min[szMin - 1];
int high = j;
for (int i = high; i >= 0; i = (i & (i + 1)) - 1) {
CUR_VAL += b1[i] * high + b0[i];
}
for (int i = low; i >= 0; i = (i & (i + 1)) - 1) {
CUR_VAL -= b1[i] * low + b0[i];
}
for (int i = low + 1; i < n; i |= i + 1) {
a0[i] -= low;
a1[i]++;
}
for (int i = high; i < n; i |= i + 1) {
a0[i] += high;
a1[i]--;
}
// st.modifySegm(min[szMin - 1] + 1, j + 1, 1);
}
min[szMin++] = j;
// max
while (szMax > 1 && a[max[szMax - 1]] <= x) {
if (b[max[szMax - 1]] == bit) {
int low = max[szMax - 2];
int high = max[szMax - 1];
for (int i = high; i >= 0; i = (i & (i + 1)) - 1) {
CUR_VAL -= a1[i] * high + a0[i];
}
for (int i = low; i >= 0; i = (i & (i + 1)) - 1) {
CUR_VAL += a1[i] * low + a0[i];
}
for (int i = low + 1; i < n; i |= i + 1) {
b0[i] += low;
b1[i]--;
}
for (int i = high; i < n; i |= i + 1) {
b0[i] -= high;
b1[i]++;
}
// st.modifySegm(max[szMax - 2] + 1, max[szMax - 1] + 1, -1);
}
--szMax;
}
if (b[j] == bit) {
int low = max[szMax - 1];
int high = j;
for (int i = high; i >= 0; i = (i & (i + 1)) - 1) {
CUR_VAL += a1[i] * high + a0[i];
}
for (int i = low; i >= 0; i = (i & (i + 1)) - 1) {
CUR_VAL -= a1[i] * low + a0[i];
}
for (int i = low + 1; i < n; i |= i + 1) {
b0[i] -= low;
b1[i]++;
}
for (int i = high; i < n; i |= i + 1) {
b0[i] += high;
b1[i]--;
}
// st.modifySegm(max[szMax - 1] + 1, j + 1, 1);
}
max[szMax++] = j;
ret += CUR_VAL;
}
szMin = szMax = 1;
Arrays.fill(a0, 0);
Arrays.fill(a1, 0);
Arrays.fill(b0, 0);
Arrays.fill(b1, 0);
CUR_VAL = 0;
}
out.println(ret);
}
void test() {
}
void stress() {
for (int tst = 0;; tst++) {
if (false) {
throw new AssertionError();
}
System.err.println(tst);
}
}
F_fenwick() throws IOException {
is = System.in;
out = new PrintWriter(System.out);
submit();
// stress();
// test();
out.close();
}
static final Random rng = new Random();
static final int C = 5;
static int rand(int l, int r) {
return l + rng.nextInt(r - l + 1);
}
public static void main(String[] args) throws IOException {
new F_fenwick();
}
private InputStream is;
PrintWriter out;
private byte[] buf = new byte[1 << 14];
private int bufSz = 0, bufPtr = 0;
private int readByte() {
if (bufSz == -1)
throw new RuntimeException("Reading past EOF");
if (bufPtr >= bufSz) {
bufPtr = 0;
try {
bufSz = is.read(buf);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (bufSz <= 0)
return -1;
}
return buf[bufPtr++];
}
private boolean isTrash(int c) {
return c < 33 || c > 126;
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isTrash(b))
;
return b;
}
String nextToken() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!isTrash(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
String nextString() {
int b = readByte();
StringBuilder sb = new StringBuilder();
while (!isTrash(b) || b == ' ') {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
char nextChar() {
return (char) skip();
}
int nextInt() {
int ret = 0;
int b = skip();
if (b != '-' && (b < '0' || b > '9')) {
throw new InputMismatchException();
}
boolean neg = false;
if (b == '-') {
neg = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
ret = ret * 10 + (b - '0');
} else {
if (b != -1 && !isTrash(b)) {
throw new InputMismatchException();
}
return neg ? -ret : ret;
}
b = readByte();
}
}
long nextLong() {
long ret = 0;
int b = skip();
if (b != '-' && (b < '0' || b > '9')) {
throw new InputMismatchException();
}
boolean neg = false;
if (b == '-') {
neg = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
ret = ret * 10 + (b - '0');
} else {
if (b != -1 && !isTrash(b)) {
throw new InputMismatchException();
}
return neg ? -ret : ret;
}
b = readByte();
}
}
} | Java | ["5\n1 2 3 4 5", "10\n0 5 7 3 9 10 1 6 13 7"] | 2 seconds | ["9", "18"] | null | Java 11 | standard input | [
"data structures",
"divide and conquer",
"meet-in-the-middle",
"two pointers"
] | 026a7c78986c67593dbb4603da73e7df | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^6$$$), the size of array $$$a$$$. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 10^{18}$$$), the contents of array $$$a$$$. | 2,800 | Output a single number — the total number of segments that passed the check. | standard output | |
PASSED | 842bc3023514b18915dd6add3b281039 | train_110.jsonl | 1618839300 | Given an array $$$a$$$ of length $$$n$$$, tell us whether it has a non-empty subsequence such that the product of its elements is not a perfect square.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int testcase = sc.nextInt();
for (int limit = 0; limit < testcase; limit++) {
boolean flag = false;
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
int in = sc.nextInt();
if (((int)Math.sqrt(in)*(int)Math.sqrt(in)) != in) {
flag = true;
}
}
if(flag) System.out.println("YES");
else System.out.println("NO");
}
}
} | Java | ["2\n3\n1 5 4\n2\n100 10000"] | 1 second | ["YES\nNO"] | NoteIn the first example, the product of the whole array ($$$20$$$) isn't a perfect square.In the second example, all subsequences have a perfect square product. | Java 11 | standard input | [
"math",
"number theory"
] | 33a31edb75c9b0cf3a49ba97ad677632 | The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^4$$$) — the elements of the array $$$a$$$. | 800 | If there's a subsequence of $$$a$$$ whose product isn't a perfect square, print "YES". Otherwise, print "NO". | standard output | |
PASSED | facdffbc90c6adda76f220ea93277089 | train_110.jsonl | 1618839300 | Given an array $$$a$$$ of length $$$n$$$, tell us whether it has a non-empty subsequence such that the product of its elements is not a perfect square.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. | 256 megabytes | import java.util.*;
@SuppressWarnings("unused")
public class Main {
private static void solve(int[] nums, int n) {
for (int num : nums) {
long d = (long) Math.sqrt(num);
if (d * d != num) {
System.out.println("YES");
return;
}
}
System.out.println("NO");
}
public static void main(String[] args) {
int tnum = scanner.nextInt();
for (int t = 0; t < tnum; t++) {
int n = scanner.nextInt();
int[] nums = readIntArray(n);
solve(nums, n);
}
}
private static int[] readIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
return arr;
}
private static int[][] readIntGrid(int n, int m) {
int[][] grid = new int[n][m];
for (int i = 0; i < n; i++) {
grid[i] = readIntArray(m);
}
return grid;
}
private static char[][] readStringsIntoCharGrid(int n, int m) {
char[][] grid = new char[n][m];
for (int i = 0; i < n; i++) {
String s = scanner.next();
for (int j = 0; j < m; j++) {
grid[i][j] = s.charAt(j);
}
}
return grid;
}
private static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
private static final Scanner scanner = new Scanner(System.in);
private static final Map<?, ?> unused_map = new HashMap<>();
private static final List<?> unused_list = new ArrayList<>();
}
| Java | ["2\n3\n1 5 4\n2\n100 10000"] | 1 second | ["YES\nNO"] | NoteIn the first example, the product of the whole array ($$$20$$$) isn't a perfect square.In the second example, all subsequences have a perfect square product. | Java 11 | standard input | [
"math",
"number theory"
] | 33a31edb75c9b0cf3a49ba97ad677632 | The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^4$$$) — the elements of the array $$$a$$$. | 800 | If there's a subsequence of $$$a$$$ whose product isn't a perfect square, print "YES". Otherwise, print "NO". | standard output | |
PASSED | a3c2adb4968e21110e4b178a78f26ef1 | train_110.jsonl | 1618839300 | Given an array $$$a$$$ of length $$$n$$$, tell us whether it has a non-empty subsequence such that the product of its elements is not a perfect square.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. | 256 megabytes | import java.io.DataInputStream;
import java.io.IOException;
import java.io.PrintWriter;
public class A_div2_716 {
public static void main(String[] args) throws IOException {
Reader scan = new Reader();
PrintWriter p = new PrintWriter(System.out);
StringBuilder sb = new StringBuilder();
int t = scan.nextInt();
while (t-- > 0) {
int n = scan.nextInt();
int[] a = new int[n];
for(int i=0;i<n;i++) {
a[i] = scan.nextInt();
}
if(solve(a, n))
sb.append("YES").append("\n");
else
sb.append("NO").append("\n");
}
p.print(sb);
p.close();
}
static boolean solve(int[] a, int n) {
for(int i=0;i<n;i++) {
double temp = Math.sqrt(a[i]);
if(Math.ceil(temp) != Math.floor(temp))
return true;
}
return false;
}
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
}
| Java | ["2\n3\n1 5 4\n2\n100 10000"] | 1 second | ["YES\nNO"] | NoteIn the first example, the product of the whole array ($$$20$$$) isn't a perfect square.In the second example, all subsequences have a perfect square product. | Java 11 | standard input | [
"math",
"number theory"
] | 33a31edb75c9b0cf3a49ba97ad677632 | The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^4$$$) — the elements of the array $$$a$$$. | 800 | If there's a subsequence of $$$a$$$ whose product isn't a perfect square, print "YES". Otherwise, print "NO". | standard output | |
PASSED | 025a7af7f6867da677f304ef76715939 | train_110.jsonl | 1618839300 | Given an array $$$a$$$ of length $$$n$$$, tell us whether it has a non-empty subsequence such that the product of its elements is not a perfect square.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int entries = Integer.parseInt(scan.nextLine());
for (int i = 0; i < entries; i++) {
int ent = Integer.parseInt(scan.nextLine());
ArrayList<Integer> nums = new ArrayList<Integer>();
String[] num = scan.nextLine().split(" ");
int[] numl = new int[num.length];
for (int j = 0; j < num.length; j++) {
numl[j] = Integer.parseInt(num[j]);
}
boolean found = false;
for (int j = 0; j < numl.length; j++) {
if (Math.sqrt(numl[j])-Math.floor(Math.sqrt(numl[j])) != 0) {
found = true;
System.out.println("YES");
break;
}
}
if (found == false) {
System.out.println("NO");
}
}
}
} | Java | ["2\n3\n1 5 4\n2\n100 10000"] | 1 second | ["YES\nNO"] | NoteIn the first example, the product of the whole array ($$$20$$$) isn't a perfect square.In the second example, all subsequences have a perfect square product. | Java 11 | standard input | [
"math",
"number theory"
] | 33a31edb75c9b0cf3a49ba97ad677632 | The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^4$$$) — the elements of the array $$$a$$$. | 800 | If there's a subsequence of $$$a$$$ whose product isn't a perfect square, print "YES". Otherwise, print "NO". | standard output | |
PASSED | 5bc4cd57b2cdf49076ae34cdbd3252ca | train_110.jsonl | 1618839300 | Given an array $$$a$$$ of length $$$n$$$, tell us whether it has a non-empty subsequence such that the product of its elements is not a perfect square.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int entries = Integer.parseInt(scan.nextLine());
for (int i = 0; i < entries; i++) {
int ent = Integer.parseInt(scan.nextLine());
ArrayList<Integer> nums = new ArrayList<Integer>();
String[] num = scan.nextLine().split(" ");
int[] numl = new int[num.length];
for (int j = 0; j < num.length; j++) {
numl[j] = Integer.parseInt(num[j]);
}
int prod = 1;
boolean found = false;
for (int j = 0; j < numl.length; j++) {
if (Math.sqrt(numl[j])-Math.floor(Math.sqrt(numl[j])) != 0) {
found = true;
System.out.println("YES");
break;
}
}
if (found == false) {
System.out.println("NO");
}
}
}
} | Java | ["2\n3\n1 5 4\n2\n100 10000"] | 1 second | ["YES\nNO"] | NoteIn the first example, the product of the whole array ($$$20$$$) isn't a perfect square.In the second example, all subsequences have a perfect square product. | Java 11 | standard input | [
"math",
"number theory"
] | 33a31edb75c9b0cf3a49ba97ad677632 | The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^4$$$) — the elements of the array $$$a$$$. | 800 | If there's a subsequence of $$$a$$$ whose product isn't a perfect square, print "YES". Otherwise, print "NO". | standard output | |
PASSED | c87e81c4fd63c6dd929729e6b087290b | train_110.jsonl | 1618839300 | Given an array $$$a$$$ of length $$$n$$$, tell us whether it has a non-empty subsequence such that the product of its elements is not a perfect square.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. | 256 megabytes | // HOPE
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////// //////////
/////// //////////
/////// RRRRRRRRRRRRR YY YY AA NN NN //////////
/////// RR RR YY YY AA AA NN NN NN //////////
/////// RR RR YY YY AA AA NN NN NN //////////
/////// RRRRRRRRRR YY YY AAAAAAAAAAAA NN NN NN //////////
/////// RR RR YY AAAAAAAAAAAAAA NN NN NN //////////
/////// RR RR YY AA AA NN NNNN //////////
/////// RR RR YY AA AA NN NN //////////
/////// RR RR_____________________________________________________________________________ //////////
//////// //////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Codeforces {
static final int mod=1_000_000_007;
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) {
FastReader s = new FastReader();
int t = s.nextInt();
while (t-- > 0)
{
int n = s.nextInt();
int[] a = new int[n];
for(int i=0;i<n;i++)
{
a[i] = s.nextInt();
}
int valid = 0;
for(int i=0;i<n;i++)
{
if(isPerfect(a[i]))
{
valid = 1;
break;
}
}
if(valid==1)
System.out.println("Yes");
else
System.out.println("No");
}
}
public static boolean isPerfect(long n)
{
return Math.ceil( Math.sqrt(n)) != Math.floor( Math.sqrt(n));
}
// public static int find()
// {
//
// }
/////////////////////////////////////////////////THE END///////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static int gcd(int x,int y)
{
return y==0?x:gcd(y,x%y);
}
public static long gcd(long x,long y)
{
return y==0L?x:gcd(y,x%y);
}
public static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
public static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
public static long pow(long a,long b)
{
if(b==0L)
return 1L;
long tmp=1;
while(b>1L)
{
if((b&1L)==1)
tmp*=a;
a*=a;
b>>=1;
}
return (tmp*a);
}
public static long modPow(long a,long b,long mod)
{
if(b==0L)
return 1L;
long tmp=1;
while(b>1L)
{
if((b&1L)==1L)
tmp*=a;
a*=a;
a%=mod;
tmp%=mod;
b>>=1;
}
return (tmp*a)%mod;
}
static long mul(long a, long b) {
return a*b%mod;
}
static long fact(int n) {
long ans=1;
for (int i=2; i<=n; i++) ans=mul(ans, i);
return ans;
}
static long fastPow(long base, long exp) {
if (exp==0) return 1;
long half=fastPow(base, exp/2);
if (exp%2==0) return mul(half, half);
return mul(half, mul(half, base));
}
static boolean check(int n,int d)//check for digit 7 in 504732 numbe
{
String s = n+"";
return s.contains(d + "");
}
static void reverseArray(int[] a) {
int n = a.length;
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = a[n - i - 1];
for (int i = 0; i < n; i++)
a[i] = arr[i];
}
static void reverseArray(long[] a) {
int n = a.length;
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = a[n - i - 1];
for (int i = 0; i < n; i++)
a[i] = arr[i];
}
static class Pair{
int x, y;
Pair(int x, int y)
{
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "Pair{" +
"x=" + x +
", y=" + y +
'}';
}
}
}
| Java | ["2\n3\n1 5 4\n2\n100 10000"] | 1 second | ["YES\nNO"] | NoteIn the first example, the product of the whole array ($$$20$$$) isn't a perfect square.In the second example, all subsequences have a perfect square product. | Java 11 | standard input | [
"math",
"number theory"
] | 33a31edb75c9b0cf3a49ba97ad677632 | The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^4$$$) — the elements of the array $$$a$$$. | 800 | If there's a subsequence of $$$a$$$ whose product isn't a perfect square, print "YES". Otherwise, print "NO". | standard output | |
PASSED | 9f98949959e7e9ce619138a02a30ac2e | train_110.jsonl | 1618839300 | Given an array $$$a$$$ of length $$$n$$$, tell us whether it has a non-empty subsequence such that the product of its elements is not a perfect square.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. | 256 megabytes | // HOPE
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////// //////////
/////// //////////
/////// RRRRRRRRRRRRR YY YY AA NN NN //////////
/////// RR RR YY YY AA AA NN NN NN //////////
/////// RR RR YY YY AA AA NN NN NN //////////
/////// RRRRRRRRRR YY YY AAAAAAAAAAAA NN NN NN //////////
/////// RR RR YY AAAAAAAAAAAAAA NN NN NN //////////
/////// RR RR YY AA AA NN NNNN //////////
/////// RR RR YY AA AA NN NN //////////
/////// RR RR_____________________________________________________________________________ //////////
//////// //////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Codeforces {
static final int mod=1_000_000_007;
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) {
FastReader s = new FastReader();
int t = s.nextInt();
while (t-- > 0)
{
int n = s.nextInt();
int[] a = new int[n];
for(int i=0;i<n;i++)
{
a[i] = s.nextInt();
}
int valid = 0;
for(int i=0;i<n;i++)
{
if(isPerfect(a[i]))
{
valid = 1;
break;
}
}
if(valid==1)
System.out.println("Yes");
else
System.out.println("No");
}
}
public static boolean isPerfect(long n)
{
return Math.ceil( Math.sqrt(n)) != Math.floor( Math.sqrt(n));
}
// public static int find()
// {
//
// }
/////////////////////////////////////////////////THE END///////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static int gcd(int x,int y)
{
return y==0?x:gcd(y,x%y);
}
public static long gcd(long x,long y)
{
return y==0L?x:gcd(y,x%y);
}
public static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
public static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
public static long pow(long a,long b)
{
if(b==0L)
return 1L;
long tmp=1;
while(b>1L)
{
if((b&1L)==1)
tmp*=a;
a*=a;
b>>=1;
}
return (tmp*a);
}
public static long modPow(long a,long b,long mod)
{
if(b==0L)
return 1L;
long tmp=1;
while(b>1L)
{
if((b&1L)==1L)
tmp*=a;
a*=a;
a%=mod;
tmp%=mod;
b>>=1;
}
return (tmp*a)%mod;
}
static long mul(long a, long b) {
return a*b%mod;
}
static long fact(int n) {
long ans=1;
for (int i=2; i<=n; i++) ans=mul(ans, i);
return ans;
}
static long fastPow(long base, long exp) {
if (exp==0) return 1;
long half=fastPow(base, exp/2);
if (exp%2==0) return mul(half, half);
return mul(half, mul(half, base));
}
static boolean check(int n,int d)//check for digit 7 in 504732 number
{
String s = n+"";
return s.contains(d + "");
}
static void reverseArray(int[] a) {
int n = a.length;
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = a[n - i - 1];
for (int i = 0; i < n; i++)
a[i] = arr[i];
}
static void reverseArray(long[] a) {
int n = a.length;
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = a[n - i - 1];
for (int i = 0; i < n; i++)
a[i] = arr[i];
}
static class Pair{
int x, y;
Pair(int x, int y)
{
this.x = x;
this.y = y;
}
@Override
public String toString() {
return "Pair{" +
"x=" + x +
", y=" + y +
'}';
}
}
}
| Java | ["2\n3\n1 5 4\n2\n100 10000"] | 1 second | ["YES\nNO"] | NoteIn the first example, the product of the whole array ($$$20$$$) isn't a perfect square.In the second example, all subsequences have a perfect square product. | Java 11 | standard input | [
"math",
"number theory"
] | 33a31edb75c9b0cf3a49ba97ad677632 | The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^4$$$) — the elements of the array $$$a$$$. | 800 | If there's a subsequence of $$$a$$$ whose product isn't a perfect square, print "YES". Otherwise, print "NO". | standard output | |
PASSED | 1a07765a2ddea51972ee8a47f61da4e0 | train_110.jsonl | 1618839300 | Given an array $$$a$$$ of length $$$n$$$, tell us whether it has a non-empty subsequence such that the product of its elements is not a perfect square.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. | 256 megabytes | import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class TaskA {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solveA solver = new solveA();
solver.solve(1, in, out);
out.close();
}
static class solveA{
static boolean checkPerfectSquare(double x)
{
double sq = Math.sqrt(x);
return ((sq - Math.floor(sq)) == 0);
}
static boolean hasImperfect(ArrayList<Integer> curr){
int countofNotsquare = 0;
for (int j = 0 ; j< curr.size();j++){
if(!checkPerfectSquare(curr.get(j))){return true;} //countofNotsquare++;}
//if(countofNotsquare>2) {return true;}
}
return false;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] alllength = new int[n];
ArrayList<Integer>[] al = new ArrayList[n];
for (int i = 0; i < n; ++i) {
alllength[i] = in.nextInt();
ArrayList<Integer> neu = new ArrayList<Integer>(alllength[i]);
for (int j = 0; j < alllength[i]; j++) {
neu.add(in.nextInt());
}
al[i] = neu;
}
//solve
for (int i = 0; i < al.length; i++) {
ArrayList<Integer> curr = al[i];
if (hasImperfect(curr)) out.println("YES");
else out.println("NO");
}
}}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public String nextString(){
return next();
}
}
}
| Java | ["2\n3\n1 5 4\n2\n100 10000"] | 1 second | ["YES\nNO"] | NoteIn the first example, the product of the whole array ($$$20$$$) isn't a perfect square.In the second example, all subsequences have a perfect square product. | Java 11 | standard input | [
"math",
"number theory"
] | 33a31edb75c9b0cf3a49ba97ad677632 | The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^4$$$) — the elements of the array $$$a$$$. | 800 | If there's a subsequence of $$$a$$$ whose product isn't a perfect square, print "YES". Otherwise, print "NO". | standard output | |
PASSED | 372c185de43d6e1c84ecf28ff1409ab9 | train_110.jsonl | 1618839300 | Given an array $$$a$$$ of length $$$n$$$, tell us whether it has a non-empty subsequence such that the product of its elements is not a perfect square.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while(st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch(IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
public static String ans(int n, int[] a) {
int product = 1;
for(int i = 0; i < n; i++) {
int check = (int)Math.sqrt(a[i]);
if(check*check!=a[i]) return "YES";
}
return "NO";
}
public static void main(String[] args) {
FastReader fs = new FastReader();
int t = fs.nextInt();
while(t-- > 0) {
int n = fs.nextInt();
int[] a = new int[n];
for(int x = 0; x < n; x++) {
a[x] = fs.nextInt();
}
System.out.println(ans(n,a));
}
}
} | Java | ["2\n3\n1 5 4\n2\n100 10000"] | 1 second | ["YES\nNO"] | NoteIn the first example, the product of the whole array ($$$20$$$) isn't a perfect square.In the second example, all subsequences have a perfect square product. | Java 11 | standard input | [
"math",
"number theory"
] | 33a31edb75c9b0cf3a49ba97ad677632 | The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^4$$$) — the elements of the array $$$a$$$. | 800 | If there's a subsequence of $$$a$$$ whose product isn't a perfect square, print "YES". Otherwise, print "NO". | standard output | |
PASSED | ca61f96c38b96c98afce5c571c8c207e | train_110.jsonl | 1618839300 | Given an array $$$a$$$ of length $$$n$$$, tell us whether it has a non-empty subsequence such that the product of its elements is not a perfect square.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
String[] res = new String[t];
for (int i = 0; i < t; i++) {
int n = scan.nextInt();
boolean inperfectSq = false;
for (int j = 0; j < n; j++) {
int num = scan.nextInt();
if (Math.pow((int) (Math.sqrt(num)), 2) != num) {
inperfectSq = true;
}
}
res[i] = inperfectSq ? "YES" : "NO";
}
for (String _res : res) System.out.println(_res);
scan.close();
}
} | Java | ["2\n3\n1 5 4\n2\n100 10000"] | 1 second | ["YES\nNO"] | NoteIn the first example, the product of the whole array ($$$20$$$) isn't a perfect square.In the second example, all subsequences have a perfect square product. | Java 11 | standard input | [
"math",
"number theory"
] | 33a31edb75c9b0cf3a49ba97ad677632 | The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^4$$$) — the elements of the array $$$a$$$. | 800 | If there's a subsequence of $$$a$$$ whose product isn't a perfect square, print "YES". Otherwise, print "NO". | standard output | |
PASSED | b93c1100becb393a48eab0fb181e4ddd | train_110.jsonl | 1618839300 | Given an array $$$a$$$ of length $$$n$$$, tell us whether it has a non-empty subsequence such that the product of its elements is not a perfect square.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. | 256 megabytes | import java.util.Scanner;
public class JavaApplication12 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
while(n--!=0){
boolean check=true;
int r = in.nextInt();
int[]arr=new int[r];
for (int i = 0; i < r; i++)
arr[i]=in.nextInt();
for (int i = 0; i < arr.length; i++) {
int k = (int)Math.sqrt(arr[i]);
if ((k*k)!=arr[i]) {
System.out.println("YES");
check= false;
break;
}
}
if (check) {
System.out.println("NO");
}
}
}
} | Java | ["2\n3\n1 5 4\n2\n100 10000"] | 1 second | ["YES\nNO"] | NoteIn the first example, the product of the whole array ($$$20$$$) isn't a perfect square.In the second example, all subsequences have a perfect square product. | Java 11 | standard input | [
"math",
"number theory"
] | 33a31edb75c9b0cf3a49ba97ad677632 | The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^4$$$) — the elements of the array $$$a$$$. | 800 | If there's a subsequence of $$$a$$$ whose product isn't a perfect square, print "YES". Otherwise, print "NO". | standard output | |
PASSED | 44becf97e696fb6b81359bd8f139628d | train_110.jsonl | 1618839300 | Given an array $$$a$$$ of length $$$n$$$, tell us whether it has a non-empty subsequence such that the product of its elements is not a perfect square.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. | 256 megabytes | import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class a {
static long mod = 1000000007;
public static void main(String[] args) throws Exception {
FastScanner in = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int t = in.nextInt();
while (t-- > 0) {
int n = in.nextInt();
// long n = in.nextLong();
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
long ans=1;
boolean flag=false;
for(int i=0;i<n;i++) {
ans=a[i];
if(!perf(a[i])) {
System.out.println("Yes");
flag=true;
break;
}
}
if(!flag) {
System.out.println("No");
}
}
out.close();
}
static boolean perf(double x) {
long xx=(long)Math.sqrt(x);
if(x==(xx*xx)) {
return true;
}
return false;
}
public static long gcd(long x, long y) {
if (x % y == 0)
return y;
else
return gcd(y, x % y);
}
public static long pow(long n, long p, long m) {
long result = 1;
if (p == 0)
return 1;
if (p == 1)
return n;
while (p != 0) {
if (p % 2 == 1)
result *= n;
if (result >= m)
result %= m;
p >>= 1;
n *= n;
if (n >= m)
n %= m;
}
return result;
}
static class Pair implements Comparable<Pair> {
int a, b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
public int compareTo(Pair o) {
if (this.a != o.a)
return Integer.compare(this.a, o.a);
else
return Integer.compare(this.b, o.b);
// return 0;
}
public boolean equals(Object o) {
if (o instanceof Pair) {
Pair p = (Pair) o;
return p.a == a && p.b == b;
}
return false;
}
public int hashCode() {
return new Integer(a).hashCode() * 31 + new Integer(b).hashCode();
}
}
public static class Debug {
//change to System.getProperty("ONLINE_JUDGE")==null; for CodeForces
// public static final boolean LOCAL = System.getProperty("LOCAL")!=null;
private static <T> String ts(T t) {
if(t==null) {
return "null";
}
try {
return ts((Iterable) t);
}catch(ClassCastException e) {
if(t instanceof int[]) {
String s = Arrays.toString((int[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}else if(t instanceof long[]) {
String s = Arrays.toString((long[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}else if(t instanceof char[]) {
String s = Arrays.toString((char[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}else if(t instanceof double[]) {
String s = Arrays.toString((double[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}else if(t instanceof boolean[]) {
String s = Arrays.toString((boolean[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}
try {
return ts((Object[]) t);
}catch(ClassCastException e1) {
return t.toString();
}
}
}
private static <T> String ts(T[] arr) {
StringBuilder ret = new StringBuilder();
ret.append("{");
boolean first = true;
for(T t: arr) {
if(!first) {
ret.append(", ");
}
first = false;
ret.append(ts(t));
}
ret.append("}");
return ret.toString();
}
private static <T> String ts(Iterable<T> iter) {
StringBuilder ret = new StringBuilder();
ret.append("{");
boolean first = true;
for(T t: iter) {
if(!first) {
ret.append(", ");
}
first = false;
ret.append(ts(t));
}
ret.append("}");
return ret.toString();
}
public static void dbg(Object... o) {
// if(LOCAL) {
System.err.print("Line #"+Thread.currentThread().getStackTrace()[2].getLineNumber()+": [");
for(int i = 0; i<o.length; i++) {
if(i!=0) {
System.err.print(", ");
}
System.err.print(ts(o[i]));
}
System.err.println("]");
// }
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() throws IOException {
String st = br.readLine();
return st;
}
}
} | Java | ["2\n3\n1 5 4\n2\n100 10000"] | 1 second | ["YES\nNO"] | NoteIn the first example, the product of the whole array ($$$20$$$) isn't a perfect square.In the second example, all subsequences have a perfect square product. | Java 11 | standard input | [
"math",
"number theory"
] | 33a31edb75c9b0cf3a49ba97ad677632 | The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^4$$$) — the elements of the array $$$a$$$. | 800 | If there's a subsequence of $$$a$$$ whose product isn't a perfect square, print "YES". Otherwise, print "NO". | standard output | |
PASSED | 8a0f2e4fb058b0318ef7148cce327d5e | train_110.jsonl | 1618839300 | Given an array $$$a$$$ of length $$$n$$$, tell us whether it has a non-empty subsequence such that the product of its elements is not a perfect square.A sequence $$$b$$$ is a subsequence of an array $$$a$$$ if $$$b$$$ can be obtained from $$$a$$$ by deleting some (possibly zero) elements. | 256 megabytes |
import java.util.Scanner;
public class PerfectlyImperfectArray {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int t=scan.nextInt();
while(t-->0)
{
int n=scan.nextInt();
int flag=0;
for(int i=0;i<n;i++)
{
int arr=scan.nextInt();
if(((int)Math.sqrt(arr)*(int)Math.sqrt(arr))!=arr & flag==0)
{
flag++;
}
}
if(flag==0)
{
System.out.println("no");
}
else
{
System.out.println("yes");
}
}
}
}
| Java | ["2\n3\n1 5 4\n2\n100 10000"] | 1 second | ["YES\nNO"] | NoteIn the first example, the product of the whole array ($$$20$$$) isn't a perfect square.In the second example, all subsequences have a perfect square product. | Java 11 | standard input | [
"math",
"number theory"
] | 33a31edb75c9b0cf3a49ba97ad677632 | The first line contains an integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer $$$n$$$ ($$$1 \le n \le 100$$$) — the length of the array $$$a$$$. The second line of each test case contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_{n}$$$ ($$$1 \le a_i \le 10^4$$$) — the elements of the array $$$a$$$. | 800 | If there's a subsequence of $$$a$$$ whose product isn't a perfect square, print "YES". Otherwise, print "NO". | standard output |
Subsets and Splits