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 | ec6accf6e09b2b8f40525040720e4aa1 | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class Main{
public static void main (String[] args){
FastReader s = new FastReader();
int t=1;//t=s.ni();
for(int test=1;test<=t;test++){
int n=s.ni(),q=s.ni(),cnt=0;
String S=s.nextLine();char a[]=S.toCharArray();
for(int i = 0; i < n-2; i++){
if(isAbc(a,i)){
cnt++;
}
}
for(int i=0;i<q;i++){
int pos = s.ni()-1;
char c = s.next().charAt(0);
if(a[pos]!=c){
cnt=update(a,cnt,pos,n,-1);//Destroys
a[pos]=c;
cnt=update(a,cnt,pos,n,1);//Creates
}
System.out.println(cnt);
}
}
}
static int update(char a[], int cnt, int pos, int n, int add){
for(int i = pos-2; i<=pos ; i++){
if(i>=0&&i+2<n){
if(isAbc(a,i)){
cnt+=add;
}
}
}
return cnt;
}
static boolean isAbc(char a[],int i){
if(a[i]=='a'&&a[i+1]=='b'&&a[i+2]=='c')return true;
else return false;
}
static class FastReader {
BufferedReader br; StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));}
int ni() { return Integer.parseInt(next()); }
long nl() { return Long.parseLong(next()); }
double nd() { return Double.parseDouble(next()); }
long[] readArray(int n){
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] =Long.parseLong(next());
return a;
}
String next(){
while (st == null || !st.hasMoreElements()) {try {st = new StringTokenizer(br.readLine());}
catch (IOException e){e.printStackTrace();}}return st.nextToken();}
String nextLine(){String str = "";try {str = br.readLine();}catch (IOException e)
{e.printStackTrace();}return str;}
}
} | Java | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | 499ad9960a15b1e3fd0a9ae0c805a6e2 | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 256 megabytes | import java.io.*;
import java.util.*;
public class deltix_21_a {
public static void main(String args[]){
FScanner in = new FScanner();
PrintWriter out = new PrintWriter(System.out);
//int t = in.nextInt();
//while(t-->0) {
int n=in.nextInt();
int q=in.nextInt();
char ch[]=in.next().toCharArray();
int co=0;
for(int i=1;i<ch.length-1;i++)
{
if(ch[i]=='b' && ch[i-1]=='a' && ch[i+1]=='c')
co++;
}
for(int i=0;i<q;i++)
{
int pos=in.nextInt()-1;
char c[]=in.next().toCharArray();
if(ch[pos]!=c[0])
{
if(ch[pos]=='a')
{
if(pos+2<n && ch[pos+1]=='b' && ch[pos+2]=='c')co--;
}
else if (ch[pos]=='b')
{
if(pos+1<n && pos-1>=0 && ch[pos+1]=='c' && ch[pos-1]=='a')
co--;
}
else
{
if(pos-2>=0 && ch[pos-2]=='a' && ch[pos-1]=='b')
co--;
}
ch[pos]=c[0];
if(ch[pos]=='a')
{
if(pos+2<n && ch[pos+1]=='b' && ch[pos+2]=='c')co++;
}
else if(ch[pos]=='b')
{
if(pos+1<n && pos-1>=0 && ch[pos+1]=='c' && ch[pos-1]=='a')
co++;
}
else
{
if(pos-2>=0 && ch[pos-2]=='a' && ch[pos-1]=='b')
co++;
}
}
out.println(co);
}
// }
out.close();
}
static class FScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer sb = new StringTokenizer("");
String next(){
while(!sb.hasMoreTokens()){
try{
sb = new StringTokenizer(br.readLine());
} catch(IOException e){ }
}
return sb.nextToken();
}
String nextLine(){
try{ return br.readLine(); }
catch(IOException e) { } return "";
}
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] = nextInt();
return a;
}
float nextFloat(){
return Float.parseFloat(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
}
}
| Java | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | 7c0b58ca6c2754c23ad968db29c0ba0b | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 256 megabytes | import java.util.Scanner;
/**
*
* @author Acer
*/
public class WilliamAndVigilant {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int q = sc.nextInt();
String s = sc.next();
int count = 0;
for (int i = 0; i < n-2; i++) {
if(s.charAt(i) == 'a' && s.charAt(i+1) == 'b' && s.charAt(i+2) == 'c'){
count++;
}
}
char ch[] = s.toCharArray();
while(q-- > 0){
int i = sc.nextInt();
i--;
char c = sc.next().charAt(0);
if(ch[i] == c){
System.out.println(count);
continue;
}
else{
for (int j = Math.max(0, i-2); j <= Math.min(i, n-3); j++) {
if(ch[j] == 'a' && ch[j+1] == 'b' && ch[j+2] == 'c'){
count--;
}
}
ch[i] = c;
for (int j = Math.max(0, i-2); j <= Math.min(i, n-3); j++) {
if(ch[j] == 'a' && ch[j+1] == 'b' && ch[j+2] == 'c'){
count++;
}
}
System.out.println(count);
}
}
//System.out.println(count);
}
} | Java | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | 13a03072397333ef9cfde604aeae8430 | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import static java.lang.Math.*;
import static java.lang.System.out;
import java.util.*;
import java.io.File;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.math.BigInteger;
public class Main {
/* 10^(7) = 1s.
* ceilVal = (a+b-1) / b */
static final int mod = 1000000007;
static final long temp = 998244353;
static final long MOD = 1000000007;
static final long M = (long)1e9+7;
static class Pair implements Comparable<Pair>
{
int first, second;
public Pair(int first, int second)
{
this.first = first;
this.second = second;
}
public int compareTo(Pair ob)
{
return (int)(first - ob.first);
}
}
static class Tuple implements Comparable<Tuple>
{
int first, second,third;
public Tuple(int first, int second, int third)
{
this.first = first;
this.second = second;
this.third = third;
}
public int compareTo(Tuple o)
{
return (int)(o.third - this.third);
}
}
public static class DSU
{
int[] parent;
int[] rank; //Size of the trees is used as the rank
public DSU(int n)
{
parent = new int[n];
rank = new int[n];
Arrays.fill(parent, -1);
Arrays.fill(rank, 1);
}
public int find(int i) //finding through path compression
{
return parent[i] < 0 ? i : (parent[i] = find(parent[i]));
}
public boolean union(int a, int b) //Union Find by Rank
{
a = find(a);
b = find(b);
if(a == b) return false; //if they are already connected we exit by returning false.
// if a's parent is less than b's parent
if(rank[a] < rank[b])
{
//then move a under b
parent[a] = b;
}
//else if rank of j's parent is less than i's parent
else if(rank[a] > rank[b])
{
//then move b under a
parent[b] = a;
}
//if both have the same rank.
else
{
//move a under b (it doesnt matter if its the other way around.
parent[b] = a;
rank[a] = 1 + rank[a];
}
return true;
}
}
static class Reader
{
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) throws IOException {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long[] longReadArray(int n) throws IOException {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
public static int gcd(int a, int b)
{
if(b == 0)
return a;
else
return gcd(b,a%b);
}
public static long lcm(long a, long b)
{
return (a / LongGCD(a, b)) * b;
}
public static long LongGCD(long a, long b)
{
if(b == 0)
return a;
else
return LongGCD(b,a%b);
}
public static long LongLCM(long a, long b)
{
return (a / LongGCD(a, b)) * b;
}
//Count the number of coprime's upto N
public static long phi(long n) //euler totient/phi function
{
long ans = n;
// for(long i = 2;i*i<=n;i++)
// {
// if(n%i == 0)
// {
// while(n%i == 0) n/=i;
// ans -= (ans/i);
// }
// }
//
// if(n > 1)
// {
// ans -= (ans/n);
// }
for(long i = 2;i<=n;i++)
{
if(isPrime(i))
{
ans -= (ans/i);
}
}
return ans;
}
public static long fastPow(long x, long n)
{
if(n == 0)
return 1;
else if(n%2 == 0)
return fastPow(x*x,n/2);
else
return x*fastPow(x*x,(n-1)/2);
}
public static long modPow(long x, long y, long p)
{
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 modInverse(long n, long p)
{
return modPow(n, p - 2, p);
}
// Returns nCr % p using Fermat's little theorem.
public static long nCrModP(long n, long r,long p)
{
if (n<r)
return 0;
if (r == 0)
return 1;
long[] fac = new long[(int)(n) + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = fac[i - 1] * i % p;
return (fac[(int)(n)] * modInverse(fac[(int)(r)], p)
% p * modInverse(fac[(int)(n - r)], p)
% p)
% p;
}
public static long fact(long n)
{
long[] fac = new long[(int)(n) + 1];
fac[0] = 1;
for (long i = 1; i <= n; i++)
fac[(int)(i)] = fac[(int)(i - 1)] * i;
return fac[(int)(n)];
}
public static long nCr(long n, long k)
{
long ans = 1;
for(long i = 0;i<k;i++)
{
ans *= (n-i);
ans /= (i+1);
}
return ans;
}
//Modular Operations for Addition and Multiplication.
public static long perfomMod(long x)
{
return ((x%M + M)%M);
}
public static long addMod(long a, long b)
{
return perfomMod(perfomMod(a)+perfomMod(b));
}
public static long subMod(long a, long b)
{
return perfomMod(perfomMod(a)-perfomMod(b));
}
public static long mulMod(long a, long b)
{
return perfomMod(perfomMod(a)*perfomMod(b));
}
public static boolean isPrime(long n)
{
if(n == 1)
{
return false;
}
//check only for sqrt of the number as the divisors
//keep repeating so only half of them are required. So,sqrt.
for(int i = 2;i*i<=n;i++)
{
if(n%i == 0)
{
return false;
}
}
return true;
}
public static List<Integer> SieveList(int n)
{
boolean prime[] = new boolean[(int)(n+1)];
Arrays.fill(prime, true);
List<Integer> l = new ArrayList<>();
for (int p = 2; p*p<=n; p++)
{
if (prime[p] == true)
{
for(int i = p*p; i<=n; i += p)
{
prime[i] = false;
}
}
}
for (int p = 2; p<=n; p++)
{
if (prime[p] == true)
{
l.add(p);
}
}
return l;
}
public static int countDivisors(int x)
{
int c = 0;
for(int i = 1;i*i<=x;i++)
{
if(x%i == 0)
{
if(x/i != i)
{
c+=2;
}
else
{
c++;
}
}
}
return c;
}
public static long log2(long n)
{
long ans = (long)(log(n)/log(2));
return ans;
}
public static boolean isPow2(long n)
{
return (n != 0 && ((n & (n-1))) == 0);
}
public static boolean isSq(int x)
{
long s = (long)Math.round(Math.sqrt(x));
return s*s==x;
}
/*
*
* >= <=
0 1 2 3 4 5 6 7
5 5 5 6 6 6 7 7
lower_bound for 6 at index 3 (>=)
upper_bound for 6 at index 6(To get six reduce by one) (<=)
*/
public static int LowerBound(long a[], long x)
{
int l=-1,r=a.length;
while(l+1<r)
{
int m=(l+r)>>>1;
if(a[m]>=x) r=m;
else l=m;
}
return r;
}
public static int UpperBound(long a[], long x)
{
int l=-1, r=a.length;
while(l+1<r)
{
int m=(l+r)>>>1;
if(a[m]<=x) l=m;
else r=m;
}
return l+1;
}
public static void Sort(long[] a)
{
List<Long> l = new ArrayList<>();
for (long i : a) l.add(i);
Collections.sort(l);
// Collections.reverse(l); //Use to Sort decreasingly
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
public static void ssort(char[] a)
{
List<Character> l = new ArrayList<>();
for (char i : a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
public static int count(int x, char[] s)
{
int n = s.length;
return (x >= 0 && x + 2 < n && s[x] == 'a' && s[x+1] == 'b' && s[x+2] == 'c') ? 1 : 0;
}
public static void main(String[] args) throws Exception
{
Reader sc = new Reader();
PrintWriter fout = new PrintWriter(System.out);
int n = sc.nextInt(), t = sc.nextInt();
char[] s = sc.next().toCharArray();
long ans = 0;
for(int i = 0;i<n;i++) ans += count(i,s);
while(t-- > 0)
{
int q = sc.nextInt()-1;
char ch = sc.next().charAt(0);
ans -= count(q-2,s);
ans -= count(q-1,s);
ans -= count(q,s);
s[q] = ch;
ans += count(q-2,s);
ans += count(q-1,s);
ans += count(q,s);
fout.println(ans);
}
fout.close();
}
} | Java | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | f58ad8f9c111a2ede34191432aedd27c | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 256 megabytes |
import java.awt.Container;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.*;
public class Main
{
public static boolean check(char a[],int index)
{
if(a[index]=='a')
{
if(index+2<a.length&&(a[index+1]=='b'&&a[index+2] =='c'))
{
return true;
}
else
{
return false;
}
}
else if(a[index]=='b')
{
if(index-1>=0&&index+1<a.length&&(a[index-1]=='a'&&a[index+1] =='c'))
{
return true;
}
else
{
return false;
}
}
else
{
if(index-2>=0&&(a[index-1]=='b'&&a[index-2] =='a'))
{
return true;
}
else
{
return false;
}
}
}
public static void main(String[] args)
{
FastScanner input = new FastScanner();
int n = input.nextInt();
int q = input.nextInt();
char a[] =input.next().toCharArray();
int count=0;
for (int i = 0; i < n-2; i++) {
if(a[i]=='a'&&a[i+1]=='b'&&a[i+2]=='c')
{
count++;
}
}
// System.out.println(count);
StringBuilder result = new StringBuilder();
for (int i = 0; i < q; i++) {
int index = input.nextInt()-1;
char c = input.next().charAt(0);
if(a[index]==c)
{
result.append(count+"\n");
}
else
{
boolean ch = check(a, index);
a[index] = c;
if(ch&&!check(a, index))
{
result.append((count-1)+"\n");
count--;
}
else if(!ch&&check(a, index))
{
count++;
result.append(count+"\n");
}
else
{
result.append(count+"\n");
}
}
}
System.out.println(result);
}
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) {
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine() throws IOException
{
return br.readLine();
}
}
}
| Java | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | 74a359bf855107d57e0562388623e316 | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 256 megabytes | import java.util.*;
import java.io.*;
public class B1609{
static FastScanner fs = null;
public static void main(String[] args) {
fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = fs.nextInt();
int q = fs.nextInt();
String s = fs.next();
char ch[] = s.toCharArray();
int count = 0;
for(int i=0;i<n-2;){
if(ch[i]=='a' && ch[i+1]=='b' && ch[i+2]=='c'){
count+=1;
i+=3;
}
else{
i+=1;
}
}
while(q-->0){
int id = fs.nextInt()-1;
char c1 = fs.next().charAt(0);
char c2 = ch[id];
if(c2=='a' && id+1<n && id+2<n && ch[id+1]=='b'&&ch[id+2]=='c'){
count-=1;
}
else if(c2=='b' && id-1>=0 && id+1<n && ch[id-1]=='a'&&ch[id+1]=='c'){
count-=1;
}
else if(c2=='c' && id-1>=0 && id-2>=0 && ch[id-1]=='b'&&ch[id-2]=='a'){
count-=1;
}
if(c1=='a' && id+1<n && id+2<n && ch[id+1]=='b'&&ch[id+2]=='c'){
count+=1;
}
else if(c1=='b' && id-1>=0 && id+1<n && ch[id-1]=='a'&&ch[id+1]=='c'){
count+=1;
}
else if(c1=='c' && id-1>=0 && id-2>=0 && ch[id-1]=='b'&&ch[id-2]=='a'){
count+=1;
}
ch[id] = c1;
out.println(count);
}
out.close();
}
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 | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | 35c8aaf3e646ec3e81577637af063b4f | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 256 megabytes | import java.awt.Container;
import java.awt.image.SampleModel;
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.CountDownLatch;
import javax.naming.TimeLimitExceededException;
import java.io.PrintStream;
import java.security.KeyStore.Entry;
public class Solution {
static class Pair<T,V>{
T first;
V second;
public Pair(T first, V second) {
super();
this.first = first;
this.second = second;
}
}
// public static final boolean LOCAL = System.getProperty("ONLINE_JUDGE")==null;
private static FastScanner fs=new FastScanner();
private static Scanner sc=new Scanner(System.in);
static int upperBound(long[] arr,int l,int r,long x) {
int ans=r+1;
while (l <= r) {
// mid = l + (r - l) / 2;
int mid = (l + r) / 2;
if (arr[mid] >= x) {
ans = mid;
r = mid - 1;
} else {
l = mid + 1;
}
}
return ans;
}
private static int log2(int n) {
if(n<=1) {
return 0;
}
return 1+log2(n/2);
}
public static void main(String[] args) throws Exception {
int tcr=1;
//tcr = sc.nextInt();
//tcr=fs.nextInt();
while(tcr-->0) {
solve(tcr);
}
System.gc();
}
private static void solve(int TC) throws Exception{
int n=fs.nextInt();
int q=fs.nextInt();
char s[]=fs.next().toCharArray();
int cnt=0;
for(int i=0;i<s.length-2;i++) {
if(s[i]=='a' && s[i+1]=='b' && s[i+2]=='c') {
cnt++;
}
}
while(q-->0) {
int i=fs.nextInt();
i--;
char c=fs.next().charAt(0);
if( i < n-2 && s[i]=='a' && s[i+1]=='b' && s[i+2]=='c') {
cnt--;
}
if( i < n-1 && i>0 && s[i-1]=='a' && s[i]=='b' && s[i+1]=='c') {
cnt--;
}
if( i >=2 && s[i]=='c' && s[i-1]=='b' && s[i-2]=='a') {
cnt--;
}
s[i]=c;
if( i < n-2 && s[i]=='a' && s[i+1]=='b' && s[i+2]=='c') {
cnt++;
}
if( i < n-1 && i>0 && s[i-1]=='a' && s[i]=='b' && s[i+1]=='c') {
cnt++;
}
if( i >=2 && s[i]=='c' && s[i-1]=='b' && s[i-2]=='a') {
cnt++;
}
System.out.println(cnt);
}
}
static boolean isPalindrome(ArrayList<Integer> list) {
int i=0,j=list.size()-1;
while(i<j) {
if( !list.get(i).equals( list.get(j) ) ) {
return false;
}
i++;
j--;
}
return true;
}
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());
}
String readLine() throws IOException{
return br.readLine();
}
}
public static boolean isPrime(int n) {
for(int i=2;i<n;i++) {
if(n%i==0) {
return false;
}
}
return true;
}
public static long gcd(long a,long b){
if(b == 0l){
return a;
}
return gcd(b,a%b);
}
public static List<Integer> sieve(){
List<Integer> prime = new ArrayList<>();
int arr[] = new int[100001];
Arrays.fill(arr,1);
arr[1] = 0;
arr[2] = 1;
for(int i=2;i<=100000;i++){
if(arr[i] == 1){
prime.add(i);
for(long j = (i*1l*i);j<100001;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;
}
} | Java | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | 3a8a15cce53c7deed190fe58e4544097 | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.Stack;
import java.util.stream.Stream;
public class CP {
static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws NumberFormatException, IOException {
//int cases = Integer.parseInt(reader.readLine());
int cases = 1;
while(cases-- > 0) {
String[] firstLine = reader.readLine().split(" ");
int n = Integer.parseInt(firstLine[0]);
int q = Integer.parseInt(firstLine[1]);
char[] ch = reader.readLine().toCharArray();
int i = 0;
int count = 0;
while(i<ch.length) {
if(i+2 < ch.length && ch[i]=='a' && ch[i+1] == 'b' && ch[i+2] == 'c') {
count++;
i+=2;
}else {
i++;
}
}
while(q-- > 0) {
String[] query = reader.readLine().split(" ");
int index = Integer.parseInt(query[0]);
index--;
char oldChar = ch[index];
char newChar = query[1].charAt(0);
//ch[index] = newChar;
if(oldChar != newChar) {
if(index+2 < ch.length && ch[index] == 'a' && ch[index+1] =='b' && ch[index+2] =='c') {
count--;
}else if(index-1 >= 0 && index+1 < ch.length && ch[index-1] == 'a' && ch[index] =='b' && ch[index+1] =='c') {
count--;
}else if(index-2 >= 0 && ch[index-2] == 'a' && ch[index-1] =='b' && ch[index] =='c') {
count--;
}
ch[index] = newChar;
if(index+2 < ch.length && ch[index] == 'a' && ch[index+1] =='b' && ch[index+2] =='c') {
count++;
}else if(index-1 >= 0 && index+1 < ch.length && ch[index-1] == 'a' && ch[index] =='b' && ch[index+1] =='c') {
count++;
}else if (index - 2 >= 0 && ch[index - 2] == 'a' && ch[index - 1] == 'b' && ch[index] == 'c') {
count++;
}
}
// for(int j=0;j<ch.length;j++)
// System.out.print( ch[j] + " ");
// System.out.println(count);
printNumber(count);
}
}
out.flush();
}
public static boolean func(int[] arr, int i, int j, int val) {
while(i<j) {
if(arr[i]==arr[j]) {
i++;
j--;
}else if(arr[i] == val){
i++;
}else if(arr[j] == val) {
j--;
}else {
return false;
}
}
return true;
}
public static int[] convertToIntPrimitiveArray(String[] str) {
return Stream.of(str).mapToInt(Integer::parseInt).toArray();
}
public static Integer[] convertToIntArray(String[] str) {
Integer[] arr = new Integer[str.length];
for(int i=0;i<str.length;i++) {
arr[i] = Integer.parseInt(str[i]);
}
return arr;
}
public static Long[] convertToLongArray(String[] str) {
Long[] arr = new Long[str.length];
for(int i=0;i<str.length;i++) {
arr[i] = Long.parseLong(str[i]);
}
return arr;
}
public static void printYes() throws IOException {
out.append("YES" + "\n");
}
public static void printNo() throws IOException {
out.append("NO" + "\n");
}
public static void printNumber(long num) throws IOException {
out.append(num + "\n");
}
public static long hcf(long a, long b) {
if(b==0) return a;
return hcf(b, a%b);
}
public static void customSort(int[] arr) {
int n = arr.length;
Random rnd = new Random();
for(int i=0; i<n; ++i){
int tmp = arr[i];
int randomPos = i + rnd.nextInt(n-i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
Arrays.sort(arr);
return;
}
}
| Java | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | a90b0c621b4b3ad8c80dc51e31dab10c | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// int t = Integer.parseInt(br.readLine());
int t = 1;
while (t-- > 0) {
String[] inp = br.readLine().split(" ");
int n = Integer.parseInt(inp[0]);
int q = Integer.parseInt(inp[1]);
char[] input = br.readLine().toCharArray();
int count = 0;
for(int i = 0; i<n-2; i++){
if(input[i] == 'a'&&input[i+1]=='b'&&input[i+2]=='c'){
count++;
}
}
int finalVal = count;
for(int i = 0; i<q; i++){
inp = br.readLine().split(" ");
int pos = Integer.parseInt(inp[0])-1;
char c = inp[1].charAt(0);
// System.out.println("found: "+ c+ " count now: "+count + " arr: "+new String(input) + " pos: "+pos);
if(c=='a'){
if(input[pos]=='a'){
finalVal = count;
}else if(input[pos]=='b'){
boolean sanity = (pos+1)<n&&(pos+2)<n;
boolean sanity2 = (pos-1)>=0&&(pos+1)<n;
if(sanity&&input[pos+1]=='b'&&input[pos+2]=='c'){
count++;
}
if(sanity2&&input[pos-1]=='a'&&input[pos+1]=='c'){
count--;
}
}else if(input[pos] == 'c'){
boolean sanity = (pos+1)<n&&(pos+2)<n;
boolean sanity2 = (pos-2)>=0;
if(sanity&&input[pos+1]=='b'&&input[pos+2]=='c'){
count++;
}
if(sanity2&&input[pos-2]=='a'&&input[pos-1]=='b'){
count--;
}
}
}else if(c=='b'){
if(input[pos]=='b'){
finalVal = count;
}else if(input[pos]=='a'){
boolean sanity = (pos-1)>=0&&(pos+1)<n;
boolean sanity2 = (pos+2)<n;
if(sanity&&input[pos-1]=='a'&&input[pos+1]=='c'){
count++;
}
if(sanity2&&input[pos+1]=='b'&&input[pos+2]=='c'){
count--;
}
}else if(input[pos] == 'c'){
boolean sanity = (pos-1)>=0&&(pos+1)<n;
boolean sanity2 = (pos-2)>=0;
if(sanity&&input[pos-1]=='a'&&input[pos+1]=='c'){
count++;
}
if(sanity2&&input[pos-2]=='a'&&input[pos-1]=='b'){
count--;
}
}
}else if(c=='c'){
if(input[pos]=='c'){
finalVal = count;
}else if(input[pos]=='a'){
boolean sanity = (pos-2)>=0;
boolean sanity2 = (pos+2)<n;
if(sanity&&input[pos-2]=='a'&&input[pos-1]=='b'){
count++;
}
if(sanity2&&input[pos+1]=='b'&&input[pos+2]=='c'){
count--;
}
}else if(input[pos] == 'b'){
boolean sanity = (pos-2)>=0;
boolean sanity2 = (pos-1)>=0&&(pos+1)<n;
if(sanity&&input[pos-2]=='a'&&input[pos-1]=='b'){
count++;
}
if(sanity2&&input[pos-1]=='a'&&input[pos+1]=='c'){
count--;
}
}
}
input[pos] = c;
System.out.println(count);
}
// System.out.println(maxSoFar);
}
}
static Num[] Normalize(int [] arr){
for(int i : arr){
// System.out.println(i);
}
Num[] ans = new Num[arr.length];
for(int i=0; i< arr.length; i++){
ans[i] = new Num();
int val = arr[i];
// System.out.println("val "+val);
while(val%2==0){
ans[i].power++;
val/=2;
}
// System.out.println(ans[i].oddPart + " | "+ans[i].power);
// System.out.println("val:last: " + val);
ans[i].oddPart = val;
}
return ans;
}
static void solve(String ss){
StringBuilder sb = new StringBuilder();
String vowels = "AEIOUY";
for(int i = 0; i<ss.length(); i++){
String ch = ss.charAt(i)+"";
if(vowels.indexOf(ch.toUpperCase())>-1){
continue;
}
if(ch.charAt(0)>=65&&ch.charAt(0)<=90){
ch= ((char)(ch.charAt(0)+32))+"";
}
sb.append("."+ch);
}
System.out.println(sb.toString());
}
}
class Num{
long oddPart;
long power;
} | Java | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | c257da605a1fbf6e7f287539e82b859b | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class WilliamtheVigilant {
public static void main(String[] args) {
// TODO Auto-generated method stub
FastReader in=new FastReader();
int n = in.nextInt();
int q = in.nextInt();
String str = in.next();
char cha[] = str.toCharArray();
int res = 0;
for (int i = 0; i < n; i++) {
if (i + 2 < n) {
if (cha[i] == 'a' && cha[i + 1] == 'b' && cha[i + 2] == 'c') {
res++;
i = i + 2;
}
}
}
while (q-- > 0) {
int pos = in.nextInt();
pos = pos - 1;
char ori = cha[pos];
char ch = in.next().charAt(0);
if (ch == ori) {
System.out.println(res);
} else {
cha[pos] = ch;
if (ch == 'a') {
if (pos + 2 < n && cha[pos + 1] == 'b' && cha[pos + 2] == 'c') {
res = res + 1;
}
if (pos - 1 >= 0 && pos + 1 < n && ori == 'b' && cha[pos + 1] == 'c' && cha[pos - 1] == 'a') {
res = res - 1;
} else if (pos - 2 >= 0 && ori == 'c' && cha[pos - 1] == 'b' && cha[pos - 2] == 'a') {
res = res - 1;
}
} else if (ch == 'b') {
if (pos - 1 >= 0 && pos + 1 < n && cha[pos - 1] == 'a' && cha[pos + 1] == 'c') {
res = res + 1;
}
if (pos + 2 < n && ori == 'a' && cha[pos + 1] == 'b' && cha[pos + 2] == 'c') {
res = res - 1;
} else if (pos - 2 >= 0 && ori == 'c' && cha[pos - 1] == 'b' && cha[pos - 2] == 'a') {
res = res - 1;
}
} else {
if (pos - 2 >= 0 && cha[pos - 1] == 'b' && cha[pos - 2] == 'a') {
res = res + 1;
}
if (pos + 2 < n && ori == 'a' && cha[pos + 1] == 'b' && cha[pos + 2] == 'c') {
res = res - 1;
} else if (pos - 1 >= 0 && pos + 1 < n && ori == 'b' && cha[pos + 1] == 'c'
&& cha[pos - 1] == 'a') {
res = res - 1;
}
}
System.out.println(res);
}
}
}
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 | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | 2f6a013739f242e1642cfa6062f266ef | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 256 megabytes |
import java.util.*;
//import javax.swing.plaf.basic.BasicInternalFrameTitlePane.SystemMenuBar;
import java.lang.*;
import java.io.*;
public class Main
{
public static class FastReader {
BufferedReader b;
StringTokenizer s;
public FastReader() {
b=new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while(s==null ||!s.hasMoreElements()) {
try {
s=new StringTokenizer(b.readLine());
}
catch(IOException e) {
e.printStackTrace();
}
}
return s.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str="";
try {
str=b.readLine();
}
catch(IOException e) {
e.printStackTrace();
}
return str;
}
boolean hasNext() {
if (s != null && s.hasMoreTokens()) {
return true;
}
String tmp;
try {
b.mark(1000);
tmp = b.readLine();
if (tmp == null) {
return false;
}
b.reset();
} catch (IOException e) {
return false;
}
return true;
}
}
/*static int LEN = 10000000;
int lp[]=new int[LEN+1];
List<Inter>
public void sieve()
{
for (int i=2; i <= N; ++i) {
if (lp[i] == 0) {
lp[i] = i;
pr.push_back(i);
}
for (int j=0; j < (int)pr.size() && pr[j] <= lp[i] && i*pr[j] <= N; ++j) {
lp[i * pr[j]] = pr[j];
}
}
}*/
public static long gcd(long a,long b) {if(a==0)return b; return gcd(b%a,a);}
public static int gcd(int a,int b) {if(a==0)return b; return gcd(b%a,a);};
static int power(int x, int y){
if (y == 0)
return 1;
else if (y % 2 == 0)
return power(x, y / 2) * power(x, y / 2);
else
return x * power(x, y / 2) * power(x, y / 2);
}
static long power(long x , long y)
{
if (y == 0)
return 1;
else if (y % 2 == 0)
return power(x, y / 2) * power(x, y / 2);
else
return x * power(x, y / 2) * power(x, y / 2);
}
public static int Substr(String s2, String s1){
int counter = 0; //pointing s2
int i = 0;
for(;i<s1.length();i++){
if(counter==s2.length())
break;
if(s2.charAt(counter)==s1.charAt(i)){
counter++;
}else{
//Special case where character preceding the i'th character is duplicate
if(counter>0){
i -= counter;
}
counter = 0;
}
}
return counter < s2.length()?-1:i-counter;
}
public static long find(long spcreq[],long k)
{
long count=0;
for(int i=0;i<26;i++)
{
if(spcreq[i]!=0)
count+=(k-spcreq[i]);
}
return count;
}
static Map<Integer,Map<Integer,Long>>dp=new HashMap<>();
public static long helper(long r[],int l,int i,int n)
{
if(i>=n)
return Integer.MAX_VALUE;
if(l<=0)
return 0;
if(dp.containsKey(l)&&dp.get(l).containsKey(i))
return dp.get(l).get(i);
//System.out.println("S");
long ans1,ans2;
ans1=r[i]+helper(r,l-power(2,i),i,n);
ans2=helper(r,l,i+1,n);
//System.out.println(ans1);
long ans=Math.min(ans1, ans2);
Map<Integer,Long>map=new HashMap<>();
map.put(i, ans);
dp.put(l,map);
return ans;
}
static long min;
public static void dfs(int i,boolean visited[],long arr[],ArrayList<ArrayList<Integer>>adj)
{
visited[i]=true;
min=Math.min(arr[i-1],min);
for(int it:adj.get(i))
{
if(!visited[it])
dfs(it,visited,arr,adj);
}
}
public static long cnt(long n)
{
long c=0;
long i=0;;
while((n&(1<<i))==0)
{
c++;
i++;
}
return c;
}
public static void main (String[] args) throws java.lang.Exception
{
long mod=1000000007;
FastReader in=new FastReader();
if(in.hasNext()){
if(in.hasNext()){
BufferedWriter log = new BufferedWriter(new OutputStreamWriter(System.out));
//int test=in.nextInt();
int n=in.nextInt();
int q=in.nextInt();
String s=in.next();
String std="abc";
int c=0;
for(int i=0;i<n-2;i++)
{
String str="";
for(int j=i;j<i+3;j++)
str+=s.charAt(j);
if(std.equals(str))
c++;
}
char charr[]=s.toCharArray();
for(int i=0;i<q;i++)
{
int pos=in.nextInt();
pos--;
char ch=in.next().charAt(0);
//charr[pos]=ch;
String strl,strr,strm;
if(pos+2<n)
{
if(charr[pos]=='a'&&charr[pos+1]=='b'&&charr[pos+2]=='c')
c--;
}
if(pos-2>=0)
{
if(charr[pos]=='c'&&charr[pos-1]=='b'&&charr[pos-2]=='a')
c--;
}
if(pos>0&&pos<n-1)
{
if(charr[pos]=='b'&&charr[pos-1]=='a'&&charr[pos+1]=='c')
c--;
}
charr[pos]=ch;
if(pos+2<n)
{
if(charr[pos]=='a'&&charr[pos+1]=='b'&&charr[pos+2]=='c')
c++;
}
if(pos-2>=0)
{
if(charr[pos]=='c'&&charr[pos-1]=='b'&&charr[pos-2]=='a')
c++;
}
if(pos>0&&pos<n-1)
{
if(charr[pos]=='b'&&charr[pos-1]=='a'&&charr[pos+1]=='c')
c++;
}
System.out.println(c);
}
}
}
}
}
| Java | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | 29df3291fadc3f3ac96fd46fec3ce2e4 | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 256 megabytes | import java.util.*;
public class Solution
{
public static int count(char[] ch,char c,int pos,int n)
{
int temp1=0,temp2=0;
for(int i=pos-2;i<pos+3;i++)
{
if(i>=0&&i<n)
{
if(ch[i]=='a')
{
if(i+1<n&&i+2<n&&ch[i+1]=='b'&&ch[i+2]=='c')
temp1++;
}
}
}
ch[pos]=c;
for(int i=pos-2;i<pos+3;i++)
{
if(i>=0&&i<n)
{
if(ch[i]=='a')
{
if(i+1<n&&i+2<n&&ch[i+1]=='b'&&ch[i+2]=='c')
temp2++;
}
}
}
//System.out.println(temp1+" "+temp2);
return temp2-temp1;
}
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
int q=sc.nextInt();
String s=sc.next();
char [] ch= s.toCharArray();
int temp=0;
for(int i=0;i<n;i++)
{
if(ch[i]=='a')
{
if(i+1<n&&i+2<n&&ch[i+1]=='b'&&ch[i+2]=='c')
temp++;
}
}
//System.out.println(temp);
for(int i=0;i<q;i++)
{
int k=sc.nextInt();
char c=sc.next().charAt(0);
System.out.println(temp=temp+count(ch,c,k-1,n));
}
}
} | Java | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | 711e0165a0ef21deec22fbf04d1cb899 | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 256 megabytes | //package Div2.B;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class WilliamTheVigilant {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String []nq=br.readLine().split(" ");
int n=Integer.parseInt(nq[0]);
int q=Integer.parseInt(nq[1]);
String s=br.readLine();
char []c=new char[n];
for(int i=0;i<n;i++)
c[i]=s.charAt(i);
int cnt=0;
for(int i=0;i<n-2;i++){
if(c[i]=='a' && c[i+1]=='b' && c[i+2]=='c') {
cnt += 1;
i+=2;
}
}
while (q > 0) {
String[] posc = br.readLine().split(" ");
int pos = Integer.parseInt(posc[0]);
char ch = posc[1].charAt(0);
pos--;
//is abc already around pos
if (c[pos] != ch) {
boolean res1 = isABCAroundPos(c, pos);
if (res1)
cnt--;
c[pos] = ch;
boolean res2 = isABCAroundPos(c, pos);
if (res2)
cnt++;
}
System.out.println(cnt);
q--;
}
}
private static boolean isABCAroundPos(char[] c, int pos) {
if (c[pos] == 'a') {
return pos + 2 < c.length && c[pos + 1] == 'b' && c[pos + 2] == 'c';
} else if (c[pos] == 'b') {
return pos - 1 >= 0 && pos + 1 < c.length && c[pos - 1] == 'a' && c[pos + 1] == 'c';
} else {
return pos - 2 >= 0 && c[pos - 2] == 'a' && c[pos - 1] == 'b';
}
}
}
| Java | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | 226673e17455c08c4024d5f02273d6a3 | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 256 megabytes | import java.io.*;
import java.util.*;
public class Division {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n = nextInt();
int a = nextInt();
String str = nextToken();
char[] chars = str.toCharArray();
int all = 0;
for (int i = 0; i < str.length() - 2; i++) {
if (str.substring(i, i + 3).equals("abc")) {
all++;
}
}
for (int i = 0; i < a; i++) {
int place = nextInt() - 1;
String b = nextToken();
char c = b.charAt(0);
for (int j = place - 2; j <= place; j++) {
if (j < 0 || j + 2 >= n) continue;
if (chars[j] == 'a' && chars[j + 1] == 'b' && chars[j + 2] == 'c') {
all--;
}
}
chars[place] = c;
for (int j = place - 2; j <= place; j++) {
if (j < 0 || j + 2 >= n) continue;
if (chars[j] == 'a' && chars[j + 1] == 'b' && chars[j + 2] == 'c') {
all++;
}
}
System.out.println(all);
}
}
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter out = new PrintWriter(System.out);
static StringTokenizer in = new StringTokenizer("");
public static boolean hasNext() throws IOException {
if (in.hasMoreTokens()) return true;
String s;
while ((s = br.readLine()) != null) {
in = new StringTokenizer(s);
if (in.hasMoreTokens()) return true;
}
return false;
}
public static String nextToken() throws IOException {
while (!in.hasMoreTokens()) {
in = new StringTokenizer(br.readLine());
}
return in.nextToken();
}
public static int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public static double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
public static long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
} | Java | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | 7d3f942a4f9e935c4c3041e6ad950f15 | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 256 megabytes | import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.io.*;
public class TestClass {
BufferedReader br;
StringTokenizer st;
public TestClass(){ // constructor
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 void sort(int[] arr){
int n = arr.length;
Random rnd = new Random();
for(int i = 0; i < n; ++i){
int tmp = arr[i];
int randomPos = i + rnd.nextInt(n - i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
Arrays.sort(arr);
}
static long gcd(long a, long b) {
if(b == 0) {
return a;
}
return gcd(b, a % b);
}
static class Edge{
int v;
Edge(int v){
this.v = v;
}
}
//static int n;
static ArrayList<Edge> graph[];
static void addEdge(int u, int v){
graph[u].add(new Edge(v));
}
static boolean isSafe(int r, int c, int n, int m){
if(r >= 0 && r < n && c >= 0 && c < m){
return true;
}
return false;
}
static class Points{
int x;
int y;
Points(int x, int y){
this.x = x;
this.y = y;
}
}
//static long mod = (long)1e9 + 7;
static int dir[][] = {{1, 0}, {-1, 0}, {0 ,1}, {0, -1}};
public static void main(String[] args) throws Exception{
TestClass in = new TestClass();
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int q = in.nextInt();
String str = in.next();
char ch[] = str.toCharArray();
Set<Integer> a = new HashSet<>();
for(int i = 0; i < n - 2; i++) {
if(ch[i] == 'a' && ch[i + 1] == 'b' && ch[i + 2] == 'c') {
a.add(i);
}
}
StringBuilder sb = new StringBuilder();
int size = a.size();
while(q-- > 0) {
//prev
int idx = in.nextInt();
idx--;
char ip = in.next().charAt(0);
String p1 = "";
String p2 = "";
String p3 = "";
for(int i = idx; i < idx + 3; i++) {
if(i < n) {
p1 = p1 + ch[i];
}
}
for(int i = idx - 1; i < idx + 2; i++) {
if(i < n && i >= 0) {
p2 = p2 + ch[i];
}
}
for(int i = idx - 2; i < idx + 1; i++) {
if(i < n && i >= 0) {
p3 = p3 + ch[i];
}
}
if(p1.equals("abc") || p2.equals("abc") || p3.equals("abc")) {
size--;
}
// change
ch[idx] = ip;
p1 = "";
p2 = "";
p3 = "";
for(int i = idx; i < idx + 3; i++) {
if(i < n) {
p1 = p1 + ch[i];
}
}
for(int i = idx - 1; i < idx + 2; i++) {
if(i < n && i >= 0) {
p2 = p2 + ch[i];
}
}
for(int i = idx - 2; i < idx + 1; i++) {
if(i < n && i >= 0) {
p3 = p3 + ch[i];
}
}
if(p1.equals("abc") || p2.equals("abc") || p3.equals("abc")) {
size++;
}
sb.append(size + "\n");
}
out.println(sb.toString());
out.flush();
out.close();
}
} | Java | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | 32f66ede03c97415f2063609ccb1da7e | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 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 B_William_the_Vigilant{
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 q=s.nextInt();
String str1=s.nextToken();
char array[]= new char[n];
for(int i=0;i<n;i++){
array[i]=str1.charAt(i);
}
long count=0;
HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i=0;i<n;i++){
int end=Math.min((i+3),n);
String yo=str1.substring(i,end);
if(yo.equals("abc")){
count++;
map.put(i,1);
}
}
for(int i=0;i<q;i++){
int pos=s.nextInt();
String hh=s.nextToken();
char ch=hh.charAt(0);
pos--;
if(array[pos]==ch){
res.append(count+" \n");
}
else{
if(map.containsKey(pos)){
if(ch=='b'){
array[pos]=ch;
count--;
map.remove(pos);
int flag1=0;
int flag2=0;
if((pos-1>=0)&&array[pos-1]=='a'){
flag1=1;
}
if((pos+1<n)&&array[pos+1]=='c'){
flag2=1;
}
if(flag1==1 && flag2==1){
count++;
map.put((pos-1),1);
}
}
else if(ch=='c'){
array[pos]=ch;
count--;
map.remove(pos);
int flag1=0;
int flag2=0;
if((pos-1>=0)&&array[pos-1]=='b'){
flag1=1;
}
if((pos-2>=0)&&array[pos-2]=='a'){
flag2=1;
}
if(flag1==1 && flag2==1){
count++;
map.put((pos-2),1);
}
}
}
else if(map.containsKey(pos-1)){
////
if(ch=='a'){
array[pos]=ch;
count--;
map.remove(pos-1);
int flag1=0;
int flag2=0;
if((pos+2<n)&&array[pos+2]=='c'){
flag1=1;
}
if((pos+1<n)&&array[pos+1]=='b'){
flag2=1;
}
if(flag1==1 && flag2==1){
count++;
map.put((pos),1);
}
}
else if(ch=='c'){
array[pos]=ch;
count--;
map.remove(pos-1);
int flag1=0;
int flag2=0;
if((pos-1>=0)&&array[pos-1]=='b'){
flag1=1;
}
if((pos-2>=0)&&array[pos-2]=='a'){
flag2=1;
}
if(flag1==1 && flag2==1){
count++;
map.put((pos-2),1);
}
}
////
}
else if(map.containsKey(pos-2)){
/////
if(ch=='b'){
array[pos]=ch;
count--;
map.remove(pos-2);
int flag1=0;
int flag2=0;
if((pos-1>=0)&&array[pos-1]=='a'){
flag1=1;
}
if((pos+1<n)&&array[pos+1]=='c'){
flag2=1;
}
if(flag1==1 && flag2==1){
count++;
map.put((pos-1),1);
}
}
else if(ch=='a'){
array[pos]=ch;
count--;
map.remove(pos-2);
int flag1=0;
int flag2=0;
if((pos+2<n)&&array[pos+2]=='c'){
flag1=1;
}
if((pos+1<n)&&array[pos+1]=='b'){
flag2=1;
}
if(flag1==1 && flag2==1){
count++;
map.put((pos),1);
}
}
////
}
else{
if(ch=='a'){
array[pos]=ch;
int flag1=0;
int flag2=0;
if((pos+2<n)&&array[pos+2]=='c'){
flag1=1;
}
if((pos+1<n)&&array[pos+1]=='b'){
flag2=1;
}
if(flag1==1 && flag2==1){
count++;
map.put((pos),1);
}
}
else if(ch=='b'){
array[pos]=ch;
int flag1=0;
int flag2=0;
if((pos-1>=0)&&array[pos-1]=='a'){
flag1=1;
}
if((pos+1<n)&&array[pos+1]=='c'){
flag2=1;
}
if(flag1==1 && flag2==1){
count++;
map.put((pos-1),1);
}
}
else{
array[pos]=ch;
int flag1=0;
int flag2=0;
if((pos-1>=0)&&array[pos-1]=='b'){
flag1=1;
}
if((pos-2>=0)&&array[pos-2]=='a'){
flag2=1;
}
if(flag1==1 && flag2==1){
count++;
map.put((pos-2),1);
}
}
}
res.append(count+" \n");
}
// for(int j=0;j<10;j++){
// if(map.containsKey(j)){
// System.out.print(j+" ");
// }
// }
// System.out.println();
// for(int j=0;j<n;j++){
// System.out.print(array[j]);
// }
// System.out.println();
}
System.out.println(res);
}
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 | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | ddb2a7f9b350ecf11c3fe44184c18806 | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 256 megabytes | import java.util.*;
import java.io.*;
public class Solution{
public static int f(char ch[],int pos,char c,int n)
{
int count = 0;
if(ch[pos]=='a')
{
if(pos+1<n&&pos+2<n&&ch[pos+1]=='b'&&ch[pos+2]=='c')
count++;
}
else if(ch[pos]=='b')
{
if(pos+1<n&&pos-1>=0&&ch[pos-1]=='a'&&ch[pos+1]=='c')
count++;
}
else
{
if(pos-1>=0&&pos-2>=0&&ch[pos-1]=='b'&&ch[pos-2]=='a')
count++;
}
ch[pos] = c;
if(ch[pos]=='a')
{
if(pos+1<n&&pos+2<n&&ch[pos+1]=='b'&&ch[pos+2]=='c')
count--;
}
else if(ch[pos]=='b')
{
if(pos+1<n&&pos-1>=0&&ch[pos-1]=='a'&&ch[pos+1]=='c')
count--;
}
else
{
if(pos-1>=0&&pos-2>=0&&ch[pos-1]=='b'&&ch[pos-2]=='a')
count--;
}
return count;
}
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out));
String s1[] = br.readLine().split(" ");
int n=Integer.parseInt(s1[0]);
int q=Integer.parseInt(s1[1]);
char ch[] = br.readLine().toCharArray();
int sum = 0;
for(int i=0;i<n-2;i++)
{
if(ch[i]=='a'&&ch[i+1]=='b'&&ch[i+2]=='c')
sum++;
}
while(q-->0)
{
String str[]=br.readLine().split(" ");
int pos=Integer.parseInt(str[0])-1;
char c= str[1].charAt(0);
sum=sum-f(ch,pos,c,n);
System.out.println(sum+"\n");
}
bw.close();
}
} | Java | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | 2d2ddbf93d3131005cf8fbb7a835b64f | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static long startTime = System.currentTimeMillis();
// for global initializations and methods starts here
// 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 q = r.ni();
char[] s = r.word().toCharArray();
int count = 0;
for (int i = 0; i < n - 2; i++) {
if (s[i] == 'a' && s[i + 1] == 'b' && s[i + 2] == 'c') {
count++;
}
}
while (q-- > 0) {
int ind = r.ni() - 1;
char c = r.word().charAt(0);
int st = Math.max(0, ind - 2);
int en = Math.min(ind + 1, n - 2);
if (s[ind] == c) {
out.write((count + " ").getBytes());
out.write(("\n").getBytes());
continue;
}
{
int i = st;
while (i < en) {
if (s[i] == 'a' && s[i + 1] == 'b' && s[i + 2] == 'c') {
count--;
}
i++;
}
}
s[ind] = c;
int i = st;
while (i < en) {
if (s[i] == 'a' && s[i + 1] == 'b' && s[i + 2] == 'c') {
count++;
}
i++;
}
out.write((count + " ").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 | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | 9907e01676e7ac153661bab375ed9d51 | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 256 megabytes |
import java.util.*;
import java.util.stream.Collectors;
import java.io.*;
import java.math.*;
public class B2 {
public static FastScanner sc;
public static PrintWriter pw;
public static StringBuilder sb;
public static int MOD= 1000000007;
public 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) {}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
public static void printList(List<Long> al) {
System.out.println(al.stream().map(it -> it.toString()).collect(Collectors.joining(" ")));
}
public static void printList(Deque<Long> al) {
System.out.println(al.stream().map(it -> it.toString()).collect(Collectors.joining(" ")));
}
public static void printArr(int[] arr) {
System.out.println(Arrays.toString(arr).trim().replace("[", "").replace("]","").replace(","," "));
}
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 void decreasingOrder(ArrayList<Long> al) {
Comparator<Long> c = Collections.reverseOrder();
Collections.sort(al,c);
}
public static boolean[] sieveOfEratosthenes(int n) {
boolean isPrime[] = new boolean[n+1];
Arrays.fill(isPrime, true);
isPrime[0]=false;
isPrime[1]=false;
for(int i=2;i*i<n;i++) {
for(int j=2*i;j<n;j+=i) {
isPrime[j]=false;
}
}
return isPrime;
}
public static long nCr(long N, long R) {
double result=1;
for(int i=1;i<=R;i++) result=((result*(N-R+i))/i);
return (long) result;
}
public static long fastPow(long a, long b, int n) {
long result=1;
while(b>0) {
if((b&1)==1)
result=(result*a %n)%n;
a=(a%n * a%n)%n;
b>>=1;
}
return result;
}
public static int BinarySearch(long[] arr, long key) {
int low=0;
int high=arr.length-1;
while(low<=high) {
int mid=(low+high)/2;
if(arr[mid]==key)
return mid;
else if(arr[mid]>key)
high=mid-1;
else
low=mid+1;
}
return low; //High=low-1
}
public static void solve(int t) {
int n=sc.nextInt();
int q=sc.nextInt();
String s=sc.next();
int countM=0;
for(int i=0;i<n-2;i++) {
if(s.charAt(i)=='a' && s.charAt(i+1)=='b' && s.charAt(i+2)=='c') countM++;
}
char[] arr=s.toCharArray();
int count=countM;
while(q-->0) {
int a=sc.nextInt();
char c=sc.next().charAt(0);
a--;
if(arr[a]=='a' && a+1<n && arr[a+1]=='b' && a+2<n && arr[a+2]=='c' && c!='a') {
count--;
}
if(arr[a]=='b' && a+1<n && arr[a+1]=='c' && a-1>=0 && arr[a-1]=='a' && c!='b') {
count--;
}
if(arr[a]=='c' && a-1>=0 && arr[a-1]=='b' && a-2>=0 && arr[a-2]=='a' && c!='c') {
count--;
}
// System.out.println(a+" YES");
if(arr[a]!=c && a+1<n && arr[a+1]=='b' && a+2<n && arr[a+2]=='c' && c=='a') {
count++;
}
if(arr[a]!=c && a+1<n && arr[a+1]=='c' && a-1>=0 && arr[a-1]=='a' && c=='b') {
count++;
}
if(arr[a]!=c && a-1>=0 && arr[a-1]=='b' && a-2>=0 && arr[a-2]=='a' && c=='c') {
count++;
}
arr[a]=c;
System.out.println(count);
}
}
public static void main(String[] args) {
sc = new FastScanner();
pw = new PrintWriter(new OutputStreamWriter(System.out));
sb= new StringBuilder("");
solve(0);
}
}
| Java | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | d4057c427e70badc0a78dad27b479bb8 | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 256 megabytes | import java.io.*;
import java.util.*;
/**
* Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools
*/
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);
Task solver = new Task();
solver.solve(1, in, out);
out.close();
}
public static class Task {
private long[] div2(long num) {
long t=0;
while (num%2==0 && num>0) {
num = num/2;
t++;
}
return new long[]{t, num};
}
public void solve(int cnt, InputReader in, PrintWriter out) {
cnt = 1;
for(int c=0;c<cnt;c++) {
int n = in.nextInt();
int q = in.nextInt();
String str = in.next();
char[] cs = str.toCharArray();
Map<Integer, Integer[]> idx = new HashMap<>();
int num = 0;
for(int i=0;i<cs.length;i++) {
if(i>= 0 && i+2<str.length() &&
cs[i]=='a' && cs[i+1]=='b' && cs[i+2]=='c') {
Integer[] tmp = new Integer[]{i,i+2};
idx.put(i, tmp);
idx.put(i+1, tmp);
idx.put(i+2, tmp);
num++;
}
}
for(int k=0;k<q;k++) {
int i = in.nextInt()-1;
char cr = in.next().charAt(0);
if(cr!=cs[i]) {
cs[i] = cr;
if(idx.containsKey(i)) {
Integer[] tmp = idx.get(i);
for(int j=tmp[0];j<=tmp[1];j++) {
idx.remove(j);
}
num--;
}
//判断有没有造成新增
for(int j=i-2;j<=i;j++) {
if(j>=0 && j+2<n && cs[j]=='a' && cs[j+1]=='b' && cs[j+2]=='c') {
Integer[] tmp = new Integer[]{j,j+2};
idx.put(j, tmp);
idx.put(j+1, tmp);
idx.put(j+2, tmp);
num++;
}
}
}
out.println(num);
}
}
}
}
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());
}
}
} | Java | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | b3b7201078ab8bc64a32cac55faea0dc | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 256 megabytes | import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
public class A {
static boolean isOkPos(int pos, char[] str) {
return pos >= 0 && pos < str.length;
}
static boolean isAtABC(int pos, char[] str) {
return isOkPos(pos, str) && isOkPos(pos + 1, str) && isOkPos(pos + 2, str) && str[pos] == 'a' && str[pos + 1] == 'b' && str[pos + 2] == 'c';
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int q = sc.nextInt();
char[] str = sc.next().toCharArray();
boolean[] positions = new boolean[n];
int count = 0;
for (int i = 0; i < str.length; i++) {
if (isAtABC(i, str)) {
count++;
positions[i] = true;
}
}
for (int i = 0; i < q; i++) {
int pos = sc.nextInt() - 1;
char c = sc.next().charAt(0);
str[pos] = c;
count += update(str, pos - 2, positions);
count += update(str, pos - 1, positions);
count += update(str, pos, positions);
System.out.println(count);
}
}
private static int update(char[] str, int pos, boolean[] positions) {
if (!isOkPos(pos, str)) {
return 0;
}
int res = 0;
if (positions[pos]) {
res--;
}
positions[pos] = false;
if (isAtABC(pos, str)) {
res++;
positions[pos] = true;
}
return res;
}
}
| Java | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | ca61267b57536329f44f7e78d65a198e | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
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;
}
}
public static void main(String[] args) {
FastReader sc = new FastReader();
int n = sc.nextInt();
int q = sc.nextInt();
StringBuilder s = new StringBuilder(sc.next());
int count = 0 ;
for (int i = 0; i < n-2; i++) {
if (s.charAt(i) == 'a' && s.charAt(i+1) == 'b' && s.charAt(i+2) == 'c') {
count++;
}
}
for (int i = 0; i < q; i++) {
int index = sc.nextInt() - 1;
char c = sc.next().charAt(0);
if (s.charAt(index) != c ) {
if (s.charAt(index) == 'a') {
if (index < n-2) {
if (s.charAt(index+1) == 'b' && s.charAt(index+2) == 'c') {
count-- ;
}
}
} else if (s.charAt(index) == 'b') {
if (index < n-1 && index > 0) {
if (s.charAt(index-1) == 'a' && s.charAt(index+1) == 'c') {
count-- ;
}
}
} else {
if ( index > 1) {
if (s.charAt(index-2) == 'a' && s.charAt(index-1) == 'b') {
count-- ;
}
}
}
s.setCharAt(index,c);
if (c == 'a') {
if (index < n-2) {
if (s.charAt(index+1) == 'b' && s.charAt(index+2) == 'c') {
count++ ;
}
}
} else if (c == 'b') {
if (index < n-1 && index > 0) {
if (s.charAt(index-1) == 'a' && s.charAt(index+1) == 'c') {
count++;
}
}
} else {
if ( index > 1) {
if (s.charAt(index-2) == 'a' && s.charAt(index-1) == 'b') {
count++ ;
}
}
}
}
System.out.println(count);
}
}
}
| Java | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | 659b5d3099748bbe71cfb9502f07daf7 | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Main {
static boolean check (StringBuilder s , int i) {
char ch = s.charAt(i);
int n = s.length();
if (ch == 'a') {
if (i == n - 2 || i == n - 1) {
return false;
}
String sub = s.substring(i, i + 3);
if (sub.equals("abc")) {
return true;
} else {
return false;
}
}
if (ch == 'b') {
if (i == 0 || i == n - 1) {
return false;
}
String sub = s.substring(i - 1, i + 2);
if (sub.equals("abc")) {
return true;
} else {
return false;
}
}
if (ch == 'c') {
if (i == 0 || i == 1) {
return false;
}
String sub = s.substring(i - 2, i + 1);
if (sub.equals("abc")) {
return true;
} else {
return false;
}
}
return false;
}
public static void solve() {
int n = in.nextInt();
int q = in.nextInt();
StringBuilder s = new StringBuilder(in.nextLine());
int count = 0;
for (int i = 0; i < n - 2; i++) {
char ch = s.charAt(i);
if (ch == 'a' && check(s, i)) {
count++;
i += 2;
}
}
while (q-- != 0) {
int pos = in.nextInt();
char ch = in.next().charAt(0);
// System.out.println(pos + " " + ch);
if (check(s, pos - 1)) {
count--;
}
s.setCharAt(pos - 1, ch);
if (check(s, pos - 1)) {
count++;
}
out.append(count + "\n");
}
}
public static void main (String[] args) throws java.lang.Exception {
// your code goes here
// int t = in.nextInt();
// while (t-- != 0) {
solve();
// }
System.out.print(out);
}
public static <T> void print(T s) {
System.out.print(s);
}
public static <T> void println(T s) {
System.out.println(s);
}
public static void print(int s) {
System.out.print(s);
}
public static void println(int s) {
System.out.println(s);
}
public static void print(int[] a) {
int k = 0;
for (int i : a) {
print(k++ +":" + i + " ");
}
println("");
}
public static int[] array(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
return a;
}
public static int[] array1(int n) {
int[] a = new int[n + 1];
for (int i = 1; i <= n; i++) {
a[i] = in.nextInt();
}
return a;
}
static FastReader in = new FastReader();
static StringBuffer out = new StringBuffer();
static final int MAX = Integer.MAX_VALUE;
static final int MIN = Integer.MIN_VALUE;
static int mod = 1000000007;
}
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 | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | 39ca70b5e07d95e348d6e42d2387ab21 | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 256 megabytes | import java.util.*;
import java.io.*;
public class Codechef{
static final int mod = (int)(1e9 + 7);
static final FastReader sc = new FastReader();
static boolean forms_abc(int pos, char ch[]){
boolean res = true;
if(ch[pos] == 'a'){
if(!(pos + 2 < ch.length && ch[pos+1] == 'b' && ch[pos+2] == 'c') ){
res = false;
}
}
else if(ch[pos] == 'b'){
if(! (pos != 0 && pos+1 < ch.length && ch[pos -1] == 'a' && ch[pos+1] == 'c' )){
res = false;
}
}
else{
if(! (pos - 2 >= 0 && ch[pos-2] == 'a' && ch[pos-1] == 'b') ){
res = false;
}
}
return res;
}
public static void main(String args[]){
int n = sc.nextInt();
int q = sc.nextInt();
String s = sc.nextLine();
int count = 0;
for(int i=0; i+3 <= n; i++){
if("abc".equals(s.substring(i, i+3))){
count++;
}
}
char ch[] = s.toCharArray();
while(q-- > 0){
int pos = sc.nextInt() -1 ;
char x = sc.nextChar();
if( forms_abc(pos, ch)){
count--;
}
ch[pos] = x;
if(forms_abc(pos, ch)){
count++;
}
System.out.println(count);
}
}
static class DSU{
int[] parent, rank;
public DSU(int v){
parent = new int[v];
rank = new int[v];
for(int i=0; i<v; i++){
parent[i] = -1;
rank[i] = 1;
}
}
int findParent(int u){
if(parent[u] == -1) return u;
parent[u] = findParent(parent[u]);
return parent[u];
}
void union(int u, int v){
u = findParent(u);
v = findParent(v);
if(u == v) return;
if(rank[u] < rank[v]){
parent[u] = v;
rank[v] += rank[u];
}
else{
parent[v] = u;
rank[u] += v;
}
}
}
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());
}
char nextChar(){
return next().charAt(0);
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
void print( char output){
System.out.print(output + " ");
}
void print( int output){
System.out.print(output + " ");
}
void print( long output){
System.out.print(output + " ");
}
void print( double output){
System.out.print(output + " ");
}
void print(String output){
System.out.print(output);
}
void print(StringBuilder output){
System.out.print(output);
}
void println( char output){
System.out.println(output);
}
void println( int output){
System.out.println(output);
}
void println( long output){
System.out.println(output);
}
void println(double output){
System.out.println(output);
}
void println(String output){
System.out.println(output);
}
void println(StringBuilder output){
System.out.println(output);
}
void printArray(char arr[]){
StringBuilder str = new StringBuilder();
int n = arr.length;
for(int i=0; i<n; i++){
str.append(arr[i]+" ");
}
System.out.println(str);
}
void printArray(int arr[]){
StringBuilder str = new StringBuilder();
int n = arr.length;
for(int i=0; i<n; i++){
str.append(arr[i]+" ");
}
System.out.println(str);
}
void printArray(Integer arr[]){
StringBuilder str = new StringBuilder();
int n = arr.length;
for(int i=0; i<n; i++){
str.append(arr[i]+" ");
}
System.out.println(str);
}
void printArray(boolean arr[]){
StringBuilder str = new StringBuilder();
int n = arr.length;
for(int i=0; i<n; i++){
str.append(arr[i]+" ");
}
System.out.println(str);
}
void printArray(int arr[], int fromIndex){
StringBuilder str = new StringBuilder();
int n = arr.length;
for(int i=fromIndex; i<n; i++){
str.append(arr[i]+" ");
}
System.out.println(str);
}
void printArray(long arr[]){
StringBuilder str = new StringBuilder();
int n = arr.length;
for(int i=0; i<n; i++){
str.append(arr[i]+" ");
}
System.out.println(str);
}
void printArray(double arr[]){
StringBuilder str = new StringBuilder();
int n = arr.length;
for(int i=0; i<n; i++){
str.append(arr[i]+" ");
}
System.out.println(str);
}
void printArray(int arr[][]){
StringBuilder str = new StringBuilder();
int n = arr.length;
int m = arr[0].length;
for(int i=0; i<n; i++){
for(int j = 0; j<m; j++){
str.append(arr[i][j]+" ");
}
str.append("\n");
}
System.out.println(str);
}
void printArray(long arr[][]){
StringBuilder str = new StringBuilder();
int n = arr.length;
int m = arr[0].length;
for(int i=0; i<n; i++){
for(int j = 0; j<m; j++){
str.append(arr[i][j]+" ");
}
str.append("\n");
}
System.out.println(str);
}
void printArray(double arr[][]){
StringBuilder str = new StringBuilder();
int n = arr.length;
int m = arr[0].length;
for(int i=0; i<n; i++){
for(int j = 0; j<m; j++){
str.append(arr[i][j]+" ");
}
str.append("\n");
}
System.out.println(str);
}
void printGraph(List<List<Integer>> G){
int nodes = G.size();
for(int i=0; i<nodes; i++){
System.out.print(i+"-> ");
for(int j : G.get(i)){
System.out.print(j+" ");
}
System.out.println();
}
}
static long pow(long base, int p, int mod){
if(p == 0)
return 1;
long m = (base * base ) % mod;
if(p % 2 == 0){
return pow(m, p/2, mod) % mod;
}
else
return (base % mod * pow(m , p/2, mod) % mod ) % mod ;
}
static long pow(long base, long p){
if(p == 0)
return 1;
long product = base * base % mod ;
if(p % 2 == 0){
return pow(product, p/2) % mod;
}
else
return ( base * ( pow(product , p/2) % mod ) ) % mod ;
}
static long inverse(long a, long mod){
return sc.pow(a, mod - 2);
}
static long inverse(long a){
return sc.pow(a, mod - 2);
}
static int max(int arr[]){
int len = arr.length;
int max = Integer.MIN_VALUE;
for(int i=0; i<len; i++){
if( max < arr[i]){
max = arr[i];
}
}
return max;
}
static int[] inputArray(int n){
int arr[] = new int[n];
for(int i=0; i<n; i++){
arr[i] = sc.nextInt();
}
return arr;
}
static int[] inputArray(int n, int fromIndex){
int size = n + fromIndex;
int arr[] = new int[size];
for(int i=fromIndex; i<size; i++){
arr[i] = sc.nextInt();
}
return arr;
}
static long[] inputArray(long n){
long arr[] = new long[(int)n];
for(int i=0; i<n; i++){
arr[i] = sc.nextLong();
}
return arr;
}
static long[] inputArray(long n, int fromIndex){
int size = (int)n + fromIndex;
long arr[] = new long[size];
for(int i=fromIndex; i<size; i++){
arr[i] = sc.nextLong();
}
return arr;
}
static double[] inputArray(double n, int fromIndex){
int size = (int)n + fromIndex;
double arr[] = new double[size];
for(int i=fromIndex; i<size; i++){
arr[i] = sc.nextDouble();
}
return arr;
}
static List<Integer> findPrimes(int n){
int sieve[] = new int[n+1];
for(long i = 2; i<= n; i++){
if(sieve[(int)i] == 0){
for(long j = i*i; j <= n; j += i){
sieve[(int)j] = 1;
}
}
}
List<Integer> primes = new ArrayList<>();
for(int i=2; i<=n ; i++){
if(sieve[i] == 0){
primes.add(i);
}
}
return primes;
}
}
} | Java | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | 595543ce50312e2e81e57d7a2e30582d | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 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;
}
}
public void solve() {
int n = io.ri();
int t = io.ri();
char[] s = io.readWord().toCharArray();
int k = 0;
for(int i = 2;i<s.length;i++){
if(s[i-2] =='a' && s[i-1] == 'b' && s[i] == 'c')
k++;
}
for(int i = 0 ; i < t; i++) {
int p = io.ri() - 1;
char v = io.readSymbol();
if(good(s, p)) {
k--;
}
s[p] = v;
if(good(s,p)) {
k++;
}
io.writeLine(Integer.toString(k));
}
}
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 | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | 7b774842b11cfb88c901357422b9f6b2 | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 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 q = s.nextInt();
String str = s.next();
char arr[] = str.toCharArray();
int cnt = 0;
for(int i=0;i<n-2;i++){
if(arr[i]=='a' && arr[i+1]=='b' && arr[i+2]=='c'){cnt++;}
}
for(int i=0;i<q;i++){
int index = s.nextInt();
index--;
char curr = s.next().charAt(0);
dbg(debug,arr);
if(arr[index] == curr){
}
else{
if((curr == 'a') && (index + 2 < arr.length && (arr[index+1]=='b') && (arr[index+2]=='c'))){
cnt++;
}else if((curr == 'b') && ((index + 1 < arr.length) && (index - 1 >= 0) && (arr[index-1]=='a') && (arr[index+1]=='c'))){
cnt++;
}else if((curr == 'c') && (index - 2 >=0) && (arr[index-1]=='b' && arr[index-2]=='a')){
cnt++;
}
if(check(arr,index)){
cnt--;
}
arr[index] = curr;
}
sb.append(cnt+"\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 | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | 96934714a2bba6986619b2633dc5c5d1 | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.StringTokenizer;
public class B {
static BufferedReader br;
static StringTokenizer st;
static PrintWriter pw;
static String nextToken() {
try {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
static int nextInt() {
return Integer.parseInt(nextToken());
}
public static void main(String[] args) {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(System.out);
run();
pw.close();
}
private static void run() {
int n = nextInt();
int q = nextInt();
String s = nextToken();
char[] chars = s.toCharArray();
int kol = 0;
for (int j = 0; j < n - 2; j++) {
if (s.charAt(j) == 'a' && s.charAt(j + 1) == 'b' && s.charAt(j + 2) == 'c') {
kol++;
}
}
for (int i = 0; i < q; i++) {
int x = nextInt() - 1;
String ch = nextToken();
for (int j = x - 2; j <= x; j++) {
if (j < 0 || j + 2 >= n) continue;
if (chars[j] == 'a' && chars[j + 1] == 'b' && chars[j + 2] == 'c') {
kol--;
}
}
chars[x] = ch.charAt(0);
for (int j = x - 2; j <= x; j++) {
if (j < 0 || j + 2 >= n) continue;
if (chars[j] == 'a' && chars[j + 1] == 'b' && chars[j + 2] == 'c') {
kol++;
}
}
pw.println(kol);
}
}
}
| Java | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | 28f96a1b2e37da01416700fee7c36fcc | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 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 q = i();
char[] chars = s().toCharArray();
int cnt = 0;
for (int i = 0; i + 2 < n; i++) {
if (chars[i] == 'a' && chars[i + 1] == 'b' && chars[i + 2] == 'c') {
cnt++;
}
}
for (int i = 0; i < q; i++) {
int x = i() - 1;
char c = c().toCharArray()[0];
if (chars[x] == c) {
out.println(cnt);
} else {
int ocnt = 0;
for (int j = Math.max(0, x - 2); j <= x && j + 2 < n; j++) {
if (chars[j] == 'a' && chars[j + 1] == 'b' && chars[j + 2] == 'c') {
ocnt++;
}
}
chars[x] = c;
int ncnt = 0;
for (int j = Math.max(0, x - 2); j <= x && j + 2 < n; j++) {
if (chars[j] == 'a' && chars[j + 1] == 'b' && chars[j + 2] == 'c') {
ncnt++;
}
}
out.println(cnt + ncnt - ocnt);
cnt = cnt + ncnt - ocnt;
}
}
}
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 | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | 9bd034f2359a7eb7b5df8174e7d51a6a | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 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.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/B" target="_top">https://codeforces.com/contest/1609/problem/B</a>
* @since 28/11/21 8:19 PM
*/
public class B {
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();
char[] str = sc.next().toCharArray();
int cnt = 0;
for (int i = 0; i < n - 2; i++) {
if (isAbcAt(str, i))
cnt++;
}
while (q-- > 0) {
int pos = sc.nextInt() - 1;
char c = sc.next().charAt(0);
if (str[pos] != c) {
//if this is part of a valid substring
cnt = updateCount(n, str, cnt, pos, -1);
str[pos] = c;
//if any new is formed
cnt = updateCount(n, str, cnt, pos, 1);
}
System.out.println(cnt);
}
}
}
}
private static int updateCount(int n, char[] str, int cnt, int pos, int add) {
for (int j = pos - 2; j <= pos; j++) {
int end = j + 2;
if (j >= 0 && end < n) {
if (isAbcAt(str, j)) {
cnt += add;
}
}
}
return cnt;
}
private static boolean isAbcAt(char[] str, int i) {
return str[i] == 'a' && str[i + 1] == 'b' && str[i + 2] == 'c';
}
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 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | 51abf977677c6dc3dc25fc84c7ee0091 | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 256 megabytes | import java.util.*;
import java.io.*;
public class s1 {
public static FastScanner scan;
public static PrintWriter out;
public static void main(String[] args) throws Exception {
scan=new FastScanner(System.in);
out=new PrintWriter(System.out);
int T=1;
// int T=scan.nextInt();
while(T-->0) {
int n=scan.nextInt(),q=scan.nextInt();
char[] s=scan.nextLine().toCharArray();
int ori=0;
for(int i=0;i<n-2;i++) {
if(s[i]=='a'&&s[i+1]=='b'&&s[i+2]=='c') {
ori++;
}
}
while(q-->0) {
String[] input=scan.nextLine().split(" ");
int pos=Integer.parseInt(input[0])-1;
char cur=input[1].charAt(0);
int alr=0;
if(pos-2>=0&&s[pos-2]=='a'&&s[pos-1]=='b'&&s[pos]=='c') alr++;
if(pos-1>=0&&pos+1<n&&s[pos-1]=='a'&&s[pos]=='b'&&s[pos+1]=='c') alr++;
if(pos+2<n&&s[pos]=='a'&&s[pos+1]=='b'&&s[pos+2]=='c') alr++;
s[pos]=cur;
int now=0;
if(pos-2>=0&&s[pos-2]=='a'&&s[pos-1]=='b'&&s[pos]=='c') now++;
if(pos-1>=0&&pos+1<n&&s[pos-1]=='a'&&s[pos]=='b'&&s[pos+1]=='c') now++;
if(pos+2<n&&s[pos]=='a'&&s[pos+1]=='b'&&s[pos+2]=='c') now++;
ori+=now-alr;
out.println(ori);
}
} out.close();
}
}
class Pair {
int 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 | ["9 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 8 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | 3a153f6a1df92211f16c9d43c7140cf7 | 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 the correct formal description of the homework assignment: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 substring. A valid replacement of a character is replacing it with "a", "b" or "c".A string $$$x$$$ is a substring of a string $$$y$$$ if $$$x$$$ can be obtained from $$$y$$$ by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end. | 256 megabytes | import java.util.*;
import java.util.function.*;
import java.io.*;
// you can compare with output.txt and expected out
public class RoundDeltixAutumn2021B {
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();
RoundDeltixAutumn2021B sol = new RoundDeltixAutumn2021B();
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);
}
boolean isABC(int start) {
return start >= 0 && start+2 < n && s[start] == 'a' && s[start+1] == 'b' && s[start+2] == 'c';
}
int[] ans;
void solve(){
ans = new int[q];
for(int i=0; i<=n-3; i++)
if(isABC(i))
ans[0]++;
for(int i=0; i<q; i++) {
if(i > 0)
ans[i] = ans[i-1];
if(isABC(pos[i]-2))
ans[i]--;
else if(isABC(pos[i]-1))
ans[i]--;
else if(isABC(pos[i]))
ans[i]--;
s[pos[i]] = ch[i];
if(isABC(pos[i]-2))
ans[i]++;
else if(isABC(pos[i]-1))
ans[i]++;
else if(isABC(pos[i]))
ans[i]++;
}
}
// 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 10\nabcabcabc\n1 a\n1 b\n2 c\n3 a\n4 b\n5 c\n8 a\n9 b\n1 c\n4 a"] | 2 seconds | ["3\n2\n2\n2\n1\n2\n1\n1\n1\n0"] | NoteLet's consider the state of the string after each query: $$$s =$$$ "abcabcabc". In this case $$$3$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcaccabb". This string does not contain "abc" as a substring. $$$s =$$$ "bbcabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bbcbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bccabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bccbbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcaabcabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcbbc". This string does not contain "abc" as a substring. $$$s =$$$ "bcabbcabc". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccabc". In this case $$$2$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcabb". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaac". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaac". This string does not contain "abc" as a substring. $$$s =$$$ "bcabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "bcabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccabccaab". In this case $$$1$$$ replacements can be performed to get, for instance, string $$$s =$$$ "ccabbcaab". This string does not contain "abc" as a substring. $$$s =$$$ "ccaaccaab". In this case the string does not contain "abc" as a substring and no replacements are needed. | Java 17 | standard input | [
"implementation",
"strings"
] | db473ad780a93983667d12b1357c6e2f | 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". | 1,100 | 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 substring. | standard output | |
PASSED | 6069523695dfeb42dd8ea8b445b91f7d | 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 Div21609D {
static int[] parent, nodes, edges;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int d = Integer.parseInt(st.nextToken());
parent = new int[n];
nodes = new int[n];
edges = new int[n];
for(int i = 0; i < n; i++)
make_set(i);
for(int i = 0; i < d; i++) {
st = new StringTokenizer(br.readLine());
int u = Integer.parseInt(st.nextToken())-1;
int v = Integer.parseInt(st.nextToken())-1;
union_sets(u, v);
TreeSet<Pair> sets = new TreeSet<Pair>(new Comp());
int surplus = 0;
for(int j = 0; j < n; j++) {
if(parent[j] == j) {
surplus += Math.max(0, 1 + edges[j] - nodes[j]);
sets.add(new Pair(nodes[j], edges[j], j));
}
}
Iterator<Pair> it = sets.iterator();
int nodes = 0;
Pair start = it.next();
nodes += start.nodes;
while(it.hasNext()) {
Pair cp = it.next();
if(surplus > 0) {
nodes += cp.nodes;
surplus--;
}else
break;
}
pw.println(nodes-1);
}
pw.close();
}
static int find_set(int v) {
if (v == parent[v])
return v;
return parent[v] = find_set(parent[v]);
}
static void make_set(int v) {
parent[v] = v;
nodes[v] = 1;
edges[v] = 0;
}
static void union_sets(int a, int b) {
a = find_set(a);
b = find_set(b);
if (a != b) {
if (nodes[a] < nodes[b]) {
int tmp = a;
a = b;
b = tmp;
}
parent[b] = a;
nodes[a] += nodes[b];
edges[a] += edges[b];
}
edges[a]++;
}
static class Pair{
@Override
public String toString() {
// TODO Auto-generated method stub
return nodes + " " + edges + " " + index;
}
int nodes;
int edges;
int index;
public Pair(int a, int b, int c) {
nodes = a;
edges = b;
index = c;
}
}
static class Comp implements Comparator<Pair>{
@Override
public int compare(Pair a, Pair b) {
// TODO Auto-generated method stub
if(a.nodes == b.nodes)
return Integer.compare(b.index, a.index);
return Integer.compare(b.nodes, a.nodes);
}
}
}
| 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 | 0a75e8833667ac1ce686afcb66e17016 | 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.Map;
import java.util.TreeMap;
public class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
FastScanner fs = new FastScanner();
java.io.PrintWriter out = new java.io.PrintWriter(System.out);
solve(fs, out);
out.flush();
}
public void solve(FastScanner fs, java.io.PrintWriter out) {
int n = fs.nextInt(), d = fs.nextInt();
DSU dsu = new DSU(n);
MaxKSum sum = new MaxKSum(1);
for (int i = 0;i < n;++ i) sum.add(1);
int free = 1;
for (int i = 0;i < d;++ i) {
int x = fs.nextInt() - 1, y = fs.nextInt() - 1;
if (dsu.isSame(x, y)) {
sum.remove(dsu.size(x));
free -= Math.max(0, dsu.edge(x) - dsu.size(x) + 1);
dsu.merge(x, y);
free += Math.max(0, dsu.edge(x) - dsu.size(x) + 1);
sum.setK(free);
sum.add(dsu.size(x));
} else {
sum.remove(dsu.size(x));
sum.remove(dsu.size(y));
free -= Math.max(0, dsu.edge(x) - dsu.size(x) + 1);
free -= Math.max(0, dsu.edge(y) - dsu.size(y) + 1);
dsu.merge(x, y);
free += Math.max(0, dsu.edge(x) - dsu.size(x) + 1);
sum.setK(free);
sum.add(dsu.size(x));
}
out.println(sum.sum() - 1);
}
}
class MaxKSum {
int K;
int bigCount = 0;
TreeMap<Integer, Integer> big = new TreeMap<>(), small = new TreeMap<>();
int sum = 0;
MaxKSum(int k) {
K = k;
}
void setK(int k) {
K = k;
balance();
}
private void balance() {
while(K > bigCount && !small.isEmpty()) {
++ bigCount;
Map.Entry<Integer, Integer> entry = small.lastEntry();
big.merge(entry.getKey(), 1, (l, r) -> l + r);
sum += entry.getKey();
if (entry.getValue() == 1) small.pollLastEntry();
else small.put(entry.getKey(), entry.getValue() - 1);
}
while(K < bigCount) {
-- bigCount;
Map.Entry<Integer, Integer> entry = big.firstEntry();
small.merge(entry.getKey(), 1, (l, r) -> l + r);
sum -= entry.getKey();
if (entry.getValue() == 1) big.pollFirstEntry();
else big.put(entry.getKey(), entry.getValue() - 1);
}
}
int sum() {
return sum;
}
void add(int e) {
big.merge(e, 1, (l, r) -> l + r);
sum += e;
++ bigCount;
balance();
}
void remove(int e) {
int border = big.firstKey();
if (border <= e) {
Integer val = big.merge(e, -1, (l, r) -> l + r == 0 ? null : l + r);
if (val != null && val < 0) throw new IllegalArgumentException();
sum -= e;
-- bigCount;
} else {
Integer val = small.merge(e, -1, (l, r) -> l + r == 0 ? null : l + r);
if (val != null && val < 0) throw new IllegalArgumentException();
}
balance();
}
}
class DSU {
int[] parent;
int[] edge;
DSU(int N) {
parent = new int[N];
edge = new int[N];
for (int i = 0;i < N;++ i) parent[i] = -1;
}
int leader(int i) {
if (parent[i] < 0) return i;
return parent[i] = leader(parent[i]);
}
int size(int i) {
return -parent[leader(i)];
}
int edge(int i) {
return edge[leader(i)];
}
boolean isTree(int i) {
return size(i) == edge(i) + 1;
}
boolean isSame(int i, int j) {
return leader(i) == leader(j);
}
boolean merge(int i, int j) {
i = leader(i);
j = leader(j);
if (i == j) {
++ edge[i];
return false;
}
if (size(i) < size(j)) {
int swap = i;
i = j;
j = swap;
}
parent[i] += parent[j];
parent[j] = i;
edge[i] += edge[j] + 1;
return true;
}
}
final int MOD = 998_244_353;
int plus(int n, int m) {
int sum = n + m;
if (sum >= MOD) sum -= MOD;
return sum;
}
int minus(int n, int m) {
int sum = n - m;
if (sum < 0) sum += MOD;
return sum;
}
int times(int n, int m) {
return (int)((long)n * m % MOD);
}
int divide(int n, int m) {
return times(n, IntMath.pow(m, MOD - 2, MOD));
}
int[] fact, invf;
void calc(int len) {
len += 2;
fact = new int[len];
invf = new int[len];
fact[0] = fact[1] = invf[0] = invf[1] = 1;
for (int i = 2;i < fact.length;++ i) fact[i] = times(fact[i - 1], i);
invf[len - 1] = divide(1, fact[len - 1]);
for (int i = len - 1;i > 1;-- i) invf[i - 1] = times(i, invf[i]);
}
int comb(int n, int m) {
if (n < m) return 0;
return times(fact[n], times(invf[n - m], invf[m]));
}
}
class FastScanner {
private final java.io.InputStream in = System.in;
private final byte[] buffer = new byte[8192];
private int ptr = 0;
private int buflen = 0;
private boolean hasNextByte() {
if (ptr < buflen) return true;
ptr = 0;
try {
buflen = in.read(buffer);
} catch (java.io.IOException e) {
e.printStackTrace();
}
return buflen > 0;
}
private byte readByte() {
return hasNextByte() ? buffer[ptr++ ] : -1;
}
private static boolean isPrintableChar(byte c) {
return 32 < c || c < 0;
}
private static boolean isNumber(int c) {
return '0' <= c && c <= '9';
}
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();
byte b;
while (isPrintableChar(b = readByte()))
sb.appendCodePoint(b);
return sb.toString();
}
public final char nextChar() {
if (!hasNext()) throw new java.util.NoSuchElementException();
return (char)readByte();
}
public final long nextLong() {
if (!hasNext()) throw new java.util.NoSuchElementException();
long n = 0;
try {
byte b = readByte();
if (b == '-') {
while (isNumber(b = readByte()))
n = n * 10 + '0' - b;
return n;
} else if (!isNumber(b)) throw new NumberFormatException();
do
n = n * 10 + b - '0';
while (isNumber(b = readByte()));
} catch (java.util.NoSuchElementException e) {}
return n;
}
public final int nextInt() {
if (!hasNext()) throw new java.util.NoSuchElementException();
int n = 0;
try {
byte b = readByte();
if (b == '-') {
while (isNumber(b = readByte()))
n = n * 10 + '0' - b;
return n;
} else if (!isNumber(b)) throw new NumberFormatException();
do
n = n * 10 + b - '0';
while (isNumber(b = readByte()));
} catch (java.util.NoSuchElementException e) {}
return n;
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
class Arrays {
public static void sort(final int[] array) {
sort(array, 0, array.length);
}
public static void sort(final int[] array, int fromIndex, int toIndex) {
if (toIndex - fromIndex <= 512) {
java.util.Arrays.sort(array, fromIndex, toIndex);
return;
}
sort(array, fromIndex, toIndex, 0, new int[array.length]);
}
private static final void sort(int[] a, final int from, final int to, final int l, final int[] bucket) {
if (to - from <= 512) {
java.util.Arrays.sort(a, from, to);
return;
}
final int BUCKET_SIZE = 256;
final int INT_RECURSION = 4;
final int MASK = 0xff;
final int shift = l << 3;
final int[] cnt = new int[BUCKET_SIZE + 1];
final int[] put = new int[BUCKET_SIZE];
for (int i = from; i < to; i++) ++ cnt[(a[i] >>> shift & MASK) + 1];
for (int i = 0; i < BUCKET_SIZE; i++) cnt[i + 1] += cnt[i];
for (int i = from; i < to; i++) {
int bi = a[i] >>> shift & MASK;
bucket[cnt[bi] + put[bi]++] = a[i];
}
for (int i = BUCKET_SIZE - 1, idx = from; i >= 0; i--) {
int begin = cnt[i];
int len = cnt[i + 1] - begin;
System.arraycopy(bucket, begin, a, idx, len);
idx += len;
}
final int nxtL = l + 1;
if (nxtL < INT_RECURSION) {
sort(a, from, to, nxtL, bucket);
if (l == 0) {
int lft, rgt;
lft = from - 1; rgt = to;
while (rgt - lft > 1) {
int mid = lft + rgt >> 1;
if (a[mid] < 0) lft = mid;
else rgt = mid;
}
reverse(a, from, rgt);
reverse(a, rgt, to);
}
}
}
public static void sort(final long[] array) {
sort(array, 0, array.length);
}
public static void sort(final long[] array, int fromIndex, int toIndex) {
if (toIndex - fromIndex <= 512) {
java.util.Arrays.sort(array, fromIndex, toIndex);
return;
}
sort(array, fromIndex, toIndex, 0, new long[array.length]);
}
private static final void sort(long[] a, final int from, final int to, final int l, final long[] bucket) {
final int BUCKET_SIZE = 256;
final int LONG_RECURSION = 8;
final int MASK = 0xff;
final int shift = l << 3;
final int[] cnt = new int[BUCKET_SIZE + 1];
final int[] put = new int[BUCKET_SIZE];
for (int i = from; i < to; i++) ++ cnt[(int) ((a[i] >>> shift & MASK) + 1)];
for (int i = 0; i < BUCKET_SIZE; i++) cnt[i + 1] += cnt[i];
for (int i = from; i < to; i++) {
int bi = (int) (a[i] >>> shift & MASK);
bucket[cnt[bi] + put[bi]++] = a[i];
}
for (int i = BUCKET_SIZE - 1, idx = from; i >= 0; i--) {
int begin = cnt[i];
int len = cnt[i + 1] - begin;
System.arraycopy(bucket, begin, a, idx, len);
idx += len;
}
final int nxtL = l + 1;
if (nxtL < LONG_RECURSION) {
sort(a, from, to, nxtL, bucket);
if (l == 0) {
int lft, rgt;
lft = from - 1; rgt = to;
while (rgt - lft > 1) {
int mid = lft + rgt >> 1;
if (a[mid] < 0) lft = mid;
else rgt = mid;
}
reverse(a, from, rgt);
reverse(a, rgt, to);
}
}
}
public static void reverse(int[] array) {
reverse(array, 0, array.length);
}
public static void reverse(int[] array, int fromIndex, int toIndex) {
for (-- toIndex;fromIndex < toIndex;++ fromIndex, -- toIndex) {
int swap = array[fromIndex];
array[fromIndex] = array[toIndex];
array[toIndex] = swap;
}
}
public static void reverse(long[] array) {
reverse(array, 0, array.length);
}
public static void reverse(long[] array, int fromIndex, int toIndex) {
for (-- toIndex;fromIndex < toIndex;++ fromIndex, -- toIndex) {
long swap = array[fromIndex];
array[fromIndex] = array[toIndex];
array[toIndex] = swap;
}
}
public static void shuffle(int[] array) {
java.util.Random rnd = new java.util.Random();
for (int i = 0;i < array.length;++ i) {
int j = rnd.nextInt(array.length - i) + i;
int swap = array[i];
array[i] = array[j];
array[j] = swap;
}
}
public static void shuffle(long[] array) {
java.util.Random rnd = new java.util.Random();
for (int i = 0;i < array.length;++ i) {
int j = rnd.nextInt(array.length - i) + i;
long swap = array[i];
array[i] = array[j];
array[j] = swap;
}
}
}
class IntMath {
public static int gcd(int a, int b) {
while (a != 0)
if ((b %= a) != 0) a %= b;
else return a;
return b;
}
public static int gcd(int... array) {
int ret = array[0];
for (int i = 1; i < array.length; ++i)
ret = gcd(ret, array[i]);
return ret;
}
public static long gcd(long a, long b) {
while (a != 0)
if ((b %= a) != 0) a %= b;
else return a;
return b;
}
public static long gcd(long... array) {
long ret = array[0];
for (int i = 1; i < array.length; ++i)
ret = gcd(ret, array[i]);
return ret;
}
public static long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
public static int pow(int a, int b) {
int ans = 1;
for (int mul = a; b > 0; b >>= 1, mul *= mul)
if ((b & 1) != 0) ans *= mul;
return ans;
}
public static long pow(long a, long b) {
long ans = 1;
for (long mul = a; b > 0; b >>= 1, mul *= mul)
if ((b & 1) != 0) ans *= mul;
return ans;
}
public static int pow(int a, long b, int mod) {
if (b < 0) b = b % (mod - 1) + mod - 1;
long ans = 1;
for (long mul = a; b > 0; b >>= 1, mul = mul * mul % mod)
if ((b & 1) != 0) ans = ans * mul % mod;
return (int)ans;
}
public static int pow(long a, long b, int mod) {
return pow((int)(a % mod), b, mod);
}
public static int floorsqrt(long n) {
return (int)Math.sqrt(n + 0.1);
}
public static int ceilsqrt(long n) {
return n <= 1 ? (int)n : (int)Math.sqrt(n - 0.1) + 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 | 065614ae49715f35c4f12ce3454e7af8 | 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 static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.Double.parseDouble;
import static java.lang.Math.PI;
import static java.lang.Math.min;
import static java.lang.System.arraycopy;
import static java.lang.System.exit;
import static java.util.Arrays.copyOf;
import java.util.LinkedList;
import java.util.List;
import java.util.Iterator;
import java.io.FileReader;
import java.io.FileWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.Comparator;
import java.lang.StringBuilder;
import java.util.Collections;
import java.util.*;
import java.text.DecimalFormat;
public class Solution {
static BufferedReader in;
static PrintWriter out;
static StringTokenizer tok;
static long mod= (long)1e9+7;
static boolean isPrime[];
private static int find(int x, int[] parent){
if(parent[x] != x)
return parent[x] = find(parent[x], parent);
return parent[x];
}
private static void solve() throws IOException{
int n = scanInt(), d = scanInt();
int parent[] = new int[n+1];
int size[] = new int[n+1];
for(int i = 1; i<=n ;++i)
parent[i] = i;
Arrays.fill(size, 1);
int u, v, extra = 0, components = n;
while(d-- > 0){
u = scanInt(); v = scanInt();
int rootX = find(u, parent);
int rootY = find(v, parent);
if(rootX == rootY)
++extra;
else{
if(size[rootX] > size[rootY]){
size[rootX] += size[rootY];
parent[rootY] = rootX;
}
else{
size[rootY] += size[rootX];
parent[rootX] = rootY;
}
--components;
}
Integer arr[] = new Integer[components];
int j =0;
for(int i = 1; i<=n; ++i){
if(parent[i] == i){
arr[j++] = size[i];
}
}
Arrays.sort(arr, Collections.reverseOrder());
int sum = 0;
for(int i = 0; i<=extra && i<components; ++i){
sum += arr[i];
}
out.println(sum-1);
}
}
public static void main(String[] args) {
try {
long startTime = System.currentTimeMillis();
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
//in = new BufferedReader(new FileReader("input.txt"));
//out = new PrintWriter(new FileWriter("output.txt"));
// int test=scanInt();
// for(int t=1; t<=test; t++){
// out.print("Case #"+t+": ");
solve();
// }
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
//out.println(totalTime+" "+System.currentTimeMillis() );
in.close();
out.close();
} catch (Throwable e) {
e.printStackTrace();
exit(1);
}
}
static int scanInt() throws IOException {
return parseInt(scanString());
}
static long scanLong() throws IOException {
return parseLong(scanString());
}
static double scanDouble() throws IOException {
return parseDouble(scanString());
}
static String scanString() throws IOException {
if (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
static String scanLine() throws IOException {
return in.readLine();
}
}
| 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 | 4aa1a1aeb607a2a0039f133b6bebaa38 | 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 static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.Double.parseDouble;
import static java.lang.Math.PI;
import static java.lang.Math.min;
import static java.lang.System.arraycopy;
import static java.lang.System.exit;
import static java.util.Arrays.copyOf;
import java.util.LinkedList;
import java.util.List;
import java.util.Iterator;
import java.io.FileReader;
import java.io.FileWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.Comparator;
import java.lang.StringBuilder;
import java.util.Collections;
import java.util.*;
import java.text.DecimalFormat;
public class Solution {
static BufferedReader in;
static PrintWriter out;
static StringTokenizer tok;
static long mod= (long)1e9+7;
static boolean isPrime[];
private static int find(int x, int[] parent){
if(parent[x] != x)
return parent[x] = find(parent[x], parent);
return parent[x];
}
private static void solve() throws IOException{
int n = scanInt(), d = scanInt();
int parent[] = new int[n+1];
int size[] = new int[n+1];
for(int i = 1; i<=n ;++i)
parent[i] = i;
Arrays.fill(size, 1);
int u, v, extra = 0, components = n;
while(d-- > 0){
u = scanInt(); v = scanInt();
int rootX = find(u, parent);
int rootY = find(v, parent);
if(rootX == rootY)
++extra;
else{
size[rootX] += size[rootY];
parent[rootY] = rootX;
--components;
}
Integer arr[] = new Integer[components];
int j =0;
for(int i = 1; i<=n; ++i){
if(parent[i] == i){
arr[j++] = size[i];
}
}
Arrays.sort(arr, Collections.reverseOrder());
int sum = 0;
for(int i = 0; i<=extra && i<components; ++i){
sum += arr[i];
}
out.println(sum-1);
}
}
public static void main(String[] args) {
try {
long startTime = System.currentTimeMillis();
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
//in = new BufferedReader(new FileReader("input.txt"));
//out = new PrintWriter(new FileWriter("output.txt"));
// int test=scanInt();
// for(int t=1; t<=test; t++){
// out.print("Case #"+t+": ");
solve();
// }
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
//out.println(totalTime+" "+System.currentTimeMillis() );
in.close();
out.close();
} catch (Throwable e) {
e.printStackTrace();
exit(1);
}
}
static int scanInt() throws IOException {
return parseInt(scanString());
}
static long scanLong() throws IOException {
return parseLong(scanString());
}
static double scanDouble() throws IOException {
return parseDouble(scanString());
}
static String scanString() throws IOException {
if (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
static String scanLine() throws IOException {
return in.readLine();
}
}
| 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 | 253adae0b86d7430c39fa802b5716e98 | 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.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Main {
static int mod = (int) (1e9) + 7;
/* ======================DSU===================== */
static class dsu {
static int parent[], n;// min[],value[];
static long size[];
dsu(int n) {
parent = new int[n + 1];
size = new long[n + 1];
// min=new int[n+1];
// value=new int[n+1];
Main.dsu.n = n;
makeSet();
}
static void makeSet() {
for (int i = 1; i <= n; i++) {
parent[i] = i;
size[i] = 1;
// min[i]=i;
}
}
static int find(int a) {
if (parent[a] == a)
return a;
else {
return parent[a] = find(parent[a]);// Path Compression
}
}
static void union(int a, int b) {
int setA = find(a);
int setB = find(b);
if (setA == setB)
return;
if (size[setA] >= size[setB]) {
parent[setB] = setA;
size[setA] += size[setB];
} else {
parent[setA] = setB;
size[setB] += size[setA];
}
}
}
/* ======================================================== */
static class Pair<X extends Number, Y extends Number> implements Comparator<Pair> {
X x;
Y y;
// Constructor
public Pair(X x, Y y) {
this.x = x;
this.y = y;
}
public Pair() {
}
@Override
public int compare(Main.Pair o1, Main.Pair o2) {
return ((int) (o1.y.intValue() - o2.y.intValue()));// Ascending Order based on 'y'
}
}
/* ===============================Tries================================= */
static class TrieNode {
private HashMap<Character, TrieNode> children = new HashMap<>();
public int size;
boolean endOfWord;
public void putChildIfAbsent(char ch) {
children.putIfAbsent(ch, new TrieNode());
}
public TrieNode getChild(char ch) {
return children.get(ch);
}
}
static private TrieNode root;
public static void insert(String str) {
TrieNode curr = root;
for (char ch : str.toCharArray()) {
curr.putChildIfAbsent(ch);
curr = curr.getChild(ch);
curr.size++;
}
// mark the current nodes endOfWord as true
curr.endOfWord = true;
}
public static int search(String word) {
TrieNode curr = root;
for (char ch : word.toCharArray()) {
curr = curr.getChild(ch);
if (curr == null) {
return 0;
}
}
// size contains words starting with prefix- word
return curr.size;
}
public boolean delete(TrieNode current, String word, int index) {
if (index == word.length()) {
// when end of word is reached only delete if currrent.endOfWord is true.
if (!current.endOfWord) {
return false;
}
current.endOfWord = false;
// if current has no other mapping then return true
return current.children.size() == 0;
}
char ch = word.charAt(index);
TrieNode node = current.children.get(ch);
if (node == null) {
return false;
}
boolean shouldDeleteCurrentNode = delete(node, word, index + 1);
// if true is returned then delete the mapping of character and trienode
// reference from map.
if (shouldDeleteCurrentNode) {
current.children.remove(ch);
// return true if no mappings are left in the map.
return current.children.size() == 0;
}
return false;
}
/* ================================================================= */
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 (long i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static Pair<Integer, Integer> lowerBound(long[] a, long x) { // x is the target, returns lowerBound. If not found
// return -1
int l = -1, r = a.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (a[m] == x) {
return new Pair<>(m, 1);
}
if (a[m] >= x)
r = m;
else
l = m;
}
return new Pair<>(r, 0);
}
static Pair<Integer, Integer> upperBound(long[] a, long x) {// x is the target, returns upperBound. If not found
int l = -1, r = a.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (a[m] == x) {
return new Pair<>(m, 1);
}
if (a[m] <= x)
l = m;
else
r = m;
}
return new Pair<>(l + 1, 0);
}
static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
static long lcm(long a, long b) {
return (a * b) / gcd(a, b);
}
static long power(long x, long y) {
long res = 1;
while (y > 0) {
if (y % 2 == 1)
res = (res * x);
y >>= 1;
x = (x * x);
}
return res;
}
public double binPow(double x, int n) {// binary exponentiation with negative power as well
if (n == 0)
return 1.0;
double binPow = binPow(x, n / 2);
if (n % 2 == 0) {
return binPow * binPow;
} else {
return n > 0 ? (binPow * binPow * x) : (binPow * binPow / x);
}
}
static long ceil(long x, long y) {
return (x % y == 0 ? x / y : (x / y + 1));
}
/*
* ===========Modular Operations==================
*/
static long modPower(long x, long y, long p) {
long res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
static long modInverse(long n, long p) {
return modPower(n, p - 2, p);
}
static long modAdd(long a, long b) {
return ((a + b + mod) % mod);
}
static long modMul(long a, long b) {
return ((a % mod) * (b % mod)) % mod;
}
static long[] fac = new long[200000 + 5];
static long[] invFac = new long[200000 + 5];
static long nCrModPFermat(int n, int r) {
if (r == 0)
return 1;
// return (fac[n] * modInverse(fac[r], mod) % mod * modInverse(fac[n - r], mod)
// % mod) % mod;
return (fac[n] * invFac[r] % mod * invFac[n - r] % mod) % mod;
}
/*
* ===============================================
*/
static void ruffleSort(long[] a) {
int n = a.length;
Random r = new Random();
for (int i = 0; i < a.length; i++) {
int oi = r.nextInt(n);
long temp = a[i];
a[i] = a[oi];
a[oi] = temp;
}
Arrays.sort(a);
}
static void ruffleSort(int[] a) {
int n = a.length;
Random r = new Random();
for (int i = 0; i < a.length; i++) {
int oi = r.nextInt(n);
int temp = a[i];
a[i] = a[oi];
a[oi] = temp;
}
Arrays.sort(a);
}
static String binString32(int n) {
StringBuilder str = new StringBuilder("");
String bin = Integer.toBinaryString(n);
if (bin.length() != 32) {
for (int k = 0; k < 32 - bin.length(); k++) {
str.append("0");
}
str.append(bin);
}
return str.toString();
}
static class sparseTable {
public static int st[][];
public static int log = 4;
static int func(int a, int b) {// make func as per question(here min range query)
return (int) gcd(a, b);
}
void makeTable(int n, int a[]) {
st = new int[n][log];
for (int i = 0; i < n; i++) {
st[i][0] = a[i];
}
for (int j = 1; j < log; j++) {
for (int i = 0; i + (1 << j) <= n; i++) {
st[i][j] = func(st[i][j - 1], st[i + (1 << (j - 1))][j - 1]);
}
}
}
static int query(int l, int r) {
int length = r - l + 1;
int k = 0;
while ((1 << (k + 1)) <= length) {
k++;
}
return func(st[l][k], st[r - (1 << k) + 1][k]);
}
static void printTable(int n) {
for (int j = 0; j < log; j++) {
for (int i = 0; i < n; i++) {
System.out.print(st[i][j] + " ");
}
System.out.println();
}
}
}
/*
* ====================================Main=================================
*/
// static int st[], a[];
// static void buildTree(int treeIndex, int lo, int hi) {
// if (hi == lo) {
// st[treeIndex] = a[lo];
// return;
// }
// int mid = (lo + hi) / 2;
// buildTree(treeIndex * 2 + 1, lo, mid);
// buildTree(treeIndex * 2 + 2, mid + 1, hi);
// st[treeIndex] = merge(st[treeIndex * 2 + 1], st[treeIndex * 2 + 2]);
// }
// static void update(int treeIndex, int lo, int hi, int arrIndex, int val) {
// if (hi == lo) {
// st[treeIndex] = val;
// a[arrIndex] = val;
// return;
// }
// int mid = (hi + lo) / 2;
// if (mid < arrIndex) {
// update(treeIndex * 2 + 2, mid + 1, hi, arrIndex, val);
// } else {
// update(treeIndex * 2 + 1, lo, mid, arrIndex, val);
// }
// st[treeIndex] = merge(st[treeIndex * 2 + 1], st[treeIndex * 2 + 2]);
// }
// static int query(int treeIndex, int lo, int hi, int l, int r) {
// if (l <= lo && r >= hi) {
// return st[treeIndex];
// }
// if (l > hi || r < lo) {
// return 0;
// }
// int mid = (hi + lo) / 2;
// return query(treeIndex * 2 + 1, lo, mid, l, Math.min(mid, r));
// }
// static int merge(int a, int b) {
// return a + b;
// }
public static long findKthPositive(long[] A, long k) {
int l = 0, r = A.length, m;
while (l < r) {
m = (l + r) / 2;
if (A[m] - 1 - m < k)
l = m + 1;
else
r = m;
}
return l + k;
}
static int[] z_function(char ar[]) {
int[] z = new int[ar.length];
z[0] = ar.length;
int l = 0;
int r = 0;
for (int i = 1; i < ar.length; i++) {
if (r < i) {
l = i;
r = i;
while (r < ar.length && ar[r - l] == ar[r])
r++;
z[i] = r - l;
r--;
} else {
int k = i - l;
if (z[k] < r - i + 1) {
z[i] = z[k];
} else {
l = i;
while (r < ar.length && ar[r - l] == ar[r])
r++;
z[i] = r - l;
r--;
}
}
}
return z;
}
static void mergeSort(int a[]) {
int n = a.length;
if (n >= 2) {
int mid = n / 2;
int left[] = new int[mid];
int right[] = new int[n - mid];
for (int i = 0; i < mid; i++) {
left[i] = a[i];
}
for (int i = mid; i < n; i++) {
right[i - mid] = a[i];
}
mergeSort(left);
mergeSort(right);
mergeSortedArray(left, right, a);
}
}
static void mergeSortedArray(int left[], int right[], int a[]) {
int i = 0, j = 0, k = 0, n = left.length, m = right.length;
while (i != n && j != m) {
if (left[i] < right[j]) {
a[k++] = left[i++];
} else {
a[k++] = right[j++];
}
}
while (i != n) {
a[k++] = left[i++];
}
while (j != m) {
a[k++] = right[j++];
}
}
// BINARY SEARCH
// count of set bits in a particular position
// suffix max array/ suffix sum array/ prefix
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;
}
int[] intArr(int n) {
int res[] = new int[n];
for (int i = 0; i < n; i++)
res[i] = nextInt();
return res;
}
long[] longArr(int n) {
long res[] = new long[n];
for (int i = 0; i < n; i++)
res[i] = nextLong();
return res;
}
}
static FastReader f = new FastReader();
static BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out));
static ArrayList<String> strArr = new ArrayList<>();
public static void main(String args[]) throws Exception {
int t = 1;
// t = f.nextInt();
int tc = 1;
// fac[0] = 1;
// for (int i = 1; i <= 200000; i++) {
// fac[i] = fac[i - 1] * i % mod;
// invFac[i] = modInverse(fac[i], mod);
// }
while (t-- != 0) {
int n = f.nextInt();
int d = f.nextInt();
dsu ob = new dsu(n);
int extras=0;
for (int i = 0; i < d; i++) {
int x = f.nextInt();
int y = f.nextInt();
int parent = ob.find(x);
if (parent == ob.find(y)) {
extras++;
} else {
ob.union(x, y);
}
HashMap<Integer,Integer> hm=new HashMap<>();
for(int j=1;j<=n;j++){
int p=ob.find(j);
// System.out.println(p);
hm.putIfAbsent(p, 0);
hm.put(p, hm.get(p)+1);
}
ArrayList<Long> ar = new ArrayList<>();
for(int j:hm.keySet()){
ar.add((long)hm.get(j));
}
Collections.sort(ar,(p,q)->(int)(q-p));
long sum=0;
// System.out.println(ar);
// System.out.println(hm);
for(int j=0;j<Math.min(extras+1,ar.size());j++){
sum+=ar.get(j);
}
w.write((sum-1)+"\n");
}
}
w.flush();
}
static class Data {
int parent;
long size;
Data(int x, long y) {
parent = x;
size = 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 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 | a4bf69eed701d8e1907aebce63b142cb | 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 ProblemD {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt(), d = scanner.nextInt();
int available = 0;
List<Integer>[] connections = new List[n];
for (int i=0; i<d; i++) {
int num1 = scanner.nextInt(), num2 = scanner.nextInt();
num1--; num2--;
if (connections[num1] == null) {
connections[num1] = new LinkedList<>();
}
if (connections[num2] == null) {
connections[num2] = new LinkedList<>();
}
if (!isConnected(connections, num1, num2)) {
connections[num1].add(num2);
connections[num2].add(num1);
} else {
available++;
}
System.out.println(maxConnected(connections, available)-1);
}
}
public static boolean isConnected(List<Integer>[] connections, int vertex1, int vertex2) {
Queue<Integer> queue = new ArrayDeque<>();
queue.add(vertex1);
boolean[] visited = new boolean[connections.length];
int elemNum;
while (!queue.isEmpty()) {
do {
elemNum = queue.poll();
} while (visited[elemNum] && !queue.isEmpty());
if (connections[elemNum] != null) {
for (Integer i : connections[elemNum]) {
if (i == vertex2) {
return true;
}
if (!visited[i]) queue.add(i);
}
visited[elemNum] = true;
}
}
return false;
}
public static int maxConnected(List<Integer>[] connections, int available) {
boolean[] visited = new boolean[connections.length];
int[] maxItems = new int[available+1];
int filledIndex = available;
//int max = 0;
int cur = 0;
while (cur < connections.length) {
Queue<Integer> queue = new ArrayDeque<>();
queue.add(cur);
int elemNum;
int subSize = 0;
while (!queue.isEmpty()) {
do {
elemNum = queue.poll();
} while (visited[elemNum] && !queue.isEmpty());
if (connections[elemNum] != null) {
for (Integer i : connections[elemNum]) {
if (!visited[i]) queue.add(i);
}
}
subSize++;
visited[elemNum] = true;
}
if (filledIndex >= 0) {
maxItems[filledIndex] = subSize;
filledIndex--;
} else {
if (maxItems[0] < subSize) {
maxItems[0] = subSize;
}
}
Arrays.sort(maxItems);
while (cur<connections.length && visited[cur]) cur++;
}
int sum = maxItems[0];
for (int i = 1; i<= available; i++) {
sum+=maxItems[i];
}
return sum;
}
}
| 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 | b7fd9a36dea110e0bcde032f8e75ae2a | 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.*;
/**
__ __
( _) ( _)
/ / \\ / /\_\_
/ / \\ / / | \ \
/ / \\ / / |\ \ \
/ / , \ , / / /| \ \
/ / |\_ /| / / / \ \_\
/ / |\/ _ '_| \ / / / \ \\
| / |/ 0 \0\ / | | \ \\
| |\| \_\_ / / | \ \\
| | |/ \.\ o\o) / \ | \\
\ | /\\`v-v / | | \\
| \/ /_| \\_| / | | \ \\
| | /__/_ `-` / _____ | | \ \\
\| [__] \_/ |_________ \ | \ ()
/ [___] ( \ \ |\ | | //
| [___] |\| \| / |/
/| [____] \ |/\ / / ||
( \ [____ / ) _\ \ \ \| | ||
\ \ [_____| / / __/ \ / / //
| \ [_____/ / / \ | \/ //
| / '----| /=\____ _/ | / //
__ / / | / ___/ _/\ \ | ||
(/-(/-\) / \ (/\/\)/ | / | /
(/\/\) / / //
_________/ / /
\____________/ (
@author NTUDragons-Reborn
*/
public class Solution{
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(in, out);
out.close();
}
// main solver
static class Task{
double eps= 0.00000001;
static final int MAXN = 200015;
static final int MOD= 998244353;
// stores smallest prime factor for every number
static int spf[] = new int[MAXN];
static boolean[] prime;
Map<Integer,Set<Integer>> dp= new HashMap<>();
// Calculating SPF (Smallest Prime Factor) for every
// number till MAXN.
// Time Complexity : O(nloglogn)
public void sieve()
{
spf[1] = 1;
for (int i=2; i<MAXN; i++)
// marking smallest prime factor for every
// number to be itself.
spf[i] = i;
// separately marking spf for every even
// number as 2
for (int i=4; i<MAXN; i+=2)
spf[i] = 2;
for (int i=3; i*i<MAXN; i++)
{
// checking if i is prime
if (spf[i] == i)
{
// marking SPF for all numbers divisible by i
for (int j=i*i; j<MAXN; j+=i)
// marking spf[j] if it is not
// previously marked
if (spf[j]==j)
spf[j] = i;
}
}
}
void sieveOfEratosthenes(int n)
{
// Create a boolean array
// "prime[0..n]" and
// initialize all entries
// it as true. A value in
// prime[i] will finally be
// false if i is Not a
// prime, else true.
prime= new boolean[n + 1];
for (int i = 0; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++)
{
// If prime[p] is not changed, then it is a
// prime
if (prime[p] == true)
{
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
}
// A O(log n) function returning primefactorization
// by dividing by smallest prime factor at every step
public Set<Integer> getFactorization(int x)
{
if(dp.containsKey(x)) return dp.get(x);
Set<Integer> ret = new HashSet<>();
while (x != 1)
{
if(spf[x]!=2) ret.add(spf[x]);
x = x / spf[x];
}
dp.put(x,ret);
return ret;
}
// function to find first index >= x
public int lowerIndex(List<Integer> arr, int n, int x)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr.get(mid) >= x)
h = mid - 1;
else
l = mid + 1;
}
return l;
}
public int lowerIndex(int[] arr, int n, int x)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr[mid] >= x)
h = mid - 1;
else
l = mid + 1;
}
return l;
}
// function to find last index <= y
public int upperIndex(List<Integer> arr, int n, int y)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr.get(mid) <= y)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
public int upperIndex(int[] arr, int n, int y)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr[mid] <= y)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
// function to count elements within given range
public int countInRange(List<Integer> arr, int n, int x, int y)
{
// initialize result
int count = 0;
count = upperIndex(arr, n, y) -
lowerIndex(arr, n, x) + 1;
return count;
}
public int add(int a, int b){
a+=b;
while(a>=MOD) a-=MOD;
while(a<0) a+=MOD;
return a;
}
public int mul(int a, int b){
long res= (long)a*(long)b;
return (int)(res%MOD);
}
public int power(int a, int b) {
int ans=1;
while(b>0){
if((b&1)!=0) ans= mul(ans,a);
b>>=1;
a= mul(a,a);
}
return ans;
}
int[] fact= new int[MAXN];
int[] inv= new int[MAXN];
public int Ckn(int n, int k){
if(k<0 || n<0) return 0;
return mul(mul(fact[n],inv[k]),inv[n-k]);
}
public int inverse(int a){
return power(a,MOD-2);
}
public void preprocess() {
fact[0]=1;
for(int i=1;i<MAXN;i++) fact[i]= mul(fact[i-1],i);
inv[MAXN-1]= inverse(fact[MAXN-1]);
for(int i=MAXN-2;i>=0;i--){
inv[i]= mul(inv[i+1],i+1);
}
}
/**
* return VALUE of lower bound for unsorted array
*/
public int lowerBoundNormalArray(int[] arr, int x){
TreeSet<Integer> set= new TreeSet<>();
for(int num: arr) set.add(num);
return set.lower(x);
}
/**
* return VALUE of upper bound for unsorted array
*/
public int upperBoundNormalArray(int[] arr, int x){
TreeSet<Integer> set= new TreeSet<>();
for(int num: arr) set.add(num);
return set.higher(x);
}
public void debugArr(int[] arr){
for(int i: arr) out.print(i+" ");
out.println();
}
public int rand(){
int min=0, max= MAXN;
int random_int = (int)Math.floor(Math.random()*(max-min+1)+min);
return random_int;
}
InputReader in; PrintWriter out;
CustomFileReader cin;
int[] xor= new int[3*100000+5];
int[] pow2= new int[1000000+1];
public void solve(InputReader in, PrintWriter out) {
this.in=in; this.out=out;
// sieve();
// pow2[0]=1;
// for(int i=1;i<pow2.length;i++){
// pow2[i]= mul(pow2[i-1],2);
// }
int t= 1;
// preprocess();
// int t=in.nextInt();
// int t= cin.nextIntArrLine()[0];
for(int i=1;i<=t;i++) solveA(i);
}
final double pi= Math.acos(-1);
static Point base;
int[] par;
int[] size;
PriorityQueue<Pair> q= new PriorityQueue<>((a,b)->b.x-a.x);
private int find(int u){
if(par[u]==u) return u;
par[u]= find(par[u]);
return par[u];
}
private boolean union(int u, int v){
u= find(u); v= find(v);
if(u==v) return false;
if(size[u]>size[v]){
int temp= u; u=v; v= temp;
}
par[u]=v;
size[v]+= size[u];
return true;
}
private boolean already(int u, int v){
return find(u)==find(v);
}
public void solveA(int t){
int n=in.nextInt(), d= in.nextInt();
par= new int[n+1]; size= new int[n+1];
for(int i=1;i<=n;i++) {
par[i]=i; size[i]=1;
}
int rem=0;
while(d-->0){
int u= in.nextInt(), v= in.nextInt();
if(!union(u,v)) rem++;
//flatten
for(int i=1;i<=n;i++) find(i);
Set<Integer> root= new HashSet<>();
for(int i=1;i<=n;i++) root.add(par[i]);
List<Integer> sizes= new ArrayList<>();
for(int i: root) sizes.add(size[i]);
Collections.sort(sizes, Collections.reverseOrder());
int res=0;
for(int i=0;i<=Math.min(sizes.size()-1, rem);i++){
res+= sizes.get(i);
}
out.println(res-1);
}
}
static class Node implements Comparable<Node>{
char op;
int s;
public Node (char op, int s) {
this.op= op;
this.s= s;
}
@Override
public int compareTo(Node o) {
if (this.s==o.s) return (int)(this.op-o.op);
return this.s-o.s;
}
}
private long distance(Point p1, Point p2) {
long x= p1.x-p2.x, y= p1.y-p2.y;
return x*x+y*y;
}
private boolean eqPoint(Point p1, Point p2){
return p1.x==p2.x && p1.y==p2.y;
}
private double polarAngle(Point p1, Point p2) {
// p1 -> p2
if (p1.x==p2.x) return pi/2;
else if (p1.y==p2.y){
if(p1.x<p2.x) return 0;
else return pi;
}
else {
double y= (double)p2.y-(double)p1.y;
double x= (double)p2.x-(double)p1.x;
BigDecimal alpha1= new BigDecimal(y);
BigDecimal alpha2= new BigDecimal(x);
BigDecimal val= alpha1.divide(alpha2);
double angle= Math.atan(val.doubleValue());
if (angle<0) angle+= pi;
out.println("angle: "+angle);
return angle;
}
}
private boolean isRightTurn(Point p1, Point p2, Point p3){
Vector v1= new Vector(p1,p2), v2= new Vector(p1,p3);
if(crossProd(v1,v2)<0) return true;
else return false;
}
private long crossProd(Vector v1, Vector v2){
//x1*y2-x2*y1
return v1.x*v2.y - v2.x*v1.y;
}
static class PointAngle implements Comparable<PointAngle>{
Point p;
double angle;
long dis;
public PointAngle(Point p, double angle, long dis) {
this.p= p;
this.angle= angle;
this.dis= dis;
}
@Override
public int compareTo(PointAngle o) {
double dif= this.angle-o.angle;
if (dif <0) return -1;
else if(dif >0) return 1;
else {
long dif2r= this.dis-o.dis;
long dif2l= o.dis-this.dis;
if (base.x < this.p.x) return intDif(dif2r);
else return intDif(dif2l);
}
}
private int intDif(long a){
if (a>0) return 1;
else if(a<0) return -1;
else return 0;
}
}
public long _gcd(long a, long b)
{
if(b == 0) {
return a;
}
else {
return _gcd(b, a % b);
}
}
public long _lcm(long a, long b){
return (a*b)/_gcd(a,b);
}
}
// static class SEG {
// Pair[] segtree;
// public SEG(int n){
// segtree= new Pair[4*n];
// Arrays.fill(segtree, new Pair(-1,Long.MAX_VALUE));
// }
// // void buildTree(int l, int r, int index) {
// // if (l == r) {
// // segtree[index].y = a[l];
// // return;
// // }
// // int mid = (l + r) / 2;
// // buildTree(l, mid, 2 * index + 1);
// // buildTree(mid + 1, r, 2 * index + 2);
// // segtree[index].y = Math.min(segtree[2 * index + 1].y, segtree[2 * index + 2].y);
// // }
// void update(int l, int r, int index, int pos, Pair val) {
// if (l == r) {
// segtree[index] = val;
// return;
// }
// int mid = (l + r) / 2;
// if (pos <= mid) update(l, mid, 2 * index + 1, pos, val);
// else update(mid + 1, r, 2 * index + 2, pos, val);
// if(segtree[2 * index + 1].y < segtree[2 * index + 2].y){
// segtree[index]= segtree[2 * index + 1];
// }
// else {
// segtree[index]= segtree[2 * index + 2];
// }
// }
// // Pair query(int l, int r, int from, int to, int index) {
// // if (from <= l && r <= to)
// // return segtree[index];
// // if (r < from | to < l)
// // return 0;
// // int mid = (l + r) / 2;
// // Pair left= query(l, mid, from, to, 2 * index + 1);
// // Pair right= query(mid + 1, r, from, to, 2 * index + 2);
// // if(left.y < right.y) return left;
// // else return right;
// // }
// }
static class Venice{
public Map<Long,Long> m= new HashMap<>();
public long base=0;
public long totalValue=0;
private int M= 1000000007;
private long addMod(long a, long b){
a+=b;
if(a>=M) a-=M;
return a;
}
public void reset(){
m= new HashMap<>();
base=0;
totalValue=0;
}
public void update(long add){
base= base+ add;
}
public void add(long key, long val){
long newKey= key-base;
m.put(newKey, addMod(m.getOrDefault(newKey,(long)0),val));
}
}
static class Tuple implements Comparable<Tuple>{
int x, y, z;
public Tuple(int x, int y, int z){
this.x= x;
this.y= y;
this.z=z;
}
@Override
public int compareTo(Tuple o){
return this.z-o.z;
}
}
static class Point implements Comparable<Point>{
public long x;
public long y;
public Point(long x, long y){
this.x= x;
this.y= y;
}
@Override
public int compareTo(Point o) {
if(this.y!=o.y) return (int)(this.y-o.y);
return (int)(this.x-o.x);
}
}
static class Vector {
public long x;
public long y;
// p1 -> p2
public Vector(Point p1, Point p2){
this.x= p2.x-p1.x;
this.y= p2.y-p1.y;
}
}
static class Pair implements Comparable<Pair>{
public int x;
public int y;
public Pair(int x, int y){
this.x= x;
this.y= y;
}
@Override
public int compareTo(Pair o) {
if(this.x!=o.x) return this.x-o.x;
return (int)(this.y-o.y);
}
}
// public static class compareL implements Comparator<Tuple>{
// @Override
// public int compare(Tuple t1, Tuple t2) {
// return t2.l - t1.l;
// }
// }
// fast input reader class;
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream));
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public double nextDouble(){
return Double.parseDouble(nextToken());
}
public long nextLong(){
return Long.parseLong(nextToken());
}
public int[] nextIntArr(int n){
int[] arr= new int[n];
for(int i=0;i<n;i++) arr[i]= nextInt();
return arr;
}
public long[] nextLongArr(int n){
long[] arr= new long[n];
for(int i=0;i<n;i++) arr[i]= nextLong();
return arr;
}
public List<Integer> nextIntList(int n){
List<Integer> arr= new ArrayList<>();
for(int i=0;i<n;i++) arr.add(nextInt());
return arr;
}
public int[][] nextIntMatArr(int n, int m){
int[][] mat= new int[n][m];
for(int i=0;i<n;i++) for(int j=0;j<m;j++) mat[i][j]= nextInt();
return mat;
}
public List<List<Integer>> nextIntMatList(int n, int m){
List<List<Integer>> mat= new ArrayList<>();
for(int i=0;i<n;i++){
List<Integer> temp= new ArrayList<>();
for(int j=0;j<m;j++) temp.add(nextInt());
mat.add(temp);
}
return mat;
}
public char[] nextStringCharArr(){
return nextToken().toCharArray();
}
}
static class CustomFileReader{
String path="";
Scanner sc;
public CustomFileReader(String path){
this.path=path;
try{
sc= new Scanner(new File(path));
}
catch(Exception e){}
}
public String nextLine(){
return sc.nextLine();
}
public int[] nextIntArrLine(){
String line= sc.nextLine();
String[] part= line.split("[\\s+]");
int[] res= new int[part.length];
for(int i=0;i<res.length;i++) res[i]= Integer.parseInt(part[i]);
return res;
}
}
} | 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 | 68738db06fcbea510ebeff8179a7d4a9 | 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.*;
/**
__ __
( _) ( _)
/ / \\ / /\_\_
/ / \\ / / | \ \
/ / \\ / / |\ \ \
/ / , \ , / / /| \ \
/ / |\_ /| / / / \ \_\
/ / |\/ _ '_| \ / / / \ \\
| / |/ 0 \0\ / | | \ \\
| |\| \_\_ / / | \ \\
| | |/ \.\ o\o) / \ | \\
\ | /\\`v-v / | | \\
| \/ /_| \\_| / | | \ \\
| | /__/_ `-` / _____ | | \ \\
\| [__] \_/ |_________ \ | \ ()
/ [___] ( \ \ |\ | | //
| [___] |\| \| / |/
/| [____] \ |/\ / / ||
( \ [____ / ) _\ \ \ \| | ||
\ \ [_____| / / __/ \ / / //
| \ [_____/ / / \ | \/ //
| / '----| /=\____ _/ | / //
__ / / | / ___/ _/\ \ | ||
(/-(/-\) / \ (/\/\)/ | / | /
(/\/\) / / //
_________/ / /
\____________/ (
@author NTUDragons-Reborn
*/
public class Solution{
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(in, out);
out.close();
}
// main solver
static class Task{
double eps= 0.00000001;
static final int MAXN = 200015;
static final int MOD= 998244353;
// stores smallest prime factor for every number
static int spf[] = new int[MAXN];
static boolean[] prime;
Map<Integer,Set<Integer>> dp= new HashMap<>();
// Calculating SPF (Smallest Prime Factor) for every
// number till MAXN.
// Time Complexity : O(nloglogn)
public void sieve()
{
spf[1] = 1;
for (int i=2; i<MAXN; i++)
// marking smallest prime factor for every
// number to be itself.
spf[i] = i;
// separately marking spf for every even
// number as 2
for (int i=4; i<MAXN; i+=2)
spf[i] = 2;
for (int i=3; i*i<MAXN; i++)
{
// checking if i is prime
if (spf[i] == i)
{
// marking SPF for all numbers divisible by i
for (int j=i*i; j<MAXN; j+=i)
// marking spf[j] if it is not
// previously marked
if (spf[j]==j)
spf[j] = i;
}
}
}
void sieveOfEratosthenes(int n)
{
// Create a boolean array
// "prime[0..n]" and
// initialize all entries
// it as true. A value in
// prime[i] will finally be
// false if i is Not a
// prime, else true.
prime= new boolean[n + 1];
for (int i = 0; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++)
{
// If prime[p] is not changed, then it is a
// prime
if (prime[p] == true)
{
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
}
// A O(log n) function returning primefactorization
// by dividing by smallest prime factor at every step
public Set<Integer> getFactorization(int x)
{
if(dp.containsKey(x)) return dp.get(x);
Set<Integer> ret = new HashSet<>();
while (x != 1)
{
if(spf[x]!=2) ret.add(spf[x]);
x = x / spf[x];
}
dp.put(x,ret);
return ret;
}
// function to find first index >= x
public int lowerIndex(List<Integer> arr, int n, int x)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr.get(mid) >= x)
h = mid - 1;
else
l = mid + 1;
}
return l;
}
public int lowerIndex(int[] arr, int n, int x)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr[mid] >= x)
h = mid - 1;
else
l = mid + 1;
}
return l;
}
// function to find last index <= y
public int upperIndex(List<Integer> arr, int n, int y)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr.get(mid) <= y)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
public int upperIndex(int[] arr, int n, int y)
{
int l = 0, h = n - 1;
while (l <= h)
{
int mid = (l + h) / 2;
if (arr[mid] <= y)
l = mid + 1;
else
h = mid - 1;
}
return h;
}
// function to count elements within given range
public int countInRange(List<Integer> arr, int n, int x, int y)
{
// initialize result
int count = 0;
count = upperIndex(arr, n, y) -
lowerIndex(arr, n, x) + 1;
return count;
}
public int add(int a, int b){
a+=b;
while(a>=MOD) a-=MOD;
while(a<0) a+=MOD;
return a;
}
public int mul(int a, int b){
long res= (long)a*(long)b;
return (int)(res%MOD);
}
public int power(int a, int b) {
int ans=1;
while(b>0){
if((b&1)!=0) ans= mul(ans,a);
b>>=1;
a= mul(a,a);
}
return ans;
}
int[] fact= new int[MAXN];
int[] inv= new int[MAXN];
public int Ckn(int n, int k){
if(k<0 || n<0) return 0;
return mul(mul(fact[n],inv[k]),inv[n-k]);
}
public int inverse(int a){
return power(a,MOD-2);
}
public void preprocess() {
fact[0]=1;
for(int i=1;i<MAXN;i++) fact[i]= mul(fact[i-1],i);
inv[MAXN-1]= inverse(fact[MAXN-1]);
for(int i=MAXN-2;i>=0;i--){
inv[i]= mul(inv[i+1],i+1);
}
}
/**
* return VALUE of lower bound for unsorted array
*/
public int lowerBoundNormalArray(int[] arr, int x){
TreeSet<Integer> set= new TreeSet<>();
for(int num: arr) set.add(num);
return set.lower(x);
}
/**
* return VALUE of upper bound for unsorted array
*/
public int upperBoundNormalArray(int[] arr, int x){
TreeSet<Integer> set= new TreeSet<>();
for(int num: arr) set.add(num);
return set.higher(x);
}
public void debugArr(int[] arr){
for(int i: arr) out.print(i+" ");
out.println();
}
public int rand(){
int min=0, max= MAXN;
int random_int = (int)Math.floor(Math.random()*(max-min+1)+min);
return random_int;
}
InputReader in; PrintWriter out;
CustomFileReader cin;
int[] xor= new int[3*100000+5];
int[] pow2= new int[1000000+1];
public void solve(InputReader in, PrintWriter out) {
this.in=in; this.out=out;
// sieve();
// pow2[0]=1;
// for(int i=1;i<pow2.length;i++){
// pow2[i]= mul(pow2[i-1],2);
// }
int t= 1;
// preprocess();
// int t=in.nextInt();
// int t= cin.nextIntArrLine()[0];
for(int i=1;i<=t;i++) solveA(i);
}
final double pi= Math.acos(-1);
static Point base;
int[] par;
int[] size;
PriorityQueue<Pair> q= new PriorityQueue<>((a,b)->b.x-a.x);
private int find(int u){
if(par[u]==u) return u;
par[u]= find(par[u]);
return par[u];
}
private boolean union(int u, int v){
u= find(u); v= find(v);
if(u==v) return false;
if(size[u]>size[v]){
int temp= u; u=v; v= temp;
}
par[u]=v;
size[v]+= size[u];
return true;
}
private boolean already(int u, int v){
return find(u)==find(v);
}
public void solveA(int t){
int n=in.nextInt(), d= in.nextInt();
par= new int[n+1]; size= new int[n+1];
for(int i=1;i<=n;i++) {
par[i]=i; size[i]=1;
}
int rem=0;
while(d-->0){
int u= in.nextInt(), v= in.nextInt();
if(!union(u,v)) rem++;
List<Integer> sizes= new ArrayList<>();
for(int i=1;i<=n;i++) if(i==par[i]) sizes.add(size[i]);
Collections.sort(sizes, Collections.reverseOrder());
int res=0;
for(int i=0;i<=Math.min(sizes.size()-1, rem);i++){
res+= sizes.get(i);
}
out.println(res-1);
}
}
static class Node implements Comparable<Node>{
char op;
int s;
public Node (char op, int s) {
this.op= op;
this.s= s;
}
@Override
public int compareTo(Node o) {
if (this.s==o.s) return (int)(this.op-o.op);
return this.s-o.s;
}
}
private long distance(Point p1, Point p2) {
long x= p1.x-p2.x, y= p1.y-p2.y;
return x*x+y*y;
}
private boolean eqPoint(Point p1, Point p2){
return p1.x==p2.x && p1.y==p2.y;
}
private double polarAngle(Point p1, Point p2) {
// p1 -> p2
if (p1.x==p2.x) return pi/2;
else if (p1.y==p2.y){
if(p1.x<p2.x) return 0;
else return pi;
}
else {
double y= (double)p2.y-(double)p1.y;
double x= (double)p2.x-(double)p1.x;
BigDecimal alpha1= new BigDecimal(y);
BigDecimal alpha2= new BigDecimal(x);
BigDecimal val= alpha1.divide(alpha2);
double angle= Math.atan(val.doubleValue());
if (angle<0) angle+= pi;
out.println("angle: "+angle);
return angle;
}
}
private boolean isRightTurn(Point p1, Point p2, Point p3){
Vector v1= new Vector(p1,p2), v2= new Vector(p1,p3);
if(crossProd(v1,v2)<0) return true;
else return false;
}
private long crossProd(Vector v1, Vector v2){
//x1*y2-x2*y1
return v1.x*v2.y - v2.x*v1.y;
}
static class PointAngle implements Comparable<PointAngle>{
Point p;
double angle;
long dis;
public PointAngle(Point p, double angle, long dis) {
this.p= p;
this.angle= angle;
this.dis= dis;
}
@Override
public int compareTo(PointAngle o) {
double dif= this.angle-o.angle;
if (dif <0) return -1;
else if(dif >0) return 1;
else {
long dif2r= this.dis-o.dis;
long dif2l= o.dis-this.dis;
if (base.x < this.p.x) return intDif(dif2r);
else return intDif(dif2l);
}
}
private int intDif(long a){
if (a>0) return 1;
else if(a<0) return -1;
else return 0;
}
}
public long _gcd(long a, long b)
{
if(b == 0) {
return a;
}
else {
return _gcd(b, a % b);
}
}
public long _lcm(long a, long b){
return (a*b)/_gcd(a,b);
}
}
// static class SEG {
// Pair[] segtree;
// public SEG(int n){
// segtree= new Pair[4*n];
// Arrays.fill(segtree, new Pair(-1,Long.MAX_VALUE));
// }
// // void buildTree(int l, int r, int index) {
// // if (l == r) {
// // segtree[index].y = a[l];
// // return;
// // }
// // int mid = (l + r) / 2;
// // buildTree(l, mid, 2 * index + 1);
// // buildTree(mid + 1, r, 2 * index + 2);
// // segtree[index].y = Math.min(segtree[2 * index + 1].y, segtree[2 * index + 2].y);
// // }
// void update(int l, int r, int index, int pos, Pair val) {
// if (l == r) {
// segtree[index] = val;
// return;
// }
// int mid = (l + r) / 2;
// if (pos <= mid) update(l, mid, 2 * index + 1, pos, val);
// else update(mid + 1, r, 2 * index + 2, pos, val);
// if(segtree[2 * index + 1].y < segtree[2 * index + 2].y){
// segtree[index]= segtree[2 * index + 1];
// }
// else {
// segtree[index]= segtree[2 * index + 2];
// }
// }
// // Pair query(int l, int r, int from, int to, int index) {
// // if (from <= l && r <= to)
// // return segtree[index];
// // if (r < from | to < l)
// // return 0;
// // int mid = (l + r) / 2;
// // Pair left= query(l, mid, from, to, 2 * index + 1);
// // Pair right= query(mid + 1, r, from, to, 2 * index + 2);
// // if(left.y < right.y) return left;
// // else return right;
// // }
// }
static class Venice{
public Map<Long,Long> m= new HashMap<>();
public long base=0;
public long totalValue=0;
private int M= 1000000007;
private long addMod(long a, long b){
a+=b;
if(a>=M) a-=M;
return a;
}
public void reset(){
m= new HashMap<>();
base=0;
totalValue=0;
}
public void update(long add){
base= base+ add;
}
public void add(long key, long val){
long newKey= key-base;
m.put(newKey, addMod(m.getOrDefault(newKey,(long)0),val));
}
}
static class Tuple implements Comparable<Tuple>{
int x, y, z;
public Tuple(int x, int y, int z){
this.x= x;
this.y= y;
this.z=z;
}
@Override
public int compareTo(Tuple o){
return this.z-o.z;
}
}
static class Point implements Comparable<Point>{
public long x;
public long y;
public Point(long x, long y){
this.x= x;
this.y= y;
}
@Override
public int compareTo(Point o) {
if(this.y!=o.y) return (int)(this.y-o.y);
return (int)(this.x-o.x);
}
}
static class Vector {
public long x;
public long y;
// p1 -> p2
public Vector(Point p1, Point p2){
this.x= p2.x-p1.x;
this.y= p2.y-p1.y;
}
}
static class Pair implements Comparable<Pair>{
public int x;
public int y;
public Pair(int x, int y){
this.x= x;
this.y= y;
}
@Override
public int compareTo(Pair o) {
if(this.x!=o.x) return this.x-o.x;
return (int)(this.y-o.y);
}
}
// public static class compareL implements Comparator<Tuple>{
// @Override
// public int compare(Tuple t1, Tuple t2) {
// return t2.l - t1.l;
// }
// }
// fast input reader class;
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream));
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public double nextDouble(){
return Double.parseDouble(nextToken());
}
public long nextLong(){
return Long.parseLong(nextToken());
}
public int[] nextIntArr(int n){
int[] arr= new int[n];
for(int i=0;i<n;i++) arr[i]= nextInt();
return arr;
}
public long[] nextLongArr(int n){
long[] arr= new long[n];
for(int i=0;i<n;i++) arr[i]= nextLong();
return arr;
}
public List<Integer> nextIntList(int n){
List<Integer> arr= new ArrayList<>();
for(int i=0;i<n;i++) arr.add(nextInt());
return arr;
}
public int[][] nextIntMatArr(int n, int m){
int[][] mat= new int[n][m];
for(int i=0;i<n;i++) for(int j=0;j<m;j++) mat[i][j]= nextInt();
return mat;
}
public List<List<Integer>> nextIntMatList(int n, int m){
List<List<Integer>> mat= new ArrayList<>();
for(int i=0;i<n;i++){
List<Integer> temp= new ArrayList<>();
for(int j=0;j<m;j++) temp.add(nextInt());
mat.add(temp);
}
return mat;
}
public char[] nextStringCharArr(){
return nextToken().toCharArray();
}
}
static class CustomFileReader{
String path="";
Scanner sc;
public CustomFileReader(String path){
this.path=path;
try{
sc= new Scanner(new File(path));
}
catch(Exception e){}
}
public String nextLine(){
return sc.nextLine();
}
public int[] nextIntArrLine(){
String line= sc.nextLine();
String[] part= line.split("[\\s+]");
int[] res= new int[part.length];
for(int i=0;i<res.length;i++) res[i]= Integer.parseInt(part[i]);
return res;
}
}
} | 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 | cfb150d868b390d1a8804adbc8103e97 | 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 {
class DSU {
int[] dsu;
public DSU(int n) {
dsu = new int[n];
Arrays.fill(dsu, -1);
}
public int find(int u) {
if (dsu[u] < 0)
return u;
return dsu[u] = find(dsu[u]);
}
public boolean merge(int u, int v) {
u = find(u);
v = find(v);
if (u == v)
return false;
if (dsu[u] > dsu[v]) {
int temp = dsu[u];
dsu[u] = dsu[v];
dsu[v] = temp;
}
dsu[u] += dsu[v];
dsu[v] = u;
return true;
}
public int getSize(int u) {
return -dsu[find(u)];
}
}
public void prayGod() throws IOException {
int n = nextInt(), d = nextInt();
int[] u = new int[d];
int[] v = new int[d];
for (int i = 0; i < d; i++) {
u[i] = nextInt() - 1;
v[i] = nextInt() - 1;
DSU dsu = new DSU(n);
int notMerge = 0;
TreeSet<Integer> q = new TreeSet<>((Integer a, Integer b) -> {
if (dsu.getSize(a) != dsu.getSize(b))
return Integer.compare(dsu.getSize(b), dsu.getSize(a));
return Integer.compare(a, b);
});
for (int j = 0; j <= i; j++) {
if (!dsu.merge(u[j], v[j])) {
notMerge++;
continue;
}
}
for (int j = 0; j < n; j++) {
if (dsu.find(j) != j)
continue;
q.add(j);
}
while (notMerge > 0 && q.size() > 1) {
int first = q.pollFirst(), second = q.pollFirst();
if (!dsu.merge(first, second)) {
System.exit(1);
}
q.add(dsu.find(first));
notMerge--;
}
int ret = 0;
for (int j = 0; j < n; j++) {
ret = Math.max(ret, dsu.getSize(j));
}
out.println(ret - 1);
}
}
static final boolean RUN_TIMING = true;
static final boolean AUTOFLUSH = false;
static final boolean FILE_INPUT = false;
static final boolean FILE_OUTPUT = false;
static int iinf = 0x3f3f3f3f;
static long inf = (long) 1e18 + 10;
static long mod = 998244353L;
static char[] inputBuffer = new char[1 << 20];
static PushbackReader in = new PushbackReader(new BufferedReader(new InputStreamReader(System.in)), 1 << 20);
static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), AUTOFLUSH);
// int data-type
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
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 void sort(int[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++)
out.print(arr[i] + " ");
out.println();
}
// long data-type
public long nextLong() throws IOException {
return Long.parseLong(next());
}
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 static void printArray(long[] arr) {
for (int i = 0; i < arr.length; i++)
out.print(arr[i] + " ");
out.println();
}
public void sort(long[] a) {
shuffle(a);
Arrays.sort(a);
}
// double data-type
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
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 static void printArray(double[] arr) {
for (int i = 0; i < arr.length; i++)
out.print(arr[i] + " ");
out.println();
}
// Generic type
public <T> void sort(T[] a) {
shuffle(a);
Arrays.sort(a);
}
public static <T> void printArray(T[] arr) {
for (int i = 0; i < arr.length; i++)
out.print(arr[i] + " ");
out.println();
}
public String next() throws IOException {
int len = 0;
int c;
do {
c = in.read();
} while (Character.isWhitespace(c) && c != -1);
if (c == -1) {
throw new NoSuchElementException("Reached EOF");
}
do {
inputBuffer[len] = (char) c;
len++;
c = in.read();
} while (!Character.isWhitespace(c) && c != -1);
while (c != '\n' && Character.isWhitespace(c) && c != -1) {
c = in.read();
}
if (c != -1 && c != '\n') {
in.unread(c);
}
return new String(inputBuffer, 0, len);
}
public String nextLine() throws IOException {
int len = 0;
int c;
while ((c = in.read()) != '\n' && c != -1) {
if (c == '\r') {
continue;
}
inputBuffer[len] = (char) c;
len++;
}
return new String(inputBuffer, 0, len);
}
public boolean hasNext() throws IOException {
String line = nextLine();
if (line.isEmpty()) {
return false;
}
in.unread('\n');
in.unread(line.toCharArray());
return true;
}
public void shuffle(int[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int j = (int) (Math.random() * (n - i));
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
public void shuffle(long[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int j = (int) (Math.random() * (n - i));
long temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
public void shuffle(Object[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
int j = (int) (Math.random() * (n - i));
Object temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
public static void main(String[] args) throws IOException {
if (FILE_INPUT)
in = new PushbackReader(new BufferedReader(new FileReader(new File("output.txt"))), 1 << 20);
if (FILE_OUTPUT)
out = new PrintWriter(new FileWriter(new File("output.txt")));
long time = 0;
time -= System.nanoTime();
new D().prayGod();
time += System.nanoTime();
if (RUN_TIMING)
System.err.printf("%.3f ms%n", time / 1000000.0);
out.flush();
in.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 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 | 3ba6e434865baa8fbd464b98b2af617a | 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 | /*
Codeforces
Problem 1609D
*/
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.PriorityQueue;
import java.util.Set;
public class SocialNetwork {
public static int n;
public static int d;
public static int free = 0;
public static Pair[] p;
public static DSU dsu;
public static void main(String[] args) throws IOException {
FastIO in = new FastIO(System.in);
n = in.nextInt();
d = in.nextInt();
p = new Pair[d];
dsu = new DSU(n);
for (int i = 0; i < d; i++) {
int x = in.nextInt() - 1;
int y = in.nextInt() - 1;
p[i] = new Pair(x,y);
}
for (int i = 0; i < d; i++) {
if (dsu.find(p[i].x) != dsu.find(p[i].y)) {
dsu.union(p[i].x, p[i].y);
System.out.println(find());
} else {
free++;
System.out.println(find());
}
}
in.close();
}
public static long find() {
Set<Integer> found = new HashSet<>();
PriorityQueue<Integer> maxs = new PriorityQueue<>(Collections.reverseOrder());
for (int i = 0; i < n; i++) {
if (!found.add(dsu.find(i))) continue;
maxs.add(dsu.size[dsu.find(i)]);
}
long ans = maxs.poll();
for (int i = 0; i < free && !maxs.isEmpty(); i++) {
ans += maxs.poll();
}
return ans - 1;
}
public static class Pair {
int x, y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
public static class DSU {
public int[] disjoint;
public int[] size;
public DSU(int n) {
disjoint = new int[n];
size = new int[n];
Arrays.fill(disjoint, -1);
Arrays.fill(size, 1);
}
public int find(int v) {
if (disjoint[v] == -1) {
return v;
}
disjoint[v] = find(disjoint[v]);
return disjoint[v];
}
public void union(int u, int v) {
int uroot = find(u);
int vroot = find(v);
if (uroot == vroot) {
return;
}
if (size[uroot] < size[vroot]) {
disjoint[uroot] = vroot;
size[vroot] = size[uroot] + size[vroot];
} else {
disjoint[vroot] = uroot;
size[uroot] = size[uroot] + size[vroot];
}
}
}
public static class FastIO {
private InputStream dis;
private byte[] buffer = new byte[1 << 17];
private int pointer = 0;
public FastIO(String fileName) throws IOException {
dis = new FileInputStream(fileName);
}
public FastIO(InputStream is) throws IOException {
dis = is;
}
public int nextInt() throws IOException {
int ret = 0;
byte b;
do {
b = nextByte();
} while (b <= ' ');
boolean negative = false;
if (b == '-') {
negative = true;
b = nextByte();
}
while (b >= '0' && b <= '9') {
ret = 10 * ret + b - '0';
b = nextByte();
}
return (negative) ? -ret : ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte b;
do {
b = nextByte();
} while (b <= ' ');
boolean negative = false;
if (b == '-') {
negative = true;
b = nextByte();
}
while (b >= '0' && b <= '9') {
ret = 10 * ret + b - '0';
b = nextByte();
}
return (negative) ? -ret : ret;
}
public byte nextByte() throws IOException {
if (pointer == buffer.length) {
dis.read(buffer, 0, buffer.length);
pointer = 0;
}
return buffer[pointer++];
}
public String next() throws IOException {
StringBuffer ret = new StringBuffer();
byte b;
do {
b = nextByte();
} while (b <= ' ');
while (b > ' ') {
ret.appendCodePoint(b);
b = nextByte();
}
return ret.toString();
}
public void close() throws IOException {
dis.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 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 | 2b9eb72ea79b39286229b99220f57303 | 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 D1609 {
public static int[] size;
public static int[] parent;
public static TreeSet<Size> sizes;
public static int ans = 1;
public static void main(String[] args) throws IOException, FileNotFoundException {
// Scanner in = new Scanner(new File("test.in"));
Kattio in = new Kattio();
int N = in.nextInt();
int D = in.nextInt();
size = new int[N];
parent = new int[N];
sizes = new TreeSet<Size>();
for(int i = 0; i < N; i++){
parent[i] = i;
size[i] = 1;
sizes.add(new Size(i, 1));
}
int free = 0;
for(int i = 0; i < D; i++){
int x = in.nextInt() - 1;
int y = in.nextInt() - 1;
if(findRoot(x) != findRoot(y)){
join(x, y);
} else {
free++;
}
int sum = 0;
int count = 0;
Size curr = sizes.last();
while(count <= free && curr != null){
sum += curr.size;
curr = sizes.lower(curr);
count++;
}
System.out.println(sum - 1);
}
}
static class Kattio extends PrintWriter {
private BufferedReader r;
private StringTokenizer st;
// standard input
public Kattio() { this(System.in, System.out); }
public Kattio(InputStream i, OutputStream o) {
super(o);
r = new BufferedReader(new InputStreamReader(i));
}
// USACO-style file input
public Kattio(String problemName) throws IOException {
super(problemName + ".out");
r = new BufferedReader(new FileReader(problemName + ".in"));
}
// returns null if no more input
public String next() {
try {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(r.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 static class Size implements Comparable<Size> {
int person, size;
public Size(int person, int size){
this.person = person;
this.size = size;
}
public boolean equals(Object o){
Size s = (Size) o;
return s.person == person && s.size == size;
}
public int compareTo(Size s){
if(size == s.size) {
return person - s.person;
}
return size - s.size;
}
}
public static void join(int a, int b){
a = findRoot(a);
b = findRoot(b);
if(a == b){
return;
}
if(size[a] < size[b]){
parent[a] = b;
sizes.remove(new Size(b, size[b]));
size[b] += size[a];
sizes.remove(new Size(a, size[a]));
sizes.add(new Size(b, size[b]));
ans = Math.max(ans, size[b]);
} else {
parent[b] = a;
sizes.remove(new Size(a, size[a]));
size[a] += size[b];
sizes.remove(new Size(b, size[b]));
sizes.add(new Size(a, size[a]));
ans = Math.max(ans, size[a]);
}
}
public static int findRoot(int a){
if(parent[a] == a){
return a;
}
return parent[a] = findRoot(parent[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 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 | cda388e94f77e24b823c6b0a90fb324a | 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.lang.*;
public class Main implements Runnable {
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream) {
this.stream = stream;
}
public 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++];
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
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;
}
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 double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString() {
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 boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception {
new Thread(null, new Main(), "Main", 1 << 27).start();
}
static class Pair {
int f;
int s;
int p;
PrintWriter w;
// int t;
Pair(int f, int s) {
// Pair(int f,int s, PrintWriter w){
this.f = f;
this.s = s;
// this.p = p;
// this.w = w;
// this.t = t;
}
public static Comparator<Pair> wc = new Comparator<Pair>() {
public int compare(Pair e1,Pair e2){
// 1 for swap
if(Math.abs(e1.f)-Math.abs(e2.f)!=0){
// if(e1.f<=e2.f)return -1;
// else return 1;
return (Math.abs(e1.f)-Math.abs(e2.f));
}
else{
// if(e1.s<=e2.s)return -1;
// else return 1;
// e1.w.println("##"+e1.f+" "+e2.f);
return (Math.abs(e1.s)-Math.abs(e2.s));
}
}
};
}
public Integer[] sort(Integer[] a) {
Arrays.sort(a);
return a;
}
public Long[] sort(Long[] a) {
Arrays.sort(a);
return a;
}
public static ArrayList<Integer> sieve(int N) {
int i, j, flag;
ArrayList<Integer> p = new ArrayList<Integer>();
for (i = 1; i < N; i++) {
if (i == 1 || i == 0)
continue;
flag = 1;
for (j = 2; j <= i / 2; ++j) {
if (i % j == 0) {
flag = 0;
break;
}
}
if (flag == 1) {
p.add(i);
}
}
return p;
}
public static long gcd(long a, long b) {
if (b == 0)
return a;
else
return gcd(b, a % b);
}
public static int gcd(int a, int b) {
if (b == 0)
return a;
else
return gcd(b, a % b);
}
//// recursive dfs
public static int dfs(int s, ArrayList<Integer>[] g, long[] dist, boolean[] v, PrintWriter w, int p) {
v[s] = true;
int ans = 1;
// int n = dist.length - 1;
int t = g[s].size();
// int max = 1;
for (int i = 0; i < t; i++) {
int x = g[s].get(i);
if (!v[x]) {
// dist[x] = dist[s] + 1;
ans = Math.min(ans, dfs(x, g, dist, v, w, s));
} else if (x != p) {
// w.println("* " + s + " " + x + " " + p);
ans = 0;
}
}
// max = Math.max(max,(n-p));
return ans;
}
//// iterative BFS
public static int bfs(int s, ArrayList<Integer>[] g, long[] dist, boolean[] b, PrintWriter w, int p) {
b[s] = true;
int siz = 1;
// dist--;
Queue<Integer> q = new LinkedList<>();
q.add(s);
while (q.size() != 0) {
int i = q.poll();
Iterator<Integer> it = g[i].listIterator();
int z = 0;
while (it.hasNext()) {
z = it.next();
if (!b[z]) {
b[z] = true;
// dist--;
dist[z] = dist[i] + 1;
// siz++;
q.add(z);
} else if (z != p) {
siz = 0;
}
}
}
return siz;
}
public static int lower(int a[], int x) { // x is the target value or key
int l = -1, r = a.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (a[m] >= x)
r = m;
else
l = m;
}
return r;
}
public static int upper(int a[], int x) {// x is the key or target value
int l = -1, r = a.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (a[m] <= x)
l = m;
else
r = m;
}
return l + 1;
}
public static int lower(ArrayList<Integer> a, int x) { // x is the target value or key
int l = -1, r = a.size();
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (a.get(m) >= x)
r = m;
else
l = m;
}
return r;
}
public static int upper(ArrayList<Integer> a, int x) {// x is the key or target value
int l = -1, r = a.size();
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (a.get(m) <= x)
l = m;
else
r = m;
}
return l + 1;
}
public static long power(long x, long y, long m) {
if (y == 0)
return 1;
long p = power(x, y / 2, m) % m;
p = (p * p) % m;
if (y % 2 == 0)
return p;
else
return (x * p) % m;
}
public void yesOrNo(boolean f) {
if (f) {
w.println("YES");
} else {
w.println("NO");
}
}
// Arrays.sort(rooms, (room1, room2) -> room1[1] == room2[1] ? room1[0]-room2[0] : room2[1]-room1[1]);
// Arrays.sort(A, (a, b) -> Integer.compare(a[0] , b[0]));
//////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////
// code here
int oo = (int) 1e9;
// int[] parent;
// int[] dist;
// int[][] val;
boolean[] vis;
// ArrayList<Integer>[] g;
// int[] col;
//HashMap<Long, Boolean> vis = new HashMap<Long, Boolean>();
//char[][] g;
//boolean[][] v;
// Long[] a;
// ArrayList<Integer[]> a;
// int[][] ans;
// long[][] dp;
long mod;
// int n;
// int m;
// int k;
// long[][] pre;
// StringBuilder[] a;
// StringBuilder[] b;
// StringBuilder ans;
PrintWriter w = new PrintWriter(System.out);
public void run() {
InputReader sc = new InputReader(System.in);
int defaultValue = 0;
mod = 1000000007;
int test = 1;
// test = sc.nextInt();
while (test-- > 0) {
int n = sc.nextInt();
int d = sc.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 extra = 0;
for(int i=0; i<d; i++){
int ans = 0;
int x = sc.nextInt();
int y = sc.nextInt();
int px = find(x, parent);
int py = find(y, parent);
if(px==py) extra++;
else union(px, py, parent, size);
int[] temp = new int[n+1];
for(int j=1; j<=n; j++)temp[j] = size[j];
Arrays.sort(temp);
int ee = extra;
for(int j=n; j>0 && ee>=0; j--,ee--){
ans+=temp[j];
}
w.println(ans-1);
}
}
w.flush();
w.close();
}
public void union(int a, int b, int[] parent, int[] size){
int parentOfA = find(a, parent);
int parentOfB = find(b, parent);
if(parentOfB != parentOfA) {
size[parentOfA] += size[parentOfB];
size[parentOfB] = 0;
parent[parentOfB] = parentOfA;
}
}
public int find(int a, int[] parent){
if(parent[a]==a)return a;
else return find(parent[a], parent);
}
}
| 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 | 6b24b2d499cf798d302fb07eb4f803f1 | 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 : Ryan Ranaut
__Hope is a big word, never lose it__
------------- --------------*/
import java.io.*;
import java.util.*;
public class Codeforces1 {
static PrintWriter out = new PrintWriter(System.out);
static final int mod = 1_000_000_007;
static int max = (int)(2e9);
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());
}
int[] readIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
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;
}
}
/*--------------------------------------------------------------------------*/
//Try seeing general case
//Minimization Maximization - BS..... Connections - Graphs.....
//Greedy not worthy - Try DP
public static void main(String[] args) {
FastReader s = new FastReader();
int n = s.nextInt();
int d = s.nextInt();
DSU dsu = new DSU(n);
StringBuilder sb = new StringBuilder();
int count = 1;
for(int i=0;i<d;i++)
{
int u = s.nextInt()-1;
int v = s.nextInt()-1;
if(dsu.find(u) == dsu.find(v))
count++;
else
dsu.union(u, v);
//Now calculate max acquaintances
int res = 0;
List<Integer> ls = new ArrayList<>();
for(int j=0;j<n;j++)
{
if(dsu.find(j) == j)
ls.add(dsu.groupSize[j]);
}
ls.sort(Collections.reverseOrder());
for(int j=0;j<count;j++)
res += ls.get(j);
sb.append((res-1)+"\n");
}
out.println(sb);
out.close();
}
/*----------------------------------End of the road--------------------------------------*/
static class DSU {
int[] parent;
int[] ranks;
int[] groupSize;
int size;
public DSU(int n) {
size = n;
parent = new int[n];//0 based
ranks = new int[n];
groupSize = new int[n];//Size of each component
for (int i = 0; i < n; i++) {
parent[i] = i;
ranks[i] = 1; groupSize[i] = 1;
}
}
public int find(int x)//Path Compression
{
if (parent[x] == x)
return x;
else
return parent[x] = find(parent[x]);
}
public void union(int x, int y)//Union by rank
{
int x_rep = find(x);
int y_rep = find(y);
if (x_rep == y_rep)
return;
if (ranks[x_rep] < ranks[y_rep])
{
parent[x_rep] = y_rep;
groupSize[y_rep] += groupSize[x_rep];
}
else if (ranks[x_rep] > ranks[y_rep])
{
parent[y_rep] = x_rep;
groupSize[x_rep] += groupSize[y_rep];
}
else {
parent[y_rep] = x_rep;
ranks[x_rep]++;
groupSize[x_rep] += groupSize[y_rep];
}
size--;//Total connected components
}
}
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 void debug(int ...a)
{
for(int x: a)
out.print(x+" ");
out.println();
}
static void debug(long ...a)
{
for(long x: a)
out.print(x+" ");
out.println();
}
static void debugMatrix(int[][] a)
{
for(int[] x:a)
out.println(Arrays.toString(x));
}
static void debugMatrix(long[][] a)
{
for(long[] x:a)
out.println(Arrays.toString(x));
}
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 void sort(int[] a)
{
ArrayList<Integer> ls = new ArrayList<>();
for(int x: a) ls.add(x);
Collections.sort(ls);
for(int i=0;i<a.length;i++)
a[i] = ls.get(i);
}
static void sort(long[] a)
{
ArrayList<Long> ls = new ArrayList<>();
for(long x: a) ls.add(x);
Collections.sort(ls);
for(int i=0;i<a.length;i++)
a[i] = ls.get(i);
}
static class Pair{
int x, y;
Pair(int x, int y)
{
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
return x == pair.x && y == pair.y;
}
@Override
public int hashCode() {
return Objects.hash(x, 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 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 | 3f30da15f63983dc1c4e4feab21aebb3 | 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.InputStreamReader;
import java.util.StringTokenizer;
import java.util.*;
import java.io.*;
public class Main {
// Graph
// prefix sums
//inputs
public static void main(String args[])throws Exception{
Input sc=new Input();
precalculates p=new precalculates();
StringBuilder sb=new StringBuilder();
int d[]=sc.readArray();
int n=d[0],k=d[1];
int par[]=new int[n+1];
int dp[]=new int[n+1];
int count=0;
int max=1;
Arrays.fill(par,-1);
Arrays.fill(dp,1);
int ans=0;
for(int i=0;i<k;i++){
d=sc.readArray();
int v1=parent(d[0],par);
int v2=parent(d[1],par);
if(v1==v2 && v1!=-1){
// cycle
//dp[v2]++;
count++;
}else{
par[v1]=v2;
//if(v2!=-1 && )
dp[v2]+=dp[v1];
//dp[v1]=1;
// else
// dp[d[1]]+=dp[v1];
ans=Math.max(ans,dp[v2]-1);
}
ArrayList<Integer> lst=new ArrayList<>();
for(int j=1;j<=n;j++){
if(par[j]==-1)
lst.add(dp[j]);
}
Collections.sort(lst);
// System.out.println(lst);
int sum=0;
for(int j=lst.size()-1;j>=lst.size()-1-count;j--){
sum+=lst.get(j);
}
ans=Math.max(ans,sum-1);
//System.out.println(ans);
sb.append(ans+"\n");
}
System.out.print(sb);
}
public static int parent(int src,int a[]){
while(src!=-1 && a[src]!=-1){
src=a[src];
}
return src;
}
}
class Input{
BufferedReader br;
StringTokenizer st;
Input(){
br=new BufferedReader(new InputStreamReader(System.in));
st=new StringTokenizer("");
}
public int[] readArray() throws Exception{
st=new StringTokenizer(br.readLine());
int a[]=new int[st.countTokens()];
for(int i=0;i<a.length;i++){
a[i]=Integer.parseInt(st.nextToken());
}
return a;
}
public long[] readArrayLong() throws Exception{
st=new StringTokenizer(br.readLine());
long a[]=new long[st.countTokens()];
for(int i=0;i<a.length;i++){
a[i]=Long.parseLong(st.nextToken());
}
return a;
}
public int readInt() throws Exception{
st=new StringTokenizer(br.readLine());
return Integer.parseInt(st.nextToken());
}
public long readLong() throws Exception{
st=new StringTokenizer(br.readLine());
return Long.parseLong(st.nextToken());
}
public String readString() throws Exception{
return br.readLine();
}
public int[][] read2dArray(int n,int m)throws Exception{
int a[][]=new int[n][m];
for(int i=0;i<n;i++){
st=new StringTokenizer(br.readLine());
for(int j=0;j<m;j++){
a[i][j]=Integer.parseInt(st.nextToken());
}
}
return a;
}
}
class precalculates{
public int[] prefixSumOneDimentional(int a[]){
int n=a.length;
int dp[]=new int[n];
for(int i=0;i<n;i++){
if(i==0)
dp[i]=a[i];
else
dp[i]=dp[i-1]+a[i];
}
return dp;
}
public int[] postSumOneDimentional(int a[]) {
int n = a.length;
int dp[] = new int[n];
for (int i = n - 1; i >= 0; i--) {
if (i == n - 1)
dp[i] = a[i];
else
dp[i] = dp[i + 1] + a[i];
}
return dp;
}
public int[][] prefixSum2d(int a[][]){
int n=a.length;int m=a[0].length;
int dp[][]=new int[n+1][m+1];
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
dp[i][j]=a[i-1][j-1]+dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1];
}
}
return dp;
}
public long pow(long a,long b){
long mod=1000000007;
long ans=0;
if(b<=0)
return 1;
if(b%2==0){
ans=pow(a,b/2)%mod;
return ((ans%mod)*(ans%mod))%mod;
}else{
return ((a%mod)*(ans%mod))%mod;
}
}
}
class GraphInteger{
HashMap<Integer,vertex> vtces;
class vertex{
HashMap<Integer,Integer> children;
public vertex(){
children=new HashMap<>();
}
}
public GraphInteger(){
vtces=new HashMap<>();
}
public void addVertex(int a){
vtces.put(a,new vertex());
}
public void addEdge(int a,int b,int cost){
if(!vtces.containsKey(a)){
vtces.put(a,new vertex());
}
if(!vtces.containsKey(b)){
vtces.put(b,new vertex());
}
vtces.get(a).children.put(b,cost);
// vtces.get(b).children.put(a,cost);
}
public boolean isCyclicDirected(){
boolean isdone[]=new boolean[vtces.size()+1];
boolean check[]=new boolean[vtces.size()+1];
for(int i=1;i<=vtces.size();i++) {
if (!isdone[i] && isCyclicDirected(i,isdone, check)) {
return true;
}
}
return false;
}
private boolean isCyclicDirected(int i,boolean isdone[],boolean check[]){
if(check[i])
return true;
if(isdone[i])
return false;
check[i]=true;
isdone[i]=true;
Set<Integer> set=vtces.get(i).children.keySet();
for(Integer ii:set){
if(isCyclicDirected(ii,isdone,check))
return true;
}
check[i]=false;
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 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 | fe6278f7f17115e8954e4b8220bd104b | 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.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.IntStream;
public class One {
public static void print(Object o) {
System.out.println(o);
}
public static void print(String pattern, Object ...args) {
System.out.println(String.format(pattern, args));
}
public static void print(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
System.out.println(Arrays.toString(matrix[i]));
}
}
public static void debug(Object o) {
System.out.print("[DEBUG]");
System.out.println(o);
}
public static void debug(int[] arr) {
System.out.print("[DEBUG]");
System.out.println(Arrays.toString(arr));
}
public static void debug(String pattern, Object... args) {
System.out.print("[DEBUG]");
System.out.println(String.format(pattern, args));
}
public static void main(String[] args) throws java.io.IOException{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int d = sc.nextInt();
int[] id = new int[n]; // getRoot node
int[] size = new int[n]; //get size
for (int i = 0; i < n; i++) {
id[i] = i;
size[i] = 1;
}
int prev = 1;
int numComponents = n;
int balance = 0;
for (int jelly = 0; jelly < d; jelly++) {
int x = sc.nextInt() - 1;
int y = sc.nextInt() - 1;
int r1 = find(x, id);
int r2 = find(y, id);
if (r1 == r2) {
balance++;
}
else {
if (size[r1] < size[r2]) {
size[r2] += size[r1];
id[r1] = r2;
} else {
size[r1] += size[r2];
id[r2] = r1;
}
numComponents--;
}
int currMax = findAdditional(id, size, balance + 1, n)- 1;
print(Math.max(prev, currMax));
prev = Math.max(prev, currMax);
}
}
public static int find(int p, int[] id) {
int root = p;
while (root != id[root]) root = id[root];
while (p != root) {
int next = id[p];
id[p] = root;
p = next;
}
return root;
}
public static int findAdditional(int[] id, int[] size, int balance, int n) {
List<Integer> t = new ArrayList<>();
// get all #balance largest componenets, add to prev
for (int i = 0; i < n ; i++) {
if (id[i] == i) {
t.add(size[i]);
}
}
t.sort(null);
int additional = 0;
for (int i = t.size() - 1; i > t.size() - 1 - balance && i >=0; i--) {
additional += t.get(i);
}
return additional;
}
}
| 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 | 8e8c62fc44b6605fcce775d697ee9edd | 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.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// https://codeforces.com/contest/1609/problem/D
// Explicación https://www.geeksforgeeks.org/disjoint-set-data-structures/
public class D {
private static class DSU {
int[] parent;
int[] sz;
int n;
public DSU(int n)
{
this.n = n;
parent = new int[n];
for(int i = 0; i < n; i++)
parent[i] = i;
sz = new int[n];
for(int i = 0; i < n; i++)
sz[i] = 1;
}
public int find(int x)
{
//return (x == parent[x] ? x : (parent[x] = find(parent[x])));
if(parent[x] == x)
return x;
else
return find(parent[x]);
}
public boolean unite(int x, int y)
{
x = find(x);
y = find(y);
if(x != y)
{
parent[x] = y;
sz[y] += sz[x];
sz[x] = 0;
return true;
}
return false;
}
}
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] nd = br.readLine().split(" ");
int n = Integer.parseInt(nd[0]);
int d = Integer.parseInt(nd[1]);
DSU dsu = new DSU(n);
int cc = 1;
for(int it = 1; it <= d; it++)
{
String[] xy = br.readLine().split(" ");
int x = Integer.parseInt(xy[0]);
int y = Integer.parseInt(xy[1]);
--x;
--y;
if(!dsu.unite(x, y))
cc += 1;
List<Integer> b = new ArrayList<Integer>();
for(int i = 0; i < n; i++)
{
if(dsu.find(i) == i)
b.add(dsu.sz[i]);
}
Collections.sort(b, Collections.reverseOrder());
int count = 0;
for(int i = 0; i < cc; i++)
count += b.get(i);
System.out.println(count-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 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 | ca28643655bb2e57ddb1a44a4eb48bdf | 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.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class D {
private static class DSU {
int[] p;
int[] sz;
int n;
public DSU(int n)
{
this.n = n;
p = new int[n];
for(int i = 0; i < n; i++)
p[i] = i;
sz = new int[n];
for(int i = 0; i < n; i++)
sz[i] = 1;
}
public int get(int x)
{
return (x == p[x] ? x : (p[x] = get(p[x])));
}
public boolean unite(int x, int y)
{
x = get(x);
y = get(y);
if(x != y)
{
p[x] = y;
sz[y] += sz[x];
sz[x] = 0;
return true;
}
return false;
}
}
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] nd = br.readLine().split(" ");
int n = Integer.parseInt(nd[0]);
int d = Integer.parseInt(nd[1]);
DSU dsu = new DSU(n);
int cc = 1;
for(int it = 1; it <= d; it++)
{
String[] xy = br.readLine().split(" ");
int x = Integer.parseInt(xy[0]);
int y = Integer.parseInt(xy[1]);
--x;
--y;
if(!dsu.unite(x, y))
cc += 1;
List<Integer> b = new ArrayList<Integer>();
for(int i = 0; i < n; i++)
{
if(dsu.get(i) == i)
b.add(dsu.sz[i]);
}
Collections.sort(b, Collections.reverseOrder());
int count = 0;
for(int i = 0; i < cc; i++)
count += b.get(i);
System.out.println(count-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 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 | fbd2b977e6b95e957d8acd35353ef083 | 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) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
StringTokenizer tokenizer = new StringTokenizer(in.readLine());
int size = Integer.parseInt(tokenizer.nextToken());
int conditions = Integer.parseInt(tokenizer.nextToken());
Network[] components = new Network[size];
Network[] complist = new Network[size];
for (int i = 0; i < size; i++) {
Network c = new Network();
c.id = i;
c.children.add(i);
components[i] = c;
complist[i] = c;
}
StringBuilder b = new StringBuilder();
int free = 0;
for (int i = 0; i < conditions; i++) {
tokenizer = new StringTokenizer(in.readLine());
int i1 = Integer.parseInt(tokenizer.nextToken()) - 1;
int i2 = Integer.parseInt(tokenizer.nextToken()) - 1;
Network c1 = components[i1];
Network c2 = components[i2];
if (c1 == c2)
free++;
else {
for(int j = 0; j < c2.children.size();){
c1.children.add(c2.children.get(j));
components[c2.children.get(j)] = c1;
c2.children.remove(j);
}
}
Arrays.sort(complist);
int answer = complist[0].children.size();
for (int j = 0; j < free; j++) {
answer += complist[1 + j].children.size();
}
b.append((answer - 1) + "\n");
}
System.out.print(b);
in.close();
out.close();
}
public static class Network implements Comparable<Network> {
int id;
ArrayList<Integer> children = new ArrayList<>();
@Override
public int compareTo(Network o) {
return o.children.size() - this.children.size();
}
}
} | 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 | 9a6ae5392585195bfb3783f2de7c57b6 | 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.PrintWriter;
import java.util.*;
public class Main {
public static class union_find {
int n;
int[] sz;
int[] par;
union_find(int nval) {
n = nval;
sz = new int[n + 1];
par = new int[n + 1];
for (int i = 0; i <= n; i++) {
par[i] = i;
sz[i] = 1;
}
}
int root(int x) {
if (par[x] == x) return x;
return par[x] = root(par[x]);
}
boolean find(int a, int b) {
return root(a) == root(b);
}
int union(int a, int b) {
int ra = root(a);
int rb = root(b);
if (ra == rb) return 1;
if (sz[a] > sz[b]) {
int temp = ra;
ra = rb;
rb = temp;
}
par[ra] = rb;
sz[rb] += sz[ra];
return 0;
}
}
public static void main(String[] args) {
Scanner obj = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = obj.nextInt();
int q = obj.nextInt();
union_find dsu = new union_find(n + 1);
int extra = 0;
for (int i = 1; i <= q; i++) {
int a = dsu.root(obj.nextInt());
int b = dsu.root(obj.nextInt());
extra += dsu.union(a, b);
HashSet<Integer> h = new HashSet<>();
PriorityQueue<Integer> pq = new PriorityQueue<>((f, g) -> {
int val = f - g;
if (val == 0) return 0;
else if (val < 0) return 1;
else return -1;
});
for (int j = 1; j <= n; j++) {
h.add(dsu.root(j));
}
for (int nd : h) pq.add(dsu.sz[nd]);
int ans = pq.poll(), temp = extra;
while (temp-- != 0 && !pq.isEmpty()) {
ans += pq.poll();
}
out.println(ans - 1);
}
out.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 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 | e150218de7f2b5fa03f540021acca9fa | 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 BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
public static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
public static int mod = (int)1e9+7;
static boolean[] isprime=new boolean[1];
static {
for(int i=2;i<isprime.length;i++) isprime[i]=true;
for(int i=2;i<isprime.length;i++) {
if(isprime[i]) {
for(int k = 2; i*k<isprime.length; k++) {
isprime[i*k] = false;
}
}
}
}
public static void main(String[] args) throws Exception {
String s[] = bf.readLine().split(" ");
int n = Integer.parseInt(s[0]);
int d = Integer.parseInt(s[1]);
Main main = new Main();
DisjointSet disjointSet = main.new DisjointSet(n);
int cnt = 0;//多余的边的个数
for(int i = 0;i < d;i++){
String s1[] = bf.readLine().split(" ");
int a = Integer.parseInt(s1[0])-1;
int b = Integer.parseInt(s1[1])-1;
if(disjointSet.find(a) == disjointSet.find(b)) cnt++;
else disjointSet.join(a,b);
Map<Integer, Integer> map = new HashMap<>();
for(int j = 0;j < n;j++){
int m = disjointSet.find(j);
map.put(m,map.getOrDefault(m,0)+1);
}
int ans = 0;
List<Integer> list = new ArrayList<>();
for(int k : map.keySet()){
list.add(map.get(k));
}
Collections.sort(list);
int k = cnt;
for(int j = list.size()-1;j >= 0 && k-- >= 0;j--){
ans += list.get(j);
}
bw.write(ans-1+"\n");
}
bw.flush();
}
public static long gcd(long a, long b){
return b == 0 ? a : gcd(b,a%b);
}
public static long lcm(long a, long b){
return a*b / gcd(a,b);
}
class DisjointSet{
int father[];
DisjointSet(int n){
father = new int[n];
for(int i = 0;i < n;i++) father[i] = i;
}
int find(int x){
int old = x;
while(x != father[x]){
x = father[x];
}
while(old != x){
int oldfather = father[old];
father[old] = x;
old = oldfather;
}
return x;
}
void join(int x, int y){
int rx = find(x);
int ry = find(y);
if(rx != ry){
father[rx] = ry;
}
}
}
} | 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 | 0fb32462d43881c873f39b7286216242 | 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.Arrays;
import java.util.InputMismatchException;
import java.util.TreeSet;
public class D {
static int M = (int) 1e6;
public static void main(String[] args) {
FastIO io = new FastIO();
int n = io.nextInt();
int d = io.nextInt();
TreeSet<Pair> multiSet = new TreeSet<>();
for (int i = 0; i < n; i++) {
multiSet.add(new Pair(i, 1));
}
DisjointSets uf = new DisjointSets(n);
int count = 1;
for (int i = 0; i < d; i++) {
int x = io.nextInt() - 1;
int y = io.nextInt() - 1;
if (!uf.connected(x, y)) {
int sizeX = uf.sizes[uf.find(x)];
int sizeY = uf.sizes[uf.find(y)];
multiSet.remove(new Pair(uf.find(x), sizeX));
multiSet.remove(new Pair(uf.find(y), sizeY));
uf.union(x, y);
int id = uf.find(x);
multiSet.add(new Pair(id, uf.sizes[id]));
} else {
count++;
}
int sum = 0;
int c = count;
for (Pair p : multiSet)
if (c-- > 0) {
sum += p.val;
}
io.println(sum - 1);
}
io.flush();
}
static class Pair implements Comparable<Pair> {
int id, val;
public Pair(int id, int val) {
this.id = id;
this.val = val;
}
@Override
public int compareTo(Pair o) {
if (val == o.val) {
return Integer.compare(id, o.id);
}
return -Integer.compare(val, o.val);
}
}
private static class DisjointSets {
int[] parents; // 0-indexed
int[] sizes;
public DisjointSets(int size) {
sizes = new int[size];
parents = new int[size];
Arrays.fill(sizes, 1);
Arrays.fill(parents, -1);
}
// finds the "representative" node in a's component
public int find(int x) {
return parents[x] == -1 ? x : (parents[x] = find(parents[x]));
}
// returns whether the merge changed connectivity
public boolean union(int x, int y) {
int xRoot = find(x);
int yRoot = find(y);
if (xRoot == yRoot) {
return false;
}
if (sizes[xRoot] < sizes[yRoot]) {
parents[xRoot] = yRoot;
sizes[yRoot] += sizes[xRoot];
} else {
parents[yRoot] = xRoot;
sizes[xRoot] += sizes[yRoot];
}
return true;
}
// returns whether two nodes are in the same connected component
public boolean connected(int x, int y) {
return find(x) == find(y);
}
}
private 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 int nextInt() { // nextLong() would be implemented similarly
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 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 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 | c7efdace1cd3f516ad33953886b76212 | 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.math.*;
import java.io.*;
import java.util.stream.Collectors;
import java.text.DecimalFormat;
public class A{
static FastScanner scan=new FastScanner();
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
static int cnt=0;
static LinkedList<Integer>edges[];
static boolean vis[];
static void dfs(int x)
{
vis[x]=true;
cnt++;
for(int v:edges[x])
{
if(!vis[v])
{
dfs(v);
}
}
}
static boolean vis2[];
static void dfs3(int x)
{
vis2[x]=true;
res[x]=Math.max(res[x]+1,cnt);
for(int v:edges[x])
{
if(!vis2[v])
{
dfs3(v);
}
}
}
static void dfs2(int x)
{
vis[x]=true;
res[x]++;
for(int v:edges[x])
{
if(!vis[v])
{
dfs2(v);
}
}
}
static int res[];
public static void main(String[] args) throws Exception
{
int tt=1;
// tt=scan.nextInt();
// scan=new FastScanner("clumsy.in");
//out=new PrintWriter("clumsy.out");
outer:while(tt-->0)
{
int n=scan.nextInt(),d=scan.nextInt();
edges=new LinkedList[n];
for(int i=0;i<n;i++)edges[i]=new LinkedList();
vis=new boolean[n];
res=new int[n];
DSU ds=new DSU(n);
int have=0;
for(int i=0;i<d;i++)
{
vis=new boolean[n];
int x=scan.nextInt()-1,y=scan.nextInt()-1;
edges[x].add(y);
edges[y].add(x);
if(ds.iscon(x,y))
{
have++;
}
cnt=0;
ds.union(x,y);
ArrayList<Integer>comps=new ArrayList<Integer>();
for(int j=0;j<n;j++)
{
if(!vis[j])
{
cnt=0;
dfs(j);
comps.add(cnt);
}
}
Collections.sort(comps);
Collections.reverse(comps);
int nw=0;
for(int j=0;j<Math.min(have+1,comps.size());j++)nw+=comps.get(j);
out.println(nw-1);
}
}
out.close();
}
static class DSU{
int par[],size[];
public DSU(int n)
{
par=new int[n];
size=new int[n];
for(int i=0;i<n;i++){
par[i]=i;
size[i]=1;
}
}
int find(int x)
{
if(x==par[x])
return x;
return find(par[x]);
}
void union(int x,int y)
{
x=find(x);
y=find(y);
if(x==y)
return;
if(size[x]<=size[y])
{
size[y]+=size[x];
par[x]=y;
}
else {
size[x]+=size[y];
par[y]=x;
}
}
boolean iscon(int x,int y)
{
return find(x)==find(y);
}
}
static class FastScanner
{
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] nextDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
static class Pair implements Comparable<Pair>{
public long x, y,z;
public Pair(long x1, long y1,long z1) {
x=x1;
y=y1;
z=z1;
}
public Pair(long x1, long y1) {
x=x1;
y=y1;
}
@Override
public int hashCode() {
return (int)(x + 31 * y);
}
public String toString() {
return x + " " + y+" "+z;
}
@Override
public boolean equals(Object o){
if (o == this) return true;
if (o.getClass() != getClass()) return false;
Pair t = (Pair)o;
return t.x == x && t.y == y&&t.z==z;
}
public int compareTo(Pair o)
{
//if(o.x==x)
// return (int)(y-o.y);
return Long.compare(o.x,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 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 | 12e10070bed8411eb717c3bb24a09f52 | 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.math.*;
import java.io.*;
import java.util.stream.Collectors;
import java.text.DecimalFormat;
public class A{
static FastScanner scan=new FastScanner();
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
static int cnt=0;
static LinkedList<Integer>edges[];
static boolean vis[];
static void dfs(int x)
{
vis[x]=true;
cnt++;
for(int v:edges[x])
{
if(!vis[v])
{
dfs(v);
}
}
}
static boolean vis2[];
static void dfs3(int x)
{
vis2[x]=true;
res[x]=Math.max(res[x]+1,cnt);
for(int v:edges[x])
{
if(!vis2[v])
{
dfs3(v);
}
}
}
static void dfs2(int x)
{
vis[x]=true;
res[x]++;
for(int v:edges[x])
{
if(!vis[v])
{
dfs2(v);
}
}
}
static int res[];
public static void main(String[] args) throws Exception
{
int tt=1;
// tt=scan.nextInt();
// scan=new FastScanner("clumsy.in");
//out=new PrintWriter("clumsy.out");
outer:while(tt-->0)
{
int n=scan.nextInt(),d=scan.nextInt();
edges=new LinkedList[n];
for(int i=0;i<n;i++)edges[i]=new LinkedList();
vis=new boolean[n];
res=new int[n];
DSU ds=new DSU(n);
int have=0;
for(int i=0;i<d;i++)
{
vis=new boolean[n];
vis2=new boolean[n];
int x=scan.nextInt()-1,y=scan.nextInt()-1;
edges[x].add(y);
edges[y].add(x);
if(ds.iscon(x,y))
{
have++;
}
cnt=0;
dfs(x);
dfs3(x);
vis=new boolean[n];
ds.union(x,y);
ArrayList<Integer>comps=new ArrayList<Integer>();
for(int j=0;j<n;j++)
{
if(!vis[j])
{
cnt=0;
dfs(j);
comps.add(cnt);
}
}
Collections.sort(comps);
Collections.reverse(comps);
int nw=0;
for(int j=0;j<Math.min(have+1,comps.size());j++)nw+=comps.get(j);
out.println(nw-1);
}
}
out.close();
}
static class DSU{
int par[],size[];
public DSU(int n)
{
par=new int[n];
size=new int[n];
for(int i=0;i<n;i++){
par[i]=i;
size[i]=1;
}
}
int find(int x)
{
if(x==par[x])
return x;
return find(par[x]);
}
void union(int x,int y)
{
x=find(x);
y=find(y);
if(x==y)
return;
if(size[x]<=size[y])
{
size[y]+=size[x];
par[x]=y;
}
else {
size[x]+=size[y];
par[y]=x;
}
}
boolean iscon(int x,int y)
{
return find(x)==find(y);
}
}
static class FastScanner
{
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] nextDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
static class Pair implements Comparable<Pair>{
public long x, y,z;
public Pair(long x1, long y1,long z1) {
x=x1;
y=y1;
z=z1;
}
public Pair(long x1, long y1) {
x=x1;
y=y1;
}
@Override
public int hashCode() {
return (int)(x + 31 * y);
}
public String toString() {
return x + " " + y+" "+z;
}
@Override
public boolean equals(Object o){
if (o == this) return true;
if (o.getClass() != getClass()) return false;
Pair t = (Pair)o;
return t.x == x && t.y == y&&t.z==z;
}
public int compareTo(Pair o)
{
//if(o.x==x)
// return (int)(y-o.y);
return Long.compare(o.x,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 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 | 6e7aeeb2477336e84dfd4561a909fb23 | 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.File;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
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
// D. Social Network
// https://codeforces.com/contest/1609/problem/D
// time limit per test 2 seconds; memory limit per test 256 megabytes
//
// 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 xi to have a connection to person yi.
// Formally, two people x and y have a connection if there is such a chain p1=x,p2,p3,...,pk=y for
// which for all i from 1 to k-1 it's true that two people with numbers pi and pi+1 know each other.
//
// For every i (1<=i<=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.
//
// Input
//
// The first line contains two integers n and d (2<=n<=10^3,1<=d<=n-1), the number of people, and
// number of conditions, respectively.
//
// Each of the next d lines each contain two integers xi and yi (1<=xi,yi<=n,xi!=yi), the numbers of
// people which must have a connection according to condition i.
//
// Output
//
// Output d integers. ith 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.
//
// Example
/*
input:
7 6
1 2
3 4
2 4
7 6
6 5
1 7
output:
1
1
3
3
3
6
input:
10 8
1 2
2 3
3 4
1 4
6 7
8 9
8 10
1 4
output:
1
2
3
4
5
5
6
8
*/
// Note
//
// The 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.
// https://espresso.codeforces.com/758cd71474e38e42aa7fbd9646140431c4e6641c.png
public class C1609D {
static final int MOD = (int)1e9+7;
static final Random RAND = new Random();
static int[] solve(int n, int[][] a) {
int d = a.length;
int[] ans = new int[d];
UnionFind uf = new UnionFind(n + 1);
for (int i = 0; i < d; i++) {
int x = a[i][0];
int y = a[i][1];
uf.union(x, y);
ans[i] = uf.getAns(i + 1);
}
return ans;
}
static class UnionFind {
int n;
int[] gids;
// sizes[i] is the size of group i of 0 if group i is no longer outstanding
int[] sizes;
public UnionFind(int n) {
this.n = n;
this.gids = new int[n];
for (int i = 0; i < n; i++) {
gids[i] = i;
}
this.sizes = new int[n];
Arrays.fill(sizes, 1);
}
public int union(int i, int j) {
int ri = find(i);
int rj = find(j);
if (ri == rj) {
return ri;
}
int id = Math.min(ri, rj);
int max = Math.max(ri, rj);
sizes[id] = sizes[ri] + sizes[rj];
sizes[max] = 0;
// Note that we must set gids[ri] instead of gids[i] etc
gids[ri] = id;
gids[rj] = id;
return id;
}
public int find(int i) {
while (i != gids[i]) {
gids[i] = gids[gids[i]];
i = gids[i];
}
return i;
}
// Get
public int getAns(int k) {
List<Integer> nums = new ArrayList<>();
int budget = 0;
for (int v : sizes) {
if (v > 0) {
nums.add(v);
budget += v - 1;
}
}
Collections.sort(nums, Collections.reverseOrder());
int sum = 0;
for (int i = 0; i <= k - budget; i++) {
sum += nums.get(i);
}
return sum -1;
}
}
public static void main(String[] args) {
Scanner in = getInputScanner();
int n = in.nextInt();
int d = in.nextInt();
int[][] a = new int[d][2];
for (int i = 0; i < d; i++) {
a[i][0] = in.nextInt();
a[i][1] = in.nextInt();
}
int[] ans = solve(n, a);
StringBuilder sb = new StringBuilder();
for (int v : ans) {
sb.append(v);
sb.append(' ');
}
System.out.println(sb.toString());
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);
}
}
}
| 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 | 22d6597098cd3bf889e26103d7a0147e | 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 {
private static int get_parent(int[] dsu, int node) {
if (dsu[node] == node) {
return node;
}
dsu[node] = get_parent(dsu, dsu[node]);
return dsu[node];
}
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 D = Integer.parseInt(line[1]);
int[] X = new int[D+1];
int[] Y = new int[D+1];
int[] dsu = new int[N+1];
int[] size = new int[N+1];
for (int i=1; i<=D; i++) {
line = in.readLine().split(" ");
X[i] = Integer.parseInt(line[0]);
Y[i] = Integer.parseInt(line[1]);
//out.write(X[i] + " " + Y[i] + "\n");
for (int v=1; v<=N; v++) {
dsu[v] = v;
size[v] = 1;
}
int spare = 0;
for (int k=1; k<=i; k++) {
int px = get_parent(dsu, X[k]);
int py = get_parent(dsu, Y[k]);
if (px != py) {
//size optimization
if (size[py] > size[px]) {
dsu[px] = py;
size[py] += size[px];
} else {
dsu[py] = px;
size[px] += size[py];
}
} else {
spare++;
}
}
/*out.write(i + " **** " + "\n");
for (int v=1; v<=N; v++) {
out.write(v + " " + get_parent(dsu, v) + " " + size[get_parent(dsu, v)] + "\n");
}*/
List<Integer> disjoints = new ArrayList<>();
for (int v=1; v<=N; v++) {
if (get_parent(dsu, v) == v) {
disjoints.add(size[v]);
}
}
Collections.sort(disjoints, Collections.reverseOrder());
/*out.write(i + " **** " + "\n");
for (final Integer sz : disjoints) {
out.write(sz + " ");
}
out.write("\n");*/
int ans = disjoints.get(0);
for (int sp=1; sp<=spare; sp++) {
ans += disjoints.get(sp);
}
out.write(ans - 1 + "\n");
}
in.close();
out.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 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 | b893f1a933857902fbc22d9864c3c2fc | 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 {
private static int get_parent(int[] dsu, int node) {
if (dsu[node] == node) {
return node;
}
dsu[node] = get_parent(dsu, dsu[node]);
return dsu[node];
}
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 D = Integer.parseInt(line[1]);
int[] X = new int[D+1];
int[] Y = new int[D+1];
int[] dsu = new int[N+1];
int[] size = new int[N+1];
for (int i=1; i<=D; i++) {
line = in.readLine().split(" ");
X[i] = Integer.parseInt(line[0]);
Y[i] = Integer.parseInt(line[1]);
//out.write(X[i] + " " + Y[i] + "\n");
for (int v=1; v<=N; v++) {
dsu[v] = v;
size[v] = 1;
}
int spare = 0;
for (int k=1; k<=i; k++) {
int px = get_parent(dsu, X[k]);
int py = get_parent(dsu, Y[k]);
if (px != py) {
//size optimization
if (size[py] > size[px]) {
dsu[px] = py;
size[py] += size[px];
} else {
dsu[py] = px;
size[px] += size[py];
}
} else {
spare++;
}
}
/*out.write(i + " **** " + "\n");
for (int v=1; v<=N; v++) {
out.write(v + " " + get_parent(dsu, v) + " " + size[get_parent(dsu, v)] + "\n");
}*/
List<Integer> disjoints = new ArrayList<>();
for (int v=1; v<=N; v++) {
if (get_parent(dsu, v) == v) {
disjoints.add(size[v]);
}
}
Collections.sort(disjoints, Collections.reverseOrder());
/*out.write(i + " **** " + "\n");
for (final Integer sz : disjoints) {
out.write(sz + " ");
}
out.write("\n");*/
int ans = disjoints.get(0);
for (int sp=1; sp<=spare; sp++) {
// check after contest
if (sp>=disjoints.size()) {
continue;
}
ans += disjoints.get(sp);
}
out.write(ans - 1 + "\n");
}
in.close();
out.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 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 | fa9141fb74b752b4366dfe07ba94ba8c | 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) throws java.lang.Exception {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solution solver = new Solution();
boolean isTest = false;
int tC = isTest ? Integer.parseInt(in.next()) : 1;
for (int i = 1; i <= tC; i++)
solver.solve(in, out, i);
out.close();
}
/* ............................................................. */
static class Solution {
InputReader in;
PrintWriter out;
public void solve(InputReader in, PrintWriter out, int test) {
this.in = in;
this.out = out;
int n=ni();
int d=ni();
int max=1;
DSU dsu=new DSU(n);
int c=0;
for(int i=0;i<d;i++) {
int u=ni()-1;
int v=ni()-1;
boolean q=dsu.unite(u, v);
if(!q){
c++;
}
ArrayList<Integer> arr=new ArrayList<>();
for(int j=0;j<n;j++){
if(dsu.par[j]<0)arr.add(dsu.par[j]);
}
Collections.sort(arr);
int ans=0;
for(int j=0;j<Math.min(arr.size(),c+1);j++){
ans=ans+Math.abs(arr.get(j));
}
out.println(ans-1);
}
}
class DSU {
int n;
int par[];
DSU(int n) {
this.n = n;
par = new int[n + 1];
Arrays.fill(par, -1);
}
int find(int x) {
return par[x] < 0 ? x : find(par[x]);
}
boolean unite(int x, int y) {
int p1 = find(x);
int p2 = find(y);
if (p1 == p2)
return false;
if (par[p1] < par[p2]) {
par[p1]=par[p1]+par[p2];
par[p2] = p1;
} else {
par[p2]=par[p1]+par[p2];
par[p1] = p2;
}
return true;
}
}
class Pair {
int x;
int y;
long w;
Pair(int x, int y, long w) {
this.x = x;
this.y = y;
this.w = w;
}
}
char[] n() {
return in.next().toCharArray();
}
int ni() {
return in.nextInt();
}
long nl() {
return in.nextLong();
}
long[] nal(int n) {
long a[] = new long[n];
for (int i = 0; i < n; i++)
a[i] = nl();
return a;
}
void pn(long zx) {
out.println(zx);
}
void pn(String sz) {
out.println(sz);
}
void pn(double dx) {
out.println(dx);
}
void pn(long ar[]) {
for (int i = 0; i < ar.length; i++)
out.print(ar[i] + " ");
out.println();
}
void pn(String ar[]) {
for (int i = 0; i < ar.length; i++)
out.println(ar[i]);
}
}
/* ......................Just Input............................. */
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());
}
}
/* ......................Just Input............................. */
} | 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 | 8b0837c4a475859cf0d453db06640398 | 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.HashMap;
import java.util.TreeSet;
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: 18:54:51 28/11/2021
Custom Competitive programming helper.
*/
public class Main {
public static void solve() {
ts = new TreeSet<>();
pMap = new HashMap<>();
int n = in.nextInt(), d = in.nextInt();
DSU ds = new DSU(n);
int extras = 0;
for(int i = 0; i<d; i++) {
int u = in.nextInt()-1, v = in.nextInt()-1;
if(!ds.union(u, v)) extras++;
ArrayList<Pair> take = new ArrayList<>();
Pair da = ts.pollLast();
take.add(da);
int ans = da.sz;
for(int j = 0; j<extras; j++) {
Pair x = ts.pollLast();
ans += x.sz;
take.add(x);
}
for(Pair p : take) ts.add(p);
out.println(ans-1);
}
}
static class Pair implements Comparable<Pair>{
int person, sz;
public Pair(int person, int sz) {
this.person = person;
this.sz = sz;
}
public String toString() {
return person +","+sz;
}
@Override
public int compareTo(Pair o) {
if(this.sz == o.sz) return this.person-o.person;
return this.sz - o.sz;
}
}
static HashMap<Integer, Pair> pMap;
static TreeSet<Pair> ts;
static class DSU{
int n;
int[] parent;
public DSU(int n) {
this.n = n;
parent = new int[n];
for(int i = 0; i<n; i++) {
parent[i] = i;
Pair p = new Pair(i, 1);
ts.add(p);
pMap.put(i, p);
}
}
public int find(int i){
if(parent[i]==i) return i;
return parent[i] = find(parent[i]);
}
public boolean union(int i, int j){
int pI = find(i), pJ = find(j);
if(pI==pJ) return false; //Already united
parent[pI] = pJ;
Pair one = pMap.get(pI), two = pMap.get(pJ);
ts.remove(one);
ts.remove(two);
pMap.remove(pI);
pMap.remove(pJ);
Pair p = new Pair(pJ, one.sz + two.sz);
ts.add(p);
pMap.put(pJ, p);
return true;
}
}
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 | ["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 | 3708918f4eb7d8e03002c0085f4e4f89 | 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 Solution {
static Scanner sc;
public static void main (String[] args) {
sc = new Scanner(System.in);
solve();
}
static boolean ans;
public static void solve() {
int n = sc.nextInt();
int d = sc.nextInt();
int[]parent = new int[n+1];
int[]rank = new int[n+1];
int[]size = new int[n+1];
for(int i = 1;i<=n;i++){
parent[i] = i;
size[i] = 1;
}
int extra = 0;
for(int i = 0;i<d;i++){
int u = sc.nextInt();
int v = sc.nextInt();
if(find(u,parent) == find(v,parent)){
extra++;
}
else{
union(u,v,parent,rank,size);
}
PriorityQueue<Integer>pq = new PriorityQueue<>((a,b)->(b - a));
for(int j = 1;j<=n;j++){
pq.offer(size[j]);
}
long sum = pq.poll();
for(int j = 0;j<extra;j++){
sum += pq.poll();
}
System.out.println(sum - 1);
}
}
public static int find(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;
}
}
} | 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 | 124a426b2986e64509b6b3e9f8350796 | 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.text.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
PrintWriter writer = new PrintWriter(System.out);
int t = 1;
while(t-->0) {
int n = sc.nextInt();
int m = sc.nextInt();
int arr[] = new int[n+1];
int size[] = new int[n+1];
Arrays.fill(size, 1);
for(int i = 1; i<=n;i++)arr[i]=i;
int extra = 1;
while(m-->0) {
int aa = sc.nextInt();
int bb = sc.nextInt();
if(find(aa,arr) != find(bb,arr) ) {
union(aa,bb,arr,size);
}else {
extra++;
}
boolean vis[] = new boolean [n+1];
ArrayList<Integer> list = new ArrayList<>();
for(int i = 1; i <= n; i++) {
int par = find(i,arr);
if(!vis[par]) {
list.add(size[par]);
vis[par] = true;
}
}
Collections.sort(list, Collections.reverseOrder());
long sum = 0;
int extraa = extra;
for(int i = 0; i < list.size() && extraa > 0; i++, extraa--) {
sum+=list.get(i);
}
writer.println(sum-1);
}
}
writer.flush();
writer.close();
}
private static long power (long a, long n, long p) {
long res = 1;
while(n!=0) {
if(n%2==1) {
res=(res*a)%p;
n--;
}else {
a= (a*a)%p;
n/=2;
}
}
return res;
}
private static boolean isPrime(int c) {
for (int i = 2; i*i <= c; i++) {
if(c%i==0)return false;
}
return true;
}
private static int find(int a , int arr[]) {
if(arr[a] != a) return arr[(int)a] = find(arr[(int)a], arr);
return arr[(int)a];
}
private static void union(int a, int b, int arr[], int size[]) {
int aa = find(a,arr);
int bb = find(b, arr);
if(aa!=bb) {
if(size[bb] > size[aa]) {
int temp = bb;
bb = aa;
aa = temp;
}
arr[bb] = aa;
size[aa]+=size[bb];
}
}
private static int gcd(int a, int b) {
if(a==0)return b;
return gcd(b%a, a);
}
public static int[] readIntArray(int size, FastReader s) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = s.nextInt();
}
return array;
}
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;
}
}
}
class SegmentTree{
int size;
long arr[];
SegmentTree(int n){
size = 1;
while(size<n)size*=2;
arr = new long[size*2];
}
public void build(int input[]) {
build(input, 0,0, size);
}
public void set(int i, int v) {
set(i,v,0,0,size);
}
// sum from l + r-1
public long sum(int l, int r) {
return sum(l,r,0,0,size);
}
private void build(int input[], int x, int lx, int rx) {
if(rx-lx==1) {
if(lx < input.length )
arr[x] = 1;
return;
}
int mid = (lx+rx)/2;
build(input, 2*x+1, lx, mid);
build(input,2*x+2,mid,rx);
arr[x] = arr[2*x+1] + arr[2*x+2];
}
private void set(int i, int v, int x, int lx, int rx) {
if(rx-lx==1) {
arr[x] = v;
return;
}
int mid = (lx+rx)/2;
if(i < mid) set(i, v, 2*x+1, lx, mid);
else set(i,v,2*x+2,mid,rx);
arr[x] = arr[2*x+1] + arr[2*x+2];
}
private long sum(int l, int r, int x, int lx, int rx) {
if(lx>=r || rx <= l)return 0;
if(lx>=l && rx <= r)return arr[x];
int mid = (lx+rx)/2;
long s1 = sum(l,r,2*x+1,lx,mid);
long s2 = sum(l,r,2*x+2,mid,rx);
return s2+s1;
}
// int first_above(int v, int l, int x, int lx, int rx) {
// if(arr[x].a<v)return -1;
// if(rx<=l)return -1;
// if(rx-lx==1)return lx;
// int m = (lx+rx)/2;
// int res = first_above(v,l,2*x+1,lx,m);
// if(res==-1)res = first_above(v,l,2*x+2,m,rx);
// return res;
//
// }
}
class Trie{
Trie arr[] = new Trie[26];
boolean isEnd;
Trie(){
for(int i = 0; i < 26; i++)arr[i] = null;
isEnd = false;
}
}
class Pair implements Comparable<Pair>{
long a;
long b;
long c;
Pair(long a, long b, long c){
this.a = a;
this.b = b;
this.c = c;
}
Pair(long a, long b){
this.a = a;
this.b = b;
this.c = 0;
}
@Override
public boolean equals(Object obj) {
if(this == obj) return true;
if(obj == null || obj.getClass()!= this.getClass()) return false;
Pair pair = (Pair) obj;
return (pair.a == this.a && pair.b == this.b && pair.c == this.c);
}
@Override
public int compareTo(Pair o) {
// if(o.a != this.a) return Long.compare(this.a, o.a);
// else
return Long.compare(this.b, o.b);
}
@Override
public String toString() {
return this.a + " " + this.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 | 8fd2002338a8b94fe74272f89cd66708 | 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 | //Utilities
import java.io.*;
import java.util.*;
public class a {
static int t;
static int n, d;
static int x, y;
static int[] dsu, rank, sz;
static int extra;
static HashSet<Integer> group;
static int max;
public static void main(String[] args) throws IOException {
t = 1;
while (t-- > 0) {
n = in.iscan(); d = in.iscan();
dsu = new int[n+1]; rank = new int[n+1]; sz = new int[n+1];
for (int i = 0; i <= n; i++) {
dsu[i] = i; rank[i] = 0; sz[i] = 1;
}
extra = 0;
group = new HashSet<Integer>();
for (int i = 1; i <= n; i++) {
group.add(i);
}
while (d-- > 0) {
x = in.iscan(); y = in.iscan();
int rx = find(x), ry = find(y);
if (rx == ry) {
extra++;
}
else {
union(rx, ry);
}
ArrayList<Integer> tmp = new ArrayList<Integer>();
for (int x : group) {
tmp.add(sz[x]);
}
Collections.sort(tmp, Collections.reverseOrder());
// out.println(tmp + " " + extra);
max = tmp.get(0);
int e = extra, idx = 1;
while (e > 0 && idx < tmp.size()) {
max += tmp.get(idx);
idx++;
e--;
}
max += e;
max--;
out.println(max);
}
}
out.close();
}
static int find(int idx) {
if (dsu[idx] == idx) {
return idx;
}
return find(dsu[idx]);
}
static void union(int rx, int ry) {
if (rank[rx] < rank[ry]) {
dsu[rx] = ry;
sz[ry] += sz[rx];
group.remove(rx);
}
else if (rank[rx] == rank[ry]) {
dsu[rx] = ry;
rank[ry]++;
sz[ry] += sz[rx];
group.remove(rx);
}
else {
dsu[ry] = rx;
sz[rx] += sz[ry];
group.remove(ry);
}
}
static INPUT in = new INPUT(System.in);
static PrintWriter out = new PrintWriter(System.out);
private static class INPUT {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public INPUT (InputStream stream) {
this.stream = stream;
}
public INPUT (String file) throws IOException {
this.stream = new FileInputStream (file);
}
public int cscan () throws IOException {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read (buf);
}
if (numChars == -1)
return numChars;
return buf[curChar++];
}
public int iscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
int res = 0;
do {
res = (res << 1) + (res << 3);
res += c - '0';
c = cscan ();
}
while (!space (c));
return res * sgn;
}
public String sscan () throws IOException {
int c = cscan ();
while (space (c))
c = cscan ();
StringBuilder res = new StringBuilder ();
do {
res.appendCodePoint (c);
c = cscan ();
}
while (!space (c));
return res.toString ();
}
public double dscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
double res = 0;
while (!space (c) && c != '.') {
if (c == 'e' || c == 'E')
return res * UTILITIES.fast_pow (10, iscan ());
res *= 10;
res += c - '0';
c = cscan ();
}
if (c == '.') {
c = cscan ();
double m = 1;
while (!space (c)) {
if (c == 'e' || c == 'E')
return res * UTILITIES.fast_pow (10, iscan ());
m /= 10;
res += (c - '0') * m;
c = cscan ();
}
}
return res * sgn;
}
public long lscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
long res = 0;
do {
res = (res << 1) + (res << 3);
res += c - '0';
c = cscan ();
}
while (!space (c));
return res * sgn;
}
public boolean space (int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
public static class UTILITIES {
static final double EPS = 10e-6;
public static void sort(int[] a, boolean increasing) {
ArrayList<Integer> arr = new ArrayList<Integer>();
int n = a.length;
for (int i = 0; i < n; i++) {
arr.add(a[i]);
}
Collections.sort(arr);
for (int i = 0; i < n; i++) {
if (increasing) {
a[i] = arr.get(i);
}
else {
a[i] = arr.get(n-1-i);
}
}
}
public static void sort(long[] a, boolean increasing) {
ArrayList<Long> arr = new ArrayList<Long>();
int n = a.length;
for (int i = 0; i < n; i++) {
arr.add(a[i]);
}
Collections.sort(arr);
for (int i = 0; i < n; i++) {
if (increasing) {
a[i] = arr.get(i);
}
else {
a[i] = arr.get(n-1-i);
}
}
}
public static void sort(double[] a, boolean increasing) {
ArrayList<Double> arr = new ArrayList<Double>();
int n = a.length;
for (int i = 0; i < n; i++) {
arr.add(a[i]);
}
Collections.sort(arr);
for (int i = 0; i < n; i++) {
if (increasing) {
a[i] = arr.get(i);
}
else {
a[i] = arr.get(n-1-i);
}
}
}
public static int lower_bound (int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= x)
high = mid;
else
low = mid + 1;
}
return low;
}
public static int upper_bound (int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] > x)
high = mid;
else
low = mid + 1;
}
return low;
}
public static void updateMap(HashMap<Integer, Integer> map, int key, int v) {
if (!map.containsKey(key)) {
map.put(key, v);
}
else {
map.put(key, map.get(key) + v);
}
if (map.get(key) == 0) {
map.remove(key);
}
}
public static long gcd (long a, long b) {
return b == 0 ? a : gcd (b, a % b);
}
public static long lcm (long a, long b) {
return a * b / gcd (a, b);
}
public static long fast_pow_mod (long b, long x, int mod) {
if (x == 0) return 1;
if (x == 1) return b;
if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod;
return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod;
}
public static long fast_pow (long b, long x) {
if (x == 0) return 1;
if (x == 1) return b;
if (x % 2 == 0) return fast_pow (b * b, x / 2);
return b * fast_pow (b * b, x / 2);
}
public static long choose (long n, long k) {
k = Math.min (k, n - k);
long val = 1;
for (int i = 0; i < k; ++i)
val = val * (n - i) / (i + 1);
return val;
}
public static long permute (int n, int k) {
if (n < k) return 0;
long val = 1;
for (int i = 0; i < k; ++i)
val = (val * (n - i));
return val;
}
// start of permutation and lower/upper bound template
public static void nextPermutation(int[] nums) {
//find first decreasing digit
int mark = -1;
for (int i = nums.length - 1; i > 0; i--) {
if (nums[i] > nums[i - 1]) {
mark = i - 1;
break;
}
}
if (mark == -1) {
reverse(nums, 0, nums.length - 1);
return;
}
int idx = nums.length-1;
for (int i = nums.length-1; i >= mark+1; i--) {
if (nums[i] > nums[mark]) {
idx = i;
break;
}
}
swap(nums, mark, idx);
reverse(nums, mark + 1, nums.length - 1);
}
public static void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
public static void reverse(int[] nums, int i, int j) {
while (i < j) {
swap(nums, i, j);
i++;
j--;
}
}
static int lower_bound (int[] arr, int hi, int cmp) {
int low = 0, high = hi, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= cmp) high = mid;
else low = mid + 1;
}
return low;
}
static int upper_bound (int[] arr, int hi, int cmp) {
int low = 0, high = hi, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] > cmp) high = mid;
else low = mid + 1;
}
return low;
}
// end of permutation and lower/upper bound template
}
} | 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 | 8be4861a6ecaee4c304254522c8e6474 | 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.lang.reflect.Array;
import java.util.*;
public class Main {
private static class IO extends PrintWriter {
private BufferedReader reader;
private StringTokenizer st;
public IO() {
super(System.out);
reader = new BufferedReader(new InputStreamReader(System.in));
}
public String nextToken() throws IOException {
while(st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(reader.readLine());
}
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
}
public static void main(String[] args) throws Exception {
IO io = new IO();
int n = io.nextInt(), k = io.nextInt();
int[] p = new int[n + 1];
int[] s = new int[n + 1];
int max = 1;
ArrayList<Integer> o = new ArrayList<>();
for (int i = 1; i <= n; i++) {
p[i] = i;
s[i] = 1;
o.add(1);
}
int w = 0;
for (int i = 0; i < k; i++) {
int x = io.nextInt(), y = io.nextInt();
int xr = f(p, x), yr = f(p, y);
if (xr != yr) {
p[xr] = yr;
o.remove(new Integer(s[xr]));
o.remove(new Integer(s[yr]));
s[yr] += s[xr];
o.add(new Integer(s[yr]));
max = Math.max(max, s[yr]);
} else {
w++;
}
Collections.sort(o);
int a = 0;
int c = w, d = o.size() - 2;
while (c > 0 && d >= 0) {
a += o.get(d);
c--;
d--;
}
io.println(max + a - 1);
}
io.close();
}
private static int f(int[] p, int r) {
while (p[r] != r) {
r = p[r] = p[p[r]];
}
return 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 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 | 51fcdccb2c826555fb0820ee627cd3d1 | 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.Iterator;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) {
int n = fs.nextInt();
int d = fs.nextInt();
// union-find, but since some introductions
// merge already-joined groups,
// we can use those "free" moves to join the largest groups
int freeIntroductions = 0;
TreeSet<Pair> ts = new TreeSet<>();
for (int i = 1; i<= n; i++) {
ts.add(Pair.from(1, i));
}
int[] leader = new int[n+1];
int[] groupSize = new int[n+1];
for (int i = 0; i < n; i++) {
leader[i] = i;
groupSize[i] = 1;
}
while (d-- > 0) {
int s = fs.nextInt(), t = fs.nextInt();
int sLeader = calculateLeader(s, leader);
int tLeader = calculateLeader(t, leader);
int sSize = groupSize[sLeader];
int tSize = groupSize[tLeader];
if (sLeader == tLeader) {
freeIntroductions++;
} else {
if (sSize >= tSize) {
mergeInto(tLeader, sLeader, leader, groupSize);
removeFromTS(ts, Pair.from(tSize, tLeader));
removeFromTS(ts, Pair.from(sSize, sLeader));
addToTS(ts, Pair.from(groupSize[sLeader], sLeader));
} else {
mergeInto(sLeader, tLeader, leader, groupSize);
removeFromTS(ts, Pair.from(tSize, tLeader));
removeFromTS(ts, Pair.from(sSize, sLeader));
addToTS(ts, Pair.from(groupSize[tLeader], tLeader));
}
}
// use free moves to join the largest components, then subtract 1
// since an individual in the resulting mega-component C knows |C|-1
int ansToPrint = sumLargestK(ts, freeIntroductions+1) - 1;
o.println(ansToPrint);
}
o.flush();
}
private static int sumLargestK(TreeSet<Pair> ts, int k) {
Iterator<Pair> it = ts.descendingIterator();
int ans = 0;
while (k-- >0) {
ans += it.next().first;
}
return ans;
}
private static void addToTS(TreeSet<Pair> ts, Pair pr) {
ts.add(pr);
}
private static void removeFromTS(TreeSet<Pair> ts, Pair pr) {
ts.remove(pr);
}
private static void mergeInto(int tLeader, int sLeader, int[] leader, int[] groupSize) {
leader[tLeader] = sLeader;
groupSize[sLeader] += groupSize[tLeader];
}
private static int calculateLeader(int i, int[] leader) {
int iLeader = i;
while (iLeader != leader[iLeader]) {
iLeader = leader[iLeader];
}
return iLeader;
}
static FastScanner fs = new FastScanner();
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());
}
}
static PrintWriter o = new PrintWriter(new OutputStreamWriter(System.out));
}
class Pair implements Comparable<Pair> {
int first;
int second;
private Pair(int first, int second) {
this.first = first;
this.second = second;
}
static Pair from(int first, int second) {
return new Pair(first, second);
}
@Override
public int compareTo(Pair that) {
if (this.first == that.first) {
return this.second - that.second;
} else {
return this.first - that.first;
}
}
} | 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 | 8ce8959a145278a33916f4a8f032f163 | 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 CodeForces {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public void solve() throws Exception {
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int d = Integer.parseInt(st.nextToken());
Union union = new Union(n + 1);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < d; i++) {
st = new StringTokenizer(br.readLine());
int xi = Integer.parseInt(st.nextToken());
int yi = Integer.parseInt(st.nextToken());
union.merge(xi, yi);
ArrayList<Integer> list = new ArrayList<>();
for (int j = 1; j <= n; j++) {
if (j == union.getParent(j)) {
list.add(union.num[j]);
}
}
list.sort((e1, e2) -> (e2.compareTo(e1)));
int ans = 0;
for (int k = 0; k < union.extra; k++) {
ans += list.get(k);
}
sb.append(ans-1);
sb.append("\n");
}
System.out.print(sb.toString());
}
public void run() throws Exception {
// int t = Integer.parseInt(br.readLine());
// while (t-- > 0) {
// solve();
// }
solve();
}
public static void main(String[] args) throws Exception {
new CodeForces().run();
}
public class Union {
public int n;
int[] p;
int[] num;
int extra;
public Union(int n) {
extra = 1;
p = new int[n];
num = new int[n];
for (int i = 0; i < n; i++) {
p[i] = i;
num[i] = 1;
}
}
int getParent(int x) {
if (p[x] != x) {
p[x] = getParent(p[x]);
}
return p[x];
}
void merge(int x, int y) {
int fx = getParent(x);
int fy = getParent(y);
if (fx != fy) {
num[fy] += num[fx];
p[fx] = fy;
} else {
extra++;
}
}
}
}
| 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 | 377fa560ca35be354a8488a4de4d434a | 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.Map.Entry;
import java.math.*;
import java.sql.Array;
public class Simple{
public static class Pair implements Comparable<Pair>{
int x;
int y;
public Pair(int x,int y){
this.x = x;
this.y = y;
}
public int compareTo(Pair other){
return (int) (this.y - other.y);
}
public boolean equals(Pair other){
if(this.x == other.x && this.y == other.y)return true;
return false;
}
public int hashCode(){
return 31*x + y;
}
// @Override
// public int compareTo(Simple.Pair o) {
// // TODO Auto-generated method stub
// return 0;
// }
}
static int power(int x, int y, int p)
{
// Initialize result
int res = 1;
// Update x if it is more than or
// equal to p
x = x % p;
while (y > 0) {
// If y is odd, multiply x
// with result
if (y % 2 == 1)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// Returns n^(-1) mod p
static int modInverse(int n, int p)
{
return power(n, p - 2, p);
}
// Returns nCr % p using Fermat's
// little theorem.
static int nCrModPFermat(int n, int r,
int p)
{
if (n<r)
return 0;
// Base case
if (r == 0)
return 1;
// Fill factorial array so that we
// can find all factorial of r, n
// and n-r
int[] fac = new int[n + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = fac[i - 1] * i % p;
return (fac[n] * modInverse(fac[r], p)
% p * modInverse(fac[n - r], p)
% p)
% p;
}
static int nCrModp(int n, int r, int p)
{
if (r > n - r)
r = n - r;
// The array C is going to store last
// row of pascal triangle at the end.
// And last entry of last row is nCr
int C[] = new int[r + 1];
C[0] = 1; // Top row of Pascal Triangle
// One by constructs remaining rows of Pascal
// Triangle from top to bottom
for (int i = 1; i <= n; i++) {
// Fill entries of current row using previous
// row values
for (int j = Math.min(i, r); j > 0; j--)
// nCj = (n-1)Cj + (n-1)C(j-1);
C[j] = (C[j] + C[j - 1]) % p;
}
return C[r];
}
static int gcd(int a, int b)
{
// Everything divides 0
if (a == 0)
return b;
if (b == 0)
return a;
// base case
if (a == b)
return a;
// a is greater
if (a > b)
return gcd(a-b, b);
return gcd(a, b-a);
}
public static class Node{
int root;
ArrayList<Node> al;
Node par;
public Node(int root,ArrayList<Node> al,Node par){
this.root = root;
this.al = al;
this.par = par;
}
}
// public static int helper(int arr[],int n ,int i,int j,int dp[][]){
// if(i==0 || j==0)return 0;
// if(dp[i][j]!=-1){
// return dp[i][j];
// }
// if(helper(arr, n, i-1, j-1, dp)>=0){
// return dp[i][j]=Math.max(helper(arr, n, i-1, j-1,dp)+arr[i-1], helper(arr, n, i-1, j,dp));
// }
// return dp[i][j] = helper(arr, n, i-1, j,dp);
// }
// public static void dfs(ArrayList<ArrayList<Integer>> al,int levelcount[],int node,int count){
// levelcount[count]++;
// for(Integer x : al.get(node)){
// dfs(al, levelcount, x, count+1);
// }
// }
public static long __gcd(long a, long b)
{
if (b == 0)
return a;
return __gcd(b, a % b);
}
public static long helper(int arr1[][],int m){
Arrays.sort(arr1, (int a[],int b[])-> a[0]-b[0]);
long ans =0;
for(int i=1;i<m;i++){
long count =0;
for(int j=0;j<i;j++){
if(arr1[i][1] > arr1[j][1])count++;
}
ans+=count;
}
return ans;
}
public static class DSU{
int n;
int par[];
int rank[];
public DSU(int n){
this.n = n;
par = new int[n+1];
rank = new int[n+1];
for(int i=1;i<=n;i++){
par[i] = i ;
rank[i] = 0;
}
}
public int findPar(int node){
if(node==par[node]){
return node;
}
return par[node] = findPar(par[node]);//path compression
}
public void union(int u,int v){
u = findPar(u);
v = findPar(v);
if(rank[u]<rank[v]){
par[u] = v;
}
else if(rank[u]>rank[v]){
par[v] = u;
}
else{
par[v] = u;
rank[u]++;
}
}
}
public static void main(String args[]){
Scanner s = new Scanner(System.in);
int t =1;
for(int t1 = 1;t1<=t;t1++){
// System.out.println("OUT");
int n = s.nextInt();
int d = s.nextInt();
int arr[][] = new int[d][2];
for(int i=0;i<d;i++){
arr[i][0] = s.nextInt();
arr[i][1] = s.nextInt();
}
// int j =0;
DSU dsu = new DSU(n);
int x = 0;
for(int i=0;i<d;i++){
if(dsu.findPar(arr[i][0])!=dsu.findPar(arr[i][1])){
dsu.union(arr[i][0], arr[i][1]);
}
else{
x++;
}
int count[] = new int[n+1];
for(int j=1;j<=n;j++){
count[dsu.findPar(j)]++;
}
Arrays.sort(count);
int ans = 0;
int dx = x;
for(int j=n;j>=0 && dx>=0;j--){
ans+=count[j];
dx--;
}
ans--;
System.out.println(ans);
}
// System.out.println();
}
}
}
/*
4 2 2 7
0 2 5
-2 3
5
0*x1 + 1*x2 + 2*x3 + 3*x4
*/ | 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 | a286706c0ea109aeaa28e0937be1c80d | 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 | /*
_oo0oo_
o8888888o
88" . "88
(| -_- |)
0\ = /0
___/`---'\___
.' \\| |// '.
/ \\||| : |||// \
/ _||||| -:- |||||- \
| | \\\ - /// | |
| \_| ''\---/'' |_/ |
\ .-\__ '-' ___/-. /
___'. .' /--.--\ `. .'___
."" '< `.___\_<|>_/___.' >' "".
| | : `- \`.;`\ _ /`;.`/ - ` : | |
\ \ `_. \_ __\ /__ _/ .-` / /
=====`-.____`.___ \_____/___.-`___.-'=====
`=---='
*/
import java.util.*;
import java.math.*;
import java.io.*;
import java.lang.Math.*;
public class KickStart2020 {
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());
}
float nextFloat() {
return Float.parseFloat(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
public static class Pair implements Comparable<Pair> {
public int index;
public int value;
public Pair(int index, int value) {
this.index = index;
this.value = value;
}
@Override
public int compareTo(Pair other) {
// multiplied to -1 as the author need descending sort order
if(other.value < this.value) return 1;
if(other.value > this.value) return -1;
return 0;
}
@Override
public String toString() {
return this.index + " " + value;
}
}
static boolean isPrime(long d) {
if(d == 0) return true;
if (d == 1)
return false;
for (int i = 2; i <= (long) Math.sqrt(d); i++) {
if (d % i == 0)
return false;
}
return true;
}
static void decimalTob(long n, int k , int arr[], int i) {
arr[i] += (n % k);
n /= k;
if(n > 0) {
decimalTob(n, k, arr, i + 1);
}
}
static long powermod(long x, long y, long mod) {
if(y == 0) return 1;
long value = powermod(x, y / 2, mod);
if(y % 2 == 0) return (value * value) % mod;
return (value * (value * x) % mod) % mod;
}
static long power(long x, long y) {
if(y == 0) return 1;
long value = power(x, y / 2);
if(y % 2 == 0) return (value * value);
return value * value * x;
}
static int bS(int l, int r, int find, int arr[]) {
if(r < l) return l;
int mid = (l + r) / 2;
if(arr[mid] >= find) return bS(l, mid - 1, find, arr);
return bS(mid + 1, r, find, arr);
}
static void dfs(int index, ArrayList<ArrayList<Integer>> ss, int parent[], boolean hachu[], int z) {
hachu[index] = true;
parent[index] = z;
for(int e: ss.get(index)) {
if(!hachu[e]) dfs(e, ss, parent, hachu, z);
}
hachu[index] = false;
}
static int count(int index, ArrayList<ArrayList<Integer>> ss, boolean hachu[], int count) {
count++;
hachu[index] = true;
for(int e: ss.get(index)) {
if(!hachu[e]) {
count = count(e, ss, hachu, count);
}
}
return count;
}
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int t = 1;
outerloop:
while(t-- > 0) {
int n = sc.nextInt();
int m = sc.nextInt();
ArrayList<ArrayList<Integer>> ss = new ArrayList<>();
for(int i = 0; i <= n; i++) ss.add(new ArrayList<>());
int parent[] = new int[n + 1];
for(int i = 1; i <= n; i++) parent[i] = i;
int count = 0;
for(int i = 0; i < m; i++) {
boolean hachu[] = new boolean[n + 1];
int u = sc.nextInt();
int v = sc.nextInt();
if(parent[u] != parent[v]) {
ss.get(u).add(v);
ss.get(v).add(u);
dfs(u, ss, parent, hachu, parent[v]);
}
else {
count++;
}
ArrayList<Integer> dd = new ArrayList<>();
for(int j = 1; j <= n; j++) {
if(!hachu[j]) dd.add(count(j, ss, hachu, 0));
}
// out.println(dd);
Collections.sort(dd, Collections.reverseOrder());
int sum = 0, j = 0;
int temp = count;
while(temp-- >= 0 && j < dd.size()) {
sum += (dd.get(j));
j++;
}
out.println(sum - 1);
}
}
out.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 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 | ef1ca2774905e014c5abd80f2caae985 | 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.text.DecimalFormat;
import java.util.Arrays;
import java.util.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class copy {
static int log=18;
static int[][] ancestor;
static int[] depth;
static void sieveOfEratosthenes(int n, ArrayList<Integer> arr) {
boolean prime[] = new boolean[n + 1];
for (int i = 0; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++) {
// If prime[p] is not changed, then it is a
// prime
if (prime[p]) {
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
// Print all prime numbers
for (int i = 2; i <= n; i++) {
if (prime[i]) {
arr.add(i);
}
}
}
public static long fac(long N, long mod) {
if (N == 0)
return 1;
if(N==1)
return 1;
return ((N % mod) * (fac(N - 1, mod) % mod)) % mod;
}
static long power(long x, long y, long p) {
// Initialize result
long res = 1;
// Update x if it is more than or
// equal to p
x = x % p;
while (y > 0) {
// If y is odd, multiply x
// with result
if (y % 2 == 1)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// Returns n^(-1) mod p
static long modInverse(long n, long p) {
return power(n, p - 2, p);
}
// Returns nCr % p using Fermat's
// little theorem.
static long nCrModPFermat(long n, long r,
long p) {
if (n < r)
return 0;
// Base case
if (r == 0)
return 1;
return ((fac(n, p) % p * (modInverse(fac(r, p), p)
% p)) % p * (modInverse(fac(n - r, p), p)
% p)) % p;
}
public static int find(int[] parent, int x) {
if (parent[x] == x)
return x;
return find(parent, parent[x]);
}
public static void merge(int[] parent, int[] rank, int x, int y,int[] child) {
int x1 = find(parent, x);
int y1 = find(parent, y);
if (rank[x1] > rank[y1]) {
parent[y1] = x1;
child[x1]+=child[y1];
} else if (rank[y1] > rank[x1]) {
parent[x1] = y1;
child[y1]+=child[x1];
} else {
parent[y1] = x1;
child[x1]+=child[y1];
rank[x1]++;
}
}
public static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static int power(int x, int y, int p)
{
int 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;
}
// Returns n^(-1) mod p
static int modInverse(int n, int p)
{
return power(n, p - 2, p);
}
// Returns nCr % p using Fermat's
// little theorem.
static int nCrModPFermat(int n, int r,
int p)
{
if (n<r)
return 0;
// Base case
if (r == 0)
return 1;
// Fill factorial array so that we
// can find all factorial of r, n
// and n-r
int[] fac = new int[n + 1];
fac[0] = 1;
for (int i = 1; i <= n; i++)
fac[i] = fac[i - 1] * i % p;
return (fac[n] * modInverse(fac[r], p)
% p * modInverse(fac[n - r], p)
% p)
% p;
}
public static long[][] ncr(int n,int r)
{
long[][] dp=new long[n+1][r+1];
for(int i=0;i<=n;i++)
dp[i][0]=1;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=r;j++)
{
if(j>i)
continue;
dp[i][j]=dp[i-1][j-1]+dp[i-1][j];
}
}
return dp;
}
public static boolean prime(long N)
{
int c=0;
for(int i=2;i*i<=N;i++)
{
if(N%i==0)
++c;
}
return c==0;
}
public static int sparse_ancestor_table(ArrayList<ArrayList<Integer>> arr,int x,int parent,int[] child)
{
int c=0;
for(int i:arr.get(x))
{
if(i!=parent)
{
// System.out.println(i+" hello "+x);
depth[i]=depth[x]+1;
ancestor[i][0]=x;
// if(i==2)
// System.out.println(parent+" hello");
for(int j=1;j<log;j++)
ancestor[i][j]=ancestor[ancestor[i][j-1]][j-1];
c+=sparse_ancestor_table(arr,i,x,child);
}
}
child[x]=1+c;
return child[x];
}
public static int lca(int x,int y)
{
if(depth[x]<depth[y])
{
int temp=x;
x=y;
y=temp;
}
x=get_kth_ancestor(depth[x]-depth[y],x);
if(x==y)
return x;
// System.out.println(x+" "+y);
for(int i=log-1;i>=0;i--)
{
if(ancestor[x][i]!=ancestor[y][i])
{
x=ancestor[x][i];
y=ancestor[y][i];
}
}
return ancestor[x][0];
}
public static int get_kth_ancestor(int K,int x)
{
if(K==0)
return x;
int node=x;
for(int i=0;i<log;i++)
{
if(K%2!=0)
{
node=ancestor[node][i];
}
K/=2;
}
return node;
}
public static void main(String[] args) throws IOException {
Reader.init(System.in);
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
int N=Reader.nextInt();
int d=Reader.nextInt();
int[][] con=new int[d][2];
for(int i=0;i<d;i++)
{
con[i][0]=Reader.nextInt()-1;
con[i][1]=Reader.nextInt()-1;
}
int[] parent=new int[N];
int[] rank=new int[N];
int[] child=new int[N];
for(int i=0;i<d;i++)
{
for(int j=0;j<N;j++)
{
parent[j]=j;
rank[j]=0;
child[j]=1;
}
int extra=0;
for(int j=0;j<=i;j++)
{
int x1=find(parent,con[j][0]);
int y1=find(parent,con[j][1]);
if(x1==y1)
++extra;
else
merge(parent,rank,con[j][0],con[j][1],child);
}
//
// if(i==4)
// for(int j=0;j<N;j++)
// output.write(child[j]+" "+parent[j]+"\n");
HashSet<Integer> par=new HashSet<>();
PriorityQueue<Integer> pq=new PriorityQueue<>(Collections.reverseOrder());
for(int j=0;j<N;j++)
{
int x=find(parent,j);
if(!par.contains(x))
{
par.add(x);
pq.add(child[x]);
}
}
// if(i==4)
// System.out.println(par);
int ans=pq.poll();
while(extra>0 && pq.size()>0)
{
ans+=pq.poll();
--extra;
}
ans+=extra;
output.write(ans-1+"\n");
}
output.flush();
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(
reader.readLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
class sortat implements Comparator<div>
{
public int compare(div o1,div o2)
{
return o1.x-o2.x;
}
}
class TreeNode
{
int data;
TreeNode left;
TreeNode right;
TreeNode(int data)
{
left=null;
right=null;
this.data=data;
}
}
class div {
int x;
int y;
int z;
div(int x,int y,int z) {
this.x = x;
this.y=y;
this.z=z;
}
}
| 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 | 671ae06f7ed390b960a18887c9a6dff5 | 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.lang.*;
import java.io.*;
public class Main {
class DSU {
int[] parent , rank;
int n ;
int extra;
DSU(int n) {
this.n = n;
parent = new int[n];
for (int i = 0; i < n; i++)parent[i] = i;
rank = new int[n];
extra = 0;
}
int find(int child) {
if (parent[child] == child) {
return child;
}
parent[child] = find(parent[child]);
return parent[child];
}
int union(int a, int b) {
int pa = find(a);
int pb = find(b);
println(a + " " + b + " " + pa + " " + pb);
if (pa != pb) {
parent[pb] = pa;
} else {
extra++;
}
println(parent);
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0 ; i < n; i++) {
int p = find(i);
map.put(p, map.getOrDefault(p, 0) + 1);
}
ArrayList<Integer> sum = new ArrayList<>();
for (var entry : map.entrySet()) {
sum.add(entry.getValue());
}
Collections.sort(sum, Collections.reverseOrder());
int res = 0;
for (int i = 1; i <= extra + 1; i++) {
res += sum.get(i - 1);
}
return res - 1;
}
}
void solve() {
int n = in.nextInt();
int d = in.nextInt();
DSU dsu = new DSU(n);
while (d-- != 0) {
int a = in.nextInt() - 1;
int b = in.nextInt() - 1;
out.append(dsu.union(a, b) + endl);
}
}
public static void main (String[] args) {
// It happens - Syed Mizbahuddin
Main sol = new Main();
int t = 1;
// t = in.nextInt();
while (t-- != 0) {
sol.solve();
}
System.out.print(out);
}
<T> void println(T[] s) {
if (err == null)return;
err.println(Arrays.toString(s));
}
<T> void println(T s) {
if (err == null)return;
err.println(s);
}
void println(int s) {
if (err == null)return;
err.println(s);
}
void println(int[] a) {
if (err == null)return;
println(Arrays.toString(a));
}
int[] array(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
return a;
}
int[] array1(int n) {
int[] a = new int[n + 1];
for (int i = 1; i <= n; i++) {
a[i] = in.nextInt();
}
return a;
}
int max(int[] a) {
int max = a[0];
for (int i = 0; i < a.length; i++)max = Math.max(max, a[i]);
return max;
}
int min(int[] a) {
int min = a[0];
for (int i = 0; i < a.length; i++)min = Math.min(min, a[i]);
return min;
}
int count(int[] a, int x) {
int count = 0;
for (int i = 0; i < a.length; i++)if (x == a[i])count++;
return count;
}
void printArray(int[] a) {
for (int ele : a)out.append(ele + " ");
out.append("\n");
}
static {
try {
System.setIn(new FileInputStream("input.txt"));
System.setOut(new PrintStream(new FileOutputStream("output.txt")));
err = new PrintStream(new FileOutputStream("error.txt"));
} catch (Exception e) {}
}
static FastReader in;
static StringBuilder out;
static PrintStream err;
static String yes , no , endl;
final int MAX;
final int MIN;
int mod ;
Main() {
in = new FastReader();
out = new StringBuilder();
MAX = Integer.MAX_VALUE;
MIN = Integer.MIN_VALUE;
mod = (int)1e9 + 7;
yes = "YES\n";
no = "NO\n";
endl = "\n";
}
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 Pair implements Comparable<Pair> {
int first , second;
Pair(int first, int second) {
this.first = first;
this.second = second;
}
public int compareTo(Pair b) {
return this.first - b.first;
}
public String toString() {
String s = "{ " + Integer.toString(first) + " , " + Integer.toString(second) + " }";
return s;
}
}
}
| 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 | 1d48e8d99604babfc09031b679355585 | 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.Scanner;
import java.util.Arrays;
public class D1609 {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
int n=stdin.nextInt(),d=stdin.nextInt();
int[] components = new int[n]; // Component ID of person i.
for (int i=0;i<n;i++) components[i] = i;
int num_components=1;
while (d --> 0) {
int xi=stdin.nextInt()-1,yi=stdin.nextInt()-1;
int xi_component = components[xi];
int yi_component = components[yi];
if (xi_component==yi_component) {
num_components++;
}
for (int i=0;i<n;i++) {
if (components[i] == yi_component) components[i] = xi_component;
}
int[] components_cnt = new int[n];
for (int i=0;i<n;i++) components_cnt[components[i]]++;
int sum=0;
Arrays.sort(components_cnt);
//System.out.println("=====");
//for (int cnt:components_cnt) System.out.print(cnt + " ");
//System.out.println("\n=====");
for (int i=n-num_components;i<n;i++) sum += components_cnt[i];
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 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 | 3ff29dbbb71b085b27c003848cba1759 | 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_1069 {
static String in[];
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
static int i(String s) { return Integer.parseInt(s);}
static long l(String s) { return Long.parseLong(s);}
static void input() throws Exception { in = br.readLine().split(" "); }
public static void main(String[] args) throws Exception{
input();
int N = i(in[0]);
int M = i(in[1]);
DSU dsu = new DSU(N);
int count = 0;
while(M-->0){
input();
int x = i(in[0]), y = i(in[1]);
if(!dsu.union(x, y)){
count++;
}
ArrayList<Integer> arr = new ArrayList<>();
for(int i = 1; i<=N; i++)
if(dsu.parent[i] == i) arr.add(dsu.size[i]);
Collections.sort(arr);
int tempCount = count;
int n = arr.size();
int ans = arr.get(n-1);
for(int i = n-2; i>=0; i--){
if(tempCount == 0) break;
ans += arr.get(i);
tempCount--;
}
out.write((ans-1) + "\n");
}
// for(int i = 1; i<=N; i++) if(dsu.parent[i] == i) System.out.print(dsu.size[i] + " ");
out.flush();
}
}
class DSU{
int [] parent;
int [] size;
// int[] rank;
DSU(int n){
parent = new int[n+1];
size = new int[n+1];
// rank = new int[n+1];
for(int i = 1; i<=n; i++){
parent[i] = i;
size[i] = 1;
}
}
boolean union(int a, int b){
int x = find(a), y = find(b);
if(x == y) return false;
if(size[x] > size[y]){
parent[y] = x;
size[x] += size[y];
}else{
parent[x] = y;
size[y] += size[x];
}
return true;
}
int find(int x){
if(parent[x] != x){
parent[x] = find(parent[x]);
}
return parent[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 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 | 932179ef9a8211485d64f7681d63aa55 | 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 groupbang {static int extra=1; static TreeMap <Integer,Integer> mp;
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int n=in.nextInt();int d= in.nextInt();
uf u=new uf(n,d);
for(int i=1;i<=d;i++)
{
u.union(in.nextInt(), in.nextInt());
int ans=0;int s=0;
for (Map.Entry<Integer,Integer> entry : mp.entrySet()){ int t=entry.getKey();int val =mp.get(t);
while(s<extra && val--!=0 ) {ans+=t;s++;
}}
System.out.println(ans-1);
}
}
private static class uf
{int id[];int sz[];
public uf(int n,int d)
{mp=new TreeMap<Integer,Integer>(Collections.reverseOrder());
id=new int[n+1]; sz=new int[n+1];
mp.put(1,0);
for(int i=1;i<=n;i++)
{id[i]=i;sz[i]=1;mp.put(1, mp.get(1)+1);}
}
public int root(int i)
{
while(id[i]!=i){
id[i]=id[id[i]];
i=id[i];
}return i;
}
public boolean find(int i,int j)
{
return root(i)==root(j);
}
public void union(int i, int j) {
i = root(i);
j = root(j);
if(i!=j){
if (sz[i] < sz[j]) {
id[i] = j;remover(sz[j]);remover(sz[i]);
sz[j] += sz[i];mp.put(sz[j], mp.getOrDefault(sz[j],0)+1);
}
else {
id[j] = i;remover(sz[j]);remover(sz[i]);
sz[i] += sz[j];
mp.put(sz[i], mp.getOrDefault(sz[i],0)+1);
}
}else{
extra++; return;
}
}
private void remover(int sz)
{ if(mp.get(sz)==null)
{return;}
if(mp.get(sz)-1<=0){
mp.remove(sz);
}else{
mp.put(sz, mp.get(sz)-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 | d13c7dadcc9690d0bd339bfcd1e79c69 | 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.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] tokens = scanner.nextLine().split(" ");
int num = Integer.parseInt(tokens[0]);
int conditions = Integer.parseInt(tokens[1]);
DSU dsu = new DSU(num);
int extra = 0;
for (int i = 0; i < conditions; i++) {
String[] friends = scanner.nextLine().split(" ");
int x = Integer.parseInt(friends[0]) - 1;
int y = Integer.parseInt(friends[1]) - 1;
if (dsu.findSet(x) != dsu.findSet(y)) {
dsu.union(x, y);
} else {
extra++;
}
HashMap<Integer, Integer> setSize = new HashMap<>();
for (int j = 0; j < num; j++) {
int parent = dsu.findSet(j);
setSize.put(parent, setSize.getOrDefault(parent, 0) + 1);
}
ArrayList<Integer> sizes = new ArrayList<>();
for (int key : setSize.keySet()) {
sizes.add(setSize.get(key));
}
Collections.sort(sizes);
int sum = 0;
int last = sizes.size() - 1;
for (int j = 0; j < extra + 1; j++) {
sum += sizes.get(last--);
}
System.out.println(sum - 1);
}
}
public static class DSU {
private int[] parents;
private int[] rank;
public DSU(int n) {
this.parents = new int[n];
this.rank = new int[n];
for (int i = 0; i < n; i++) {
parents[i] = i;
}
}
public int findSet(int x) {
if (parents[x] != x) {
parents[x] = findSet(parents[x]);
}
return parents[x];
}
public int union(int x, int y) {
return link(findSet(x), findSet(y));
}
public int link(int x, int y) {
if (rank[x] < rank[y]) {
parents[x] = y;
return y;
} else {
if (rank[x] == rank[y]) {
rank[x]++;
}
parents[y] = x;
return 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 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 | 9cddab152c0047177f5e77bb44acc344 | 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.Closeable;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
public class D {
public static void main(String[] args) throws IOException {
FastScanner scanner = new FastScanner();
int n = scanner.nextInt();
int d = scanner.nextInt();
int[] parent = new int[n + 1];
int[] size = new int[n + 1];
Arrays.fill(parent, -1);
Arrays.fill(size, 1);
TreeSet<Integer> treeSet = new TreeSet<>(Comparator
.<Integer, Integer>comparing(i -> size[i]).thenComparing(i -> i));
for (int i = 1; i < n + 1; i++) {
treeSet.add(i);
}
int freeEdges = 0;
for (int i = 0; i < d; i++) {
int x = scanner.nextInt();
int y = scanner.nextInt();
while (parent[x] != -1) x = parent[x];
while (parent[y] != -1) y = parent[y];
if (x == y) freeEdges++;
else {
treeSet.remove(x);
treeSet.remove(y);
if (size[x] > size[y]) {
parent[y] = x;
size[x] += size[y];
treeSet.add(x);
} else {
parent[x] = y;
size[y] += size[x];
treeSet.add(y);
}
}
Iterator<Integer> it = treeSet.descendingIterator();
int sum = 0;
for (int j = 0; j <= freeEdges && it.hasNext(); j++) {
sum += size[it.next()];
}
System.out.println(sum - 1);
}
}
/**
* Credits: https://www.geeksforgeeks.org/fast-io-in-java-in-competitive-programming/
*/
private static class FastScanner implements Closeable {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public FastScanner() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastScanner(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[64];
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n' || c == '\r') {
if (cnt != 0) {
break;
} else {
continue;
}
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public String next() throws IOException {
return next(32);
}
public String next(int len) throws IOException {
byte[] buf = new byte[len];
int ptr = 0;
byte c = read();
while (c <= ' ') c = read();
do {
if (ptr == buf.length) {
buf = Arrays.copyOf(buf, buf.length << 1);
}
buf[ptr++] = c;
} while ((c = read()) > ' ');
if (buf.length == ptr) return new String(buf);
return new String(Arrays.copyOf(buf, ptr));
}
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++];
}
@Override
public void close() throws IOException {
if (din == null) return;
din.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 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 | 7c6be28eedb59d959a0e0121ab53b473 | 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 int[] components;
public static void main(String[] args) throws Exception {
FastIO in = new FastIO();
int n = in.nextInt();
int d = in.nextInt();
ArrayList<ArrayList<Integer>> adjacent = new ArrayList<ArrayList<Integer>>();
boolean[] visited = new boolean[n];
components = new int[n];
int spareEdges = 0;
for (int i=0; i<n; i++) {
adjacent.add(new ArrayList<Integer>());
components[i] = i;
}
for (int i=0; i<d; i++) {
int a = in.nextInt()-1;
int b = in.nextInt()-1;
if (components[a]==components[b]) {
spareEdges++;
}
else {
adjacent.get(a).add(b);
adjacent.get(b).add(a);
}
visited = new boolean[n];
int component = 0;
ArrayList<Integer> sizes = new ArrayList<Integer>();
for (int j=0; j<n; j++) {
if (!visited[j]) {
int size = dfs(j, adjacent, visited, 0, component);
component++;
sizes.add(size);
}
}
Collections.sort(sizes, (o1, o2)->Integer.compare(o2, o1));
int ans = 0;
for (int j=0; j<=spareEdges; j++) {
ans+=sizes.get(j);
}
System.out.println(ans-1);
}
}
public static int dfs(int node, ArrayList<ArrayList<Integer>> adjacent, boolean[] visited, int size, int component) {
if (node>=visited.length) return size;
if (visited[node]) return size;
visited[node] = true;
components[node] = component;
size++;
for (Integer i: adjacent.get(node)) {
size = dfs(i, adjacent, visited, size, component);
}
return size;
}
static class FastIO {
BufferedReader br;
StringTokenizer st;
public FastIO() throws IOException
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
public String next() throws IOException
{
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); }
public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); }
public double nextDouble() throws NumberFormatException, IOException
{
return Double.parseDouble(next());
}
public String nextLine() throws IOException
{
String str = br.readLine();
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 | 2a5b2b8f9b24dc513ec6e6fa1c9287b4 | 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.BigInteger;
import java.util.*;
public class Main {
static int MOD = 1000000007;
// After writing solution, quick scan for:
// array out of bounds
// special cases e.g. n=1?
// npe, particularly in maps
//
// Big numbers arithmetic bugs:
// int overflow
// sorting, or taking max, after MOD
void solve() throws IOException {
int[] nd = ril(2);
int n = nd[0];
int d = nd[1];
int[][] xy = new int[d][];
for (int i = 0; i < d; i++) {
xy[i] = ril(2);
xy[i][0]--;
xy[i][1]--;
}
for (int i = 0; i < d; i++) {
UnionFind uf = new UnionFind(n);
int redundant = 0;
for (int j = 0; j <= i; j++) {
int u = xy[j][0];
int v = xy[j][1];
if (uf.find(u) == uf.find(v)) redundant++;
uf.union(u, v);
}
// a single extra edge is enough to overtake a component
Set<Integer> leaders = new HashSet<>();
for (int u = 0; u < n; u++) leaders.add(uf.find(u));
List<Integer> sizes = new ArrayList<>(leaders.size());
for (int u : leaders) sizes.add(uf.size[u]);
Collections.sort(sizes);
int ans = sizes.get(sizes.size() - 1) - 1;
for (int x = 1; x <= redundant; x++) {
ans += sizes.get(sizes.size() - 1 - x);
}
pw.println(ans);
}
}
// IMPORTANT
// DID YOU CHECK THE COMMON MISTAKES ABOVE?
// Template code below
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
public static void main(String[] args) throws IOException {
Main m = new Main();
m.solve();
m.close();
}
void close() throws IOException {
pw.flush();
pw.close();
br.close();
}
int ri() throws IOException {
return Integer.parseInt(br.readLine().trim());
}
long rl() throws IOException {
return Long.parseLong(br.readLine().trim());
}
int[] ril(int n) throws IOException {
int[] nums = new int[n];
int c = 0;
for (int i = 0; i < n; i++) {
int sign = 1;
c = br.read();
int x = 0;
if (c == '-') {
sign = -1;
c = br.read();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = br.read();
}
nums[i] = x * sign;
}
while (c != '\n' && c != -1) c = br.read();
return nums;
}
long[] rll(int n) throws IOException {
long[] nums = new long[n];
int c = 0;
for (int i = 0; i < n; i++) {
int sign = 1;
c = br.read();
long x = 0;
if (c == '-') {
sign = -1;
c = br.read();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = br.read();
}
nums[i] = x * sign;
}
while (c != '\n' && c != -1) c = br.read();
return nums;
}
int[] rkil() throws IOException {
int sign = 1;
int c = br.read();
int x = 0;
if (c == '-') {
sign = -1;
c = br.read();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = br.read();
}
return ril(x);
}
long[] rkll() throws IOException {
int sign = 1;
int c = br.read();
int x = 0;
if (c == '-') {
sign = -1;
c = br.read();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = br.read();
}
return rll(x);
}
char[] rs() throws IOException {
return br.readLine().toCharArray();
}
void sort(int[] A) {
Random r = new Random();
for (int i = A.length-1; i > 0; i--) {
int j = r.nextInt(i+1);
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
Arrays.sort(A);
}
void printDouble(double d) {
pw.printf("%.16f", d);
}
}
class UnionFind {
int n;
int numComponents;
int[] parent;
int[] rank;
int[] size;
UnionFind(int n) {
this.n = numComponents = n;
parent = new int[n];
rank = new int[n];
size = new int[n];
Arrays.fill(size, 1);
for (int i = 0; i < n; i++) parent[i] = i;
}
void union(int u, int v) {
int x = find(u);
int y = find(v);
if (x == y) return;
if (rank[x] < rank[y]) {
parent[x] = y;
size[y] += size[x];
} else if (rank[x] > rank[y]) {
parent[y] = x;
size[x] += size[y];
} else {
parent[x] = y;
rank[y]++;
size[y] += size[x];
}
numComponents--;
}
int find(int u) {
int current = u;
List<Integer> toUpdate = new ArrayList<>();
while (parent[current] != current) {
toUpdate.add(current);
current = parent[current];
}
for (Integer node : toUpdate) parent[node] = current;
return current;
}
int getNumComponents() {
return numComponents;
}
} | 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 | 4c9589433a48d58f6dd33cfe7d0e0c92 | 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 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 | 8a63edf8fa2a58c1e28ce39704ca0177 | 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.awt.Point;
public class Main{
static int mod = (int) (Math.pow(10, 9)+7);
static final int dx[] = { -1, 0, 1, 0 }, dy[] = { 0, -1, 0, 1 };
static final int[] dx8 = { -1, -1, -1, 0, 0, 1, 1, 1 }, dy8 = { -1, 0, 1, -1, 1, -1, 0, 1 };
static final int[] dx9 = { -1, -1, -1, 0, 0, 0, 1, 1, 1 }, dy9 = { -1, 0, 1, -1, 0, 1, -1, 0, 1 };
static final int inf = Integer.MAX_VALUE / 2;
static final long infL = Long.MAX_VALUE / 3;
static final double infD = Double.MAX_VALUE / 3;
static final double eps = 1e-10;
static final double pi = Math.PI;
static List<Integer> primeNumbers = new ArrayList<>();
public static void main(String[] args) {
MyScanner sc = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
int n = sc.nextInt();
int m = sc.nextInt();
DisjointUnionSets dsu = new DisjointUnionSets(n+1);
TreeMap<Integer, Integer> map = new TreeMap<>((a,b) -> Integer.compare(b, a));
map.put(1,n);
int extra = 1;
while(m --> 0){
// System.out.println(map);
// System.out.println(extra);
//keep making the connections bois
int p1 = sc.nextInt();
int p2 = sc.nextInt();
// out.println(p1 + " " + p2);
if(dsu.find(p1) != dsu.find(p2)){
int rank1 = dsu.rank[dsu.find(p1)];
int rank2 = dsu.rank[dsu.find(p2)];
//simple updation of tree
map.put(rank1, map.getOrDefault(rank1, 0)-1);
if(map.get(rank1) == 0) map.remove(rank1);
map.put(rank2, map.getOrDefault(rank2, 0)-1);
if(map.get(rank2) == 0) map.remove(rank2);
map.put(rank1 + rank2, map.getOrDefault(rank1 + rank2, 0)+1);
dsu.union(p1, p2);
//update the treemap in here
//how to update this piece of shit vaise?
}else{
extra++;
}
int ans = 0;
//some weird do fantasies for sure
int temp = extra;
for(int key : map.keySet()){
//think about it now
if(map.get(key) > temp){
ans += key*temp;
break;
}else{
ans += key* map.get(key);
temp -= map.get(key);
}
}
out.println(ans-1);
}
out.close();
}
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//-------------------------------------------------------------------
//fast java implementation for sure
public static class Graph{
public int V;
public ArrayList<ArrayList<Integer>> edges;
Graph(int V){
this.V = V;
edges = new ArrayList<>(V+1);
for(int i= 0; i <= V; i++){
edges.add(new ArrayList<>());
}
}
///single sided this for sure
public void addEdge(int from , int to){
edges.get(from).add(to);
}
}
public static class DisjointUnionSets {
int[] rank, parent;
int n;
// Constructor
public DisjointUnionSets(int n)
{
rank = new int[n];
parent = new int[n];
Arrays.fill(rank, 1);
Arrays.fill(parent,-1);
this.n = n;
}
public int find(int curr){
if(parent[curr] == -1)
return curr;
//path compression optimisation
return parent[curr] = find(parent[curr]);
}
//simple union function formation
public void union(int a, int b){
int s1 = find(a);
int s2 = find(b);
//union by rank optimisation is super duper cool
//I simply love it man!!!
if(s1 != s2){
if(rank[s1] < rank[s2]){
parent[s1] = s2;
rank[s2] += rank[s1];
}else{
parent[s2] = s1;
rank[s1] += rank[s2];
}
}
}
}
//with mod
public static long power(long x, long y)
{
long res = 1L; // Initialize result
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0){
x %= mod;
res %= mod;
res = (res * x)%mod;
}
// y must be even now
y = y >> 1; // y = y/2
x%= mod;
x = (x * x)%mod; // Change x to x^2
}
// 550193677
return res%mod;
}
//without mod
public static long power2(long x, long y)
{
long res = 1L; // Initialize result
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0){
res = (res * x);
}
// y must be even now
y = y >> 1; // y = y/
x = (x * x);
}
// 550193677
return res;
}
public static class segmentTree{
public long[] arr;
public long[] tree;
public long[] lazy;
segmentTree(long[] array){
int n = array.length;
arr = new long[n];
for(int i= 0; i < n; i++) arr[i] = array[i];
tree = new long[4*n + 1];
lazy = new long[4*n + 1];
}
public void build(int[]arr, int s, int e, int[] tree, int index){
if(s == e){
tree[index] = arr[s];
return;
}
//otherwise divide in two parts and fill both sides simply
int mid = (s+e)/2;
build(arr, s, mid, tree, 2*index);
build(arr, mid+1, e, tree, 2*index+1);
//who will build the current position dude
tree[index] = Math.min(tree[2*index], tree[2*index+1]);
}
public int query(int sr, int er, int sc, int ec, int index, int[] tree){
if(lazy[index] != 0){
tree[index] += lazy[index];
if(sc != ec){
lazy[2*index+1] += lazy[index];
lazy[2*index] += lazy[index];
}
lazy[index] = 0;
}
//no overlap
if(sr > ec || sc > er) return Integer.MAX_VALUE;
//found the index baby
if(sr <= sc && ec <= er) return tree[index];
//finding the index on both sides hehehehhe
int mid = (sc + ec)/2;
int left = query(sr, er, sc, mid, 2*index, tree);
int right = query(sr, er, mid+1, ec, 2*index + 1, tree);
return Integer.min(left, right);
}
//now we will do point update implementation
//it should be simple then we expected for sure
public void update(int index, int indexr, int increment, int[] tree, int s, int e){
if(lazy[index] != 0){
tree[index] += lazy[index];
if(s != e){
lazy[2*index+1] = lazy[index];
lazy[2*index] = lazy[index];
}
lazy[index] = 0;
}
//no overlap
if(indexr < s || indexr > e) return;
//found the required index
if(s == e){
tree[index] += increment;
return;
}
//search for the index on both sides
int mid = (s+e)/2;
update(2*index, indexr, increment, tree, s, mid);
update(2*index+1, indexr, increment, tree, mid+1, e);
//now update the current range simply
tree[index] = Math.min(tree[2*index+1], tree[2*index]);
}
public void rangeUpdate(int[] tree , int index, int s, int e, int sr, int er, int increment){
//if not at all in the same range
if(e < sr || er < s) return;
//complete then also move forward
if(s == e){
tree[index] += increment;
return;
}
//otherwise move in both subparts
int mid = (s+e)/2;
rangeUpdate(tree, 2*index, s, mid, sr, er, increment);
rangeUpdate(tree, 2*index + 1, mid+1, e, sr, er, increment);
//update current range too na
//i always forget this step for some reasons hehehe, idiot
tree[index] = Math.min(tree[2*index], tree[2*index + 1]);
}
public void rangeUpdateLazy(int[] tree, int index, int s, int e, int sr, int er, int increment){
//update lazy values
//resolve lazy value before going down
if(lazy[index] != 0){
tree[index] += lazy[index];
if(s != e){
lazy[2*index+1] += lazy[index];
lazy[2*index] += lazy[index];
}
lazy[index] = 0;
}
//no overlap case
if(sr > e || s > er) return;
//complete overlap
if(sr <= s && er >= e){
tree[index] += increment;
if(s != e){
lazy[2*index+1] += increment;
lazy[2*index] += increment;
}
return;
}
//otherwise go on both left and right side and do your shit
int mid = (s + e)/2;
rangeUpdateLazy(tree, 2*index, s, mid, sr, er, increment);
rangeUpdateLazy(tree, 2*index + 1, mid+1, e, sr, er, increment);
tree[index] = Math.min(tree[2*index+1], tree[2*index]);
return;
}
}
//prime sieve
public static void primeSieve(int n){
BitSet bitset = new BitSet(n+1);
for(long i = 0; i < n ; i++){
if (i == 0 || i == 1) {
bitset.set((int) i);
continue;
}
if(bitset.get((int) i)) continue;
primeNumbers.add((int)i);
for(long j = i; j <= n ; j+= i)
bitset.set((int)j);
}
}
//number of divisors
public static int countDivisors(long number){
if(number == 1) return 1;
List<Integer> primeFactors = new ArrayList<>();
int index = 0;
long curr = primeNumbers.get(index);
while(curr * curr <= number){
while(number % curr == 0){
number = number/curr;
primeFactors.add((int) curr);
}
index++;
curr = primeNumbers.get(index);
}
if(number != 1) primeFactors.add((int) number);
int current = primeFactors.get(0);
int totalDivisors = 1;
int currentCount = 2;
for (int i = 1; i < primeFactors.size(); i++) {
if (primeFactors.get(i) == current) {
currentCount++;
} else {
totalDivisors *= currentCount;
currentCount = 2;
current = primeFactors.get(i);
}
}
totalDivisors *= currentCount;
return totalDivisors;
}
//now adding next permutation function to java hehe
public static boolean next_permutation(int[] p) {
for (int a = p.length - 2; a >= 0; --a)
if (p[a] < p[a + 1])
for (int b = p.length - 1;; --b)
if (p[b] > p[a]) {
int t = p[a];
p[a] = p[b];
p[b] = t;
for (++a, b = p.length - 1; a < b; ++a, --b) {
t = p[a];
p[a] = p[b];
p[b] = t;
}
return true;
}
return false;
}
//finding the value of NCR in O(RlogN) time and O(1) space
public static long getNcR(int n, int r)
{
long p = 1, k = 1;
if (n - r < r) r = n - r;
if (r != 0) {
while (r > 0) {
p *= n;
k *= r;
long m = __gcd(p, k);
p /= m;
k /= m;
n--;
r--;
}
}
else {
p = 1;
}
return p;
}
public 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);
}
//for ncr calculator
public static long __gcd(long n1, long n2)
{
long gcd = 1;
for (int i = 1; i <= n1 && i <= n2; ++i) {
// Checks if i is factor of both integers
if (n1 % i == 0 && n2 % i == 0) {
gcd = i;
}
}
return gcd;
}
//is vowel function
public static boolean isVowel(char c)
{
return (c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' || c=='u' || c=='U');
}
//two add two big numbers with some mod
public static int add(int a, int b) {
a+=b;
if (a>=mod) return a-mod;
return a;
}
//two sub two numbers
public static int sub(int a, int b) {
a-=b;
if (a<0) a+=mod;
else if (a>=mod) a-=mod;
return a;
}
//to sort the array with better method
public 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);
}
//for calculating binomialCoeff
public static int binomialCoeff(int n, int k)
{
int C[] = new int[k + 1];
// nC0 is 1
C[0] = 1;
for (int i = 1; i <= n; i++) {
// Compute next row of pascal
// triangle using the previous row
for (int j = Math.min(i, k); j > 0; j--)
C[j] = C[j] + C[j - 1];
}
return C[k];
}
//Pair with int int
public static class Pair{
public int a;
public int b;
Pair(int a , int b){
this.a = a;
this.b = b;
}
@Override
public String toString(){
return a + " -> " + b;
}
}
//Triplet with int int int
public static class Triplet{
public int a;
public int b;
public int c;
Triplet(int a , int b, int c){
this.a = a;
this.b = b;
this.c = c;
}
@Override
public String toString(){
return a + " -> " + b;
}
}
//Shortcut function
public static long lcm(long a , long b){
return a * (b/gcd(a,b));
}
//let's make one for calculating lcm basically
public static int lcm(int a , int b){
return (a * b)/gcd(a,b);
}
//int version for gcd
public static int gcd(int a, int b){
if(b == 0)
return a;
return gcd(b , a%b);
}
//long version for gcd
public static long gcd(long a, long b){
if(b == 0)
return a;
return gcd(b , a%b);
}
//swapping two elements in an array
public static void swap(int[] arr, int left , int right){
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
//
//for char array
public static void swap(char[] arr, int left , int right){
char temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
//reversing an array
public static void reverse(int[] arr){
int left = 0;
int right = arr.length-1;
while(left <= right){
swap(arr, left,right);
left++;
right--;
}
}
//-----------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 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 | 5d056c4ec9248f60e1ceaa2d5c473ca0 | 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.File;import java.io.FileInputStream;import java.io.FileNotFoundException;
import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter;
import java.security.AccessControlException;import java.util.Comparator;import java.util.HashMap;
import java.util.List;import java.util.Map;import java.util.PriorityQueue;import java.util.stream.IntStream;
public class _D {static public void main(final String[] args) throws IOException
{D._main(args);}
static class D extends Solver{public D(){singleTest=true;}@Override public void solve()throws
IOException{int n=sc.nextInt();int d=sc.nextInt();sc.nextLine();DSU dsu=new DSU(n);
HashMap<Integer,Integer>map=new HashMap<>();PriorityQueue<Map.Entry<Integer,Integer>>
pq=new PriorityQueue<>(Comparator.comparingInt(v->-v.getValue()));for(int i=0;i<
n;i++){int set=dsu.find_set(i);map.put(set,map.getOrDefault(set,0)+1);}int extra
=0;for(int $i0=0;$i0<d;$i0++){int x=sc.nextInt();int y=sc.nextInt();sc.nextLine();
x--;y--;if(dsu.find_set(x)==dsu.find_set(y)){extra++;}else{dsu.union_sets(x,y);map.clear();
for(int i=0;i<n;i++){int set=dsu.find_set(i);map.put(set,map.getOrDefault(set,0)
+1);}}pq.clear();pq.addAll(map.entrySet());int count=0;for(int i=0;i<=extra;i++)
{count+=pq.poll().getValue();}pw.println(count-1);}}static public void _main(String[]
args)throws IOException{new D().run();}}static class DSU{private int[]parent;private
int[]rank;public DSU(final int n){parent=IntStream.range(0,n).toArray();rank=new
int[n];}public int find_set(final int v){if(v==parent[v]){return v;}parent[v]=find_set(parent[v]);
return parent[v];}public void union_sets(final int a,final int b){int a1=find_set(a);
int b1=find_set(b);if(a1!=b1){if(rank[a1]<rank[b1]){int t=a1;a1=b1;b1=t;}parent[b1]
=a1;if(rank[a1]==rank[b1]){++rank[a1];}}}}static class MyScanner{private StringBuilder
cache=new StringBuilder();int cache_pos=0;private int first_linebreak=-1;private
int second_linebreak=-1;private StringBuilder sb=new StringBuilder();private InputStream
is=null;public MyScanner(final InputStream is){this.is=is;}public String charToString(final
int c){return String.format("'%s'",c=='\n'?"\\n":(c=='\r'?"\\r":String.valueOf((char)c)));
}public int get(){int res=-1;if(cache_pos<cache.length()){res=cache.charAt(cache_pos);
cache_pos++;if(cache_pos==cache.length()){cache.delete(0,cache_pos);cache_pos=0;
}}else{try{res=is.read();}catch(IOException ex){throw new RuntimeException(ex);}
}return res;}private void unget(final int c){if(cache_pos==0){cache.insert(0,(char)c);
}else{cache_pos--;}}public String nextLine(){sb.delete(0,sb.length());int c;boolean
done=false;boolean end=false;while((c=get())!=-1){if(check_linebreak(c)){done=true;
if(c==first_linebreak){if(!end){end=true;}else{cache.append((char)c);break;}}else
if(second_linebreak!=-1 && c==second_linebreak){break;}}if(end && c!=first_linebreak
&& c!=second_linebreak){cache.append((char)c);break;}if(!done){sb.append((char)c);
}}return!done && sb.length()==0?null:sb.toString();}private boolean check_linebreak(int
c){if(c=='\n'|| c=='\r'){if(first_linebreak==-1){first_linebreak=c;}else if(c!=first_linebreak
&& second_linebreak==-1){second_linebreak=c;}return true;}return false;}public int
nextInt(){return Integer.parseInt(next());}public long nextLong(){return Long.parseLong(next());
}public boolean hasNext(){boolean res=false;int c;while((c=get())!=-1){if(!check_linebreak(c)
&& c!=' '&& c!='\t'){res=true;unget(c);break;}}return res;}public String next(){
sb.delete(0,sb.length());boolean started=false;int c;while((c=get())!=-1){if(check_linebreak(c)
|| c==' '|| c=='\t'){if(started){unget(c);break;}}else{started=true;sb.append((char)c);
}}return sb.toString();}public int nextChar(){return get();}public boolean eof()
{int c=get();boolean res=false;if(c!=-1){unget(c);}else{res=true;}return res;}public
double nextDouble(){return Double.parseDouble(next());}}static abstract class Solver
{protected String nameIn=null;protected String nameOut=null;protected boolean singleTest
=false;protected MyScanner sc=null;protected PrintWriter pw=null;private int current_test
=0;private int count_tests=0;protected int currentTest(){return current_test;}protected
int countTests(){return count_tests;}private void process()throws IOException{if(!singleTest)
{count_tests=sc.nextInt();sc.nextLine();for(current_test=1;current_test<=count_tests;
current_test++){solve();pw.flush();}}else{count_tests=1;current_test=1;solve();}
}abstract protected void solve()throws IOException;public void run()throws IOException
{boolean done=false;try{if(nameIn!=null){if(new File(nameIn).exists()){try(FileInputStream
fis=new FileInputStream(nameIn);PrintWriter pw0=select_output();){select_output();
done=true;sc=new MyScanner(fis);pw=pw0;process();}}else{throw new RuntimeException("File "
+new File(nameIn).getAbsolutePath()+" does not exist!");}}}catch(IOException | AccessControlException
ex){}if(!done){try(PrintWriter pw0=select_output();){sc=new MyScanner(System.in);
pw=pw0;process();}}}private PrintWriter select_output()throws FileNotFoundException
{if(nameOut!=null){return new PrintWriter(nameOut);}return new PrintWriter(System.out);
}}static abstract class Tester{static public int getRandomInt(final int min,final
int max){return(min+(int)Math.floor(Math.random()*(max-min+1)));}static public long
getRandomLong(final long min,final long max){return(min+(long)Math.floor(Math.random()
*(max-min+1)));}static public double getRandomDouble(final double min,final double
maxExclusive){return(min+Math.random()*(maxExclusive-min));}abstract protected void
testOutput(final List<String>output_data);abstract protected void generateInput();
abstract protected String inputDataToString();private boolean break_tester=false;
protected void beforeTesting(){}protected void breakTester(){break_tester=true;}
public boolean broken(){return break_tester;}}}
| 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 | b0773ea3cc98951a8284c9fd717351b1 | 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 codeforceb
{
//ArrayList<Integer> arr2=new ArrayList<Integer>();
//ArrayList<Integer> arr1=new ArrayList<Integer>();
//Map<Integer,Integer> hm=new HashMap<Integer,Integer>();
//Set<Integer> st1=new HashSet<Integer>();
static Set<Integer> prime=new HashSet<Integer>();
static int inf = Integer.MAX_VALUE ;
static long infL = Long.MAX_VALUE ;
static int mod=1000000007;
static FastReader sc=new FastReader();
static PrintWriter out=new PrintWriter(System.out);
static int max=1,c=0;
public static void main (String[] args)
{
/*Arrays.sort(time,new Comparator<Pair>(){
public int compare(Pair p1,Pair p2){
if(p1.a==p2.a)
return p1.b-p2.b;
return p1.a-p2.a;
}
});*/
//int r[][]= {{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}
// };
int t=1;
//seive(1000000);
while(t-->0)
{
solve();
}
out.close();
}
public static void solve() {
int n=sc.nextInt();
int d=sc.nextInt();
int par[]=new int[n];
int sum[]=new int[n];
for(int i=0;i<n;i++) par[i]=i+1;
Arrays.fill(sum,1);
while(d-->0) {
int i=sc.nextInt();
int j=sc.nextInt();
union(i,j,par,sum,n);
}
}
public static int findPar(int i,int par[]) {
if(par[i-1]==i) return i;
else
return par[i-1]=findPar(par[i-1],par);
}
public static void union(int i,int j,int par[],int sum[],int n) {
int u=findPar(i,par);
int v=findPar(j,par);
if(u!=v) {
par[v-1]=u;
sum[u-1]+=sum[v-1];
}
else c++;
PriorityQueue<Integer> pq=new PriorityQueue<Integer>(Collections.reverseOrder());
//for(int k:par) out.print(k+" ");
for(int k=0;k<n;k++) {
if(par[k]==k+1) pq.add(sum[k]);
}
//out.print(pq);
int sum1=pq.remove();
// out.print(pq);
int a=c;
while(a-->0) {
sum1+=pq.remove();
}
out.println(sum1-1);
max=(int)Math.max(sum[u-1],max);
}
public static boolean check(int r1,int c1,int n,int m) {
if(r1<0 || c1<0 || r1>=n || c1>=m) return false;
return true;
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long[] readLong(int n) {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
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 class Pair{
int a;
int b;
Pair(int x, int y)
{
this.a = x;
this.b = y;
}
}
static boolean isPrime(long x)
{
if(x==1)
return false;
if(x<=3)
return true;
if(x%2==0 || x%3==0)
return false;
for(int i=5;i<=Math.sqrt(x);i+=2)
if(x%i==0)
return false;
return true;
}
static long gcd(long a,long b)
{
return (b==0)?a:gcd(b,a%b);
}
static int gcd(int a,int b)
{
return (b==0)?a:gcd(b,a%b);
}
public static long myPow(long x, long n) {
if(x==0)
return 0;
if(n==0)
return 1;
if(n==1)
return x;
long calc=myPow((long)x,n/2);
//System.out.println(calc+" "+n/2);
if(Math.abs(n)%2==0)
return (calc*calc);
else
return (x*calc*calc);
}
public static long lcm(long a , long b){
return a * (b/gcd(a,b));
}
public static int lcm(int a , int b){
return (a * b)/gcd(a,b);
}
public static void swap(int[] arr, int left , int right){
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
public static void swap(char[] arr, int left , int right){
char temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
public static void reverse(int[] arr){
int left = 0;
int right = arr.length-1;
while(left <= right){
swap(arr, left,right);
left++;
right--;
}
}
public static void seive(int val) {
int arr[]=new int[val+1];
for(int i=2;i<=val;i++) {
if(arr[i]==0) {
prime.add(i);
for(int j=i;j<=val;j+=i) arr[j]=1;
}
else continue;
}
}
} | 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 | 5a75cd05921f34585a407cb2190202d9 | 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 Main{
static int [] arr;
static int tmp;
public static int find(int x){
if(arr[x]<0){
return x;
}else return find(arr[x]);
}
public static void union(int x, int y){
int rootX = find(x);
int rootY = find(y);
if(rootX!=rootY){
arr[rootX] += arr[rootY];
arr[rootY] = rootX;
}else{
tmp++;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int d = sc.nextInt();
arr = new int [n+1];
Arrays.fill(arr, -1);
for (int i = 0; i < d; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
union(x, y);
int max = -1;
for (int j =1; j < n+1; j++) {
arr[j]*=-1;
}
int [] temp = arr.clone();
Arrays.sort(temp);
int ans = 0;
for (int j = n; j >= n-tmp; j--) {
ans += temp[j];
}
for (int j = 0; j < n+1; j++) {
arr[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 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 | 19729fd7e3ee90555696e48eb789f63b | 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 Main{
static int [] arr;
static int tmp;
public static int find(int x){
if(arr[x]<0){
return x;
}else return find(arr[x]);
}
public static void union(int x, int y){
int rootX = find(x);
int rootY = find(y);
if(rootX!=rootY){
arr[rootX] += arr[rootY];
arr[rootY] = rootX;
}else{
tmp++;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int d = sc.nextInt();
arr = new int [n+1];
Arrays.fill(arr, -1);
for (int i = 0; i < d; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
union(x, y);
int max = -1;
for (int j =1; j < n+1; j++) {
arr[j]*=-1;
}
int [] temp = arr.clone();
Arrays.sort(temp);
int ans = 0;
for (int j = n; j >= n-tmp; j--) {
ans += temp[j];
}
for (int j = 0; j < n+1; j++) {
arr[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 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 | db1e138d154ef2f0c7703690f3b55432 | 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 {
void go() {
int n = Reader.nextInt();
int d = Reader.nextInt();
int[][] edges = new int[d][2];
DSU dsu = new DSU(n + 1);
for(int i = 0; i < d; i++) {
edges[i][0] = Reader.nextInt();
edges[i][1] = Reader.nextInt();
}
int free = 0;
for(int[] e : edges) {
int u = e[0];
int v = e[1];
int cnt = 0;
if(dsu.find(u) == dsu.find(v)) {
free++;
} else {
dsu.union(u, v);
}
Map<Integer, Integer> map = new HashMap<>();
if(free == 0) {
for(int i = 1; i <= n; i++) {
int p = dsu.find(i);
map.put(p, map.getOrDefault(p, 0) + 1);
cnt = Math.max(cnt, map.get(p));
}
} else {
for(int i = 1; i <= n; i++) {
map.put(dsu.find(i), map.getOrDefault(dsu.find(i), 0) + 1);
}
Queue<Integer> pq = new PriorityQueue<>(Comparator.reverseOrder());
for(int val : map.values()) {
pq.offer(val);
}
for(int i = 0; i <= free; i++) {
cnt += pq.poll();
}
}
Writer.println(cnt - 1);
}
}
void solve() {
go();
}
void run() throws Exception {
Reader.init(System.in);
Writer.init(System.out);
solve();
Writer.close();
}
private class DSU {
private int[] p;
private int[] w;
private int n;
DSU(int n) {
this.n = n;
p = new int[n];
w = new int[n];
Arrays.fill(p, -1);
}
private int find(int i) {
if(p[i] < 0) return i;
return p[i] = find(p[i]);
}
private void union(int i, int j) {
int x = find(i);
int y = find(j);
if(x == y) return;
if(w[x] == w[y]) {
p[y] = x;
w[x] += 1;
} else if(w[x] > w[y]) {
p[y] = x;
} else {
p[x] = y;
}
}
}
public static void main(String[] args) throws Exception {
new D().run();
}
public static class Reader {
public static StringTokenizer st;
public static BufferedReader br;
public static void init(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
st = new StringTokenizer("");
}
public static String next() {
while(!st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new InputMismatchException();
}
}
return st.nextToken();
}
public static int nextInt() {
return Integer.parseInt(next());
}
public static double nextDouble() {
return Double.parseDouble(next());
}
}
public static class Writer {
public static PrintWriter pw;
public static void init(OutputStream os) {
pw = new PrintWriter(new BufferedOutputStream(os));
}
public static void print(String s) {
pw.print(s);
}
public static void print(int x) {
pw.print(x);
}
public static void print(long x) {
pw.print(x);
}
public static void println(String s) {
pw.println(s);
}
public static void println(int x) {
pw.println(x);
}
public static void println(long x) {
pw.println(x);
}
public static void close() {
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 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 | 1ec3b87819bea33ac26b43376d6e0bfe | 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.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Objects;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.util.Collections;
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);
OutputWriter out = new OutputWriter(outputStream);
DSocialNetwork solver = new DSocialNetwork();
solver.solve(1, in, out);
out.close();
}
static class DSocialNetwork {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int d = in.nextInt();
dsu u;
int max = 0;
ArrayList<Pair> list = new ArrayList<>();
for (int i = 0; i < d; i++) {
int a = in.nextInt() - 1, b = in.nextInt() - 1;
list.add(new Pair(a, b));
}
for (int i = 0; i < d; i++) {
u = new dsu(n);
int count = 0;
for (int j = 0; j <= i; j++) {
Pair p = list.get(j);
if (!u.isConnected(p.a, p.b)) u.merge(p.a, p.b);
else count++;
}
ArrayList<Pair> list1 = new ArrayList<>();
for (int j = 0; j < n; j++) {
if (u.find(j) == j) list1.add(new Pair(u.componentSize(j), j));
}
Collections.sort(list1, Collections.reverseOrder());
int ans = 0;
int j = 0;
while (count >= 0) {
ans += list1.get(j++).a;
count--;
}
out.println(ans - 1);
}
}
class Pair implements Comparable<Pair> {
int a;
int b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
public int hashCode() {
return Objects.hash(a, b);
}
public boolean equals(Object obj) {
Pair that = (Pair) obj;
return a == that.a && b == that.b;
}
public String toString() {
return "[" + a + ", " + b + "]";
}
public int compareTo(Pair v) {
return a - v.a;
}
}
class dsu {
private int size;
private int[] sz;
private int[] par;
private int numComponents;
public dsu(int size) {
this.size = numComponents = size;
sz = new int[size];
par = new int[size];
clear();
}
public int find(int p) {
if (p == par[p]) return p;
return par[p] = find(par[p]);
}
public boolean isConnected(int p, int q) {
return find(p) == find(q);
}
public int componentSize(int p) {
return sz[find(p)];
}
public void merge(int p, int q) {
int root1 = find(p);
int root2 = find(q);
if (root1 == root2) return;
if (sz[root2] > sz[root1]) {
root1 ^= root2;
root2 ^= root1;
root1 ^= root2;
}
sz[root1] += sz[root2];
par[root2] = root1;
numComponents--;
}
public void clear() {
for (int i = 0; i < size; i++) {
par[i] = i;
sz[i] = 1;
}
}
}
}
static class InputReader {
BufferedReader reader;
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());
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(int i) {
writer.println(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 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 | ea3d4125a4525f57d282e0d294060fd2 | 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.concurrent.LinkedBlockingDeque;
import javax.security.auth.login.AccountExpiredException;
import javax.swing.text.Segment;
import java.io.*;
import java.math.*;
import java.sql.Array;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Main {
private static class MyScanner {
private static final int BUF_SIZE = 2048;
BufferedReader br;
private MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
private boolean isSpace(char c) {
return c == '\n' || c == '\r' || c == ' ';
}
String next() {
try {
StringBuilder sb = new StringBuilder();
int r;
while ((r = br.read()) != -1 && isSpace((char)r));
if (r == -1) {
return null;
}
sb.append((char) r);
while ((r = br.read()) != -1 && !isSpace((char)r)) {
sb.append((char)r);
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
static class Reader{
BufferedReader br;
StringTokenizer st;
public Reader() {
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 void sort(long[] arr ) {
ArrayList<Long> al = new ArrayList<>();
for(long e:arr) al.add(e);
Collections.sort(al);
for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);
}
static void sort(int[] arr ) {
ArrayList<Integer> al = new ArrayList<>();
for(int e:arr) al.add(e);
Collections.sort(al);
for(int i = 0 ; i<al.size(); i++) arr[i] = al.get(i);
}
static void sort(char[] arr) {
ArrayList<Character> al = new ArrayList<Character>();
for(char cc:arr) al.add(cc);
Collections.sort(al);
for(int i = 0 ;i<arr.length ;i++) arr[i] = al.get(i);
}
static void rvrs(int[] arr) {
int i =0 , j = arr.length-1;
while(i>=j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
static void rvrs(long[] arr) {
int i =0 , j = arr.length-1;
while(i>=j) {
long temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
static long mod_mul( long mod , long... a) {
long ans = a[0]%mod;
for(int i = 1 ; i<a.length ; i++) {
ans = (ans * (a[i]%mod))%mod;
}
return ans;
}
static long mod_sum(long mod , long... a) {
long ans = 0;
for(long e:a) {
ans = (ans + e)%mod;
}
return ans;
}
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static boolean[] prime(int num) {
boolean[] bool = new boolean[num];
for (int i = 0; i< bool.length; i++) {
bool[i] = true;
}
for (int i = 2; i< Math.sqrt(num); i++) {
if(bool[i] == true) {
for(int j = (i*i); j<num; j = j+i) {
bool[j] = false;
}
}
}
if(num >= 0) {
bool[0] = false;
bool[1] = false;
}
return bool;
}
static long modInverse(long a, long m)
{
long g = gcd(a, m);
return power(a, m - 2, m);
}
static long lcm(long a , long b) {
return (a*b)/gcd(a, b);
}
static int lcm(int a , int b) {
return (int)((a*b)/gcd(a, b));
}
static long power(long x, long y, long m){
if (y == 0) return 1; long p = power(x, y / 2, m) % m; p = (int)((p * (long)p) % m);
if (y % 2 == 0) return p; else return (int)((x * (long)p) % m); }
static class Combinations{
private long[] z;
private long[] z1;
private long[] z2;
public Combinations(long N , long mod) {
z = new long[(int)N+1];
z1 = new long[(int)N+1];
z[0] = 1;
for(int i =1 ; i<=N ; i++) z[i] = (z[i-1]*i)%mod;
z2 = new long[(int)N+1];
z2[0] = z2[1] = 1;
for (int i = 2; i <= N; i++)
z2[i] = z2[(int)(mod % i)] * (mod - mod / i) % mod;
z1[0] = z1[1] = 1;
for (int i = 2; i <= N; i++)
z1[i] = (z2[i] * z1[i - 1]) % mod;
}
long fac(long n) {
return z[(int)n];
}
long invrsNum(long n) {
return z2[(int)n];
}
long invrsFac(long n) {
return invrsFac((int)n);
}
long ncr(long N, long R, long mod)
{ if(R<0 || R>N ) return 0;
long ans = ((z[(int)N] * z1[(int)R])
% mod * z1[(int)(N - R)])
% mod;
return ans;
}
}
static class DisjointUnionSets {
int[] rank, parent;
int n;
public DisjointUnionSets(int n)
{
rank = new int[n];
parent = new int[n];
this.n = n;
makeSet();
}
void makeSet()
{
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
int find(int x)
{
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
void union(int x, int y)
{
int xRoot = find(x), yRoot = find(y);
if (xRoot == yRoot)
return;
if (rank[xRoot] < rank[yRoot])
parent[xRoot] = yRoot;
else if (rank[yRoot] < rank[xRoot])
parent[yRoot] = xRoot;
else
{
parent[yRoot] = xRoot;
rank[xRoot] = rank[xRoot] + 1;
}
}
}
static int max(int... a ) {
int max = a[0];
for(int e:a) max = Math.max(max, e);
return max;
}
static long max(long... a ) {
long max = a[0];
for(long e:a) max = Math.max(max, e);
return max;
}
static int min(int... a ) {
int min = a[0];
for(int e:a) min = Math.min(e, min);
return min;
}
static long min(long... a ) {
long min = a[0];
for(long e:a) min = Math.min(e, min);
return min;
}
static int[] KMP(String str) {
int n = str.length();
int[] kmp = new int[n];
for(int i = 1 ; i<n ; i++) {
int j = kmp[i-1];
while(j>0 && str.charAt(i) != str.charAt(j)) {
j = kmp[j-1];
}
if(str.charAt(i) == str.charAt(j)) j++;
kmp[i] = j;
}
return kmp;
}
/************************************************ Query **************************************************************************************/
/***************************************** Sparse Table ********************************************************/
static class SparseTable{
private long[][] st;
SparseTable(long[] arr){
int n = arr.length;
st = new long[n][25];
log = new int[n+2];
build_log(n+1);
build(arr);
}
private void build(long[] arr) {
int n = arr.length;
for(int i = n-1 ; i>=0 ; i--) {
for(int j = 0 ; j<25 ; j++) {
int r = i + (1<<j)-1;
if(r>=n) break;
if(j == 0 ) st[i][j] = arr[i];
else st[i][j] = Math.min(st[i][j-1] , st[ i + ( 1 << (j-1) ) ][ j-1 ] );
}
}
}
public long gcd(long a ,long b) {
if(a == 0) return b;
return gcd(b%a , a);
}
public long query(int l ,int r) {
int w = r-l+1;
int power = log[w];
return Math.min(st[l][power],st[r - (1<<power) + 1][power]);
}
private int[] log;
void build_log(int n) {
log[1] = 0;
for(int i = 2 ; i<=n ; i++) {
log[i] = 1 + log[i/2];
}
}
}
/******************************************************** Segement Tree *****************************************************/
/**
static class SegmentTree{
long[] tree;
long[] arr;
int n;
SegmentTree(long[] arr){
this.n = arr.length;
tree = new long[4*n+1];
this.arr = arr;
buildTree(0, n-1, 1);
}
void buildTree(int s ,int e ,int index ) {
if(s == e) {
tree[index] = arr[s];
return;
}
int mid = (s+e)/2;
buildTree( s, mid, 2*index);
buildTree( mid+1, e, 2*index+1);
tree[index] = Math.min(tree[2*index] , tree[2*index+1]);
}
long query(int si ,int ei) {
return query(0 ,n-1 , si ,ei , 1 );
}
private long query( int ss ,int se ,int qs , int qe,int index) {
if(ss>=qs && se<=qe) return tree[index];
if(qe<ss || se<qs) return (long)(1e17);
int mid = (ss + se)/2;
long left = query( ss , mid , qs ,qe , 2*index);
long right= query(mid + 1 , se , qs ,qe , 2*index+1);
return Math.min(left, right);
}
public void update(int index , int val) {
arr[index] = val;
for(long e:arr) System.out.print(e+" ");
update(index , 0 , n-1 , 1);
}
private void update(int id ,int si , int ei , int index) {
if(id < si || id>ei) return;
if(si == ei ) {
tree[index] = arr[id];
return;
}
if(si > ei) return;
int mid = (ei + si)/2;
update( id, si, mid , 2*index);
update( id , mid+1, ei , 2*index+1);
tree[index] = Math.min(tree[2*index] ,tree[2*index+1]);
}
}
*/
/* ***************************************************************************************************************************************************/
// static MyScanner sc = new MyScanner(); // only in case of less memory
static Reader sc = new Reader();
static StringBuilder sb = new StringBuilder();
public static void main(String args[]) throws IOException {
int tc = 1;
// tc = sc.nextInt();
for(int i = 1 ; i<=tc ; i++) {
// sb.append("Case #" + i + ": " ); // During KickStart && HackerCup
TEST_CASE();
}
System.out.println(sb);
}
static void TEST_CASE() {
int n = sc.nextInt();
int q = sc.nextInt();
DisjointUnionSets dsu = new DisjointUnionSets(n+10);;
int ext = 0;
while(q-- > 0 ) {
int x = sc.nextInt() , y = sc.nextInt();
if(dsu.find(x) == dsu.find(y)) {
ext++;
}else {
dsu.union(x, y);
}
int[] c = new int[n+10];
for(int i =0 ; i<n+10 ; i++) c[dsu.find(i)]++;
PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.reverseOrder());
for(int e:c) pq.add(e);
int tot = 0;
for(int i = 0 ;i<=ext ; i++) tot += pq.poll();
sb.append(min(tot-1 , n-1)+"\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 | c875a25eb66ae91e6c19d53c4b14f3bf | 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.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.List;
import java.util.StringTokenizer;
public class A4 {
void solve() {
int n = cint();
int d = cint();
TIntList[] groups = new TIntList[n];
List<TIntList> sorted = new ArrayList<>();
for (int i = 0; i < n; i++) {
groups[i] = new TIntList();
groups[i].add(i);
sorted.add(groups[i]);
}
int free = 0;
for (int i = 1; i <= d; i++) {
int x = cint() - 1;
int y = cint() - 1;
if (groups[x] == groups[y]) {
free++;
} else {
sorted.remove(groups[y]);
TIntList ymembers = groups[y];
for (int j = 0; j < ymembers.len; j++) {
groups[ymembers.x[j]] = groups[x];
}
groups[x].addAll(ymembers);
int xs = groups[x].len;
int index = sorted.indexOf(groups[x]);
// siftup
int j = index - 1;
for (; j >= 0 && sorted.get(j).len < xs; j--) {
sorted.set(j + 1, sorted.get(j));
}
sorted.set(j + 1, groups[x]);
}
int v = 0;
for (int j = 0; j <= free; j++) {
v += sorted.get(j).len;
}
cout(v - 1);
}
}
public static void main(String... args) {
// int t = in.nextInt();
// for (int test = 0; test < t; test++) {
new A4().solve();
// }
}
static final QuickReader in = new QuickReader(System.in);
static final PrintStream out = System.out;
static int cint() {
return in.nextInt();
}
static long clong() {
return in.nextLong();
}
static String cstr() {
return in.nextLine();
}
static int[] carr_int(int n) {
return in.nextInts(n);
}
static long[] carr_long(int n) {
return in.nextLongs(n);
}
static void cout(int... a) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < a.length; i++) {
if (i != 0) {
buf.append(' ');
}
buf.append(a[i]);
}
out.println(buf);
}
static void cout(long... a) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < a.length; i++) {
if (i != 0) {
buf.append(' ');
}
buf.append(a[i]);
}
out.println(buf);
}
static void cout(Object o) {
out.println(o);
}
static class QuickReader {
BufferedReader in;
StringTokenizer token;
public QuickReader(InputStream ins) {
in = new BufferedReader(new InputStreamReader(ins));
token = new StringTokenizer("");
}
public boolean hasNext() {
while (!token.hasMoreTokens()) {
try {
String s = in.readLine();
if (s == null) {
return false;
}
token = new StringTokenizer(s);
} catch (IOException e) {
throw new InputMismatchException();
}
}
return true;
}
public String next() {
hasNext();
return token.nextToken();
}
public String nextLine() {
try {
String s = in.readLine();
token = new StringTokenizer("");
return s;
} catch (IOException e) {
throw new InputMismatchException();
}
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] nextInts(int n) {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = nextInt();
}
return res;
}
public long nextLong() {
return Long.parseLong(next());
}
public long[] nextLongs(int n) {
long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = nextLong();
}
return res;
}
}
class TIntList {
int[] x;
int len;
public TIntList() {
this(3);
}
public TIntList(int capacity) {
this.x = new int[capacity];
}
public TIntList(int... array) {
this(false, array);
}
public TIntList(boolean copy, int... array) {
this.x = copy ? Arrays.copyOf(array, array.length) : array;
this.len = array.length;
}
public void add(int val) {
if (len >= x.length) {
x = Arrays.copyOf(x, 3 * x.length / 2 + 1);
}
x[len++] = val;
}
public void addAll(int... a) {
for (int o : a) {
add(o);
}
}
public void addAll(TIntList a) {
for (int i = 0; i < a.len; i++) {
add(a.x[i]);
}
}
public int get(int index) {
return x[index];
}
public int max() {
int m = x[0];
for (int o : x) {
if (m < o) {
m = o;
}
}
return m;
}
}
}
| 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 | 279d739d8c7cb6bf5b20d02385fd5705 | 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.*;
import static java.lang.Math.ceil;
import static java.util.Arrays.sort;
public class C {
public static void main(String[] args) throws IOException {
int n = rni();
int d = ni();
DisjointSetUnion set = new DisjointSetUnion(n+1);
int free = 0;
for (int i = 0 ; i < d; i++){
int a = rni();
int b = ni();
if (!set.union(a,b)){
free++;
}
int counts [] =new int[n];
for (int j = 0 ; j< n; j++){
counts[j] = set.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];
}
prln(ans-1);
}
close();
}
static boolean check(int[] a, int low, int high, int val) {
while (low <= high) {
if (a[low] != a[high] && a[low] != val && a[high] != val) {
return false;
}
if (a[low] == val) {
low++;
}
if (a[high] == val) {
high--;
}
if (a[high] == a[low]) {
high--;
low++;
}
}
return true;
}
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(n);
}
public void clear(int n) {
for (int i = 0; i < n; 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 BufferedReader __i = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter __o = new PrintWriter(new OutputStreamWriter(System.out));
static StringTokenizer input;
static boolean [] isPrime;
static Random __r = new Random();
// references
// IBIG = 1e9 + 7
// IMAX ~= 2e9
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final long LMAX = 9223372036854775807L;
// math util
static int minof(int a, int b, int c) {
return min(a, min(b, c));
}
static int minof(int... x) {
if (x.length == 1) return x[0];
if (x.length == 2) return min(x[0], x[1]);
if (x.length == 3) return min(x[0], min(x[1], x[2]));
int min = x[0];
for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i];
return min;
}
static long minof(long a, long b, long c) {
return min(a, min(b, c));
}
static long minof(long... x) {
if (x.length == 1) return x[0];
if (x.length == 2) return min(x[0], x[1]);
if (x.length == 3) return min(x[0], min(x[1], x[2]));
long min = x[0];
for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i];
return min;
}
static int maxof(int a, int b, int c) {
return max(a, max(b, c));
}
static int maxof(int... x) {
if (x.length == 1) return x[0];
if (x.length == 2) return max(x[0], x[1]);
if (x.length == 3) return max(x[0], max(x[1], x[2]));
int max = x[0];
for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i];
return max;
}
static long maxof(long a, long b, long c) {
return max(a, max(b, c));
}
static long maxof(long... x) {
if (x.length == 1) return x[0];
if (x.length == 2) return max(x[0], x[1]);
if (x.length == 3) return max(x[0], max(x[1], x[2]));
long max = x[0];
for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i];
return max;
}
static int powi(int a, int b) {
if (a == 0) return 0;
int ans = 1;
while (b > 0) {
if ((b & 1) > 0) ans *= a;
a *= a;
b >>= 1;
}
return ans;
}
static long powl(long a, int b) {
if (a == 0) return 0;
long ans = 1;
while (b > 0) {
if ((b & 1) > 0) ans *= a;
a *= a;
b >>= 1;
}
return ans;
}
static int fli(double d) {
return (int) d;
}
static int cei(double d) {
return (int) ceil(d);
}
static long fll(double d) {
return (long) d;
}
static long cel(double d) {
return (long) ceil(d);
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static int[] exgcd(int a, int b) {
if (b == 0) return new int[]{1, 0};
int[] y = exgcd(b, a % b);
return new int[]{y[1], y[0] - y[1] * (a / b)};
}
static long[] exgcd(long a, long b) {
if (b == 0) return new long[]{1, 0};
long[] y = exgcd(b, a % b);
return new long[]{y[1], y[0] - y[1] * (a / b)};
}
static int randInt(int min, int max) {
return __r.nextInt(max - min + 1) + min;
}
static long mix(long x) {
x += 0x9e3779b97f4a7c15L;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebL;
return x ^ (x >> 31);
}
static void setTrue(int n) {
for (int i = 0; i < n; i++) {
isPrime[i] = true;
}
}
static void prime(int n) {
for (int i = 2; i * i < n; i++) {
if (isPrime[i]) {
for (int j = i * i; j < n; j += i) isPrime[j] = false;
}
}
}
// array util
static void reverse(int[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
int swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(long[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
long swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(double[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
double swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void reverse(char[] a) {
for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {
char swap = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = swap;
}
}
static void shuffle(int[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
int swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void shuffle(long[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
long swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void shuffle(double[] a) {
int n = a.length - 1;
for (int i = 0; i < n; ++i) {
int ind = randInt(i, n);
double swap = a[i];
a[i] = a[ind];
a[ind] = swap;
}
}
static void rsort(int[] a) {
shuffle(a);
sort(a);
}
static void rsort(long[] a) {
shuffle(a);
sort(a);
}
static void rsort(double[] a) {
shuffle(a);
sort(a);
}
static int[] copy(int[] a) {
int[] ans = new int[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static long[] copy(long[] a) {
long[] ans = new long[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static double[] copy(double[] a) {
double[] ans = new double[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static char[] copy(char[] a) {
char[] ans = new char[a.length];
for (int i = 0; i < a.length; ++i) ans[i] = a[i];
return ans;
}
static void resetBoolean(boolean[] vis, int n) {
for (int i = 0; i < n; i++) {
vis[i] = false;
}
}
static void setMinusOne(int[][] matrix) {
int row = matrix.length;
int col = matrix[0].length;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
matrix[i][j] = -1;
}
}
}
// input
static void r() throws IOException {
input = new StringTokenizer(rline());
}
static int ri() throws IOException {
return Integer.parseInt(rline().split(" ")[0]);
}
static long rl() throws IOException {
return Long.parseLong(rline());
}
static double rd() throws IOException {
return Double.parseDouble(rline());
}
static int[] ria(int n) throws IOException {
int[] a = new int[n];
r();
for (int i = 0; i < n; ++i) a[i] = ni();
return a;
}
static void ria(int[] a) throws IOException {
int n = a.length;
r();
for (int i = 0; i < n; ++i) a[i] = ni();
}
static int[] riam1(int n) throws IOException {
int[] a = new int[n];
r();
for (int i = 0; i < n; ++i) a[i] = ni() - 1;
return a;
}
static void riam1(int[] a) throws IOException {
int n = a.length;
r();
for (int i = 0; i < n; ++i) a[i] = ni() - 1;
}
static long[] rla(int n) throws IOException {
long[] a = new long[n];
r();
for (int i = 0; i < n; ++i) a[i] = nl();
return a;
}
static void rla(long[] a) throws IOException {
int n = a.length;
r();
for (int i = 0; i < n; ++i) a[i] = nl();
}
static double[] rda(int n) throws IOException {
double[] a = new double[n];
r();
for (int i = 0; i < n; ++i) a[i] = nd();
return a;
}
static void rda(double[] a) throws IOException {
int n = a.length;
r();
for (int i = 0; i < n; ++i) a[i] = nd();
}
static char[] rcha() throws IOException {
return rline().toCharArray();
}
static void rcha(char[] a) throws IOException {
int n = a.length, i = 0;
for (char c : rline().toCharArray()) a[i++] = c;
}
static String rline() throws IOException {
return __i.readLine();
}
static String n() {
return input.nextToken();
}
static int rni() throws IOException {
r();
return ni();
}
static int ni() {
return Integer.parseInt(n());
}
static long rnl() throws IOException {
r();
return nl();
}
static long nl() {
return Long.parseLong(n());
}
static double rnd() throws IOException {
r();
return nd();
}
static double nd() {
return Double.parseDouble(n());
}
// output
static void pr(int i) {
__o.print(i);
}
static void prln(int i) {
__o.println(i);
}
static void pr(long l) {
__o.print(l);
}
static void prln(long l) {
__o.println(l);
}
static void pr(double d) {
__o.print(d);
}
static void prln(double d) {
__o.println(d);
}
static void pr(char c) {
__o.print(c);
}
static void prln(char c) {
__o.println(c);
}
static void pr(char[] s) {
__o.print(new String(s));
}
static void prln(char[] s) {
__o.println(new String(s));
}
static void pr(String s) {
__o.print(s);
}
static void prln(String s) {
__o.println(s);
}
static void pr(Object o) {
__o.print(o);
}
static void prln(Object o) {
__o.println(o);
}
static void prln() {
__o.println();
}
static void pryes() {
prln("yes");
}
static void pry() {
prln("Yes");
}
static void prY() {
prln("YES");
}
static void prno() {
prln("no");
}
static void prn() {
prln("No");
}
static void prN() {
prln("NO");
}
static boolean pryesno(boolean b) {
prln(b ? "yes" : "no");
return b;
}
;
static boolean pryn(boolean b) {
prln(b ? "Yes" : "No");
return b;
}
static boolean prYN(boolean b) {
prln(b ? "YES" : "NO");
return b;
}
static void prln(int... a) {
for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i) ;
if (a.length > 0) prln(a[a.length - 1]);
else prln();
}
static void prln(long... a) {
for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i) ;
if (a.length > 0) prln(a[a.length - 1]);
else prln();
}
static void prln(double... a) {
for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i) ;
if (a.length > 0) prln(a[a.length - 1]);
else prln();
}
static <T> void prln(Collection<T> c) {
int n = c.size() - 1;
Iterator<T> iter = c.iterator();
for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i) ;
if (n >= 0) prln(iter.next());
else prln();
}
static void h() {
prln("hlfd");
flush();
}
static void flush() {
__o.flush();
}
static void close() {
__o.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 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 | 3d94e8b2ec9640137921c11964255b5c | 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.PrintStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.*;
public class Main {
// static final File ip = new File("input.txt");
// static final File op = new File("output.txt");
// static {
// try {
// System.setOut(new PrintStream(op));
// System.setIn(new FileInputStream(ip));
// } catch (Exception e) {
// }
// }
public static void main(String[] args) {
FastReader sc = new FastReader();
int test = 1;
// test = sc.nextInt();
while (test-- > 0) {
int n = sc.nextInt();
int m = sc.nextInt();
DSU dsu = new DSU(n);
int cc = 0;
while (m-- > 0) {
int x = sc.nextInt();
int y = sc.nextInt();
if (!dsu.unionBySize(x, y)) {
cc++;
}
ArrayList<Integer> as = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (dsu.find(i) == i)
as.add(dsu.total_Elements[i]);
}
Collections.sort(as, Collections.reverseOrder());
long sum = 0;
for (int i = 0; i < as.size() && i <= cc; i++)
sum += as.get(i);
System.out.println(sum - 1);
}
}
}
static long power(long x, long y, long p) {
long res = 1;
x = x % p;
if (x == 0)
return 0;
while (y > 0) {
if ((y & 1) != 0)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
public static int countSetBits(long number) {
int count = 0;
while (number > 0) {
++count;
number &= number - 1;
}
return count;
}
static int lower_bound(long target, pair[] a, int pos) {
if (pos >= a.length)
return -1;
int low = pos, high = a.length - 1;
while (low < high) {
int mid = low + (high - low) / 2;
if (a[mid].a < target)
low = mid + 1;
else
high = mid;
}
return a[low].a >= target ? low : -1;
}
private static <T> void swap(int[] a, int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static class pair {
int a;
int b;
pair(int x, int y) {
this.a = x;
this.b = y;
}
}
static class first implements Comparator<pair> {
public int compare(pair p1, pair p2) {
if (p1.a > p2.a)
return -1;
else if (p1.a < p2.a)
return 1;
return 0;
}
}
static class second implements Comparator<pair> {
public int compare(pair p1, pair p2) {
if (p1.b > p2.b)
return 1;
else if (p1.b < p2.b)
return -1;
return 0;
}
}
private static long getSum(int[] array) {
long sum = 0;
for (int value : array) {
sum += value;
}
return sum;
}
private static boolean isPrime(Long x) {
if (x < 2)
return false;
for (long d = 2; d * d <= x; ++d) {
if (x % d == 0)
return false;
}
return true;
}
static int[] reverse(int a[], int n) {
int i, k, t;
for (i = 0; i < n / 2; i++) {
t = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = t;
}
return a;
}
private static boolean isPrimeInt(int x) {
if (x < 2)
return false;
for (int d = 2; d * d <= x; ++d) {
if (x % d == 0)
return false;
}
return true;
}
public static String reverse(String input) {
StringBuilder str = new StringBuilder("");
for (int i = input.length() - 1; i >= 0; i--) {
str.append(input.charAt(i));
}
return str.toString();
}
private static int[] getPrimes(int n) {
boolean[] used = new boolean[n + 1];
used[0] = used[1] = true;
int size = 0;
for (int i = 2; i <= n; ++i) {
if (!used[i]) {
++size;
for (int j = 2 * i; j <= n; j += i) {
used[j] = true;
}
}
}
int[] primes = new int[size];
for (int i = 0, cur = 0; i <= n; ++i) {
if (!used[i]) {
primes[cur++] = i;
}
}
return primes;
}
private static long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
private static long gcd(long a, long b) {
return (a == 0 ? b : gcd(b % a, a));
}
static void sortI(int[] arr) {
int n = arr.length;
Random rnd = new Random();
for (int i = 0; i < n; ++i) {
int tmp = arr[i];
int randomPos = i + rnd.nextInt(n - i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
Arrays.sort(arr);
}
static void shuffleList(ArrayList<Long> arr) {
int n = arr.size();
Random rnd = new Random();
for (int i = 0; i < n; ++i) {
long tmp = arr.get(i);
int randomPos = i + rnd.nextInt(n - i);
arr.set(i, arr.get(randomPos));
arr.set(randomPos, tmp);
}
}
static void factorize(long n) {
int count = 0;
while (!(n % 2 > 0)) {
n >>= 1;
count++;
}
if (count > 0) {
// System.out.println("2" + " " + count);
}
long i = 0;
for (i = 3; i <= (long) Math.sqrt(n); i += 2) {
count = 0;
while (n % i == 0) {
count++;
n = n / i;
}
if (count > 0) {
// System.out.println(i + " " + count);
}
}
if (n > 2) {
// System.out.println(i + " " + count);
}
}
static void sortL(long[] arr) {
int n = arr.length;
Random rnd = new Random();
for (int i = 0; i < n; ++i) {
long tmp = arr[i];
int randomPos = i + rnd.nextInt(n - i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
Arrays.sort(arr);
}
////////////////////////////////// DSU START ///////////////////////////
static class DSU {
int[] parent, rank, total_Elements;
DSU(int n) {
parent = new int[n + 1];
rank = new int[n + 1];
total_Elements = new int[n + 1];
for (int i = 0; i <= n; i++) {
parent[i] = i;
rank[i] = 1;
total_Elements[i] = 1;
}
}
int find(int u) {
if (parent[u] == u)
return u;
return parent[u] = find(parent[u]);
}
void unionByRank(int u, int v) {
int pu = find(u);
int pv = find(v);
if (pu != pv) {
if (rank[pu] > rank[pv]) {
parent[pv] = pu;
total_Elements[pu] += total_Elements[pv];
} else if (rank[pu] < rank[pv]) {
parent[pu] = pv;
total_Elements[pv] += total_Elements[pu];
} else {
parent[pu] = pv;
total_Elements[pv] += total_Elements[pu];
rank[pv]++;
}
}
}
boolean unionBySize(int u, int v) {
u = find(u);
v = find(v);
if (u != v) {
parent[u] = v;
total_Elements[v] += total_Elements[u];
total_Elements[u] = 0;
return true;
}
return false;
}
}
////////////////////////////////// DSU END /////////////////////////////
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public boolean hasNext() {
return false;
}
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 | e07a1f138b8a385c0d27eac7a24c3a3f | 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) {
FastScanner fs=new FastScanner();
/****** CODE STARTS HERE *****/
//------------------------------------------------------------------------------------------------------------
int n=fs.nextInt(), d=fs.nextInt();
DisjointSet dj = new DisjointSet(n);
int extra_edges = 0;
while(d-->0) {
int u=fs.nextInt()-1, v=fs.nextInt()-1;
if(!dj.union(u, v))
extra_edges++;
List<Integer> b = new ArrayList<>();
int[] cnt = new int[n];
for(int i=0; i<n; i++)cnt[dj.find(i)]++;
for(int i=0; i<n; i++)if(dj.find(i)==i)b.add(cnt[i]);
Collections.sort(b, Collections.reverseOrder());
int sum = 0;
for(int i=0; i<=extra_edges; i++) {
sum += b.get(i);
}
System.out.println(sum-1);
}
}
static class DisjointSet {
int[] s;
public DisjointSet(int n) {
Arrays.fill(s = new int[n], -1);
}
public int find(int i) {
return s[i] < 0 ? i : (s[i] = find(s[i]));
}
public boolean union(int a, int b) {
if ((a = find(a)) == (b = find(b))) return false;
if(s[a] == s[b]) s[a]--;
if(s[a] <= s[b]) s[b] = a;
else s[a] = b;
return true;
}
}
//****** CODE ENDS HERE *****
//----------------------------------------------------------------------------------------------------------------
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);
}
//----------- FastScanner class for faster input---------------------------
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 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 | 70efb8ef263d494925d4479f2f1dffda | 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.BigInteger;
public class Main {
private static FS sc = new FS();
private static class FS {
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) {}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
private static class extra {
static int[] intArr(int size) {
int[] a = new int[size];
for(int i = 0; i < size; i++) a[i] = sc.nextInt();
return a;
}
static long[] longArr(int size) {
Scanner scc = new Scanner(System.in);
long[] a = new long[size];
for(int i = 0; i < size; i++) a[i] = sc.nextLong();
return a;
}
static long intSum(int[] a) {
long sum = 0;
for(int i = 0; i < a.length; i++) {
sum += a[i];
}
return sum;
}
static long longSum(long[] a) {
long sum = 0;
for(int i = 0; i < a.length; i++) {
sum += a[i];
}
return sum;
}
static LinkedList[] graphD(int vertices, int edges) {
LinkedList<Integer>[] temp = new LinkedList[vertices+1];
for(int i = 0; i <= vertices; i++) temp[i] = new LinkedList<>();
for(int i = 0; i < edges; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
temp[x].add(y);
}
return temp;
}
static LinkedList[] graphUD(int vertices, int edges) {
LinkedList<Integer>[] temp = new LinkedList[vertices+1];
for(int i = 0; i <= vertices; i++) temp[i] = new LinkedList<>();
for(int i = 0; i < edges; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
temp[x].add(y);
temp[y].add(x);
}
return temp;
}
static void printG(LinkedList[] temp) {
for(LinkedList<Integer> aa:temp) System.out.println(aa);
}
static long cal(long val, long pow, long mod) {
if(pow == 0) return 1;
long res = cal(val, pow/2, mod);
long ret = (res*res)%mod;
if(pow%2 == 0) return ret;
return (val*ret)%mod;
}
static long gcd(long a, long b) { return b == 0 ? a:gcd(b, a%b); }
}
static int mod = 998244353;
static LinkedList<Integer>[] temp, idx;
static long inf = (long) Long.MAX_VALUE;
// static long inf = Long.MAX_VALUE;
static int max;
public static void main(String[] args) {
// int t = sc.nextInt();
int t = 1;
StringBuilder ret = new StringBuilder();
while(t-- > 0) {
int n = sc.nextInt(), m = sc.nextInt();
int[] par = new int[n+1], rank = new int[n+1];
for(int i = 0; i <= n; i++) par[i] = i;
int extra = 0;
for(int i = 0; i < m; i++) {
int x = sc.nextInt(), y = sc.nextInt();
if(find(x, par) != find(y, par)) {
int X = find(x, par), Y = find(y, par);
union(X, Y, rank, par);
} else {
extra++;
}
// for(int aa:par) System.out.print(aa + " ");
// System.out.println(extra);
HashMap<Integer, Integer> map = new HashMap<>();
for(int j = 1; j <= n; j++) map.put(find(par[j], par), map.getOrDefault(find(par[j], par), 0)+1);
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
for(int aa:map.keySet()) pq.add(map.get(aa));
int cur = extra, sum = 0;
while(cur-- >= 0 && !pq.isEmpty()) {
int poll = pq.poll();
sum += poll;
}
ret.append((sum - 1) + "\n");
}
}
System.out.println(ret);
}
static int find(int x, int[] par) {
if(par[x] == x) return x;
return par[x] = find(par[x], par);
}
static void union(int x, int y, int[] rank, int[] par) {
if(rank[x] > rank[y]) {
par[y] = x;
} else {
if(rank[x] == rank[y]) rank[y]++;
par[x] = 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 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 | 07e2a29931b8ce71b91d649ccabffe37 | 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.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
/**
* @author Mubtasim Shahriar
*/
public class DeltixAutumn2021 {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader sc = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Solver solver = new Solver();
// int t = sc.nextInt();
int t = 1;
while (t-- != 0) {
solver.solve(sc, out);
}
out.close();
}
static class Solver {
int[] link, size;
int max;
public void solve(InputReader sc, PrintWriter out) {
int n = sc.nextInt();
int d = sc.nextInt();
link = new int[n];
size = new int[n];
int[][] ds= new int[d][2];
for(int i = 0; i < d; i++) {
for (int j = 0; j < 2; j++) {
ds[i][j] = sc.nextInt()-1;
}
}
for(int dd = 0; dd < d; dd++) {
int extra = 0;
Arrays.fill(size,1);
for(int i = 0; i < n; i++) link[i] =i;
TreeMap<Integer,Integer> tm = new TreeMap<>(Collections.reverseOrder());
tm.put(1,n);
for(int prevdd = 0; prevdd <= dd; prevdd++) {
int a = ds[prevdd][0];
int b = ds[prevdd][1];
if(find(a)==find(b)) extra++;
else {
connect(a,b,tm);
}
}
int ans = 0;
if((int)tm.firstKey()==1) throw new RuntimeException();
ans += getFirst(tm);
while(!tm.isEmpty() && extra>0) {
ans += getFirst(tm);
extra--;
}
out.println(ans-1);
}
}
private int getFirst(TreeMap<Integer, Integer> tm) {
int firstKey = tm.firstKey();
int val = tm.get(firstKey);
if(val<=1) tm.remove(firstKey);
else tm.put(firstKey,val-1);
return firstKey;
}
private void connect(int a, int b, TreeMap<Integer,Integer> tm) {
a = find(a);
b = find(b);
if(a==b) throw new RuntimeException();
if(size[a]<size[b]) {
int tmp = a;
a = b;
b = tmp;
}
remm(tm,size[b]);
link[b] = link[a];
remm(tm,size[a]);
size[a] += size[b];
addd(tm,size[a]);
}
private void addd(TreeMap<Integer, Integer> tm, int key) {
tm.put(key,tm.getOrDefault(key,0)+1);
}
private void remm(TreeMap<Integer, Integer> tm, int key) {
if(!tm.containsKey(key)) return;
int val = tm.get(key);
if(val==1) tm.remove(key);
else tm.put(key,val-1);
}
private int find(int x) {
if(x==link[x]) return x;
return link[x] = find(link[x]);
}
}
static void sort(int[] arr) {
ArrayList<Integer> al = new ArrayList();
for (int i : arr) al.add(i);
Collections.sort(al);
int idx = 0;
for (int i : al) arr[idx++] = i;
}
static void sort(long[] arr) {
ArrayList<Long> al = new ArrayList();
for (long i : arr) al.add(i);
Collections.sort(al);
int idx = 0;
for (long i : al) arr[idx++] = i;
}
static void sortDec(int[] arr) {
ArrayList<Integer> al = new ArrayList();
for (int i : arr) al.add(i);
Collections.sort(al, Collections.reverseOrder());
int idx = 0;
for (int i : al) arr[idx++] = i;
}
static void sortDec(long[] arr) {
ArrayList<Long> al = new ArrayList();
for (long i : arr) al.add(i);
Collections.sort(al, Collections.reverseOrder());
int idx = 0;
for (long i : al) arr[idx++] = i;
}
static class InputReader {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public 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++];
}
public int peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
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;
}
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 String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0) {
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return readLine();
} else {
return readLine0();
}
}
public BigInteger readBigInteger() {
try {
return new BigInteger(nextString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char nextCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1) {
read();
}
return value == -1;
}
public String next() {
return nextString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
public int[] nextSortedIntArray(int n) {
int array[] = nextIntArray(n);
Arrays.sort(array);
return array;
}
public int[] nextSumIntArray(int n) {
int[] array = new int[n];
array[0] = nextInt();
for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt();
return array;
}
public long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; ++i) array[i] = nextLong();
return array;
}
public long[] nextSumLongArray(int n) {
long[] array = new long[n];
array[0] = nextInt();
for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt();
return array;
}
public long[] nextSortedLongArray(int n) {
long array[] = nextLongArray(n);
Arrays.sort(array);
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 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 | 8cb8f541c68b857a8e69b308ecd125a0 | 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.InputStreamReader;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* Accomplished using the EduTools plugin by JetBrains https://plugins.jetbrains.com/plugin/10081-edutools
* <p>
* To modify the template, go to Preferences -> Editor -> File and Code Templates -> Other
*/
public class Main {
static class DisjointUnionSets {
int[] rank, parent;
int n;
// Constructor
public DisjointUnionSets(int n) {
rank = new int[n + 1];
parent = new int[n + 1];
this.n = n;
makeSet();
}
// Creates n sets with single item in each
void makeSet() {
for (int i = 1; i <= n; i++) {
// Initially, all elements are in
// their own set.
parent[i] = i;
}
}
// Returns representative of x's set
int find(int x) {
// Finds the representative of the set
// that x is an element of
if (parent[x] != x) {
// if x is not the parent of itself
// Then x is not the representative of
// his set,
parent[x] = find(parent[x]);
// so we recursively call Find on its parent
// and move i's node directly under the
// representative of this set
}
return parent[x];
}
// Unites the set that includes x and the set
// that includes x
void union(int x, int y) {
// Find representatives of two sets
int xRoot = find(x), yRoot = find(y);
// Elements are in the same set, no need
// to unite anything.
if (xRoot == yRoot) {
return;
}
// If x's rank is less than y's rank
if (rank[xRoot] < rank[yRoot])
// Then move x under y so that depth
// of tree remains less
{
parent[xRoot] = yRoot;
}
// Else if y's rank is less than x's rank
else if (rank[yRoot] < rank[xRoot])
// Then move y under x so that depth of
// tree remains less
{
parent[yRoot] = xRoot;
} else // if ranks are the same
{
// Then move y under x (doesn't matter
// which one goes where)
parent[yRoot] = xRoot;
// And increment the result tree's
// rank by 1
rank[xRoot] = rank[xRoot] + 1;
}
}
Map.Entry<Integer, Integer> max() {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 1; i <= n; i++) {
int v = find(i);
map.merge(v, 1, Integer::sum);
}
int best = -1;
Map.Entry<Integer, Integer> res = null;
for (Map.Entry<Integer, Integer> e : map.entrySet()) {
if (e.getValue() > best) {
res = e;
best = e.getValue();
}
}
return res;
}
Map<Integer, Integer> total() {
Map<Integer, Integer> res = new HashMap<>();
for(int i=1; i<=n; i++) {
int v = find(i);
res.merge(v, 1, Integer::sum);
}
return res;
}
}
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] tmp = in.readLine().split(" ");
int n = Integer.parseInt(tmp[0]);
int d = Integer.parseInt(tmp[1]);
List<Integer> xx = new ArrayList<>();
List<Integer> yy = new ArrayList<>();
for (int id = 0; id < d; id++) {
tmp = in.readLine().split(" ");
int x = Integer.parseInt(tmp[0]);
int y = Integer.parseInt(tmp[1]);
xx.add(x);
yy.add(y);
DisjointUnionSets set = new DisjointUnionSets(n);
for (int i = 0; i < xx.size(); i++) {
set.union(xx.get(i), yy.get(i));
}
Map<Integer, Integer> total = set.total();
int needed = 0;
List<Integer> list = new ArrayList<>(total.values());
list.sort(Comparator.naturalOrder());
for (int val : list) {
needed += val - 1;
}
int res = list.get(list.size() - 1) - 1;
int idx = list.size() - 2;
while (needed < id + 1 && idx >= 0) {
res += list.get(idx--);
needed++;
}
System.out.println(res);
}
}
} | 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 | 4c84d75a7e2f107697c5168b9f319737 | 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.util.Map.Entry.comparingByValue;
public class codeforces_deltix_A2021_D {
private static void solve(FastIOAdapter in, PrintWriter out) {
int n = in.nextInt();
int d = in.nextInt();
DisjointUnionSets set = new DisjointUnionSets(n);
int[] count = new int[n];
Arrays.fill(count, 1);
int[][] dd = new int[d][2];
for (int i = 0; i < d; i++) {
int x = in.nextInt();
int y = in.nextInt();
x--;
y--;
dd[i][0] = x;
dd[i][1] = y;
}
int aux = 0;
for (int i = 0; i < d; i++) {
int x = dd[i][0];
int y = dd[i][1];
int px = set.find(x);
int py = set.find(y);
if (px != py) set.union(x, y);
else aux++;
int npx = set.find(x);
int npy = set.find(y);
if (npx != px) {
count[npy] += count[px];
count[px] = 0;
} else if (npy != py) {
count[npx] += count[py];
count[py] = 0;
}
int[][] copy = new int[n][2];
for (int j = 0; j < n; j++) {
copy[j][0] = j;
copy[j][1] = count[j];
}
Arrays.sort(copy, (i1, i2) -> Integer.compare(i2[1], i1[1]));
int res = 0;
for (int j = 0; j <= aux; j++) {
res += copy[j][1];
}
out.println(res - 1);
}
}
static class DisjointUnionSets {
int[] rank, parent;
int n;
public DisjointUnionSets(int n) {
rank = new int[n];
parent = new int[n];
this.n = n;
makeSet();
}
private void makeSet() {
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
int find(int x) {
if (parent[x] != x) {
parent[x] = find(parent[x]);
}
return parent[x];
}
void union(int x, int y) {
int xRoot = find(x), yRoot = find(y);
if (xRoot == yRoot)
return;
if (rank[xRoot] < rank[yRoot])
parent[xRoot] = yRoot;
else if (rank[yRoot] < rank[xRoot])
parent[yRoot] = xRoot;
else {
parent[yRoot] = xRoot;
rank[xRoot]++;
}
}
}
public static void main(String[] args) throws Exception {
try (FastIOAdapter ioAdapter = new FastIOAdapter()) {
int count = 1;
//count = ioAdapter.nextInt();
while (count-- > 0) {
solve(ioAdapter, ioAdapter.out);
}
}
}
static void ruffleSort(int[] arr) {
int n = arr.length;
Random rnd = new Random();
for (int i = 0; i < n; ++i) {
int tmp = arr[i];
int randomPos = i + rnd.nextInt(n - i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
Arrays.sort(arr);
}
static class FastIOAdapter implements AutoCloseable {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter((System.out))));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
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[] readArrayLong(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
@Override
public void close() throws Exception {
out.flush();
out.close();
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 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 | 010526c4b1b9dae81bf436968d232bb4 | 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.util.Arrays;
import java.util.HashSet;
import java.util.StringTokenizer;
public class D {
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 int[] a;
public static void main(String[] args){
FastReader sc = new FastReader();
int n = sc.nextInt();
int q = sc.nextInt();
StringBuilder s = new StringBuilder();
a = new int[n+1];
for (int i=1;i<n+1;i++){
a[i] = i;
}
int more_edge = 0;
while (q-->0){
int c_1 = sc.nextInt();
int c_2 = sc.nextInt();
if (find(c_1)==find(c_2)){
more_edge++;
}else {
unionSet(c_1,c_2);
}
int[] counter = new int[n+1];
for (int i=1;i<n+1;i++){
counter[find(a[i])]++;
}
Arrays.sort(counter);
int res = 0;
for (int i=n;i>=n-more_edge;i--){
res += counter[i];
}
s.append((res-1)+"\n");
}
System.out.println(s);
}
public static int find(int x){
if (x!=a[x]){
a[x] = find(a[x]);
}
return a[x];
}
public static void unionSet(int x,int y){
x = find(x);
y = find(y);
a[x] = 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 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 | 630b9ec280a847fbcc9e027a7da3b316 | 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 CodeForces{
/*-------------------------------------------EDITING CODE STARTS HERE-------------------------------------------*/
public static void main(String[] args) throws IOException{
openIO();
int testCase = 1;
// testCase = sc.nextInt();
preCompute();
for (int i = 1; i <= testCase; i++) solve(i);
closeIO();
}
static class DSU{
int[] parent;
int[] size;
int maxSize = 0;
int waste = 0;
public DSU(int n){
parent = new int[n+1];
size = new int[n+1];
for(int i=1;i<=n;i++){
parent[i] = i;
size[i] = 1;
}
maxSize = 1;
}
public int find(int x){
while(parent[x] != x)x = parent[x];
return x;
}
public void union(int x, int y){
x = find(x);
y = find(y);
if(x==y){
waste++;
return;
}
if(size[x] >= size[y]){
parent[y] = x;
size[x] += size[y];
maxSize = Math.max(maxSize,size[x]);
}else {
parent[x] = y;
size[y] += size[x];
maxSize = Math.max(maxSize,size[y]);
}
}
public int getMaxSize(){
List<Integer> arr = new ArrayList<>();
for(int i=1;i<parent.length;i++)if(parent[i] == i)arr.add(size[i]);
Collections.sort(arr,Collections.reverseOrder());
int sum = 0;
for(int i=0;i<waste+1;i++)sum+=arr.get(i);
return sum;
}
}
public static void solve(int tCase)throws IOException {
int n = sc.nextInt();
int m = sc.nextInt();
DSU dsu = new DSU(n);
for(int i = 0;i<m;i++){
dsu.union(sc.nextInt(), sc.nextInt());
out.println(dsu.getMaxSize()-1);
}
}
private static void preCompute(){}
/*-------------------------------------------EDITING CODE ENDS HERE-------------------------------------------*/
static FastestReader sc;
static PrintWriter out;
private static void openIO() throws IOException{
sc = new FastestReader();
out = new PrintWriter(System.out);
}
/*------------------------------------------HELPER FUNCTION STARTS HERE------------------------------------------*/
public static final int mod = (int) 1e9 +7;
private static final int mod2 = 998244353;
public static final int inf_int = (int) 2e9 + 10;
public static final long inf_long = (long) 4e18;
public static int _digitCount(long num,int base){
return (int)(1 + Math.log(num)/Math.log(base));
}
// time : O(r)
public static int _ncr(int n,int r){
if (r > n) return 0;
long[] inv = new long[r + 1];
inv[0] = 1;
if(r+1>=2)
inv[1] = 1;
// Getting the modular inversion
// for all the numbers
// from 2 to r with respect to mod
for (int i = 2; i <= r; i++)
inv[i] = mod - (mod / i) * inv[(mod % i)] % mod;
int ans = 1;
// for 1/(r!) part
for (int i = 2; i <= r; i++)
ans = (int) (((ans % mod) * (inv[i] % mod)) % mod);
// for (n)*(n-1)*(n-2)*...*(n-r+1) part
for (int i = n; i >= (n - r + 1); i--)
ans = (((ans % mod) * (i % mod)) % mod);
return ans;
}
// euclidean algorithm time O(max (loga ,logb))
public static long _gcd(long a, long b) {
if (a == 0)
return b;
return _gcd(b % a, a);
}
public static long _lcm(long a, long b) {
// lcm(a,b) * gcd(a,b) = a * b
return (a / _gcd(a, b)) * b;
}
// binary exponentiation time O(logn)
public static long _power(long x, long n) {
long ans = 1;
while (n > 0) {
if ((n & 1) == 1) {
ans *= x;
ans %= mod;
n--;
} else {
x *= x;
x %= mod;
n >>= 1;
}
}
return ans;
}
//sieve/first divisor time : O(mx * log ( log (mx) ) )
public static int[] _seive(int mx){
int[] firstDivisor = new int[mx+1];
for(int i=0;i<=mx;i++)firstDivisor[i] = i;
for(int i=2;i*i<=mx;i++)
if(firstDivisor[i] == i)
for(int j = i*i;j<=mx;j+=i)
firstDivisor[j] = i;
return firstDivisor;
}
private static boolean _isPrime(long x){
for(long i=2;i*i<=x;i++)
if(x%i==0)return false;
return true;
}
public static void _sort(int[] arr,boolean isAscending){
int n = arr.length;
List<Integer> list = new ArrayList<>();
for(int ele : arr)list.add(ele);
Collections.sort(list);
if(!isAscending)Collections.reverse(list);
for(int i=0;i<n;i++)arr[i] = list.get(i);
}
public static void _sort(long[] arr,boolean isAscending){
int n = arr.length;
List<Long> list = new ArrayList<>();
for(long ele : arr)list.add(ele);
Collections.sort(list);
if(!isAscending)Collections.reverse(list);
for(int i=0;i<n;i++)arr[i] = list.get(i);
}
/*------------------------------------------HELPER FUNCTION ENDS HERE-------------------------------------------*/
/*-------------------------------------------FAST INPUT STARTS HERE---------------------------------------------*/
public static void closeIO() throws IOException{
out.flush();
out.close();
sc.close();
}
private static final class FastestReader {
private static final int BUFFER_SIZE = 1 << 16;
private final DataInputStream din;
private final byte[] buffer;
private int bufferPointer, bytesRead;
public FastestReader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastestReader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() throws IOException {
int b;
//noinspection StatementWithEmptyBody
while ((b = read()) != -1 && isSpaceChar(b)) {}
return b;
}
public String next() throws IOException {
int b = skip();
final StringBuilder sb = new StringBuilder();
while (!isSpaceChar(b)) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = read();
}
return sb.toString();
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
final 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(); }
final 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(); }
final 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 {
din.close();
}
}
/*---------------------------------------------FAST INPUT ENDS HERE ---------------------------------------------*/
} | 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 | 6580caeae85d615253c1568cd8284668 | 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 currentContest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Random;
import java.util.StringTokenizer;
public class P1 {
static class DisjointUnionSets {
int[] rank, parent;
int n;
// Constructor
public DisjointUnionSets(int n)
{
rank = new int[n];
parent = new int[n];
this.n = n;
makeSet();
}
// Creates n sets with single item in each
void makeSet()
{
for (int i = 0; i < n; i++) {
// Initially, all elements are in
// their own set.
parent[i] = i;
}
}
// Returns representative of x's set
int find(int x)
{
// Finds the representative of the set
// that x is an element of
if (parent[x] != x) {
// if x is not the parent of itself
// Then x is not the representative of
// his set,
parent[x] = find(parent[x]);
// so we recursively call Find on its parent
// and move i's node directly under the
// representative of this set
}
return parent[x];
}
// Unites the set that includes x and the set
// that includes x
void union(int x, int y)
{
// Find representatives of two sets
int xRoot = find(x), yRoot = find(y);
// Elements are in the same set, no need
// to unite anything.
if (xRoot == yRoot)
return;
// If x's rank is less than y's rank
if (rank[xRoot] < rank[yRoot])
// Then move x under y so that depth
// of tree remains less
parent[xRoot] = yRoot;
// Else if y's rank is less than x's rank
else if (rank[yRoot] < rank[xRoot])
// Then move y under x so that depth of
// tree remains less
parent[yRoot] = xRoot;
else // if ranks are the same
{
// Then move y under x (doesn't matter
// which one goes where)
parent[yRoot] = xRoot;
// And increment the result tree's
// rank by 1
rank[xRoot] = rank[xRoot] + 1;
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
FastReader sc = new FastReader();
int t=1;
// t = sc.nextInt();
StringBuilder st = new StringBuilder();
while (t-- != 0) {
int n=sc.nextInt();
int d=sc.nextInt();
DisjointUnionSets dus =
new DisjointUnionSets(n+1);
int max=0;
int count=0;
for(int i=0;i<d;i++) {
int x=sc.nextInt();
int y=sc.nextInt();
if(dus.find(x)==dus.find(y)) {
count++;
}
dus.union(x, y);
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
for(int j=1;j<=n;j++) {
int keep=dus.find(j);
if(map.containsKey(keep)) {
map.put(keep, map.get(keep)+1);
}else {
map.put(keep, 1);
}
}
int tosort[]=new int[map.keySet().size()];
int s=0;
for(int temp:map.keySet()) {
tosort[s++]=(map.get(temp));
}
sort(tosort);
int keep=count;
for(int j=tosort.length-2;j>=0;j--) {
if(keep==0) {
break;
}
tosort[tosort.length-1]+=tosort[j];
keep--;
}
st.append(tosort[tosort.length-1]-1+"\n");
}
}
System.out.println(st);
}
static FastReader sc = new FastReader();
public static void solvegraph() {
int n = sc.nextInt();
int edge[][] = new int[n - 1][2];
for (int i = 0; i < n - 1; i++) {
edge[i][0] = sc.nextInt() - 1;
edge[i][1] = sc.nextInt() - 1;
}
ArrayList<ArrayList<Integer>> ad = new ArrayList<>();
for (int i = 0; i < n; i++) {
ad.add(new ArrayList<Integer>());
}
for (int i = 0; i < n - 1; i++) {
ad.get(edge[i][0]).add(edge[i][1]);
ad.get(edge[i][1]).add(edge[i][0]);
}
int parent[] = new int[n];
Arrays.fill(parent, -1);
parent[0] = n;
ArrayDeque<Integer> queue = new ArrayDeque<>();
queue.add(0);
int child[] = new int[n];
Arrays.fill(child, 0);
ArrayList<Integer> lv = new ArrayList<Integer>();
while (!queue.isEmpty()) {
int toget = queue.getFirst();
queue.removeFirst();
child[toget] = ad.get(toget).size() - 1;
for (int i = 0; i < ad.get(toget).size(); i++) {
if (parent[ad.get(toget).get(i)] == -1) {
parent[ad.get(toget).get(i)] = toget;
queue.addLast(ad.get(toget).get(i));
}
}
lv.add(toget);
}
child[0]++;
}
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();
}
public 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 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 | 9194b44a1fb27a474d54bc847243ed23 | 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.PrintWriter;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
var sc = new Scanner(System.in);
int n = Integer.parseInt(sc.next());
int d = Integer.parseInt(sc.next());
var x = new int[d];
var y = new int[d];
for(int i = 0; i < d; i++){
x[i] = Integer.parseInt(sc.next());
y[i] = Integer.parseInt(sc.next());
}
var pw = new PrintWriter(System.out);
var uf = new UnionFind(n+1);
var treap = new Treap();
for(int i = 0; i < n; i++){
treap.add(1);
}
int count = 0;
for(int i = 0; i < d; i++){
if(uf.same(x[i], y[i])){
count++;
}else{
treap.remove(uf.size[uf.root(x[i])]);
treap.remove(uf.size[uf.root(y[i])]);
uf.unite(x[i], y[i]);
treap.add(uf.size[uf.root(x[i])]);
}
int count2 = 0;
for(int j = 0; j <= count; j++){
int value = treap.get(treap.size() - 1 - j);
count2 += value;
if(value == 1){
count2 += count - j;
break;
}
}
pw.println(count2-1);
}
pw.flush();
}
static class UnionFind {
int[] parent, size;
public UnionFind(int n) {
parent = new int[n];
size = new int[n];
for(int i = 0; i < n; i++){
parent[i] = i;
size[i] = 1;
}
}
int root(int x){
if(parent[x] == x){
return x;
}else{
return parent[x] = root(parent[x]);
}
}
void unite(int x, int y){
x = root(x);
y = root(y);
if(x == y) return;
if(size[x] < size[y]){
parent[x] = y;
size[y] += size[x];
}else{
parent[y] = x;
size[x] += size[y];
}
}
boolean same(int x, int y){
return root(x) == root(y);
}
}
static class Treap {
Node NIL;
Node root;
Random rand;
public Treap(){
NIL = new Node(0, 0);
NIL.parent = NIL;
NIL.leftChild = NIL;
NIL.rightChild = NIL;
NIL.subtreeSize = 0;
root = NIL;
rand = new Random();
}
static class Node {
int value;
int priority;
Node parent;
Node leftChild, rightChild;
int subtreeSize;
public Node(int value, int priority){
this.value = value;
this.priority = priority;
subtreeSize = 1;
}
}
void rotate(Node pivot){
Node r = pivot.parent;
if(r.parent != NIL){
if(r.parent.leftChild == r){
r.parent.leftChild = pivot;
}else{
r.parent.rightChild = pivot;
}
}
if(r.leftChild == pivot){
r.subtreeSize -= r.leftChild.subtreeSize;
r.leftChild = pivot.rightChild;
r.leftChild.parent = r;
r.subtreeSize += r.leftChild.subtreeSize;
pivot.parent = r.parent;
pivot.subtreeSize -= pivot.rightChild.subtreeSize;
pivot.rightChild = r;
pivot.rightChild.parent = pivot;
pivot.subtreeSize += pivot.rightChild.subtreeSize;
}else{
r.subtreeSize -= r.rightChild.subtreeSize;
r.rightChild = pivot.leftChild;
r.rightChild.parent = r;
r.subtreeSize += r.rightChild.subtreeSize;
pivot.parent = r.parent;
pivot.subtreeSize -= pivot.leftChild.subtreeSize;
pivot.leftChild = r;
pivot.leftChild.parent = pivot;
pivot.subtreeSize += pivot.leftChild.subtreeSize;
}
if(pivot.parent == NIL){
root = pivot;
}
}
void add(int value){
Node newNode = new Node(value, rand.nextInt());
newNode.leftChild = NIL;
newNode.rightChild = NIL;
if(root == NIL){
root = newNode;
newNode.parent = NIL;
}else{
Node n = root;
while(true){
n.subtreeSize++;
if(newNode.value < n.value){
if(n.leftChild == NIL){
n.leftChild = newNode;
newNode.parent = n;
break;
}else{
n = n.leftChild;
}
}else{
if(n.rightChild == NIL){
n.rightChild = newNode;
newNode.parent = n;
break;
}else{
n = n.rightChild;
}
}
}
while(newNode != root && newNode.priority > newNode.parent.priority){
rotate(newNode);
}
}
}
boolean remove(int value){
if(!contains(value)){
return false;
}
Node x = root;
while(true){
x.subtreeSize--;
if(value == x.value){
break;
}else if(value < x.value){
x = x.leftChild;
}else{
x = x.rightChild;
}
}
while(true){
if(x.leftChild == NIL && x.rightChild == NIL){
if(x == root){
root = NIL;
}else if(x.parent.leftChild == x){
x.parent.leftChild = NIL;
}else{
x.parent.rightChild = NIL;
}
break;
}else if(x.rightChild == NIL){
if(x.parent.leftChild == x){
x.parent.leftChild = x.leftChild;
}else{
x.parent.rightChild = x.leftChild;
}
x.leftChild.parent = x.parent;
if(x == root){
root = x.leftChild;
}
break;
}else if(x.leftChild == NIL){
if(x.parent.leftChild == x){
x.parent.leftChild = x.rightChild;
}else{
x.parent.rightChild = x.rightChild;
}
x.rightChild.parent = x.parent;
if(x == root){
root = x.rightChild;
}
break;
}else{
if(x.leftChild.priority > x.rightChild.priority){
rotate(x.leftChild);
}else{
rotate(x.rightChild);
}
}
}
return true;
}
boolean contains(int value){
Node x = root;
while(true){
if(x == NIL){
return false;
}else if(value == x.value){
return true;
}else if(value < x.value){
x = x.leftChild;
}else{
x = x.rightChild;
}
}
}
int get(int index){
if(index < 0 || size() <= index){
throw new IndexOutOfBoundsException();
}
int count = 0;
Node x = root;
while(true){
int count2 = count + x.leftChild.subtreeSize;
if(index == count2){
return x.value;
}else if(index < count2){
x = x.leftChild;
}else{
count += x.leftChild.subtreeSize + 1;
x = x.rightChild;
}
}
}
int size(){
return root.subtreeSize;
}
}
} | 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 | f83904b3d7e6873fd9313c355962b85c | 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.Comparator;
import java.util.Scanner;
import java.util.TreeSet;
public class D {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
solve(s.nextInt(), s.nextInt(), s);
}
public static void solve(int n, int c, Scanner s) {
TreeSet<TreeSet<Integer>> zKomponenten = new TreeSet<TreeSet<Integer>>(new Comparator<TreeSet<Integer>>() {
@Override
public int compare(TreeSet<Integer> o1, TreeSet<Integer> o2) {
if (o1.size() == o2.size()) return o1.first() - o2.first();
return o2.size() - o1.size();
}
});
TreeSet<Integer> t;
for (int i = 0; i < n; i++) {
t = new TreeSet<>();
t.add(i);
zKomponenten.add(t);
}
int a;
int b;
TreeSet<Integer> tA = new TreeSet<>();
TreeSet<Integer> tB = new TreeSet<>();
int count;
int conn;
for (int i = 0; i < c; i++) {
a = s.nextInt() - 1;
b = s.nextInt() - 1;
for (TreeSet<Integer> index: zKomponenten) {
if (index.contains(a)) tA = index;
if (index.contains(b)) tB = index;
}
zKomponenten.remove(tA);
zKomponenten.remove(tB);
tB.addAll(tA);
zKomponenten.add(tB);
conn = 0;
count = 0;
for (TreeSet<Integer> index: zKomponenten) {
if (count++ <= i + 1 - (n - zKomponenten.size())) {
conn += index.size();
}
}
System.out.println(conn - 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 | 541d86b097cf3209fc1f33b7b129d980 | 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.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class ProblemD {
static class UnionFind{
int[] rep;
int[] size;
TreeMap<Integer, Integer> sizes = new TreeMap<>(Collections.reverseOrder());
public UnionFind(int n){
rep = new int[n];
size = new int[n];
for(int i = 0; i < n; i++){
rep[i] = i;
addSize(1);
}
Arrays.fill(size, 1);
}
public int find(int a){
while(rep[a] != a) a = rep[a];
return a;
}
public int size(int a){
return size[find(a)];
}
public boolean merge(int a, int b){
int aRep = find(a);
int bRep = find(b);
if(aRep == bRep) return false;
rep[bRep] = aRep;
removeSize(size[aRep]);
removeSize(size[bRep]);
size[aRep] += size[bRep];
addSize(size[aRep]);
return true;
}
public void addSize(int a){
if(sizes.containsKey(a)){
sizes.put(a, sizes.get(a)+1);
}else{
sizes.put(a, 1);
}
}
public void removeSize(int a){
if(sizes.get(a) > 1){
sizes.put(a, sizes.get(a)-1);
}else{
sizes.remove(a);
}
}
public int getSol(int a){
int sol = 0;
Iterator<Map.Entry<Integer, Integer>> i = sizes.entrySet().iterator();
while(a > 0 && i.hasNext()){
Map.Entry<Integer, Integer> e = i.next();
if(e.getValue() <= a){
a-=e.getValue();
sol += e.getValue()*e.getKey();
}else{
sol += a*e.getKey();
a = 0;
}
}
return sol;
}
}
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void solve() throws IOException{
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int d = Integer.parseInt(st.nextToken());
UnionFind uf = new UnionFind(n);
int extra = 0;
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;
if(!uf.merge(a, b)){
extra++;
}
System.out.println(uf.getSol(extra+1)-1);
}
}
public static void main(String[] args) throws IOException {
// int t = Integer.parseInt(br.readLine());
// for(int i = 0; i < t; i++) solve();
solve();
}
}
| 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 | 5833035d144260f26c43c769e5888077 | 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 {
public static void main(String[] args) {
FastScanner sc = new FastScanner();
int n = sc.nextInt();
int d = sc.nextInt();
UnionFind uf = new UnionFind(n);
Multiset inside = new Multiset();
inside.add(1);
Multiset outside = new Multiset();
for(int i = 0; i < n-1; i++) {
outside.add(1);
}
int k = 1;
StringBuilder sb = new StringBuilder();
while(d-->0) {
int u = sc.nextInt()-1;
int v = sc.nextInt()-1;
int rootu = uf.find(u);
int rootv = uf.find(v);
if(rootu != rootv) {
int a = uf.count[rootu];
int b = uf.count[rootv];
if(inside.contains(a)) {
inside.remove(a);
}
else {
outside.remove(a);
}
if(inside.contains(b)) {
inside.remove(b);
}
else {
outside.remove(b);
}
uf.union(rootu, rootv);
int c = a + b;
if(inside.isEmpty() || c > inside.map.firstKey()) {
inside.add(c);
}
else {
outside.add(c);
}
}
else {
k++;
}
while(inside.size > k) {
int a = inside.map.firstKey();
inside.remove(a);
outside.add(a);
}
while(inside.size < k) {
int a = outside.map.lastKey();
outside.remove(a);
inside.add(a);
}
sb.append((inside.sum-1)+"\n");
}
PrintWriter pw = new PrintWriter(System.out);
pw.println(sb.toString().trim());
pw.flush();
}
static class Multiset{
TreeMap<Integer, Integer> map;
int size = 0;
int sum = 0;
public Multiset() {
map = new TreeMap<>();
}
public void add(int a) {
if(!map.containsKey(a)) map.put(a, 1);
else map.put(a, map.get(a)+1);
size++;
sum += a;
}
public void remove(int a) {
map.put(a, map.get(a)-1);
if(map.get(a) == 0) map.remove(a);
size--;
sum -= a;
}
public boolean contains(int a) {
return map.containsKey(a);
}
public int count(int a) {
if(!map.containsKey(a)) return 0;
else return map.get(a);
}
public boolean isEmpty() {
return map.isEmpty();
}
public boolean equals(Multiset ms) {
for(int k: map.keySet()) {
if(count(k) != ms.count(k)) return false;
}
return true;
}
public String toString() {
return map.toString();
}
}
static class UnionFind {
//source: https://www.cs.waikato.ac.nz/~bernhard/317/source/graph/UnionFind.java
private int[] _parent;
private int[] _rank;
int[] count;
public UnionFind(int max) {
_parent = new int[max];
_rank = new int[max];
count = new int[max];
for (int i = 0; i < max; i++) {
_parent[i] = i;
count[i] = 1;
}
}
public int find(int i) {
int p = _parent[i];
if (i == p) {
return i;
}
return _parent[i] = find(p);
}
public void union(int i, int j) {
int root1 = find(i), root2 = find(j);
if (root2 == root1) return;
if (_rank[root1] > _rank[root2]) {
_parent[root2] = root1;
count[root1] += count[root2];
} else if (_rank[root2] > _rank[root1]) {
_parent[root1] = root2;
count[root2] += count[root1];
} else {
_parent[root2] = root1;
count[root1] += count[root2];
_rank[root1]++;
}
}
}
static class FastScanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastScanner() {
reader = new BufferedReader(new InputStreamReader(System.in), 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());
}
public String nextLine() {
try {
return reader.readLine();
} catch(IOException 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 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 |
Subsets and Splits