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
ba9f639cdd2361ea58e377d5487309ce
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
/*Author: Satyajeet Singh, Delhi Technological University*/ import java.io.*; import java.util.*; import java.text.*; import java.lang.*; import java.math.*; public class Main{ /*********************************************Constants******************************************/ static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out)); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static long mod=(long)1e9+7; static long mod1=998244353; static boolean sieve[]; static ArrayList<Integer> primes; static long factorial[],invFactorial[]; static ArrayList<Pair> graph[]; static boolean oj = System.getProperty("ONLINE_JUDGE") != null; /****************************************Solutions Begins***************************************/ public static void main(String[] args) throws Exception{ String st[]=nl(); int n=pi(st[0]); st=nl(); String str=st[0]; long n1=n; long ans=(n1*(n1-1))/2; int i=0; ArrayList<Integer> ls=new ArrayList<>(); while(i<n){ char ch=str.charAt(i); int cnt=0; while(i<n&&str.charAt(i)==ch){ i++; cnt++; } ls.add(cnt); } for(int j=0;j<ls.size()-1;j++){ ans-=ls.get(j); ans-=ls.get(j+1); ans++; } out.println(ans); /****************************************Solutions Ends**************************************************/ out.flush(); out.close(); } /****************************************Template Begins************************************************/ static String[] nl() throws Exception{ return br.readLine().split(" "); } static String[] nls() throws Exception{ return br.readLine().split(""); } static int pi(String str) { return Integer.parseInt(str); } static long pl(String str){ return Long.parseLong(str); } static double pd(String str){ return Double.parseDouble(str); } /***************************************Precision Printing**********************************************/ static void printPrecision(double d){ DecimalFormat ft = new DecimalFormat("0.000000000000000000000"); out.print(ft.format(d)); } /**************************************Bit Manipulation**************************************************/ static void printMask(long mask){ System.out.println(Long.toBinaryString(mask)); } static int countBit(long mask){ int ans=0; while(mask!=0){ if(mask%2==1){ ans++; } mask/=2; } return ans; } /******************************************Graph*********************************************************/ static void Makegraph(int n){ graph=new ArrayList[n]; for(int i=0;i<n;i++){ graph[i]=new ArrayList<>(); } } static void addEdge(int a,int b){ graph[a].add(new Pair(b,1)); } static void addEdge(int a,int b,int c){ graph[a].add(new Pair(b,c)); } /*********************************************PAIR********************************************************/ static class PairComp implements Comparator<Pair>{ public int compare(Pair p1,Pair p2){ return p1.u-p2.u; } } static class Pair implements Comparable<Pair> { int u; int v; int index=-1; public Pair(int u, int v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pair other = (Pair) o; return u == other.u && v == other.v; } public int compareTo(Pair other) { if(index!=other.index) return Long.compare(index, other.index); return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } /******************************************Long Pair*******************************************************/ static class PairCompL implements Comparator<Pairl>{ public int compare(Pairl p1,Pairl p2){ long a=p1.u*p2.v; long b=p2.u*p1.v; if(a>b){ return -1; } else if(a<b){ return 1; } else{ return 0; } } } static class Pairl implements Comparable<Pairl> { long u; long v; int index=-1; public Pairl(long u, long v) { this.u = u; this.v = v; } public int hashCode() { int hu = (int) (u ^ (u >>> 32)); int hv = (int) (v ^ (v >>> 32)); return 31 * hu + hv; } public boolean equals(Object o) { Pairl other = (Pairl) o; return u == other.u && v == other.v; } public int compareTo(Pairl other) { if(index!=other.index) return Long.compare(index, other.index); return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u); } public String toString() { return "[u=" + u + ", v=" + v + "]"; } } /*****************************************DEBUG***********************************************************/ public static void debug(Object... o) { if(!oj) System.out.println(Arrays.deepToString(o)); } /************************************MODULAR EXPONENTIATION***********************************************/ static long modulo(long a,long b,long c) { long x=1; long y=a%c; while(b > 0){ if(b%2 == 1){ x=(x*y)%c; } y = (y*y)%c; // squaring the base b /= 2; } return x%c; } /********************************************GCD**********************************************************/ static long gcd(long x, long y) { if(x==0) return y; if(y==0) return x; long r=0, a, b; a = (x > y) ? x : y; // a is greater number b = (x < y) ? x : y; // b is smaller number r = b; while(a % b != 0) { r = a % b; a = b; b = r; } return r; } /******************************************SIEVE**********************************************************/ static void sieveMake(int n){ sieve=new boolean[n]; Arrays.fill(sieve,true); sieve[0]=false; sieve[1]=false; for(int i=2;i*i<n;i++){ if(sieve[i]){ for(int j=i*i;j<n;j+=i){ sieve[j]=false; } } } primes=new ArrayList<Integer>(); for(int i=0;i<n;i++){ if(sieve[i]){ primes.add(i); } } } /********************************************End***********************************************************/ }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
60f9af8c5fa68407cd6ac88f493fa91c
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
import java.io.*; import java.util.StringTokenizer; import java.util.*; public class Solution { private static final long mod = 1000000007; static int ans = 0; public static void main(String args[]) throws Exception { FastScanner sc = new FastScanner(); PrintWriter out=new PrintWriter(System.out); int t; t = 1;//sc.nextInt(); while (t-- > 0) { solve(sc,out); } out.close(); } public static void solve(FastScanner sc, PrintWriter out) { int n = sc.nextInt(); String s = sc.next(); long ans = 0; int l = 0; int r = 0; char a = 'A'; char b = 'B'; int ca = 0; int cb = 0; char prev = 'x'; while(l<n && r<n){ char ch = s.charAt(r); if(ch == a) ca++; if(ch == b) cb++; boolean check = false; if((ca >=2 && cb >= 2) || (ca>=2 && cb == 1 && s.charAt(r) == a && s.charAt(r-1) == b) || (ca == 1 && cb >= 2 && s.charAt(r) == b && s.charAt(r-1) == a)) check = true; if(check){ ans = ans + n - r; int temp = s.charAt(l) == a? ca-- : cb--; temp = s.charAt(r) == a? ca-- : cb--; l++; check = false; } else r++; } l = 0; r = 0 ; while(l<n && r<=n){ if((r != n) && (r == 0 || s.charAt(r) == s.charAt(r-1))) r++; else { if(r-1 - l + 1 >= 2){ long len = (r-1) - l + 1; ans = ans + (len)*(len-1)/2; } if(r == n) break; r = r + 1; l = r - 1; } } out.println(ans); out.flush(); } public static void dfs(int node, int parent, int[] cats, ArrayList<Integer>[] edges, int catsFound, int m){ if( catsFound <= m) { if (cats[node] == 1) catsFound++; else catsFound = 0; } for(int child : edges[node]){ if(child != parent) dfs(child,node,cats,edges,catsFound,m); } if(edges[node].size() == 1 && edges[node].get(0) == parent && catsFound <= m) { ans++; } } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); public String next() { while (!st.hasMoreElements()) try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public int[] readArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
59dc62173288c8c96bbcce576f7af201
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); // number of chars in string scan.nextLine(); String s = scan.nextLine(); // input string String lastChar = "x"; // character just previous int lastBlock = 0; // length of block just previous int thisBlock = 0; // length of current block long result = ((long)n)*(n-1)/2; for (int i = 0; i < n; i++) { if (s.substring(i, i+1).equals(lastChar)) {thisBlock++;} else { lastChar = s.substring(i, i+1); if (lastBlock != 0) {result -= (thisBlock + lastBlock - 1);} lastBlock = thisBlock; thisBlock = 1; } } if (lastBlock != 0) {result -= (thisBlock + lastBlock - 1);} System.out.println(result); } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
7d468df60059e961358c69f16ad6cefc
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class F { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); long n = Integer.parseInt(reader.readLine()); char[] b = reader.readLine().toCharArray(); long ans = n * (n - 1) / 2; for(int x = 0; x < 2; ++x){ int cur = 1; if(x == 0) { for (int i = 1; i < n; ++i) { if (b[i] == b[i - 1]) { ++cur; } else { ans -= cur - x; cur = 1; } } } else{ for (int i = (int) n - 2; i >= 0; --i) { if (b[i] == b[i + 1]) { ++cur; } else { ans -= cur - x; cur = 1; } } } } writer.println(ans); writer.close(); } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
0e133b64647be82a59dcf8a67b9f5343
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
import java.io.*; import java.util.ArrayList; import java.util.StringTokenizer; public class mainD { public static PrintWriter out = new PrintWriter(System.out); public static FastScanner enter = new FastScanner(System.in); public static void main(String[] args) throws IOException { solve(); out.close(); } private static void solve() throws IOException { int n=enter.nextInt(); String s=enter.next(); int[] arr=new int[(int)(4e5)]; int[] prefixsumm = new int[(int)(4e5)]; char last='O'; int lastInd=0; for (int i = 0; i <s.length() ; i++) { if(s.charAt(i)!=last){ arr[lastInd]++; last=s.charAt(i); lastInd++; } else{ arr[lastInd-1]++; } } long ans=0; for(int i=lastInd-1;i>=0;i--){ prefixsumm[i]=prefixsumm[i+1]+arr[i]; } for(int i=0;i<lastInd;i++){ ans+=(long)arr[i]*(arr[i]-1)/2; ans+=(i+1<lastInd)?((long)(prefixsumm[i+1]-1)*(arr[i]-1)):0; ans+=(i+2<lastInd)?((long)prefixsumm[i+2]):0; } out.println(ans); } static class FastScanner { BufferedReader br; StringTokenizer stok; FastScanner(InputStream is) { br = new BufferedReader(new InputStreamReader(is)); } String next() throws IOException { while (stok == null || !stok.hasMoreTokens()) { String s = br.readLine(); if (s == null) { return null; } stok = new StringTokenizer(s); } return stok.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } char nextChar() throws IOException { return (char) (br.read()); } String nextLine() throws IOException { return br.readLine(); } } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
9cc586e8d1d1cabd2392edab8afd0458
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; public class wef { public static class FastReader { BufferedReader br; StringTokenizer st; //it reads the data about the specified point and divide the data about it ,it is quite fast //than using direct public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception r) { r.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next());//converts string to integer } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception r) { r.printStackTrace(); } return str; } } static ArrayList<String>list1=new ArrayList<String>(); static void combine(String instr, StringBuffer outstr, int index,int k) { if(outstr.length()==k) { list1.add(outstr.toString());return; } if(outstr.toString().length()==0) outstr.append(instr.charAt(index)); for (int i = 0; i < instr.length(); i++) { outstr.append(instr.charAt(i)); combine(instr, outstr, i + 1,k); outstr.deleteCharAt(outstr.length() - 1); } index++; } static ArrayList<ArrayList<Integer>>l=new ArrayList<>(); static void comb(int n,int k,int ind,ArrayList<Integer>list) { if(k==0) { l.add(new ArrayList<>(list)); return; } for(int i=ind;i<=n;i++) { list.add(i); comb(n,k-1,ind+1,list); list.remove(list.size()-1); } } static long sum(long n) { long sum=0; while(n!=0) { sum+=n%10; n/=10; } return sum; } static boolean check(HashMap<Integer,Integer>map) { for(int h:map.values()) if(h>1) return false; return true; } static class Pair implements Comparable<Pair>{ int x;int y; Pair(int x,int y){ this.x=x; this.y=y; // this.i=i; } @Override public int compareTo(Pair o) { // TODO Auto-generated method stub return x-o.x; } } static long ncr(long n, int k) { long m=(long)1e9+7; long C[] = new long[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]%m + C[j-1]%m)%m; } return C[k]%m; } static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so // that we can skip // middle five numbers // in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static long pow(long a, long n, long mod) { // a %= mod; long ret = 1; int x = 63 - Long.numberOfLeadingZeros(n); for (; x >= 0; x--) { ret = ret * ret % mod; if (n << 63 - x < 0) ret = ret * a % mod; } return ret; } static int maxsum=0; static long dp[]=new long[100000]; static long recur(int a[],int ind,int tempsum) { if(ind>=a.length) {//System.out.println(tempsum); if(maxsum==0) maxsum=tempsum; else maxsum=Math.max(maxsum, tempsum); return maxsum; } if(dp[ind]!=-1) return dp[ind]; // System.out.println(tempsum); int ct=0; for(int i=ind;i<ind+(a.length-ind)/2;i++) {ct++; // if(ind+ct<a.length) { tempsum+=a[i]; dp[i]= recur(a,ind+(2*ct),tempsum);} } return dp[ind]; } static int gcd(int a,int b) { if(b==0) return a; return gcd(b,a%b); } static int lcm(int a,int b) { return (a*b)/gcd(a,b); } static HashSet<Long> factorize(long n) { HashSet<Long> facts=new HashSet<Long>(); for (long i = 2; i * i <= n; ++i) { while (n % i == 0) { facts.add(i); n /= i; } } if (n != 1) { facts.add(n); } return facts; } public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out)); public static void main(String[] args) { // TODO Auto-generated method stub FastReader in=new FastReader(); TreeMap<Long,Integer>map=new TreeMap<Long,Integer>(); ArrayList<Long>list=new ArrayList<Long>(); // HashSet<Integer>set=new HashSet<Integer>(); HashSet<Integer>dis=new HashSet<Integer>(); Deque<Integer>qu=new LinkedList<Integer>(); int u=in.nextInt(); char ch[]=in.next().toCharArray(); long n=ch.length; long ct=1; for(int i=1;i<n;i++) { if(ch[i]==ch[i-1]) ct++; else { list.add(ct); ct=1; } } list.add(ct); ct=0;int y=0; for(int i=1;i<list.size()-1;i++) {//System.out.println(list.get(i)); ct+=(2*list.get(i));y++; } ct-=y; ct+=list.get(0); ct+=list.get(list.size()-1); ct--; long ans=(n*(n-1))/2-ct; if(list.size()>1) out.println(ans); else out.println((n*(n-1))/2); out.flush(); } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
0be15917cbbf0f616b394fc399311163
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
import java.io.*; import java.util.*; public class Sol2{ public static void main(String[] args) throws IOException{ FastScanner sc = new FastScanner(); PrintWriter out = new PrintWriter(System.out); TreeSet<Long> idx = new TreeSet<>(); long n= sc.nextLong(); String str = sc.nextToken(); long arr[] = new long[(int)n]; for(int i=0; i<n; i++) { arr[i]=str.charAt(i)-'A'; } for(int i=1; i<n; i++) { if(arr[i]!=arr[i-1])idx.add((long)i); } long tot = n*(n-1)/2; long cnt = 0; long curr = arr[0]; boolean twice = false; for(int i=0; i<n; i++) { if(i>0&&arr[i]!=arr[i-1]) { if(idx.lower((long)i)==null) { tot-=i; }else { tot-=i-(idx.lower((long)i)); } } if(i<n-1&&arr[i]!=arr[i+1]) { if(idx.higher((long)i+1)==null) { tot-=n-i-1; }else { tot-=idx.higher((long)i+1)-i-1; } } //System.out.println(tot); } tot+=idx.size(); System.out.println(tot); out.close(); } public static void shuffle(int[] a) { Random get = new Random(); for (int i = 0; i < a.length; i++) { int r = get.nextInt(a.length); int temp = a[i]; a[i] = a[r]; a[r] = temp; } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { 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) { e.printStackTrace(); } } return st.nextToken(); } String nextLine() { st = null; try { return br.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
5855ea5bdc90b4832c7e5bf673c88915
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class EducationalRound74D { public static void solve() { long n=s.nextInt(); String str = s.next(); long ans = (n * (n-1))/(long)2; //compress ArrayList<Integer> comp = new ArrayList<>(); ArrayList<Character> comp2 = new ArrayList<>(); for(int i= 0 ;i<n;) { comp2.add(str.charAt(i)); int j = i; int count = 0; char val = str.charAt(i); while(j<n && str.charAt(j)==val) { count++; j++; } comp.add(count); i=j; } if(comp2.size()==1) { out.println(ans); return; } for(int i=0;i<comp.size();i++) { if(i>0) { ans -= comp.get(i)-1; } if(i<comp.size()-1) { ans -= comp.get(i); } } out.println(ans); } public static void main(String[] args) { out = new PrintWriter(new BufferedOutputStream(System.out)); s = new FastReader(); solve(); out.close(); } public static FastReader s; public static PrintWriter out; public static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception e) { e.printStackTrace(); } return str; } } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
a03c72f00b68f246d87a925e6628c0dd
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
import java.util.*; import java.io.*; public class ABString { public static void main(String[] args) { Scanner sc = new Scanner(System.in); //BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //StringTokenizer st = new StringTokenizer(br.readLine()); //PrintWriter pw = new PrintWriter("ABString.out"); long n = sc.nextInt(); sc.nextLine(); String s = sc.nextLine(); long total = (n)*(n+1)/2; int count1 = 0; for(int i = 0; i<n;){ //String s1 = ""; //s1+=s.substring(i,i+2); int j = i+1; while(j < n && s.charAt(i) != s.charAt(j)){ j++; count1++; //s1 = s.substring(i,i+2); } if(i == j-1) { //System.out.println i++; } else { i = j - 1; } } int count2 = 0; for(int i = 0; i<n;){ int j = i+1; while(j < n && s.charAt(i) == s.charAt(j)){ j++; } if(j != n){ count2 += j-i; i = j; continue; } else{ break; } } int count3 = 0; for(int i = 0; i<n-1; i++){ if(s.charAt(i) != s.charAt(i+1)){ count3++; } } long ans = total - count1 - count2 - n + count3; //System.out.println(count1); //System.out.println(count2); System.out.println(ans); } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
167b0c7fbcd2d1d23e034b8d8ae33478
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main { //static final long MOD = 998244353; static final int MOD = 1000000007; static boolean[] visited; public static void main(String[] args) throws IOException { FastScanner sc = new FastScanner(); int N = sc.nextInt(); String s = sc.next(); int[][] prefix = new int[N+1][2]; //{cnt of A,B} for (int i = 1; i <= N; i++) { if (s.charAt(i-1)=='A') { prefix[i][0] = prefix[i-1][0]+1; prefix[i][1] = prefix[i-1][1]; } else { prefix[i][0] = prefix[i-1][0]; prefix[i][1] = prefix[i-1][1]+1; } } long bad = 0; //first get bad substrings of len 2 for (int i = 0; i < N-1; i++) { if (s.charAt(i) != s.charAt(i+1)) bad++; } //get bad substrings of len > 2 for (int i = 0; i < N; i++) { if (s.charAt(i) == 'A') { if (i < N-1 && s.charAt(i+1)=='A' && prefix[i+1][1] < prefix[N][1]) bad++; if (i > 0 && s.charAt(i-1)=='A' && prefix[i+1][1] > 0) bad++; } else { if (i < N-1 && s.charAt(i+1)=='B' && prefix[i+1][0] < prefix[N][0]) bad++; if (i > 0 && s.charAt(i-1)=='B' && prefix[i+1][0] > 0) bad++; } } System.out.println((((long)N)*(N-1)/2) - bad); } public 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 & 1)==1) res = (res * x) % p; // y must be even now // y = y / 2 y = y >> 1; x = (x * x) % p; } return res; } public static long dist(int[] point, int[] point2) { return (long)(Math.pow((point2[1]-point[1]),2)+Math.pow((point2[0]-point[0]),2)); } public static long gcd(long a, long b) { if (b == 0) return a; else return gcd(b,a%b); } public static int[][] sort(int[][] array) { //Sort an array (immune to quicksort TLE) Random rgen = new Random(); for (int i = 0; i < array.length; i++) { int randomPosition = rgen.nextInt(array.length); int[] temp = array[i]; array[i] = array[randomPosition]; array[randomPosition] = temp; } Arrays.sort(array, new Comparator<int[]>() { @Override public int compare(int[] arr1, int[] arr2) { return arr1[0]-arr2[0]; } }); return array; } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } } class Node { public HashSet<Node> children; public int n; public Node(int n) { this.n = n; children = new HashSet<Node>(); } public void addChild(Node node) { children.add(node); } public void removeChild(Node node) { children.remove(node); } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return n; } @Override public boolean equals(Object obj) { if (! (obj instanceof Node)) { return false; } else { Node node = (Node) obj; return (n == node.n); } } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
a0059059e50c5f87df01a4b2c921641b
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
/* If you want to aim high, aim high Don't let that studying and grades consume you Just live life young ****************************** If I'm the sun, you're the moon Because when I go up, you go down ******************************* */ import java.util.*; import java.io.*; public class D { public static void main(String args[]) throws Exception { BufferedReader infile = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(infile.readLine()); int N = Integer.parseInt(st.nextToken()); String input = infile.readLine(); int[] arr = new int[N]; for(int i=0; i < N; i++) if(input.charAt(i) == 'B') arr[i] = 1; //solve ArrayList<Integer> ls = new ArrayList<Integer>(); int boof = 1; for(int i=1; i < N; i++) { if(arr[i] == arr[i-1]) boof++; else { ls.add(boof); boof = 1; } } ls.add(boof); long bad = 0L; for(int i=1; i < ls.size(); i++) bad += (long)ls.get(i)+ls.get(i-1)-1; long res = (long)N*(N-1)/2-bad; System.out.println(res); } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
5f23ac202b177cfa23d604d0c4feff54
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
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.Writer; import java.io.OutputStreamWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Rustam Musin (t.me/musin_acm) */ 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); DABStroka solver = new DABStroka(); solver.solve(1, in, out); out.close(); } static class DABStroka { int n; char[] s; int[] cnt; public void solve(int testNumber, InputReader in, OutputWriter out) { n = in.readInt(); s = in.next().toCharArray(); long ans = 0; for (int i = 0; i < n; i++) { int j = i; while (j + 1 < n && s[j + 1] == s[j]) j++; ans += sum(j - i); i = j; } cnt = new int[2]; for (int i = 0, j = -1; i < n; i++) { while (j + 1 < n && !isGood(i, j)) { cnt[s[++j] - 'A']++; } if (isGood(i, j)) { ans += n - j; cnt[s[i] - 'A']--; } else { break; } } out.print(ans); } boolean isGood(int i, int j) { if (i > j) return false; if (cnt[0] + cnt[1] < 2 || cnt[0] == 0 || cnt[1] == 0) return false; if (cnt[0] >= 2 && cnt[1] >= 2) return true; if (cnt[0] == 1 && (s[i] == 'A' || s[j] == 'A')) return false; if (cnt[1] == 1 && (s[i] == 'B' || s[j] == 'B')) return false; return true; } long sum(long n) { return n * (n + 1) / 2; } } 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 print(long i) { writer.print(i); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.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 readInt() { 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 String readString() { 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; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
226ab9dde8c2e52f84709b5f4c819f05
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class D { public static void main(String[] args) throws Exception { //Scanner in = new Scanner(System.in); PrintWriter pw = new PrintWriter(System.out); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); char[] s = br.readLine().toCharArray(); PriorityQueue<Pair> pq = new PriorityQueue<>(); int last[] = new int[2]; last[0] = last[1] = -1; BinaryIndexTree bit = new BinaryIndexTree(n + 10); int next[][] = new int[2][n]; for (int i = 0; i < n; i++) { int c = s[i] - 'A'; pq.add(new Pair(last[c], i)); if (last[c] != -1) next[c][last[c]] = i; last[c] = i; bit.add(i, 1); } long ans = 0; for (int i = 0; i < n; i++) { while (!pq.isEmpty() && pq.peek().prev < i) { bit.add(pq.peek().val, -1); pq.poll(); } int nxt = next[s[i] - 'A'][i]; if(nxt > i) { ans += bit.query(nxt, n - 1); } } pw.println(ans); pw.close(); } static String randomString(int n) { final Random r = new Random(); char[] s = new char[n]; for (int i = 0; i < n; i++) { s[i] = (char) (r.nextInt(2) + 'A'); } return new String(s); } static void debug(Object... obj) { System.err.println(Arrays.deepToString(obj)); } static class BinaryIndexTree { public int bit[], n; public BinaryIndexTree(int N) { n = N; bit = new int[n]; } public void add(int index, int value) { index++; for (; index < n; index = index + (index & -index)) { bit[index] += value; } } public int sum(int index) { index++; int sum = 0; for (; index > 0; index = index - (index & -index)) { sum += bit[index]; } return sum; } public int query(int i, int j) { return sum(j) - sum(i - 1); } } static class Pair implements Comparable<Pair> { int prev, val; Pair(int F, int S) { prev = F; val = S; } public int compareTo(Pair p) { if (prev == p.prev) return val - p.val; return prev - p.prev; } public String toString() { return prev + " " + val; } } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
737af43ef13cd76fb2c98fcd6a9cc354
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.FilterInputStream; import java.io.BufferedInputStream; import java.io.InputStream; /** * @author khokharnikunj8 */ public class Main { public static void main(String[] args) { new Thread(null, new Runnable() { public void run() { new Main().solve(); } }, "1", 1 << 26).start(); } void solve() { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); DABString solver = new DABString(); solver.solve(1, in, out); out.close(); } static class DABString { public void solve(int testNumber, ScanReader in, PrintWriter out) { int n = in.scanInt(); char[] ar = in.scanString().toCharArray(); long ans = 0; int[] ct = new int[2]; for (int i = 0; i < n; i++) { if (i > 0 && ar[i - 1] == ar[i]) ct[ar[i] - 'A']++; else ct[ar[i] - 'A'] = 1; if (i > 0 && ar[i - 1] != ar[i]) { ans += Math.max(0, i - ct[(ar[i] - 'A') ^ 1]); } else { ans += Math.max(0, i - (ct[(ar[i] - 'A') ^ 1] > 0 ? 1 : 0)); } } out.println(ans); } } static class ScanReader { private byte[] buf = new byte[4 * 1024]; private int index; private BufferedInputStream in; private int total; public ScanReader(InputStream inputStream) { in = new BufferedInputStream(inputStream); } private int scan() { if (index >= total) { index = 0; try { total = in.read(buf); } catch (Exception e) { e.printStackTrace(); } if (total <= 0) return -1; } return buf[index++]; } public int scanInt() { int integer = 0; int n = scan(); while (isWhiteSpace(n)) n = scan(); int neg = 1; if (n == '-') { neg = -1; n = scan(); } while (!isWhiteSpace(n)) { if (n >= '0' && n <= '9') { integer *= 10; integer += n - '0'; n = scan(); } } return neg * integer; } public String scanString() { int c = scan(); if (c == -1) return null; while (isWhiteSpace(c)) c = scan(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = scan(); } while (!isWhiteSpace(c)); return res.toString(); } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
eba70b8f18b9e44fe4f887cad96220ff
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * Created by Katushka on 19.10.2019. */ public class ABString { public static void main(String[] args) { InputReader in = new InputReader(System.in); int n = in.nextInt(); String s = in.nextString(); char lastChar = s.charAt(0); long firstChar = 0; long prevSum = 0; long prevK = -1; long result = 0; for (int i = 1; i < n; i++) { if (s.charAt(i) != lastChar) { long k = i - firstChar; result += k * (k - 1) / 2; result += k * prevSum; if (prevK >= 0) { result += (k - 1) * (prevK - 1); prevSum += prevK; } prevK = k; firstChar = i; lastChar = s.charAt(i); } } long k = n - firstChar; result += k * (k - 1) / 2; result += k * prevSum; if (prevK >= 0) { result += (k - 1) * (prevK - 1); } System.out.println(result); } private 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 { final String str = reader.readLine(); tokenizer = new StringTokenizer(str); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public String nextString() { try { return reader.readLine(); } catch (IOException e) { throw new RuntimeException(e); } } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public char nextChar() { return next().charAt(0); } } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
4af33990c718f96feb853db8b7711406
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class Main { PrintWriter out = new PrintWriter(System.out); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer tok = new StringTokenizer(""); String next() throws IOException { if (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } int ni() throws IOException { return Integer.parseInt(next()); } long nl() throws IOException { return Long.parseLong(next()); } void solve() throws IOException { int n=ni(); String s=next(); long ans=0; int p=1; while (p<n && s.charAt(p)==s.charAt(0)) { ans+=p; p++; } if (p==n) { System.out.println(ans); return; } int last=p-1; p++; while (p<n ) { if (s.charAt(p)==s.charAt(p-1)) { ans+=p-1; p++; } else { ans+=last+1; last=p-1; p++; } } System.out.println(ans); } public static void main(String[] args) throws IOException { new Main().solve(); } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
246e47c199bb424dd29b382298632209
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
// $_Hardik_Dobariya import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.*; import java.util.Map.Entry; public class Main { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private PrintWriter pw; private long mod = 1000000000 + 7; private StringBuilder ans_sb; private void soln() { // int t = nextInt(); // while(t-- > 0) { // int h = nextInt(); // int n = nextInt(); // int[] ps = nextIntArray(n); // ArrayList<Range> ranges = new ArrayList<>(); // int st = -1; // int et = -1; // for(int i=0; i<n; i++) { // int cur = ps[i]; // if(cur != et - 1) { // if(st != -1) // ranges.add(new Range(st ,et)); // st = cur; // et = cur; // }else { // et = cur; // } // } // ranges.add(new Range(st ,et)); // //debug(ranges); // int cnt = 0; // for(Range r: ranges) { // int l = r.l; // int ri = r.r; // int diff = ri-l+1; // if(diff%2 == 0 && l==h && ri != 1) { // cnt++; // } // if(diff%2 != 0 && ri!=1 && l != h) { // cnt++; // } // } // pw.println(cnt); // } long n = nextInt(); String s = nextLine(); ArrayList<Integer> list = new ArrayList<>(); char prev = 'a'; int cnt = 1; for(int i=0;i<n;i++) { char c = s.charAt(i); if(c == prev) { cnt++; }else if(prev != 'a'){ list.add(cnt); cnt = 1; } prev = c; } list.add(cnt); long tot = (n*(n-1))/2; n = list.size(); for(int i=0;i<n-1;i++) { long right = list.get(i+1); long cur = list.get(i); tot -= (right+cur-1); } pw.println(tot); } private class Range{ int l, r; public Range(int a, int b) { l = a; r = b; } public String toString() { return "[ "+l+" "+r+" ]"; } } private long gcd(long n, long l) { if (l == 0) return n; return gcd(l, n % l); } private static void debug(Object... o) { System.out.println(Arrays.deepToString(o)); } private long pow(long a, long b, long c) { if (b == 0) return 1; long p = pow(a, b / 2, c); p = (p * p) % c; return (b % 2 == 0) ? p : (a * p) % c; } public static void main(String[] args) throws Exception { new Thread(null, new Runnable() { @Override public void run() { new Main().solve(); } }, "1", 1 << 26).start(); //new Main().solve(); } public StringBuilder solve() { InputReader(System.in); /* * try { InputReader(new FileInputStream("C:\\Users\\hardik\\Desktop\\in.txt")); * } catch(FileNotFoundException e) {} */ pw = new PrintWriter(System.out); // ans_sb = new StringBuilder(); soln(); pw.close(); // System.out.println(ans_sb); return ans_sb; } public void InputReader(InputStream stream1) { stream = stream1; } private boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } private 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++]; } private 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; } private 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; } private String nextToken() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } private int[] nextIntArray(int n) { int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = nextInt(); } return arr; } private long[] nextLongArray(int n) { long[] arr = new long[n]; for (int i = 0; i < n; i++) { arr[i] = nextLong(); } return arr; } private void pArray(int[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); return; } private void pArray(long[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); return; } private boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } private char nextChar() { int c = read(); while (isSpaceChar(c)) c = read(); char c1 = (char) c; while (!isSpaceChar(c)) c = read(); return c1; } private interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
81f22ae55c69c939e88871949adefb82
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
// Working program using Reader Class import java.io.BufferedReader; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Scanner; import java.util.StringTokenizer; import java.util.TreeSet; public class Main2{ public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n=Integer.parseInt(br.readLine()), i; String s = br.readLine(); TreeSet<Integer> seta = new TreeSet<>(); TreeSet<Integer> setb = new TreeSet<>(); long ans=(n*(n-1L))/2L; for(i=0;i<n;i++){ if(s.charAt(i)=='A'){ seta.add(i); } else{ setb.add(i); } } for(i=0;i<n-1;i++){ if(s.charAt(i)=='A'){ if(s.charAt(i+1)=='A'){ if(setb.higher(i)!=null){ ans--; } } else{ if(seta.higher(i)==null){ ans=ans-(n-i-1); } else{ ans=ans-(seta.higher(i)-i-1); } } } else{ if(s.charAt(i+1)=='B'){ if(seta.higher(i)!=null){ ans--; } } else{ if(setb.higher(i)==null){ ans=ans-(n-i-1); } else{ ans=ans-(setb.higher(i)-i-1); } } } } System.out.println(ans); } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
883eb30e9f00ae3638e80f9411e280ca
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
import java.util.*; public class D { public static void main(String[] args) { Scanner sc = new Scanner (System.in); long n = sc.nextLong(); String s = sc.next(); long bad = 0L; int currentIndex = 1; for (int i = 1; i < n; i++) { if (s.charAt(i) == s.charAt(i - 1)) { currentIndex++; } else { bad += currentIndex; currentIndex = 1; } } currentIndex = 1; for (int i = (int) n - 2; i >= 0; i--) { if (s.charAt(i) == s.charAt(i + 1)) { currentIndex++; } else { bad += currentIndex - 1; currentIndex = 1; } } long good = 1L * n * (n - 1) / 2; good -= bad; System.out.println(good); sc.close(); } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
3492c608886c4f666441b486095c5a00
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
/** * @author Juan Sebastian Beltran Rojas * @mail [email protected] * @veredict * @url * @category * @date **/ import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.stream.IntStream; import java.util.stream.LongStream; import static java.lang.Integer.parseInt; public class CF1238D { public static void main(String args[]) throws Throwable { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for (String ln; (ln = in.readLine()) != null; ) { int N = parseInt(ln); char[] S = in.readLine().toCharArray(); int[] nextA = new int[N]; int[] nextB = new int[N]; nextA[N - 1] = nextB[N - 1] = -1; for (int i = N - 2; i >= 0; i--) { if (S[i + 1] == 'A') { nextA[i] = i + 1; nextB[i] = nextB[i + 1]; } else { nextB[i] = i + 1; nextA[i] = nextA[i + 1]; } } boolean ws[] = new boolean[N]; for(int i=0;i<N;i++) { if (nextA[i] != -1 && S[i] == 'A') ws[nextA[i]] = true; if (nextB[i] != -1 && S[i] == 'B') ws[nextB[i]] = true; } long q[] = new long[N]; q[N-1]=ws[N-1]?1:0; for(int i=N-2;i>=0;i--) q[i] = q[i+1]+ (ws[i]?1:0); long s[] = new long[N]; for(int i=0;i<N;i++) { if(S[i]=='A') { if(nextA[i]!=-1) { s[i] = q[nextA[i]]; if(nextB[i]>nextA[i] && ws[nextB[i]]) s[i]--; } } if(S[i]=='B') { if(nextB[i]!=-1) { s[i] = q[nextB[i]]; if(nextA[i]>nextB[i]&& ws[nextA[i]]) s[i]--; } } } System.out.println(LongStream.of(s).sum()); } } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
aa84e98142761190ad813c522329de88
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
/*package whatever //do not write package name here */ import java.util.*; import java.io.*; public class GFG { public static void main (String[] args) { Scanner sc = new Scanner(System.in); long n = sc.nextLong(); sc.nextLine(); long res = (n*(n-1))/2; char[] S = sc.nextLine().toCharArray(); //System.out.println(S); for(int i = 0; i < 2; i++){ int curr = 1; for(int j = 1; j < S.length; j++){ if(S[j] == S[j-1]){ curr++; }else{ //System.out.println("curr "+curr); res -= curr - i; curr = 1; } } StringBuilder sb = new StringBuilder(new String(S)); sb.reverse(); S = sb.toString().toCharArray(); //System.out.println(S); } System.out.println(res); } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
c81eec1e05fba83dff8838d976b015ab
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.*; public class wef { public static class FastReader { BufferedReader br; StringTokenizer st; //it reads the data about the specified point and divide the data about it ,it is quite fast //than using direct public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception r) { r.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next());//converts string to integer } double nextDouble() { return Double.parseDouble(next()); } long nextLong() { return Long.parseLong(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (Exception r) { r.printStackTrace(); } return str; } } static ArrayList<String>list1=new ArrayList<String>(); static void combine(String instr, StringBuffer outstr, int index,int k) { if(outstr.length()==k) { list1.add(outstr.toString());return; } if(outstr.toString().length()==0) outstr.append(instr.charAt(index)); for (int i = 0; i < instr.length(); i++) { outstr.append(instr.charAt(i)); combine(instr, outstr, i + 1,k); outstr.deleteCharAt(outstr.length() - 1); } index++; } static ArrayList<ArrayList<Integer>>l=new ArrayList<>(); static void comb(int n,int k,int ind,ArrayList<Integer>list) { if(k==0) { l.add(new ArrayList<>(list)); return; } for(int i=ind;i<=n;i++) { list.add(i); comb(n,k-1,ind+1,list); list.remove(list.size()-1); } } static long sum(long n) { long sum=0; while(n!=0) { sum+=n%10; n/=10; } return sum; } static boolean check(HashMap<Integer,Integer>map) { for(int h:map.values()) if(h>1) return false; return true; } static class Pair implements Comparable<Pair>{ int x;int y; Pair(int x,int y){ this.x=x; this.y=y; // this.i=i; } @Override public int compareTo(Pair o) { // TODO Auto-generated method stub return x-o.x; } } static long ncr(long n, int k) { long m=(long)1e9+7; long C[] = new long[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]%m + C[j-1]%m)%m; } return C[k]%m; } static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so // that we can skip // middle five numbers // in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } static long pow(long a, long n, long mod) { // a %= mod; long ret = 1; int x = 63 - Long.numberOfLeadingZeros(n); for (; x >= 0; x--) { ret = ret * ret % mod; if (n << 63 - x < 0) ret = ret * a % mod; } return ret; } static int maxsum=0; static long dp[]=new long[100000]; static long recur(int a[],int ind,int tempsum) { if(ind>=a.length) {//System.out.println(tempsum); if(maxsum==0) maxsum=tempsum; else maxsum=Math.max(maxsum, tempsum); return maxsum; } if(dp[ind]!=-1) return dp[ind]; // System.out.println(tempsum); int ct=0; for(int i=ind;i<ind+(a.length-ind)/2;i++) {ct++; // if(ind+ct<a.length) { tempsum+=a[i]; dp[i]= recur(a,ind+(2*ct),tempsum);} } return dp[ind]; } static int gcd(int a,int b) { if(b==0) return a; return gcd(b,a%b); } static int lcm(int a,int b) { return (a*b)/gcd(a,b); } static HashSet<Long> factorize(long n) { HashSet<Long> facts=new HashSet<Long>(); for (long i = 2; i * i <= n; ++i) { while (n % i == 0) { facts.add(i); n /= i; } } if (n != 1) { facts.add(n); } return facts; } public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out)); public static void main(String[] args) { // TODO Auto-generated method stub FastReader in=new FastReader(); TreeMap<Long,Integer>map=new TreeMap<Long,Integer>(); ArrayList<Long>list=new ArrayList<Long>(); // HashSet<Integer>set=new HashSet<Integer>(); HashSet<Integer>dis=new HashSet<Integer>(); Deque<Integer>qu=new LinkedList<Integer>(); int u=in.nextInt(); char ch[]=in.next().toCharArray(); long n=ch.length; long ct=1; for(int i=1;i<n;i++) { if(ch[i]==ch[i-1]) ct++; else { list.add(ct); ct=1; } } list.add(ct); ct=0;int y=0; for(int i=1;i<list.size()-1;i++) {//System.out.println(list.get(i)); ct+=(2*list.get(i));y++; } ct-=y; ct+=list.get(0); ct+=list.get(list.size()-1); ct--; long ans=(n*(n-1))/2-ct; if(list.size()>1) out.println(ans); else out.println((n*(n-1))/2); out.flush(); } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
b21f4f249c5d3de29de97ec3595282b3
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class Test { public static void main(String[] args) throws Exception { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); int n = Integer.parseInt(br.readLine()); String s = br.readLine(); long res = ((long)n*(n - 1))/2; int prev = s.charAt(0), cnt = 1, grp = 0; for(int i = 1; i < s.length(); i++) { if(s.charAt(i) != prev) { if(grp == 0) res -= cnt; else res -= 2*cnt; cnt = 1; grp++; } else cnt++; prev = s.charAt(i); } if(grp != 0) res -= cnt; res += grp; writer.println(res); br.close(); writer.close(); } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
1ade32d3285dbf7107433f5c052b3a7e
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader sc = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(1, sc, out); out.close(); } static class Task { public void solve(int testNumber, InputReader sc, PrintWriter out) { int n=sc.nextInt(); char[] res=(" "+sc.next()).toCharArray(); long ans=1l*n*(n-1)/2; int cntA=0; int cntB=0; for(int i=1;i<=n;i++) { if(res[i]=='A') { cntA++; ans-=cntB; cntB=0; } else { cntB++; ans-=cntA; cntA=0; } } cntA=cntB=-1; for(int i=n;i>=1;i--) { if(res[i]=='A') { cntA++; if(cntB>0) ans-=cntB; cntB=-1; } else { cntB++; if(cntA>0) ans-=cntA; cntA=-1; } } out.println(ans); } } 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()); } } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
1804d2604300a8e3ba51d67285c37190
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader sc = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); Task solver = new Task(); solver.solve(1, sc, out); out.close(); } static class Task { public void solve(int testNumber, InputReader sc, PrintWriter out) { int n=sc.nextInt(); char[] res=(" "+sc.next()).toCharArray(); long ans=1l*n*(n-1)/2; int cntA=0; int cntB=0; for(int i=1;i<=n;i++) { if(res[i]=='A') { cntA++; ans-=cntB; cntB=0; } else { cntB++; ans-=cntA; cntA=0; } } cntA=cntB=0; for(int i=n;i>=1;i--) { if(res[i]=='A') { cntA++; ans-=cntB; cntB=0; } else { cntB++; ans-=cntA; cntA=0; } } for(int i=1;i<n;i++) if(res[i]!=res[i+1]) ans++; out.println(ans); } } 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()); } } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
f463473e0509ddf1009561469e658b5e
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
import java.util.*; import java.io.*; import java.math.BigInteger; public class Main { static final int mod = (int)1e9+7; public static void main(String[] args) throws Exception { FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); long n = in.nextInt(); char[] s = in.next().toCharArray(); ArrayList<Integer> al = new ArrayList(); for(int i = 0; i < n;) { int j = i; while(j < n && s[i] == s[j]) j++; al.add(j - i); i = j; } long ans = n * (n - 1) / 2; for(int i = 0; i < al.size() - 1; i++) { ans -= al.get(i + 1); ans -= al.get(i); ans++; } out.print(ans); out.flush(); } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } public String next() throws IOException { if(st == null || !st.hasMoreElements()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
a56a4888a1ff15a5bd29cfa7224d1249
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { BufferedReader rd = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); int n = Integer.parseInt(rd.readLine()); String s = rd.readLine(); long cnt = ((long)n * (n - 1)) / 2; for (int i = 0; i < n - 1; i++) { char a = s.charAt(i); char b = s.charAt(i + 1); if (a != b) { cnt--; int k = i + 1; while (k + 1 < n && s.charAt(k + 1) == s.charAt(k)) { k++; cnt--; } k = i; while (k - 1 >= 0 && s.charAt(k - 1) == s.charAt(k)) { k--; cnt--; } } } pw.println(cnt); pw.flush(); } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
ff324a48952fddc9297b70c4e31cadc2
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class Main2 { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); String s = br.readLine(); long res = ((long)n)*(n-1)/2; int i; char search = 'C'; for(i=0;i<n;i++) { //System.out.println(s.charAt(i)+" "+search); if(s.charAt(i)==search) res--; if(i+1<n) { if(s.charAt(i)=='A'&&s.charAt(i+1)=='B') search = 'B'; if(s.charAt(i)=='B'&&s.charAt(i+1)=='A') search = 'A'; } } //System.out.println(res); search = 'C'; for(i=n-1;i>=0;i--) { if(s.charAt(i)==search) { if(s.charAt(i+1)==search) res--; } if(i>0) { if(s.charAt(i)=='A'&&s.charAt(i-1)=='B') search = 'B'; if(s.charAt(i)=='B'&&s.charAt(i-1)=='A') search = 'A'; } } System.out.println(res); } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
e01d5bb0d75ace07f594a644a4461aa8
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); String s=sc.next(); long ans=0,ls=0; for(int i=1;i<=n;i++) { if(i==1||s.charAt(i-1)==s.charAt(i-2)) {ls++;ans+=i-1-(ls<i?1:0);} else { ans+=i-1-ls;ls=1; } } System.out.println(ans); } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
e864fe681f3237cad92fe498c59bc0ae
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String args[]) {new Main().run();} FastReader in = new FastReader(); PrintWriter out = new PrintWriter(System.out); void run(){ work(); out.flush(); } long mod=1000000007; long gcd(long a,long b) { return b==0?a:gcd(b,a%b); } void work() { long n=in.nextInt(); String str=in.next(); long ret=(1+n-1)*(n-1)/2; for(int i=0,j=0;j<n;) { while(j<n&&str.charAt(i)==str.charAt(j)) { j++; } if(i>0) { ret-=j-i-1; } if(j<n) { ret-=j-i; } i=j; } out.println(ret); } } class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br=new BufferedReader(new InputStreamReader(System.in)); } public String next() { if(st==null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
ae4554cc4fc15ef3783d4d8055954074
train_000.jsonl
1570545300
The string $$$t_1t_2 \dots t_k$$$ is good if each letter of this string belongs to at least one palindrome of length greater than 1.A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not.Here are some examples of good strings: $$$t$$$ = AABBB (letters $$$t_1$$$, $$$t_2$$$ belong to palindrome $$$t_1 \dots t_2$$$ and letters $$$t_3$$$, $$$t_4$$$, $$$t_5$$$ belong to palindrome $$$t_3 \dots t_5$$$); $$$t$$$ = ABAA (letters $$$t_1$$$, $$$t_2$$$, $$$t_3$$$ belong to palindrome $$$t_1 \dots t_3$$$ and letter $$$t_4$$$ belongs to palindrome $$$t_3 \dots t_4$$$); $$$t$$$ = AAAAA (all letters belong to palindrome $$$t_1 \dots t_5$$$); You are given a string $$$s$$$ of length $$$n$$$, consisting of only letters A and B.You have to calculate the number of good substrings of string $$$s$$$.
256 megabytes
import java.util.*; import java.util.Map.Entry; import java.math.*; import java.io.*; public class Main { public static void main(String[] args) throws FileNotFoundException { // InputReader in = new InputReader(System.in); // Scanner in = new Scanner(System.in); Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in))); PrintWriter out = new PrintWriter(System.out); // InputReader in = new InputReader(new // File("ethan_traverses_a_tree.txt")); // PrintWriter out = new PrintWriter(new // File("ethan_traverses_a_tree-output.txt")); int n = in.nextInt(); String s = in.next(); char[] a = s.toCharArray(); int[][] next = new int[n][2]; next[n - 1][0] = -1; next[n - 1][1] = -1; for (int i = n - 2; i >= 0; i--) { next[i][0] = next[i + 1][0]; next[i][1] = next[i + 1][1]; next[i][a[i + 1] - 'A'] = i + 1; } long sum = 0; for (int i = n - 2; i >= 0; i--) { char ch = a[i]; int chInt = ch - 'A'; if (a[i + 1] == ch) { if (next[i][1 - chInt] == -1) { sum = sum + (n - 1 - i); } else { sum = sum + (n - 1 - i - 1); } } else { if (next[i][chInt] != -1) { sum = sum + (n - next[i][chInt]); } } } out.printf("%d\n", sum); out.close(); } static class InputReader { BufferedReader br; StringTokenizer st; public InputReader(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public boolean hasNext() { 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; } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["5\nAABBB", "3\nAAA", "7\nAAABABB"]
2 seconds
["6", "3", "15"]
NoteIn the first test case there are six good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_4$$$, $$$s_1 \dots s_5$$$, $$$s_3 \dots s_4$$$, $$$s_3 \dots s_5$$$ and $$$s_4 \dots s_5$$$.In the second test case there are three good substrings: $$$s_1 \dots s_2$$$, $$$s_1 \dots s_3$$$ and $$$s_2 \dots s_3$$$.
Java 8
standard input
[ "dp", "combinatorics", "binary search", "strings" ]
3eb23b7824d06b86be72c70b969be166
The first line contains one integer $$$n$$$ ($$$1 \le n \le 3 \cdot 10^5$$$) — the length of the string $$$s$$$. The second line contains the string $$$s$$$, consisting of letters A and B.
1,900
Print one integer — the number of good substrings of string $$$s$$$.
standard output
PASSED
eed5fe8560c222db7aaff9955e9abf85
train_000.jsonl
1511449500
Vova promised himself that he would never play computer games... But recently Firestorm — a well-known game developing company — published their newest game, World of Farcraft, and it became really popular. Of course, Vova started playing it.Now he tries to solve a quest. The task is to come to a settlement named Overcity and spread a rumor in it.Vova knows that there are n characters in Overcity. Some characters are friends to each other, and they share information they got. Also Vova knows that he can bribe each character so he or she starts spreading the rumor; i-th character wants ci gold in exchange for spreading the rumor. When a character hears the rumor, he tells it to all his friends, and they start spreading the rumor to their friends (for free), and so on.The quest is finished when all n characters know the rumor. What is the minimum amount of gold Vova needs to spend in order to finish the quest?Take a look at the notes if you think you haven't understood the problem completely.
256 megabytes
import java.io.IOException; import java.io.InputStreamReader; import java.io.BufferedReader; import java.util.*; import java.math.*; import java.io.*; import java.text.*; import java.math.BigInteger; public class Main { //Life's a bitch public static boolean[] sieve(long n) { boolean[] prime = new boolean[(int)n+1]; Arrays.fill(prime,true); prime[0] = false; prime[1] = false; long m = (long)Math.sqrt(n); for(int i=2;i<=m;i++) { if(prime[i]) { for(int k=i*i;k<=n;k+=i) { prime[k] = false; } } } return prime; } static long GCD(long a,long b) { if(b==0) { return a; } return GCD(b,a%b); } static long CountCoPrimes(long n) { long res = n; for(int i=2;i*i<=n;i++) { if(n%i==0) { while(n%i==0) { n/=i; } res-=res/i; } } if(n>1) { res-=res/n; } return res; } static boolean prime(int n) { for(int i=2;i*i<=n;i++) { if(n%i==0) { return false; } } return true; } public static void main(String[] args) throws IOException { new Main().run(); } static void reverse(char[] a) { // char[] a = c.toCharArray(); int start=0; int end = a.length-1; while(start!=end) { char temp = a[start]; a[start] = a[end]; a[end] = temp; start++; end--; } } static long min; static long[] cost; static boolean[] visited; static ArrayList<Integer> arr[]; Scanner in = new Scanner(System.in); void run() throws IOException { int n = ni(); int m = ni(); visited = new boolean[n]; arr = new ArrayList[n]; cost = new long[n]; for(int i=0;i<n;i++) { arr[i] = new ArrayList<>(); cost[i] = nl(); } for(int i=0;i<m;i++){ int u = ni()-1; int v = ni()-1; arr[u].add(v); arr[v].add(u); } long ans = 0; for(int i=0;i<n;i++){ if(!visited[i]){ min = Long.MAX_VALUE; dfs(i); ans+=min; } } printL(ans); } static void dfs(int i){ if(cost[i]<min) { min = cost[i]; } visited[i] = true; for(int v:arr[i]){ if(!visited[v]){ dfs(v); } } } //xor range query static long xor(long n) { if(n%4==0) { return n; } if(n%4==1) { return 1; } if(n%4==2) { return n+1; } return 0; } static long xor(long a,long b) { return xor(b)^xor(a-1); } void printL(long a) { System.out.println(a); } void printS(String s) { System.out.println(s); } void printD(Double d) { System.out.println(d); } static void swap(char c,char p) { char t = c; c = p; p = t; } static long max(long n,long m) { return Math.max(n,m); } static long min(long n,long m) { return Math.min(n,m); } double nd() throws IOException { return Double.parseDouble(in.next()); } int ni() throws IOException { return Integer.parseInt(in.next()); } long nl() throws IOException { return Long.parseLong(in.next()); } String si() throws IOException { return in.next(); } static int abs(int n) { return Math.abs(n); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(br.readLine()); } return st.nextToken(); } public int nextInt() throws IOException {return Integer.parseInt(next());} public long nextLong() throws IOException {return Long.parseLong(next());} public String nextLine() throws IOException {return br.readLine();} public boolean ready() throws IOException {return br.ready();} } } class Pair implements Comparable<Pair> { int x,y; public Pair(int x,int y) { this.x = x; this.y = y; } public int compareTo(Pair o) { return this.y-o.y; } }
Java
["5 2\n2 5 3 4 8\n1 4\n4 5", "10 0\n1 2 3 4 5 6 7 8 9 10", "10 5\n1 6 2 7 3 8 4 9 5 10\n1 2\n3 4\n5 6\n7 8\n9 10"]
2 seconds
["10", "55", "15"]
NoteIn the first example the best decision is to bribe the first character (he will spread the rumor to fourth character, and the fourth one will spread it to fifth). Also Vova has to bribe the second and the third characters, so they know the rumor.In the second example Vova has to bribe everyone.In the third example the optimal decision is to bribe the first, the third, the fifth, the seventh and the ninth characters.
Java 11
standard input
[ "dfs and similar", "greedy", "graphs" ]
9329cb499f003aa71c6f51556bcc7b05
The first line contains two integer numbers n and m (1 ≤ n ≤ 105, 0 ≤ m ≤ 105) — the number of characters in Overcity and the number of pairs of friends. The second line contains n integer numbers ci (0 ≤ ci ≤ 109) — the amount of gold i-th character asks to start spreading the rumor. Then m lines follow, each containing a pair of numbers (xi, yi) which represent that characters xi and yi are friends (1 ≤ xi, yi ≤ n, xi ≠ yi). It is guaranteed that each pair is listed at most once.
1,300
Print one number — the minimum amount of gold Vova has to spend in order to finish the quest.
standard output
PASSED
5ce87625b7298f68b1161689779995c6
train_000.jsonl
1511449500
Vova promised himself that he would never play computer games... But recently Firestorm — a well-known game developing company — published their newest game, World of Farcraft, and it became really popular. Of course, Vova started playing it.Now he tries to solve a quest. The task is to come to a settlement named Overcity and spread a rumor in it.Vova knows that there are n characters in Overcity. Some characters are friends to each other, and they share information they got. Also Vova knows that he can bribe each character so he or she starts spreading the rumor; i-th character wants ci gold in exchange for spreading the rumor. When a character hears the rumor, he tells it to all his friends, and they start spreading the rumor to their friends (for free), and so on.The quest is finished when all n characters know the rumor. What is the minimum amount of gold Vova needs to spend in order to finish the quest?Take a look at the notes if you think you haven't understood the problem completely.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class C { static MyScanner in = new MyScanner(); static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; static long H,W; static BitSet bs; static long mod = 1000000007; // All possible moves of a knight static int X[] = { 2, 1, -1, -2, -2, -1, 1, 2 }; static int Y[] = { 1, 2, 2, 1, -1, -2, -2, -1 }; public static void main(String args[]) throws IOException { /** 1.What is the unknown: 2.What are the data: 3.What is the condition: 4.What is the restriction: 5. understand the problem: 6. What are the cases edges in the problem: */ int n= in.nextInt(); int m= in.nextInt(); int [] c = new int[n+1]; ArrayList<ArrayList<Integer>> g = new ArrayList<>(n+1); for(int i=0;i<=n;i++){ g.add(new ArrayList<>()); } for(int i=1;i<=n;i++) c[i] = in.nextInt(); BitSet bs = new BitSet(n+2); for(int i=0;i<m;i++){ int u= in.nextInt(); int v = in.nextInt(); g.get(u).add(v); g.get(v).add(u); } long sum=0; for(int i=1;i<=n;i++){ Queue<Integer> q = new LinkedList<>(); if(!bs.get(i)){ q.add(i); bs.set(i,true); int min =c[i]; while(!q.isEmpty()){ int u =q.poll(); for(int j=0;j<g.get(u).size();j++){ int v = g.get(u).get(j); if(!bs.get(v)){ bs.set(v, true); min = Math.min(c[v], min); q.add(v); } } } sum+=min; } } out.println(sum); out.flush(); } static boolean isVowel(char c) { if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'||c=='y'){ return true; } return false ; } static class IP implements Comparable<IP>{ public int first,second; IP(int first, int second){ this.first = first; this.second = second; } public int compareTo(IP ip){ if(first==ip.first) return second-ip.second; return first-ip.first; } @Override public String toString() { return first+" "+second; } } static long gcd(long a, long b){ return b!=0?gcd(b, a%b):a; } static boolean isEven(long a) { return (a&1)==0; } 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
["5 2\n2 5 3 4 8\n1 4\n4 5", "10 0\n1 2 3 4 5 6 7 8 9 10", "10 5\n1 6 2 7 3 8 4 9 5 10\n1 2\n3 4\n5 6\n7 8\n9 10"]
2 seconds
["10", "55", "15"]
NoteIn the first example the best decision is to bribe the first character (he will spread the rumor to fourth character, and the fourth one will spread it to fifth). Also Vova has to bribe the second and the third characters, so they know the rumor.In the second example Vova has to bribe everyone.In the third example the optimal decision is to bribe the first, the third, the fifth, the seventh and the ninth characters.
Java 11
standard input
[ "dfs and similar", "greedy", "graphs" ]
9329cb499f003aa71c6f51556bcc7b05
The first line contains two integer numbers n and m (1 ≤ n ≤ 105, 0 ≤ m ≤ 105) — the number of characters in Overcity and the number of pairs of friends. The second line contains n integer numbers ci (0 ≤ ci ≤ 109) — the amount of gold i-th character asks to start spreading the rumor. Then m lines follow, each containing a pair of numbers (xi, yi) which represent that characters xi and yi are friends (1 ≤ xi, yi ≤ n, xi ≠ yi). It is guaranteed that each pair is listed at most once.
1,300
Print one number — the minimum amount of gold Vova has to spend in order to finish the quest.
standard output
PASSED
c2aeb189b393ba2132e6eaae90326310
train_000.jsonl
1511449500
Vova promised himself that he would never play computer games... But recently Firestorm — a well-known game developing company — published their newest game, World of Farcraft, and it became really popular. Of course, Vova started playing it.Now he tries to solve a quest. The task is to come to a settlement named Overcity and spread a rumor in it.Vova knows that there are n characters in Overcity. Some characters are friends to each other, and they share information they got. Also Vova knows that he can bribe each character so he or she starts spreading the rumor; i-th character wants ci gold in exchange for spreading the rumor. When a character hears the rumor, he tells it to all his friends, and they start spreading the rumor to their friends (for free), and so on.The quest is finished when all n characters know the rumor. What is the minimum amount of gold Vova needs to spend in order to finish the quest?Take a look at the notes if you think you haven't understood the problem completely.
256 megabytes
import java.util.*; public class solution { static int n, m, curr; static long answer; static ArrayList<Integer>[] adj; static int[] cost; static boolean[] vis; public static void main(String[] args) { answer = 0; Scanner console = new Scanner(System.in); n = console.nextInt(); m = console.nextInt(); cost = new int[n]; adj = new ArrayList[n]; for ( int i = 0; i < n; i++ ) { adj[i] = new ArrayList<>(); } for ( int i = 0; i < n; i++ ) { cost[i] = console.nextInt(); } for ( int i = 0; i < m; i++ ) { int a = console.nextInt()-1; int b = console.nextInt()-1; adj[a].add(b); adj[b].add(a); } vis = new boolean[n]; for ( int i = 0; i < n; i++ ) { if ( !vis[i] ) { curr = cost[i]; dfs (i); answer += curr; } } System.out.println(answer); } static void dfs ( int x ) { if ( !vis[x] ) { vis[x] = true; curr = Math.min(cost[x], curr); for ( int p : adj[x] ) { dfs(p); } } } }
Java
["5 2\n2 5 3 4 8\n1 4\n4 5", "10 0\n1 2 3 4 5 6 7 8 9 10", "10 5\n1 6 2 7 3 8 4 9 5 10\n1 2\n3 4\n5 6\n7 8\n9 10"]
2 seconds
["10", "55", "15"]
NoteIn the first example the best decision is to bribe the first character (he will spread the rumor to fourth character, and the fourth one will spread it to fifth). Also Vova has to bribe the second and the third characters, so they know the rumor.In the second example Vova has to bribe everyone.In the third example the optimal decision is to bribe the first, the third, the fifth, the seventh and the ninth characters.
Java 11
standard input
[ "dfs and similar", "greedy", "graphs" ]
9329cb499f003aa71c6f51556bcc7b05
The first line contains two integer numbers n and m (1 ≤ n ≤ 105, 0 ≤ m ≤ 105) — the number of characters in Overcity and the number of pairs of friends. The second line contains n integer numbers ci (0 ≤ ci ≤ 109) — the amount of gold i-th character asks to start spreading the rumor. Then m lines follow, each containing a pair of numbers (xi, yi) which represent that characters xi and yi are friends (1 ≤ xi, yi ≤ n, xi ≠ yi). It is guaranteed that each pair is listed at most once.
1,300
Print one number — the minimum amount of gold Vova has to spend in order to finish the quest.
standard output
PASSED
905aeb3ec12dbb279bc2a88ae47f0315
train_000.jsonl
1511449500
Vova promised himself that he would never play computer games... But recently Firestorm — a well-known game developing company — published their newest game, World of Farcraft, and it became really popular. Of course, Vova started playing it.Now he tries to solve a quest. The task is to come to a settlement named Overcity and spread a rumor in it.Vova knows that there are n characters in Overcity. Some characters are friends to each other, and they share information they got. Also Vova knows that he can bribe each character so he or she starts spreading the rumor; i-th character wants ci gold in exchange for spreading the rumor. When a character hears the rumor, he tells it to all his friends, and they start spreading the rumor to their friends (for free), and so on.The quest is finished when all n characters know the rumor. What is the minimum amount of gold Vova needs to spend in order to finish the quest?Take a look at the notes if you think you haven't understood the problem completely.
256 megabytes
// package endsem; import java.util.*; import java.lang.Math; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class Cf_two { static class graph_dfs{ int num_vert; List<Integer> adjList[]; int[] vis; graph_dfs(int num_vert){ this.num_vert=num_vert; adjList=new LinkedList[num_vert]; vis=new int[num_vert]; for (int i = 0; i < num_vert; i++) { adjList[i]=new LinkedList(); } } void addEdge(int src,int dest) { adjList[src].add(dest); adjList[dest].add(src);// only for undirected graph } // only for one component of graph long dfs_trav(int root,long curr,int[] cost) { vis[root]=1; if(cost[root]<curr)curr=cost[root]; // System.out.print(root+" "); for (int j:adjList[root]) { if(vis[j]==0) { curr=dfs_trav(j,curr,cost); } } return curr; } void display() { for (int i = 0; i < adjList.length; i++) { for (int j:adjList[i]) { System.out.print(j+" "); } System.out.println(); } } } static long curr; static long ans; static int[] cost; public static void main(String[] args) throws IOException{ Reader.init(System.in); int n=Reader.nextInt(); int m=Reader.nextInt(); cost=new int[n]; for (int i = 0; i < cost.length; i++) { cost[i]=Reader.nextInt(); } graph_dfs obj=new graph_dfs(n); for (int i = 0; i < m; i++) { obj.addEdge(Reader.nextInt()-1, Reader.nextInt()-1); } for(int i=0;i<n;i++) { if(obj.vis[i]==0) { // System.out.println("hello"+i); curr=obj.dfs_trav(i,cost[i],cost); // System.out.println("d "+curr); ans=ans+curr; curr=0; } } System.out.println(ans); } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } } //5 4 //2 6 5 3 4 //1 2 //3 4 //4 5 //5 3
Java
["5 2\n2 5 3 4 8\n1 4\n4 5", "10 0\n1 2 3 4 5 6 7 8 9 10", "10 5\n1 6 2 7 3 8 4 9 5 10\n1 2\n3 4\n5 6\n7 8\n9 10"]
2 seconds
["10", "55", "15"]
NoteIn the first example the best decision is to bribe the first character (he will spread the rumor to fourth character, and the fourth one will spread it to fifth). Also Vova has to bribe the second and the third characters, so they know the rumor.In the second example Vova has to bribe everyone.In the third example the optimal decision is to bribe the first, the third, the fifth, the seventh and the ninth characters.
Java 11
standard input
[ "dfs and similar", "greedy", "graphs" ]
9329cb499f003aa71c6f51556bcc7b05
The first line contains two integer numbers n and m (1 ≤ n ≤ 105, 0 ≤ m ≤ 105) — the number of characters in Overcity and the number of pairs of friends. The second line contains n integer numbers ci (0 ≤ ci ≤ 109) — the amount of gold i-th character asks to start spreading the rumor. Then m lines follow, each containing a pair of numbers (xi, yi) which represent that characters xi and yi are friends (1 ≤ xi, yi ≤ n, xi ≠ yi). It is guaranteed that each pair is listed at most once.
1,300
Print one number — the minimum amount of gold Vova has to spend in order to finish the quest.
standard output
PASSED
abfb4ecb0cd02dac973fef0cf3f38bb7
train_000.jsonl
1511449500
Vova promised himself that he would never play computer games... But recently Firestorm — a well-known game developing company — published their newest game, World of Farcraft, and it became really popular. Of course, Vova started playing it.Now he tries to solve a quest. The task is to come to a settlement named Overcity and spread a rumor in it.Vova knows that there are n characters in Overcity. Some characters are friends to each other, and they share information they got. Also Vova knows that he can bribe each character so he or she starts spreading the rumor; i-th character wants ci gold in exchange for spreading the rumor. When a character hears the rumor, he tells it to all his friends, and they start spreading the rumor to their friends (for free), and so on.The quest is finished when all n characters know the rumor. What is the minimum amount of gold Vova needs to spend in order to finish the quest?Take a look at the notes if you think you haven't understood the problem completely.
256 megabytes
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc=new Scanner(System.in); int N=sc.nextInt(); int m=sc.nextInt(); int[] arr=new int[N+1]; for(int i=1;i<=N;i++){ arr[i]=sc.nextInt(); } Map<Integer,List<Integer>> map=new HashMap<>(); for(int i=1;i<=N;i++){ map.put(i,new ArrayList<>()); } while(m-->0){ int x=sc.nextInt(); int y=sc.nextInt(); map.get(x).add(y); map.get(y).add(x); } boolean[] visited=new boolean[N+1]; long ans=0; for(int i=1;i<=N;i++){ if(!visited[i]){ ans+=dfs(map,i,visited,arr); } } System.out.println(ans); } public static long dfs(Map<Integer,List<Integer>> map,int u,boolean[] visited,int[] price){ visited[u]=true; long min=price[u]; for(Integer i:map.get(u)){ if(!visited[i]){ min=Math.min(min,dfs(map,i,visited,price)); } } return min; } }
Java
["5 2\n2 5 3 4 8\n1 4\n4 5", "10 0\n1 2 3 4 5 6 7 8 9 10", "10 5\n1 6 2 7 3 8 4 9 5 10\n1 2\n3 4\n5 6\n7 8\n9 10"]
2 seconds
["10", "55", "15"]
NoteIn the first example the best decision is to bribe the first character (he will spread the rumor to fourth character, and the fourth one will spread it to fifth). Also Vova has to bribe the second and the third characters, so they know the rumor.In the second example Vova has to bribe everyone.In the third example the optimal decision is to bribe the first, the third, the fifth, the seventh and the ninth characters.
Java 11
standard input
[ "dfs and similar", "greedy", "graphs" ]
9329cb499f003aa71c6f51556bcc7b05
The first line contains two integer numbers n and m (1 ≤ n ≤ 105, 0 ≤ m ≤ 105) — the number of characters in Overcity and the number of pairs of friends. The second line contains n integer numbers ci (0 ≤ ci ≤ 109) — the amount of gold i-th character asks to start spreading the rumor. Then m lines follow, each containing a pair of numbers (xi, yi) which represent that characters xi and yi are friends (1 ≤ xi, yi ≤ n, xi ≠ yi). It is guaranteed that each pair is listed at most once.
1,300
Print one number — the minimum amount of gold Vova has to spend in order to finish the quest.
standard output
PASSED
e502ce3c7c4ff433ba7d96d80e8d783a
train_000.jsonl
1511449500
Vova promised himself that he would never play computer games... But recently Firestorm — a well-known game developing company — published their newest game, World of Farcraft, and it became really popular. Of course, Vova started playing it.Now he tries to solve a quest. The task is to come to a settlement named Overcity and spread a rumor in it.Vova knows that there are n characters in Overcity. Some characters are friends to each other, and they share information they got. Also Vova knows that he can bribe each character so he or she starts spreading the rumor; i-th character wants ci gold in exchange for spreading the rumor. When a character hears the rumor, he tells it to all his friends, and they start spreading the rumor to their friends (for free), and so on.The quest is finished when all n characters know the rumor. What is the minimum amount of gold Vova needs to spend in order to finish the quest?Take a look at the notes if you think you haven't understood the problem completely.
256 megabytes
// package com.company.codeforces; import java.io.*; import java.util.*; public class Solution { static int mod = (int) 1e9 + 7; static int val[]; static boolean vis[]; static ArrayList<Integer> graph[]; static long ans=0; public static void main(String[] args) { Scanner input = new Scanner(System.in); int n=input.nextInt(); int m=input.nextInt(); val=new int[n+1]; vis=new boolean[n+1]; graph=new ArrayList[n+1]; for (int i = 1; i <=n ; i++) { val[i]=input.nextInt(); } for (int i = 0; i <=n ; i++) { graph[i]=new ArrayList<>(); } for (int i = 0; i <m; i++) { int x=input.nextInt(); int y=input.nextInt(); graph[x].add(y); graph[y].add(x); } for (int i = 1; i <=n; i++) { if (!vis[i]){ if (graph[i].size()>0){ ans+=dfs(i); }else { ans+=val[i]; } } } System.out.println(ans); } private static int dfs(int i) { int min=val[i]; for (int node:graph[i]) { if (!vis[node]){ vis[node]=true; int temp=dfs(node); min=Math.min(temp,min); } } return min; } }
Java
["5 2\n2 5 3 4 8\n1 4\n4 5", "10 0\n1 2 3 4 5 6 7 8 9 10", "10 5\n1 6 2 7 3 8 4 9 5 10\n1 2\n3 4\n5 6\n7 8\n9 10"]
2 seconds
["10", "55", "15"]
NoteIn the first example the best decision is to bribe the first character (he will spread the rumor to fourth character, and the fourth one will spread it to fifth). Also Vova has to bribe the second and the third characters, so they know the rumor.In the second example Vova has to bribe everyone.In the third example the optimal decision is to bribe the first, the third, the fifth, the seventh and the ninth characters.
Java 11
standard input
[ "dfs and similar", "greedy", "graphs" ]
9329cb499f003aa71c6f51556bcc7b05
The first line contains two integer numbers n and m (1 ≤ n ≤ 105, 0 ≤ m ≤ 105) — the number of characters in Overcity and the number of pairs of friends. The second line contains n integer numbers ci (0 ≤ ci ≤ 109) — the amount of gold i-th character asks to start spreading the rumor. Then m lines follow, each containing a pair of numbers (xi, yi) which represent that characters xi and yi are friends (1 ≤ xi, yi ≤ n, xi ≠ yi). It is guaranteed that each pair is listed at most once.
1,300
Print one number — the minimum amount of gold Vova has to spend in order to finish the quest.
standard output
PASSED
cd4e3b5a80f2f36ef911150033178899
train_000.jsonl
1529591700
You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times: if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; ... remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { private static Scanner sc; private static Printer pr; private static long aLong=(long)(Math.pow(10,9)+7); private static void solve() throws IOException { int n = sc.nextInt(); int k=sc.nextInt(); StringBuilder builder=new StringBuilder(sc.next()); boolean[]b=new boolean[n]; ArrayList<Integer>list=new ArrayList<>(); for (char a='a';a<='z';a++){ for (int i=0;i<builder.length();i++){ if (builder.charAt(i)==a&&k>0){ list.add(i); b[i]=true; k--; } } } for (int i=0;i<n;i++){ if (!b[i]) System.out.print(builder.charAt(i)); else continue; } } public static int val(char c){ return c-'0'; } public static long gcd(long a,long b) { if (a == 0) return b; return gcd(b % a, a); } private static class Pair implements Comparable<Pair> { long a; long b; Pair(long a, long b) { this.a = a; this.b = b; } @Override public int compareTo(Pair o) { //if (a == o.a) { // return Long.compare(b, o.b); // } return Long.compare(this.b-this.a,o.b-o.a); //return Long.compare(b,o.b); } } public static void main(String[] args) throws IOException { sc = new Scanner(System.in); pr = new Printer(System.out); solve(); pr.close(); // sc.close(); } private static class Scanner { BufferedReader br; Scanner (InputStream in) { br = new BufferedReader(new InputStreamReader(in)); } private boolean isPrintable(int ch) { return ch >= '!' && ch <= '~'; } private boolean isCRLF(int ch) { return ch == '\n' || ch == '\r' || ch == -1; } private int nextPrintable() { try { int ch; while (!isPrintable(ch = br.read())) { if (ch == -1) { throw new NoSuchElementException(); } } return ch; } catch (IOException e) { throw new NoSuchElementException(); } } String next() { try { int ch = nextPrintable(); StringBuilder sb = new StringBuilder(); do { sb.appendCodePoint(ch); } while (isPrintable(ch = br.read())); return sb.toString(); } catch (IOException e) { throw new NoSuchElementException(); } } int nextInt() { try { // parseInt from Integer.parseInt() boolean negative = false; int res = 0; int limit = -Integer.MAX_VALUE; int radix = 10; int fc = nextPrintable(); if (fc < '0') { if (fc == '-') { negative = true; limit = Integer.MIN_VALUE; } else if (fc != '+') { throw new NumberFormatException(); } fc = br.read(); } int multmin = limit / radix; int ch = fc; do { int digit = ch - '0'; if (digit < 0 || digit >= radix) { throw new NumberFormatException(); } if (res < multmin) { throw new NumberFormatException(); } res *= radix; if (res < limit + digit) { throw new NumberFormatException(); } res -= digit; } while (isPrintable(ch = br.read())); return negative ? res : -res; } catch (IOException e) { throw new NoSuchElementException(); } } long nextLong() { try { // parseLong from Long.parseLong() boolean negative = false; long res = 0; long limit = -Long.MAX_VALUE; int radix = 10; int fc = nextPrintable(); if (fc < '0') { if (fc == '-') { negative = true; limit = Long.MIN_VALUE; } else if (fc != '+') { throw new NumberFormatException(); } fc = br.read(); } long multmin = limit / radix; int ch = fc; do { int digit = ch - '0'; if (digit < 0 || digit >= radix) { throw new NumberFormatException(); } if (res < multmin) { throw new NumberFormatException(); } res *= radix; if (res < limit + digit) { throw new NumberFormatException(); } res -= digit; } while (isPrintable(ch = br.read())); return negative ? res : -res; } catch (IOException e) { throw new NoSuchElementException(); } } float nextFloat() { return Float.parseFloat(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { try { int ch; while (isCRLF(ch = br.read())) { if (ch == -1) { throw new NoSuchElementException(); } } StringBuilder sb = new StringBuilder(); do { sb.appendCodePoint(ch); } while (!isCRLF(ch = br.read())); return sb.toString(); } catch (IOException e) { throw new NoSuchElementException(); } } void close() { try { br.close(); } catch (IOException e) { // throw new NoSuchElementException(); } } } 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()); } } static class List { String Word; int length; List(String Word, int length) { this.Word = Word; this.length = length; } } private static class Printer extends PrintWriter { Printer(PrintStream out) { super(out); } } }
Java
["15 3\ncccaabababaccbc", "15 9\ncccaabababaccbc", "1 1\nu"]
2 seconds
["cccbbabaccbc", "cccccc", ""]
null
Java 8
standard input
[ "implementation" ]
9f095a5f5b39d8c2f99c4162f2d7c5ff
The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 4 \cdot 10^5$$$) — the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.
1,200
Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
standard output
PASSED
71699000f453874e339bf70e4e20eb3a
train_000.jsonl
1529591700
You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times: if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; ... remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.
256 megabytes
import java.io.InputStream; public class Sport_Coding { static IO io=new IO(System.in); static int n, k; static String s; static boolean[] ar; public static void main(String[] args)throws Exception { n = io.nextInt(); k = io.nextInt(); s = io.next(); ar = new boolean[n]; for(char i = 'a'; i <= 'z'; ++i) for(int j = 0; k > 0 && j < n; ++j) if(s.charAt(j) == i) { --k; ar[j] = true; } for(int jk = 0; jk < n; ++jk) if(!ar[jk]) io.print(s.charAt(jk)); io.flush(); } } class IO { static byte[] buf = new byte[2048]; static int index, total; static InputStream in; static StringBuilder sb = new StringBuilder(); IO(InputStream is) { in = is; } int scan() throws Exception { if(index>=total){ index = 0; total = in.read(buf); if(total<=0) return -1; } return buf[index++]; } String next() throws Exception { int c; for(c=scan(); c<=32; c=scan()); StringBuilder sb = new StringBuilder(); for(; c>32; c=scan()) sb.append((char)c); return sb.toString(); } int nextInt() throws Exception { int c, val = 0; for(c=scan(); c<=32; c=scan()); boolean neg = c=='-'; if(c=='-' || c=='+') c = scan(); for(; c>='0' && c<='9'; c=scan()) val = (val<<3) + (val<<1) + (c&15); return neg?-val:val; } long nextLong() throws Exception { int c;long val = 0; for(c=scan(); c<=32; c=scan()); boolean neg = c=='-'; if(c=='-' || c=='+') c = scan(); for(; c>='0' && c<='9'; c=scan()) val = (val<<3) + (val<<1) + (c&15); return neg?-val:val; } void print(Object a) { sb.append(a.toString()); } void println(Object a) { sb.append(a.toString()).append("\n"); } void println() { sb.append("\n"); } void flush() { System.out.print(sb); sb = new StringBuilder(); } }
Java
["15 3\ncccaabababaccbc", "15 9\ncccaabababaccbc", "1 1\nu"]
2 seconds
["cccbbabaccbc", "cccccc", ""]
null
Java 8
standard input
[ "implementation" ]
9f095a5f5b39d8c2f99c4162f2d7c5ff
The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 4 \cdot 10^5$$$) — the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.
1,200
Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
standard output
PASSED
bca621e247346e1cecb5a2478ab42bcc
train_000.jsonl
1529591700
You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times: if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; ... remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n=sc.nextInt(); int k=sc.nextInt(); String s=sc.next(); StringBuffer sb = new StringBuffer(); int[] freq=new int[26]; for(int i=0;i<n;i++) { freq[s.charAt(i)-'a']++; } int c=0,prev=0,ind=0; for(int i=0;i<26;i++) { c+=freq[i]; if(c>=k) { ind=i; c=k-prev; break; } prev=c; } // System.out.println(ind); for(int i=0;i<n;i++) { char ch=s.charAt(i); int in=ch-'a'; // System.out.println(in); if(in>ind) sb.append(ch); if(in==ind) { if(c<=0) sb.append(ch); c--; } } System.out.print(sb); } }
Java
["15 3\ncccaabababaccbc", "15 9\ncccaabababaccbc", "1 1\nu"]
2 seconds
["cccbbabaccbc", "cccccc", ""]
null
Java 8
standard input
[ "implementation" ]
9f095a5f5b39d8c2f99c4162f2d7c5ff
The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 4 \cdot 10^5$$$) — the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.
1,200
Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
standard output
PASSED
773d3ea1096c424bc239006b16a7524e
train_000.jsonl
1529591700
You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times: if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; ... remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.
256 megabytes
//package math_codet; import java.io.*; import java.util.*; public class lets_do { public static void main(String[] args) { InputReader in=new InputReader(System.in); StringBuffer str=new StringBuffer(); int n=in.nextInt(); int k=in.nextInt(); String s=in.next(); int i=0,j=0; int[] freq=new int[26]; int[] freq1=new int[26]; int ind=-1; for(i=0;i<n;i++){ freq[s.charAt(i)-'a']++; } for(i=0;i<26;i++) freq1[i]=freq[i]; for(i=0;i<26;i++){ if(k==0) { ind=i; break; } if(k>=freq[i]){ k-=freq[i]; freq[i]=0; } else{ freq[i]-=k; } } for(i=0;i<26;i++){ if(freq[i]>0){ ind=i; break; } } if(ind==-1) { System.exit(0); } int[] st=new int[n]; for(i=0;i<n;i++){ st[i]=s.charAt(i)-'a'; } //System.out.println(ind); for(i=0;i<n;i++){ if(st[i]<ind) st[i]=-1; } int count=0; for(i=n-1;i>=0;i--){ if(count==freq[ind] && st[i]==ind){ st[i]=-1; continue; } if(st[i]==ind) count++; } for(i=0;i<n;i++){ if(st[i]!=-1) str.append((char)(st[i]+97)); } System.out.println(str); } static class InputReader{ private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new UnknownError(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new UnknownError(); } 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 void skip(int x) { while (x-- > 0) read(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public String nextString() { return next(); } public String next() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { StringBuffer buf = new StringBuffer(); int c = read(); while (c != '\n' && c != -1) { if (c != '\r') buf.appendCodePoint(c); c = read(); } return buf.toString(); } 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 hasNext() { int value; while (isSpaceChar(value = peek()) && value != -1) read(); return value != -1; } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } }
Java
["15 3\ncccaabababaccbc", "15 9\ncccaabababaccbc", "1 1\nu"]
2 seconds
["cccbbabaccbc", "cccccc", ""]
null
Java 8
standard input
[ "implementation" ]
9f095a5f5b39d8c2f99c4162f2d7c5ff
The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 4 \cdot 10^5$$$) — the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.
1,200
Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
standard output
PASSED
d2e926f279343e8999515dcf13edbd62
train_000.jsonl
1529591700
You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times: if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; ... remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; /** * * @author thachlp */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here FastReader fr = new FastReader(); int n = fr.nextInt(); int k = fr.nextInt(); String s = fr.next(); char[] arr = s.toCharArray(); for (char c = 'a'; c <= 'z'; c++) { for (int i = 0; i < n; i++) { if(k == 0){ break; } if (k > 0) { if (arr[i] == c) { arr[i] = '0'; k--; } } } } StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { if (arr[i] != '0') { sb.append(arr[i]); } } System.out.println(sb.toString()); } } 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) { } } 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) { } return str; } }
Java
["15 3\ncccaabababaccbc", "15 9\ncccaabababaccbc", "1 1\nu"]
2 seconds
["cccbbabaccbc", "cccccc", ""]
null
Java 8
standard input
[ "implementation" ]
9f095a5f5b39d8c2f99c4162f2d7c5ff
The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 4 \cdot 10^5$$$) — the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.
1,200
Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
standard output
PASSED
1518947832ccfce52f8bdd9ddb239d85
train_000.jsonl
1529591700
You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times: if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; ... remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.
256 megabytes
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.*; public class alphabeticRemovals { static class FastReader { StringTokenizer st; BufferedReader br; public FastReader(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public FastReader(FileReader fileReader) { br = new BufferedReader(fileReader); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public int[] nextIntArray(int n) throws IOException { int[] ret = new int[n]; for (int i = 0; i < n; i++) { ret[i] = nextInt(); } return ret; } public long[] nextIntLong(int n) throws IOException { long[] ret = new long[n]; for (int i = 0; i < n; i++) { ret[i] = nextLong(); } return ret; } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public boolean ready() throws IOException { return br.ready(); }} public static void main(String[] args) throws IOException { // TODO Auto-generated method stub FastReader s=new FastReader(System.in); long n=s.nextLong(); long k=s.nextLong(); String str=s.next(); long alpha[]=new long [26]; for(int i=0;i<n;i++) alpha[str.charAt(i)-'a']++; int j=0; HashMap<Character,Integer> map=new HashMap<>(); for(int i=0;i<k;i++) { while(j<26 && alpha[j]==0) { j++; } alpha[j]--; int count=0; if(map.containsKey((char)(j+'a'))) count=map.get((char)(j+'a')); count++; map.put((char)(j+'a'), count); } for(int i=0;i<n;i++) { if(map.containsKey(str.charAt(i)) && map.get(str.charAt(i))!=0) { map.put(str.charAt(i), map.get(str.charAt(i))-1); } else System.out.print(str.charAt(i)); } } }
Java
["15 3\ncccaabababaccbc", "15 9\ncccaabababaccbc", "1 1\nu"]
2 seconds
["cccbbabaccbc", "cccccc", ""]
null
Java 8
standard input
[ "implementation" ]
9f095a5f5b39d8c2f99c4162f2d7c5ff
The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 4 \cdot 10^5$$$) — the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.
1,200
Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
standard output
PASSED
966e676418e6cfa101787d681da83d75
train_000.jsonl
1529591700
You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times: if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; ... remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.
256 megabytes
//package com.prituladima.codeforce.contests.contest999; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; /** * Created by prituladima on 6/23/18. */ public class C { private static class Staff { public Staff(char c, int i) { this.c = c; this.i = i; } char c; int i; public char getC() { return c; } public int getI() { return i; } } private void solve() throws IOException { int n = nextInt(), k = nextInt(); String s = nextToken(); char[] chars = s.toCharArray(); List<Staff> list = new ArrayList<>(); for (int i = 0; i < n; i++) { list.add(new Staff(chars[i], i)); } Collections.sort(list, Comparator.comparing(Staff::getC).thenComparing(Staff::getI)); list = list.subList(k, n); Collections.sort(list, Comparator.comparing(Staff::getI)); StringBuilder SB = new StringBuilder(); for (int i = 0; i < list.size(); i++) { SB.append(list.get(i).c); } System.out.println(SB.toString()); } public static void main(String[] args) { new C().run(); } StringTokenizer tokenizer; BufferedReader reader; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; writer = new PrintWriter(System.out); solve(); reader.close(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); } return tokenizer.nextToken(); } int[] nextArr(int size) throws NumberFormatException, IOException { int[] arr = new int[size]; for (int i = 0; i < size; i++) arr[i] = nextInt(); return arr; } long[] nextArrL(int size) throws NumberFormatException, IOException { long[] arr = new long[size]; for (int i = 0; i < size; i++) arr[i] = nextLong(); return arr; } double[] nextArrD(int size) throws NumberFormatException, IOException { double[] arr = new double[size]; for (int i = 0; i < size; i++) arr[i] = nextDouble(); return arr; } }
Java
["15 3\ncccaabababaccbc", "15 9\ncccaabababaccbc", "1 1\nu"]
2 seconds
["cccbbabaccbc", "cccccc", ""]
null
Java 8
standard input
[ "implementation" ]
9f095a5f5b39d8c2f99c4162f2d7c5ff
The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 4 \cdot 10^5$$$) — the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.
1,200
Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
standard output
PASSED
3a7bb8f4e97cebae76bc4dddaaab7005
train_000.jsonl
1529591700
You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times: if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; ... remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.
256 megabytes
import java.util.*; public class asd { public static void main(String args[]) { Scanner s=new Scanner(System.in); int n=s.nextInt(); int k=s.nextInt(); String str=s.next(); int arr[]=new int[26]; for(int i=0;i<str.length();i++) { char ch=str.charAt(i); arr[(int)ch-97]++; } for(int i=0;i<26;i++) { if(k>=arr[i]) { k-=arr[i]; arr[i]=0; } else { arr[i]-=k; k=0; } } StringBuilder str2 = new StringBuilder(); for(int i=str.length()-1;i>=0;i--) { char ch=str.charAt(i); if(arr[(int)ch-97]>0) {str2.append(ch); arr[(int)ch-97]--; } } System.out.println(str2.reverse()); } }
Java
["15 3\ncccaabababaccbc", "15 9\ncccaabababaccbc", "1 1\nu"]
2 seconds
["cccbbabaccbc", "cccccc", ""]
null
Java 8
standard input
[ "implementation" ]
9f095a5f5b39d8c2f99c4162f2d7c5ff
The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 4 \cdot 10^5$$$) — the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.
1,200
Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
standard output
PASSED
f3b921f1387b659c3cb2dffab37e8bd5
train_000.jsonl
1529591700
You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times: if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; ... remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.
256 megabytes
import java.util.Scanner; public class Alp { public static void main(String [] args) { Scanner in = new Scanner(System.in); int [] alph = new int[26]; int [] toDel = new int[26]; in.nextInt(); int z = in.nextInt(); char [] word = in.next().toCharArray(); for(char w:word) { alph[w-'a']++; } for(int i=0;i<26;i++) { if(alph[i]-z<0) { toDel[i] = alph[i]; z-=alph[i]; } else { toDel[i]= z; break; } } for(char w:word) { if(toDel[w-'a']==0) { System.out.print(w); } else { toDel[w-'a']--; } } in.close(); } }
Java
["15 3\ncccaabababaccbc", "15 9\ncccaabababaccbc", "1 1\nu"]
2 seconds
["cccbbabaccbc", "cccccc", ""]
null
Java 8
standard input
[ "implementation" ]
9f095a5f5b39d8c2f99c4162f2d7c5ff
The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 4 \cdot 10^5$$$) — the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.
1,200
Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
standard output
PASSED
5e83249d5ca6a576a6e3d4e41b3d5c30
train_000.jsonl
1529591700
You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times: if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; ... remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.
256 megabytes
import java.util.Scanner; public class Ex03_2 { private static int[] array = new int[26]; // count private static int visit[]; public static void main(String args[]) { Scanner sc = new Scanner(System.in); int s = sc.nextInt(); int k = sc.nextInt(); String temp = sc.next(); visit = new int[temp.length()]; for (int i = 0; i < temp.length(); i++) { visit[i] = (temp.charAt(i) - 'a'); } for (int i = 0; i < visit.length; i++) { array[visit[i]] += 1; } removeAlphabet(k); for (int i = 0; i < visit.length; i++) { if (visit[i] > -1) { char res = (char) (visit[i] + 'a'); System.out.print(res); } } } private static void removeAlphabet(int k) { int tempK = k; for (int i = 0; i < array.length; i++) { if (tempK == 0) break; if (array[i] == 0) continue; if (array[i] >= tempK) { array[i] = array[i] - tempK; for (int j = 0; j < visit.length && tempK > 0; j++) { if (visit[j] == i) { visit[j] = -1; tempK--; } } tempK = 0; } if (tempK > array[i]) { tempK = tempK - array[i]; for (int j = 0; j < visit.length && array[i] > 0; j++) { if (visit[j] == i) { visit[j] = -1; array[i]--; } } array[i] = 0; } } } }
Java
["15 3\ncccaabababaccbc", "15 9\ncccaabababaccbc", "1 1\nu"]
2 seconds
["cccbbabaccbc", "cccccc", ""]
null
Java 8
standard input
[ "implementation" ]
9f095a5f5b39d8c2f99c4162f2d7c5ff
The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 4 \cdot 10^5$$$) — the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.
1,200
Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
standard output
PASSED
c908f8a052dab3e084ca121a7044c96a
train_000.jsonl
1529591700
You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times: if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; ... remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.
256 megabytes
import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.*; public class Main { private static Reader r; private static boolean flag[]; public static void main(String[] args) throws Exception { r = new Reader(); r.readLine(); int n = r.readInt(0); int k = r.readInt(1); flag = new boolean[n]; r.readLine(); char charArr[] = r.readString(0).toCharArray(); Map<Character,List<Integer>> freqIdx = getCharFreqWithIdx(charArr, n); for (char ch='a';ch <= 'z';++ch) { int size = 0; if (freqIdx.containsKey(ch)) size = freqIdx.get(ch).size(); else continue; if (size <= k) setCharAtIdxForEmpty(freqIdx, ch, size, charArr); else setCharAtIdxForEmpty(freqIdx, ch, k, charArr); k -= size; if (k <= 0) break; } printRes(charArr, n); r.close(); } public static Map<Character,List<Integer>> getCharFreqWithIdx(char charArr[], int size) { Map<Character,List<Integer>> freqIdxs = new HashMap<>(); int freq[] = new int[26]; for (int i=0;i < size;++i) { int fr = ++freq[charArr[i] - 'a']; List<Integer> idx = new ArrayList<>(); if (fr != 1) idx = freqIdxs.get(charArr[i]); else idx = new ArrayList<Integer>(); idx.add(i); freqIdxs.put(charArr[i], idx); } return freqIdxs; } public static void setCharAtIdxForEmpty(Map<Character,List<Integer>> freqIdx, char ch, int num, char []charArr) { List<Integer> idx = freqIdx.get(ch); for (int i=0;i < num;++i) { /*charArr[idx.get(i)] = DEFAULT_CHAR_VALUE;*/ flag[idx.get(i)] = true; } } private static void printRes(char []charArr, int size) { StringBuilder res = new StringBuilder(); for (int i=0;i < size;++i) if (!flag[i]) res.append(charArr[i]); System.out.println(res.toString()); } public static List<Integer> getDivs(int n) { List<Integer> divs = new ArrayList<>(); for (int i=1; i <= Math.sqrt(n); i++) { if (n % i == 0) { if (n / i == i) divs.add(i); else { divs.add(i); divs.add(n / i); } } } return divs; } public static void reverseOrSwap(char arr[], int fr, int to) { int step = (to - fr) / 2; for (int i=0;i <= step;++i) { char temp = arr[i]; arr[i] = arr[to - i]; arr[to - i] = temp; } } } class Pair implements Comparable<Pair> { int f,s; public Pair() {} public Pair(int f, int s) { this.f = f; this.s = s; } @Override public String toString() { return f + " " + s; } @Override public int compareTo(Pair o) { // TODO: Implement this method if (f == o.f) return s - o.s; return f - o.f; } } class Reader { private BufferedReader reader; private String line[]; public Reader() { reader = new BufferedReader(new InputStreamReader(System.in)); } public String[] getLine() { return line; } public void readLine() throws IOException { line = reader.readLine().split(" "); } public int readInt(int pos)throws IOException { return Integer.parseInt(line[pos]); } public double readDouble(int pos)throws IOException { return Double.parseDouble(line[pos]); } public long readLong(int pos)throws IOException { return Long.parseLong(line[pos]); } public String readString(int pos)throws IOException { return line[pos]; } public void close()throws IOException { reader.close(); } }
Java
["15 3\ncccaabababaccbc", "15 9\ncccaabababaccbc", "1 1\nu"]
2 seconds
["cccbbabaccbc", "cccccc", ""]
null
Java 8
standard input
[ "implementation" ]
9f095a5f5b39d8c2f99c4162f2d7c5ff
The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 4 \cdot 10^5$$$) — the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.
1,200
Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
standard output
PASSED
7326f1659dcd2cfd084f98fde7cc2ca3
train_000.jsonl
1529591700
You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times: if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; ... remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.
256 megabytes
import java.util.Scanner; public class C999 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(), k = in.nextInt(), i, upTo = -1, toRemove = 0; int[] sortedS = new int[26]; String s = in.next(), result = ""; for(i = 0; i < n; i++) sortedS[s.charAt(i) - 97]++; for(i = 0; toRemove < k && i < 26; i++) { toRemove += sortedS[i]; upTo = i; } sortedS[upTo] = sortedS[upTo] - (toRemove - k); // we only need to remove this much from the last char valid to be removed for(i = 0; i < n; i++) { if(s.charAt(i) <= 97 + upTo && sortedS[s.charAt(i) - 97] > 0) { sortedS[s.charAt(i) - 97]--; } else { System.out.print(s.charAt(i)); } } } }
Java
["15 3\ncccaabababaccbc", "15 9\ncccaabababaccbc", "1 1\nu"]
2 seconds
["cccbbabaccbc", "cccccc", ""]
null
Java 8
standard input
[ "implementation" ]
9f095a5f5b39d8c2f99c4162f2d7c5ff
The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 4 \cdot 10^5$$$) — the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.
1,200
Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
standard output
PASSED
b5165c621be1869ec1ec739c650cd21e
train_000.jsonl
1529591700
You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times: if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; ... remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class bhaa { InputStream is; PrintWriter o; /////////////////// CODED++ BY++ ++ ++ ++ BHAVYA++ ARORA++ ++ ++ ++ FROM++ JAYPEE++ INSTITUTE++ OF++ INFORMATION++ TECHNOLOGY++ //////////////// ///////////////////////// Make it work, make it right, make it fast. Make it work, make it right, make it fast. Make it work, make it right, make it fast. Make it work, make it right, make it fast. ///////////////// void solve() { int n=ni(); int k=ni(); char s[]=ns().toCharArray(); ArrayList<Integer>al[]=new ArrayList[26]; for(int i=0;i<26;i++) { al[i]=new ArrayList<Integer>(); } for(int i=0;i<n;i++) { al[s[i]-'a'].add(i); } boolean chk[]=new boolean[n]; for(int i=0;i<26;i++) { int tk=Math.min(k,al[i].size()); k-=tk; for(int j=0;j<tk;j++) { chk[al[i].get(j)]=true; } } StringBuilder sb=new StringBuilder(); for(int i=0;i<n;i++) { if(chk[i]==false) { sb.append(s[i]); } } o.println(sb); } //---------- I/O Template ---------- public static void main(String[] args) { new bhaa().run(); } void run() { is = System.in; o = new PrintWriter(System.out); solve(); o.flush(); } byte input[] = new byte[1024]; int len = 0, ptr = 0; int readByte() { if(ptr >= len) { ptr = 0; try { len = is.read(input); } catch(IOException e) { throw new InputMismatchException(); } if(len <= 0) { return -1; } } return input[ptr++]; } boolean isSpaceChar(int c) { return !( c >= 33 && c <= 126 ); } int skip() { int b = readByte(); while(b != -1 && isSpaceChar(b)) { b = readByte(); } return b; } char nc() { return (char)skip(); } String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while( !(isSpaceChar(b) && b != ' ') ) { sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } int ni() { int n = 0, b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } if(b == -1) { return -1; } //no input while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } long nl() { long n = 0L; int b = readByte(); boolean minus = false; while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); } if(b == '-') { minus = true; b = readByte(); } while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); } return minus ? -n : n; } double nd() { return Double.parseDouble(ns()); } float nf() { return Float.parseFloat(ns()); } int[] nia(int n) { int a[] = new int[n]; for(int i = 0; i < n; i++) { a[i] = ni(); } return a; } long[] nla(int n) { long a[] = new long[n]; for(int i = 0; i < n; i++) { a[i] = nl(); } return a; } int [][] nim(int n) { int mat[][]=new int[n][n]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { mat[i][j]=ni(); } } return mat; } long [][] nlm(int n) { long mat[][]=new long[n][n]; for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { mat[i][j]=nl(); } } return mat; } char[] ns(int n) { char c[] = new char[n]; int i, b = skip(); for(i = 0; i < n; i++) { if(isSpaceChar(b)) { break; } c[i] = (char)b; b = readByte(); } return i == n ? c : Arrays.copyOf(c,i); } void piarr(int arr[]) { for(int i=0;i<arr.length;i++) { o.print(arr[i]+" "); } o.println(); } void plarr(long arr[]) { for(int i=0;i<arr.length;i++) { o.print(arr[i]+" "); } o.println(); } void pimat(int mat[][]) { for(int i=0;i<mat.length;i++) { for(int j=0;j<mat[0].length;j++) { o.print(mat[i][j]+" "); } o.println(); } } void plmat(long mat[][]) { for(int i=0;i<mat.length;i++) { for(int j=0;j<mat[0].length;j++) { o.print(mat[i][j]+" "); } o.println(); } } static class DJset { int n; ty1 arr[]; class ty1 { int rank; int par; ty1(int p,int r) { par=p; rank=r; } } DJset(int nu) { n=nu; arr=new ty1[n]; for(int i=0;i<n;i++) { arr[i]=new ty1(i,1); } } int find(int x) { if(arr[x].par!=x) { arr[x].par=find(arr[x].par); } return arr[x].par; } void union(int x,int y) { x=find(x); y=find(y); if(x!=y) { if(arr[x].rank<arr[y].rank) { arr[x].par=y; } else if(arr[y].rank<arr[x].rank) { arr[y].par=x; } else { arr[x].rank++; arr[y].par=x; } } } public String toString() { String res=""; for(int i=0;i<n;i++) { res+=(arr[i].par+" "); } return res; } public int countsets() { int res=0; for(int i=0;i<n;i++) { if(arr[i].par==i) { res++; } } return res; } } //////////////////////////////////// template finished ////////////////////////////////////// }
Java
["15 3\ncccaabababaccbc", "15 9\ncccaabababaccbc", "1 1\nu"]
2 seconds
["cccbbabaccbc", "cccccc", ""]
null
Java 8
standard input
[ "implementation" ]
9f095a5f5b39d8c2f99c4162f2d7c5ff
The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 4 \cdot 10^5$$$) — the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.
1,200
Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
standard output
PASSED
730584f04b985621e5e1031542e3c2b5
train_000.jsonl
1529591700
You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times: if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; ... remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); StringBuilder sb = new StringBuilder(); int tab[] = new int[26]; int n = sc.nextInt(); int k = sc.nextInt(); sc.nextLine(); String s = sc.nextLine(); char temp = 'a'; if (k == n) System.out.println(" "); else { for (int i = 0; i < s.length(); i++) { tab[s.charAt(i) - 'a']++; } for (int i = 0; i < tab.length; i++) { if (k > tab[i]) { k -= tab[i]; } else { for (int j = 0; j < s.length(); j++) { if (s.charAt(j) >= temp) { if (s.charAt(j) == temp && k > 0 ) { k--; } else sb.append(s.charAt(j)); } } System.out.println(sb.toString()); System.exit(0); } temp++; } } } }
Java
["15 3\ncccaabababaccbc", "15 9\ncccaabababaccbc", "1 1\nu"]
2 seconds
["cccbbabaccbc", "cccccc", ""]
null
Java 8
standard input
[ "implementation" ]
9f095a5f5b39d8c2f99c4162f2d7c5ff
The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 4 \cdot 10^5$$$) — the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.
1,200
Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
standard output
PASSED
043933debdfdfd045506a900d85f6fc1
train_000.jsonl
1529591700
You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times: if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; ... remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.
256 megabytes
import java.io.*; import java.lang.reflect.Array; import java.util.*; public class Main { String fileName = ""; ////////////////////// SOLUTION SOLUTION SOLUTION ////////////////////////////// int INF = Integer.MAX_VALUE; void solve() throws IOException { int n = readInt(); int k = readInt(); String str = readString(); char[] arr = str.toCharArray(); int letter = 97; int z = 0; int x = 0; while(z < k){ boolean done = false; for(int i = x; i < n; i++){ if(arr[i] == letter){ arr[i] = 'A'; done = true; z++; x = i; break; } } if(!done){ x = 0; letter++; if(letter == 123) break; } } for(int i = 0; i < n; i++) if(arr[i] >= 97 && arr[i] <= 122) System.out.print(arr[i]); System.out.println(); } //////////////////////////////////////////////////////////// public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub new Main().run(); } void run() throws NumberFormatException, IOException { solve(); out.close(); }; BufferedReader in; PrintWriter out; StringTokenizer tok; String delim = " "; Random rnd = new Random(); Main() throws FileNotFoundException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); tok = new StringTokenizer(""); } String readLine() throws IOException { return in.readLine(); } String readString() throws IOException { while (!tok.hasMoreTokens()) { String nextLine = readLine(); if (null == nextLine) { return null; } tok = new StringTokenizer(nextLine); } return tok.nextToken(); } int readInt() throws NumberFormatException, IOException { return Integer.parseInt(readString()); } byte readByte() throws NumberFormatException, IOException { return Byte.parseByte(readString()); } int[] readIntArray (int n) throws NumberFormatException, IOException { int[] a = new int[n]; for(int i=0; i<n; ++i){ a[i] = readInt(); } return a; } Integer[] readIntegerArray (int n) throws NumberFormatException, IOException { Integer[] a = new Integer[n]; for(int i=0; i<n; ++i){ a[i] = readInt(); } return a; } long readLong() throws NumberFormatException, IOException { return Long.parseLong(readString()); } double readDouble() throws NumberFormatException, IOException { return Double.parseDouble(readString()); } }
Java
["15 3\ncccaabababaccbc", "15 9\ncccaabababaccbc", "1 1\nu"]
2 seconds
["cccbbabaccbc", "cccccc", ""]
null
Java 8
standard input
[ "implementation" ]
9f095a5f5b39d8c2f99c4162f2d7c5ff
The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 4 \cdot 10^5$$$) — the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.
1,200
Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
standard output
PASSED
2b5143680010d7cc2bc3d887af803ad5
train_000.jsonl
1529591700
You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times: if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; ... remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.
256 megabytes
import java.util.*; import java.io.*; public class Reverse { static BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); static BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(System.out)); static StringTokenizer st=null; static String next() { while(st==null || !st.hasMoreElements()) { try{ st=new StringTokenizer(br.readLine()); } catch (IOException e){ e.printStackTrace(); } } return st.nextToken(); } static int nextInt() { return Integer.parseInt(next()); } static long nextLong() { return Long.parseLong(next()); } static double nextDouble(){ return Double.parseDouble(next()); } public static void main(String[] args) { try{ int n=nextInt(); int k=nextInt(); String s=next(); int ar[]; ar=new int[28]; char ch[]=s.toCharArray(); for(int i=0;i<n;i++) { int x=(int)(ch[i]-'a'); ar[x]++; } //bw.write(Arrays.toString(ar)+"\n"); int total=0; for(int i=0;i<28;i++) { int temp=(total+ar[i]); // bw.write("i="+i+" temp="+temp+"\n"); if(temp<=k) { total+=ar[i]; ar[i]=0; } else { int sub=(temp-k); ar[i]=sub; total=k; } // bw.write("total="+total+"\n\n"); if(total==k) { break; } } // bw.write(Arrays.toString(ar)+"\n"); StringBuilder res=new StringBuilder(); for(int i=n-1;i>=0;i--) { int x=(int)(ch[i]-'a'); if(ar[x]>0) { res=res.append(ch[i]); ar[x]--; } } // bw.write(res+"\n"); int l=res.length(); for(int i=(l-1);i>=0;i--) { bw.write(res.charAt(i)+""); } bw.flush(); } catch (Exception e) { e.printStackTrace(); } } }
Java
["15 3\ncccaabababaccbc", "15 9\ncccaabababaccbc", "1 1\nu"]
2 seconds
["cccbbabaccbc", "cccccc", ""]
null
Java 8
standard input
[ "implementation" ]
9f095a5f5b39d8c2f99c4162f2d7c5ff
The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 4 \cdot 10^5$$$) — the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.
1,200
Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
standard output
PASSED
da20a5048cec41db2b624f2f8f829437
train_000.jsonl
1529591700
You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times: if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; ... remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.
256 megabytes
import java.util.*; import java.util.regex.Pattern; public class Q2 { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int i,n,k,c=0,temp=0; n=sc.nextInt(); k=sc.nextInt(); String s=sc.next(); int aa[]=new int[26]; int bb[]=new int[26]; if(n==k){ return; } for(i=0;i<n;i++){ aa[s.charAt(i)-'a']++; } i=0; temp=k; while (aa[i]==0 && i<26) i++; while(temp>0){ if(aa[i]<=temp){ bb[i]=aa[i]; temp-=aa[i]; i++; while (aa[i]==0 && i<26) i++; } else { bb[i]=temp; break; } } for(i=0;i<n;i++){ if(bb[s.charAt(i)-'a']==0) { System.out.print(s.charAt(i)); } else bb[s.charAt(i)-'a']--; } } }
Java
["15 3\ncccaabababaccbc", "15 9\ncccaabababaccbc", "1 1\nu"]
2 seconds
["cccbbabaccbc", "cccccc", ""]
null
Java 8
standard input
[ "implementation" ]
9f095a5f5b39d8c2f99c4162f2d7c5ff
The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 4 \cdot 10^5$$$) — the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.
1,200
Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
standard output
PASSED
6d61e14852cf5a69eeaec5d243eab200
train_000.jsonl
1529591700
You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times: if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; ... remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.nio.CharBuffer; import java.util.Map; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class Problem999C { public static TreeMap<Character, Integer> chars = new TreeMap<Character, Integer>(); public static int k; public static String s; public static void main(String[] args) throws Exception { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); int n = in.nextInt(); k = in.nextInt(); s = in.next(); char[] ch = new char[s.length()]; for (int i = 0; i < s.length(); i++) { Character nextChar = s.charAt(i); ch[i] = nextChar; Integer times = chars.get(nextChar); if (times == null) { chars.put(nextChar, 1); } else { chars.put(nextChar, ++times); } } if (n - k == 0) { out.println(); out.close(); return; } else if (n - k == 1) { out.println(chars.lastKey()); out.close(); return; } chars.entrySet().stream().forEachOrdered(e -> { if (k > e.getValue()) { k -= e.getValue(); e.setValue(0); } else if (k > 0) { e.setValue(e.getValue() - k); k = 0; } }); for (int i = ch.length - 1; i >= 0; i--) { Integer times = chars.get(ch[i]); if (times > 0) { chars.put(ch[i], --times); } else { ch[i] = '_'; } } out.println(String.valueOf(ch).replaceAll("_", "")); out.close(); return; } 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(), " \t\n\r\f,"); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["15 3\ncccaabababaccbc", "15 9\ncccaabababaccbc", "1 1\nu"]
2 seconds
["cccbbabaccbc", "cccccc", ""]
null
Java 8
standard input
[ "implementation" ]
9f095a5f5b39d8c2f99c4162f2d7c5ff
The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 4 \cdot 10^5$$$) — the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.
1,200
Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
standard output
PASSED
0adfcbc668d4f390df2467cda8c8abc2
train_000.jsonl
1529591700
You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times: if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; ... remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.
256 megabytes
//package pr_2; import java.util.*; import java.io.*; public class rep { public static void main(String[] args) throws IOException { Scanner scan = new Scanner(System.in); int N = scan.nextInt(), k = scan.nextInt(), f = k; char[] arr = scan.next().toCharArray(); int [] count = new int[26]; for(int i=0; i<N; i++) { count[(int)arr[i]-97]++; } for(int i=0; i<26 && k > 0; i++) { if(count[i] <= k) { k = k- count[i]; count[i] = 0; }else { count[i] = count[i]-k; k =0; } } boolean[] stamp = new boolean[N]; for(int i=N-1; i>=0 && f >0; i--) { if(count[(int)arr[i]-97] > 0) { count[(int)arr[i]-97]--; }else { stamp[i] = true; f--; } } for(int i=0; i<N; i++) { if(!stamp[i]) { System.out.print(arr[i]); } }System.out.println(); /*StringBuilder input = new StringBuilder(); input.append(answer); input.reverse(); System.out.println(input);*/ } static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(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]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } }
Java
["15 3\ncccaabababaccbc", "15 9\ncccaabababaccbc", "1 1\nu"]
2 seconds
["cccbbabaccbc", "cccccc", ""]
null
Java 8
standard input
[ "implementation" ]
9f095a5f5b39d8c2f99c4162f2d7c5ff
The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 4 \cdot 10^5$$$) — the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.
1,200
Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
standard output
PASSED
7528ff5e751a8da737e05ba728dfa4d6
train_000.jsonl
1529591700
You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times: if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; ... remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Div3 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter w = new PrintWriter(System.out); String s = br.readLine(); StringTokenizer stt = new StringTokenizer(s); int n = Integer.parseInt(stt.nextToken()); int k = Integer.parseInt(stt.nextToken()); String st = br.readLine(); TreeMap<Character, TreeSet<Integer>> tree = new TreeMap<>(); for (int i = 0; i < n; ++i) { char c = st.charAt(i); if (tree.containsKey(c)) { tree.get(c).add(i); }else { tree.put(c, new TreeSet<>()); tree.get(c).add(i); } } for (int i = 0; i < k; ++i) { char c = 'a'; while (!tree.containsKey(c)) { c += 1; } tree.get(c).pollFirst(); if (tree.get(c).size() == 0) { tree.remove(c); } } char[] arr = new char[n]; for (int i = 0; i < n; ++i) { arr[i] = '0'; } for (char c = 'a'; c <= 'z'; ++c) { if (tree.containsKey(c)) { for (int i: tree.get(c)) { arr[i] = c; } } } for (char c: arr) { if (c != '0') { w.print(c); } } w.close(); } }
Java
["15 3\ncccaabababaccbc", "15 9\ncccaabababaccbc", "1 1\nu"]
2 seconds
["cccbbabaccbc", "cccccc", ""]
null
Java 8
standard input
[ "implementation" ]
9f095a5f5b39d8c2f99c4162f2d7c5ff
The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 4 \cdot 10^5$$$) — the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.
1,200
Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
standard output
PASSED
fe8088e88eeff0362520f25d61f24aa9
train_000.jsonl
1529591700
You are given a string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters. Polycarp wants to remove exactly $$$k$$$ characters ($$$k \le n$$$) from the string $$$s$$$. Polycarp uses the following algorithm $$$k$$$ times: if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; if there is at least one letter 'b', remove the leftmost occurrence and stop the algorithm, otherwise go to next item; ... remove the leftmost occurrence of the letter 'z' and stop the algorithm. This algorithm removes a single letter from the string. Polycarp performs this algorithm exactly $$$k$$$ times, thus removing exactly $$$k$$$ characters.Help Polycarp find the resulting string.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int count=0; String s = sc.next(); char c[] = s.toCharArray(); for(char i='a';i<='z';i++){ for(int j = 0;j<n;j++){ if(c[j]==i){ c[j]=0; count++; } if(count==k) break; } if(count==k) break; } for(int j=0;j<n;j++){ if(c[j]!=0) System.out.print(c[j]); } } }
Java
["15 3\ncccaabababaccbc", "15 9\ncccaabababaccbc", "1 1\nu"]
2 seconds
["cccbbabaccbc", "cccccc", ""]
null
Java 8
standard input
[ "implementation" ]
9f095a5f5b39d8c2f99c4162f2d7c5ff
The first line of input contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 4 \cdot 10^5$$$) — the length of the string and the number of letters Polycarp will remove. The second line contains the string $$$s$$$ consisting of $$$n$$$ lowercase Latin letters.
1,200
Print the string that will be obtained from $$$s$$$ after Polycarp removes exactly $$$k$$$ letters using the above algorithm $$$k$$$ times. If the resulting string is empty, print nothing. It is allowed to print nothing or an empty line (line break).
standard output
PASSED
e738f81175e7fd2b5231a619afede6e7
train_000.jsonl
1384102800
Levko loves strings of length n, consisting of lowercase English letters, very much. He has one such string s. For each string t of length n, Levko defines its beauty relative to s as the number of pairs of indexes i, j (1 ≤ i ≤ j ≤ n), such that substring t[i..j] is lexicographically larger than substring s[i..j].The boy wondered how many strings t are there, such that their beauty relative to s equals exactly k. Help him, find the remainder after division this number by 1000000007 (109 + 7).A substring s[i..j] of string s = s1s2... sn is string sisi  +  1... sj.String x  =  x1x2... xp is lexicographically larger than string y  =  y1y2... yp, if there is such number r (r &lt; p), that x1  =  y1,  x2  =  y2,  ... ,  xr  =  yr and xr  +  1 &gt; yr  +  1. The string characters are compared by their ASCII codes.
256 megabytes
import java.text.DecimalFormat; import java.util.*; import java.io.*; public class Main { private static final int mod = 1000000007; private static char [] S; private static int [] less; private static int n,K; private static Integer [] [] [] dp; private static int add(int a,int b) { a += b; if (a >= mod) a -= mod; return a; } private static int mul(int a,int b ){ long ret = (a*(long)b)%mod; return (int)ret; } private static int solve(int p,int ctr,int r){ if (p == n) return (r == 0) ? 1 : 0; if (dp[p][ctr][r] != null) return dp[p][ctr][r]; int ret = solve(p+1,ctr+1,r); ret = add(ret,mul(solve(p+1,0,r),less[p])); long v = (ctr + 1L)*(n-p); if (v <= r) ret = add(ret,mul(solve(p+1,0,r-(int)v),25-less[p])); dp[p][ctr][r] = ret; return ret; } private static int solve() { int [] [] dp = new int[n+1][K+1]; dp[n][0] = 1; for (int r = 0;r <= K;r++) { int contrib = 0; for (int p = n-1;p >= 0;p--){ contrib = add(contrib,mul(less[p],dp[p+1][r])); int ret = contrib; if (r == 0) ret++; int m = n-p,lim = (m + 1)/2; for (int i = 0;i < lim && (i+1L)*(m-i) <= r;i++) { int j = p + i; int v = (i+1)*(n-j); ret = add(ret,mul(25-less[j],dp[j+1][r-v])); if(i < m/2) { j = p + n - j - 1; ret = add(ret, mul(25 - less[j], dp[j + 1][r - v])); } } dp[p][r] = ret; } } return dp[0][K]; } private static void init(){ less = new int[S.length]; for (int i = 0;i < n;i++) less[i] = S[i] - 'a'; // dp = new Integer[n][n+1][K+1]; } private static void test(){ Random rnd = new Random(); int N = 10,lK = 10; for (int t = 0;t < 1000;t++) { n = (rnd.nextInt()%N + N)%N + 1; K = (rnd.nextInt()%lK + lK)%lK; S = new char[n]; for (int i = 0;i < n;i++) S[i] = (char)('a' + (rnd.nextInt()%3 + 3)%3); init(); if (solve() != solve(0,0,K)) { System.err.println("failed on"); System.err.println(n + " " + K); System.err.println(S); System.err.println("expected " + solve(0,0,K) + " found " + solve()); return; } } System.err.println("passed :)"); } public static void main(String[] args) throws Exception { IO io = new IO(null, null); n = io.getNextInt(); K = io.getNextInt(); S = io.getNext().toCharArray(); init(); io.println(solve()); io.close(); } } class IO{ private BufferedReader br; private StringTokenizer st; private PrintWriter writer; private String inputFile,outputFile; public boolean hasMore() throws IOException{ if(st != null && st.hasMoreTokens()) return true; if(br != null && br.ready()) return true; return false; } public String getNext() throws FileNotFoundException, IOException{ while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String getNextLine() throws FileNotFoundException, IOException{ return br.readLine().trim(); } public int getNextInt() throws FileNotFoundException, IOException{ return Integer.parseInt(getNext()); } public long getNextLong() throws FileNotFoundException, IOException{ return Long.parseLong(getNext()); } public void print(double x,int num_digits) throws IOException{ writer.printf("%." + num_digits + "f" ,x); } public void println(double x,int num_digits) throws IOException{ writer.printf("%." + num_digits + "f\n" ,x); } public void print(Object o) throws IOException{ writer.print(o.toString()); } public void println(Object o) throws IOException{ writer.println(o.toString()); } public IO(String x,String y) throws FileNotFoundException, IOException{ inputFile = x; outputFile = y; if(x != null) br = new BufferedReader(new FileReader(inputFile)); else br = new BufferedReader(new InputStreamReader(System.in)); if(y != null) writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFile))); else writer = new PrintWriter(new OutputStreamWriter(System.out)); } protected void close() throws IOException{ br.close(); writer.close(); } public void outputArr(Object [] A) throws IOException{ int L = A.length; for (int i = 0;i < L;i++) { if(i > 0) writer.print(" "); writer.print(A[i]); } writer.print("\n"); } }
Java
["2 2\nyz", "2 3\nyx", "4 7\nabcd"]
1 second
["26", "2", "21962"]
null
Java 8
standard input
[ "dp", "combinatorics" ]
6acc6ab9e60eceebb85f41dc0aea9cf4
The first line contains two integers n and k (1 ≤ n ≤ 2000, 0 ≤ k ≤ 2000). The second line contains a non-empty string s of length n. String s consists only of lowercase English letters.
2,500
Print a single number — the answer to the problem modulo 1000000007 (109 + 7).
standard output
PASSED
328e580333e785c936f2af574be80638
train_000.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.util.*; public class CF363D2C { public static void main(String args[])throws Exception { Scanner sc=new Scanner(System.in); char ch[]=sc.next().toCharArray(); int len=ch.length; int ar[]=new int[len]; int k=0; int j=0;//it points to the location from where change might be made boolean type1=false;//stores if type 1 error exists boolean type2=false,type2_pre=false;//stores for type 2 errors(with two characters) for(int i=1;i<len;i++) { //System.out.print(ch[i]+" "+i+" "+j); if(type1) { if(ch[i]==ch[i-1]) { ar[j]=1; j++; //System.out.println(i+" "+ch[i]+" "+j+"in type 1"); } else { /*if(type2_pre) { type2_pre=false; k=i+1; }*/ type1=false; type2=true; } } else if(type2) { if(ch[i]==ch[i-1]) { if(type2_pre) { type2_pre=false; ar[k]=0; ar[j]=1; j=i-1; } else { ar[j]=1; k=j; j=i-1; type2_pre=true; } //System.out.println(i+" "+ch[i]+" "+j+"in type 2"); type2=false; type1=true; } else { j=i+1; k=i+1; type2=false; type1=false; type2_pre=false; } }else { if(ch[i]==ch[i-1]) { type1=true; j=i-1; } else { j++; type1=false; } } } for(int i=0;i<len;i++) { if(ar[i]==0) System.out.print(ch[i]); } System.out.println(); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 8
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
b6386d094522c7a940a23c965e3d4b15
train_000.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.util.Scanner; /** * * @author elshamey */ public class Examples { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner scan = new Scanner(System.in); //aabbaabbaabbaabbaabbaabbcccccc String s = scan.next(); StringBuilder sb = new StringBuilder(s); String ans = ""; StringBuilder sb1 = new StringBuilder(ans); int count = 1; int count1 = 0; int x = 0; char c = '*'; boolean b = false; for (int i = 0; i < sb.length(); i++) { if (sb.charAt(i) != c) { // ans += s.charAt(i); sb1.append(s.charAt(i)); c = sb.charAt(i); count = 1; } else { count++; if (count == 2) { count1++; if (count1 == 1) { b = true; //ans += s.charAt(i); sb1.append(s.charAt(i)); } else { if (sb1.charAt(i - 2 - x) == sb1.charAt(i - 3 - x)) { x++; } else { //ans += s.charAt(i); sb1.append(s.charAt(i)); } } } else if (count > 2) { x++; } } } System.out.println(sb1); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 8
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
f3ab875c70e095e1e63d009efcd85f4a
train_000.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.util.*; public class practice { public static void main(String[] args) { Scanner scn=new Scanner(System.in); char a ,b='@',c='/',d='>'; String s=scn.next(); for(int i=0;i<s.length();i++){ a=s.charAt(i); if(!((a==b&&b==c)||(a==b&&c==d))){ System.out.print(a); d=c; c=b; b=a; } } System.out.println(); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 8
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
222d516aa6211992e6c4ce0e19a6598b
train_000.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.util.Scanner; import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class TestClass //implements Runnable { int x,y; public TestClass(int x,int y) { this.x=x; this.y=y; } public static void main(String args[]) throws Exception {/* new Thread(null, new TestClass(),"TESTCLASS",1<<23).start(); } public void run() {*/ //Scanner scan=new Scanner(System.in); InputReader hb=new InputReader(System.in); PrintWriter w=new PrintWriter(System.out); String s=hb.next(); int n=s.length(); char []c=s.toCharArray(); char []ans=new char[n]; int j=0; for(int i=0;i<n;i++) { if(j>=2 && ans[j-1]==c[i] && ans[j-2]==c[i]) continue; if(j>=3 && ans[j-1]==c[i] && ans[j-2]==ans[j-3]) continue; ans[j++]=c[i]; } ///w.println(j); w.print(new String(ans,0,j)); w.close(); } private void shuffle(int[] arr) { Random ran = new Random(); for (int i = 0; i < arr.length; i++) { int i1 = ran.nextInt(arr.length); int i2 = ran.nextInt(arr.length); int temp = arr[i1]; arr[i1] = arr[i2]; arr[i2] = temp; } } static class DSU { int parent[]; int sizeParent[]; DSU(int n) { parent=new int[n]; sizeParent=new int[n]; Arrays.fill(sizeParent,1); for(int i=0;i<n;i++) parent[i]=i; } int find(int x) { if(x!=parent[x]) parent[x]=find(parent[x]); return parent[x]; } void union(int x,int y) { x=find(x); y=find(y); if(sizeParent[x]>=sizeParent[y]) { if(x!=y) sizeParent[x]+=sizeParent[y]; parent[y]=x; } else { if(x!=y) sizeParent[y]+=sizeParent[x]; parent[x]=y; } } } static class InputReader { 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 String nextLine() { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 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); } } static class Pair implements Comparable<Pair> { int a; int b; String str; public Pair(int a,int b) { this.a=a; this.b=b; str=min(a,b)+" "+max(a,b); } public int compareTo(Pair pair) { if(Integer.compare(a,pair.a)==0) return Integer.compare(b,pair.b); return Integer.compare(a,pair.a); } } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 8
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
29bbf1806a01c12daf99841621dd89b1
train_000.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.util.*; import java.lang.*; import java.math.*; public class main { public static void woof(String str) { char [] star = str.toCharArray(); StringBuilder f = new StringBuilder(); int en; for (int i = 0; i < str.length(); i++) { en= f.length(); try { if (star[i] == star[i-1] && star[i] == star[i - 2]) { continue; } if (star[i] == f.charAt(en - 1) && f.charAt(en - 2) == f.charAt(en - 3)) {continue; } f.append(star[i]); }catch (Exception e) { f.append( star[i]); }} System.out.println(f); } public static void main (String[]args){ Scanner s = new Scanner(System.in); String star = s.nextLine(); woof(star); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 8
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
ad24bf7621060c8ef40fb5284d9e751b
train_000.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.io.*; import java.util.*; public class fixing_typos { public boolean lastThreeSame(String ss, int i, String ans) { if ((ss.charAt(i)==(ans.charAt(i-1)))&&(ss.charAt(i-2)==( ss.charAt(i-1)))) return(true); else return(false); } public boolean twinSame(String ss, int i) { if ((ss.charAt(i)==(ss.charAt(i-1))) && (ss.charAt(i-2)==(ss.charAt(i-3)))) return(true); else return(false); } public static void main(String args[])throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); fixing_typos ft = new fixing_typos(); String ss = br.readLine(); PrintStream ps = new PrintStream(System.out); StringBuilder ans = new StringBuilder (); if (ss.length()<= 2) { System.out.println(ss); } else { int k =1; ans.append(ss.charAt(0)); ans.append(ss.charAt(1)); for (int i = 2; i<ss.length(); i++) { if (i == 2) { if ((ss.charAt(i) == ans.charAt(k-1))&&(ss.charAt(i)==ans.charAt(k))) continue; else {ans.append(ss.charAt(i)); k++;} } else { if ((ss.charAt(i) == ans.charAt(k-1))&&(ss.charAt(i)==ans.charAt(k))) continue; else if ((ss.charAt(i)==ans.charAt(k)) && (ans.charAt(k-1)==ans.charAt(k-2))) continue; else {ans.append(ss.charAt(i)); k++;} } } ps.print(ans.toString().trim()); } } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 8
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
9275b6062e623e5be2f2c42170b7a925
train_000.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.util.ArrayList; import java.util.Scanner; public class FixingTypos { static int getnum(char ch) { String str = "abcdefghijklmnopqrstuvwxyz"; return str.indexOf(ch); } public static void main(String[] args) { Scanner s = new Scanner(System.in); String str = s.next(); char ch[] = str.toCharArray(); StringBuilder sb = new StringBuilder(); int cc =1; int pc = 0; char cch = ' '; for(int i =0;i<ch.length;i++) { if(ch[i]!=cch) { cch = ch[i]; pc = cc; cc = 1; }else { cc++; if(cc>2 || (cc == 2 && cc==pc)) { cc--; continue; } } sb.append(cch); } System.out.println(sb); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 8
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
b92010f374ba773a5caba0f5f39f6845
train_000.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.util.Scanner; public class Fixingtypos2 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner s = new Scanner(System.in); String str = s.next(); char ch[] = str.toCharArray(); StringBuilder sb = new StringBuilder(); char cc = ch[0]; sb.append(ch[0]); int tp = 1; for (int i = 1; i < ch.length; i++) { if (ch[i] == cc && tp == 1) { cc = ch[i]; sb.append(ch[i]); tp = 0; } else if(cc!=ch[i]) { cc = ch[i]; sb.append(ch[i]); if (tp == 0) { tp = 2; } else if (tp == 2) { tp = 1; } } } System.out.println(sb); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 8
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
0ebc486d18d0bd7e39e66ac2c6e64312
train_000.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; public class Main { public String fix(String word) { if (word.length() < 3) { return word; } StringBuilder res = new StringBuilder(word.length()); LinkedList<Character> buf = new LinkedList<Character>(); Character[] a = new Character[4]; buf.addLast(word.charAt(0)); for (int i = 1; i < word.length() + 3; i++) { if (i < word.length()) { buf.addLast(word.charAt(i)); } else { buf.addLast((char) ('A' + (i - word.length()))); } if (buf.size() >= 4) { a = buf.toArray(a); if (!a[0].equals(a[1])) { res.append(buf.removeFirst()); } else if (a[1].equals(a[2])) { buf.removeFirst(); } else if (a[2].equals(a[3])) { buf.removeLast(); } else { res.append(buf.removeFirst()); } } } return res.toString(); } public static void main(String[] args) throws IOException { BufferedReader bis = new BufferedReader(new InputStreamReader(System.in)); String s = bis.readLine(); String f = new Main().fix(s); System.out.println(f); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 6
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
a7a39176e25e2389f5b04fd04bfb96ce
train_000.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author a.bogdanov */ public class FixTypos { public static void main(String[] args) throws IOException { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(System.in)); String str = reader.readLine(); StringBuilder res = new StringBuilder(); int currentStrike = 0; int prevStrike = 0; char currentChar = ' '; for(int i = 0;i<str.length();i++){ char c = str.charAt(i); if(c!=currentChar){ res.append(c); prevStrike = currentStrike; currentStrike = 1; }else{ if(prevStrike <= 1){ if(currentStrike <= 1){ res.append(c); currentStrike++; } } } currentChar = c; } System.out.println(res.toString()); } finally { if (reader != null) { reader.close(); } } } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 6
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
233edf55f9f883ee6cc6fe60d473ce78
train_000.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { char[] c = in.next().toCharArray(); int n = c.length; int cur,last; last = 0; cur = 1; out.print(c[0]); for(int i = 1; i < n; ++i){ if(c[i] != c[i-1]){ last = cur; cur = 0; } if(cur == 2) continue; if(last == 2 && cur == 1) continue; ++cur; out.print(c[i]); } } } 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(); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 6
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
9e5f487280002c61e8a9719a486a7a00
train_000.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class T363C { public void solve(String s) { int n = s.length(); char[] ch = new char[n]; int[] idx = new int[n]; int p = 0; ch[0] = s.charAt(0); idx[0] = 1; for (int i = 1; i < n; i ++) { if (s.charAt(i) == s.charAt(i - 1)) { idx[p] ++; } else { p ++; idx[p] ++; ch[p] = s.charAt(i); } } for (int i = 0; i < n; i ++) if (idx[i] >= 3) idx[i] = 2; for (int i = 0; i < n - 1; i ++) { if (idx[i] == 2 && idx[i + 1] == 2) { int j = i + 1; for (j = i + 1; j < n; j ++) if (idx[j] < 2) break; int x = j - i; if (x % 2 == 0) { for (int k = i; k < j; k += 2) idx[k] = 1; } else { for (int k = i + 1; k < j; k += 2) idx[k] = 1; } i = j - 1; } } StringBuffer ans = new StringBuffer(""); for (int i = 0; i < n; i ++) for (int j = 0; j < idx[i]; j ++) ans.append(ch[i]); System.out.println(ans); } public static void main(String[] args) { FastScanner in = new FastScanner(); new T363C().solve(in.nextToken()); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { 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) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 6
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
947f3f1c2aa679aef10c5eb9f6aea2f7
train_000.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Scanner; public class FixingTypos { static Scanner input = new Scanner(new BufferedReader(new InputStreamReader(System.in))); public static void main(String[] args) { String text = input.next(); int n = text.length(); int[][][][] best = new int[3][3][27][n+1]; boolean[][][][] action = new boolean[3][3][27][n+1]; for(int index = n-1; index >= 0; index--) { for(int letter = 0; letter <= 26; letter++) { int minLen = letter == 26 ? 0 : 1; int maxLen = letter == 26 ? 0 : 2; for(int curLen = minLen; curLen <= maxLen; curLen++) { for(int prevLen = 0; prevLen <= 2; prevLen++) { best[prevLen][curLen][letter][index] = Integer.MIN_VALUE; if (curLen == 2 && prevLen == 2) continue; // Try to take the letter if (letter == text.charAt(index) - 'a') { // Same letter as current int nextPrevLen = prevLen; int nextCurLen = curLen + 1; // Make sure it is valid if (!((nextPrevLen == 2 && nextCurLen == 2) || nextCurLen == 3)) { int next = 1 + best[nextPrevLen][nextCurLen][letter][index+1]; if (next > best[prevLen][curLen][letter][index]) { best[prevLen][curLen][letter][index] = next; action[prevLen][curLen][letter][index] = true; } } } else { // Different letter int nextPrevLen = curLen; int nextCurLen = 1; int nextLetter = text.charAt(index) - 'a'; // Make sure it is valid if (!((nextPrevLen == 2 && nextCurLen == 2) || nextCurLen == 3)) { int next = 1 + best[nextPrevLen][nextCurLen][nextLetter][index+1]; if (next > best[prevLen][curLen][letter][index]) { best[prevLen][curLen][letter][index] = next; action[prevLen][curLen][letter][index] = true; } } } // Try to skip the letter int next = best[prevLen][curLen][letter][index+1]; if (next > best[prevLen][curLen][letter][index]) { best[prevLen][curLen][letter][index] = next; action[prevLen][curLen][letter][index] = false; } } } } } int index = 0, letter = 26, curLen = 0, prevLen = 0; StringBuilder answer = new StringBuilder(); while(index < n) { //System.out.println(prevLen+","+curLen+","+letter+","+index+" => "+best[prevLen][curLen][letter][index]); if (action[prevLen][curLen][letter][index]) { answer.append(text.charAt(index)); if (letter == text.charAt(index) - 'a') { curLen++; } else { letter = text.charAt(index) - 'a'; prevLen = curLen; curLen = 1; } } index++; } System.out.println(answer); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 6
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
588115673e0c63310649e8a0d7cb964e
train_000.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import java.io.*; import java.math.*; import java.text.*; import java.util.*; /* br = new BufferedReader(new FileReader("input.txt")); pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); */ public class Main { private static BufferedReader br; private static StringTokenizer st; private static PrintWriter pw; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); //int qq = 1; int qq = Integer.MAX_VALUE; //int qq = readInt(); for(int casenum = 1; casenum <= qq; casenum++) { int last = 0; String str = nextToken(); StringBuilder sb = new StringBuilder(); for(int i = 0; i < str.length();) { int j = i+1; while(j < str.length() && str.charAt(i) == str.charAt(j)) { j++; } int num = j-i; while(num > 2) { num--; } if(last == 2 && num == 2) { num--; } last = num; for(int a = 0; a < num; a++) { sb.append(str.charAt(i)); } i = j; } pw.println(sb); } pw.close(); } private static void exitImmediately() { pw.close(); System.exit(0); } private static long readLong() throws IOException { return Long.parseLong(nextToken()); } private static double readDouble() throws IOException { return Double.parseDouble(nextToken()); } private static int readInt() throws IOException { return Integer.parseInt(nextToken()); } private static String nextToken() throws IOException { while(st == null || !st.hasMoreTokens()) { if(!br.ready()) { exitImmediately(); } st = new StringTokenizer(br.readLine().trim()); } return st.nextToken(); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 6
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
feb6bf71f8f4e48e1fce670644843f2c
train_000.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.util.Scanner; public class Opechatki { public static void main(String[] args) { Scanner sc = new Scanner(System.in); StringBuilder sb = new StringBuilder(); StringBuilder sbresult = new StringBuilder(); String a = ""; a = sc.next(); if (!a.equals("x")) { sb.append(a); char pre = sb.charAt(0); char prepre = 0; if (sb.length()>1) prepre = sb.charAt(1); char preprepre = 0; sbresult.append(String.valueOf(pre)+String.valueOf(prepre)); for (int i=2; i<a.length(); ++i) { //System.out.println(preprepre+" "+prepre+" "+pre); char loc = a.charAt(i); if (loc==pre && loc==prepre) {} else { if ((preprepre==prepre && pre==loc)) {} else sbresult.append(String.valueOf(loc)); } if (sbresult.length()>2) preprepre = sbresult.charAt(sbresult.length()-3); if (sbresult.length()>1) prepre = sbresult.charAt(sbresult.length()-2); pre = sbresult.charAt(sbresult.length()-1); } System.out.println(sbresult); } else { System.out.println(a); } sc.close(); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 6
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
47231d4337c8afcf7077daceb156c8a7
train_000.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.io.*; import java.util.*; public class C implements Runnable { private void solve() throws IOException { char[] c = nextToken().toCharArray(); boolean[] f = new boolean[c.length]; int cnt = 0; for (int i = 2; i < c.length; i++) { if (c[i - 2] == c[i - 1] && c[i - 1] == c[i]) { f[i] = true; cnt++; } } char[] a = new char[c.length - cnt]; int len = 0; for (int i = 0; i < c.length; i++) if (!f[i]) a[len++] = c[i]; boolean[] b = new boolean[len]; for (int i = 0; i < len - 1; i++) if (a[i] == a[i + 1]) b[i] = true; boolean[] z = new boolean[len]; for (int i = 0; i + 2 < len; i++) if (b[i] && b[i + 2]) { b[i + 2] = false; z[i + 2] = true; } for (int i = 0; i < len; i++) if (!z[i]) print(a[i]); } public static void main(String[] args) { new C().run(); } BufferedReader reader; StringTokenizer tokenizer; PrintWriter writer; public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); writer = new PrintWriter(System.out); solve(); writer.close(); } catch (Exception e) { e.printStackTrace(); System.exit(261); } } void halt() { writer.close(); System.exit(0); } void print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } void println(Object... objects) { print(objects); writer.println(); } String nextLine() throws IOException { return reader.readLine(); } String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(nextLine()); return tokenizer.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(nextToken()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(nextToken()); } double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(nextToken()); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 6
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
6e99e5d2bb0d25f68d462ed00645c750
train_000.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.util.Scanner; /** * * @author aaa */ public class newsolution { public static void main(String[] args) { Scanner sc= new Scanner(System.in); String n = sc.next(); int stage=0; StringBuilder res = new StringBuilder(); res.append(n.charAt(0)); int k=0; int cas=0; for(int i=1; i<n.length(); i++,k++) { if(n.charAt(k)==n.charAt(i)) { if(cas==0) { cas++; res.append(n.charAt(i)); } } else{ if(cas==0) { res.append(n.charAt(i)); } if(cas==1) { cas=2; res.append(n.charAt(i)); continue; } if(cas==2) { cas=0; res.append(n.charAt(i)); } } } System.out.println(res); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 6
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
47de2aeed021eddb7db773754f489e43
train_000.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.util.*; public class Main{ public static void main(String[] args) throws Exception{ Scanner a = new Scanner(System.in); char[] stack; String s=a.next(); int len=s.length(); stack = new char[len]; int index=0; for(int i=0;i<len;i++){ if(index>1) if(s.charAt(i)==stack[index-1]&&stack[index-1]==stack[index-2])continue; if(index>2) if(s.charAt(i)==stack[index-1]&&stack[index-2]==stack[index-3])continue; stack[index++]=s.charAt(i); } for(int i=0;i<index;i++)System.out.print(stack[i]); System.out.println(); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 6
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
fc90f42ce871817875d8ecf6d4f23492
train_000.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.util.*; public class Typo { public static void main(String[] args) { Scanner in = new Scanner(System.in); String line = in.nextLine(); char last1, last2; boolean reduce21 = false; int l = line.length(); if(l <= 2) { System.out.println(line); return; } last1 = line.charAt(1); last2 = line.charAt(0); char[] str = new char[line.length() + 1]; str[1] = last1; str[0] = last2; int j = 2; for(int i = 2; i < l; i++) { if(line.charAt(i) == last1 && last1 == last2) { last2 = last1; last1 = line.charAt(i); continue; } else if(line.charAt(i) != last1 && last1 == last2 && !reduce21) { reduce21 = true; str[j++] = line.charAt(i); last2 = last1; last1 = line.charAt(i); } else if(line.charAt(i) == last1 && reduce21) { last2 = last1; last1 = line.charAt(i); continue; } else if(line.charAt(i) != last1 && reduce21) { reduce21 = false; str[j++] = line.charAt(i); last2 = last1; last1 = line.charAt(i); } else { str[j++] = line.charAt(i); last2 = last1; last1 = line.charAt(i); } } for(int i = 0; i < j; i++) { System.out.print(str[i]); } System.out.println(); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 6
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
b8ef06b2f6d8921c305311a4b506a576
train_000.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * Created by 875k on 12/26/13. */ public class CF211C { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine(); char[] a = new char[str.length()]; int[] count = new int[str.length()]; int t = 0; for(int i = 0; i < str.length();) { int j, ct = 1; char c = str.charAt(i); for(j = i + 1; j < str.length(); j++) { if(c == str.charAt(j)) { ct++; } else break; } a[t] = c; count[t++] = ct; i = j; } /*for(int i = 0; i < t; i++) { System.out.println(a[i] + " " + count[i]); }*/ StringBuilder ans = new StringBuilder(); for(int i = 0; i < t;) { if(count[i] == 1) { ans.append(a[i]); i++; continue; } StringBuilder odds = new StringBuilder(); StringBuilder evens = new StringBuilder(); int j, ct = 1, odiff = 0, ediff = 0; odds.append(a[i]); odds.append(a[i]); evens.append(a[i]); odiff += count[i] - 2; ediff += count[i] - 1; //System.out.println(odiff + " " + ediff); for(j = i + 1; j < t; j++) { if(count[j] >= 2) { if((j - i - 1) % 2 == 0) { odds.append(a[j]); evens.append(a[j]); evens.append(a[j]); odiff += count[j] - 1; ediff += count[j] - 2; } else { odds.append(a[j]); odds.append(a[j]); evens.append(a[j]); odiff += count[j] - 2; ediff += count[j] - 1; } ct++; } else { break; } } if(ct >= 2) { //System.out.println("odiff: " + odiff + " ediff: " + ediff); if(odiff < ediff) { ans.append(odds.toString()); } else { ans.append(evens.toString()); } } else { ans.append(a[i]); ans.append(a[i]); } i = j; } System.out.println(ans.toString()); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 6
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
5b8d338e979ce8031375bdf0b8798283
train_000.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.Scanner; import java.util.Stack; public class C211C { public void solve() throws IOException { Scanner sc = new Scanner(System.in); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); String s = sc.nextLine(); char a[] = s.toCharArray(); int b[] = new int[s.length()]; for (int i = 0; i < s.length(); i++) { b[i] = a[i]; } Stack<Integer> stk = new Stack(); int count = 0; stk.push(b[0]); for (int i = 1; i < s.length(); i++) { if (!stk.isEmpty() && stk.peek() != b[i] && count == 0) { // System.out.println("1"); stk.push(b[i]); } else if (!stk.isEmpty() && stk.peek() != b[i] && count == 1000) { // System.out.println("3"); count = 0; stk.push(b[i]); } else if (!stk.isEmpty() && stk.peek() != b[i] && count > 0) { // System.out.println("2"); stk.push(b[i]); count = 1000; } else if (!stk.isEmpty() && stk.peek() == b[i] && count == 0) { // System.out.println("4"); stk.push(b[i]); count++; } else if (!stk.isEmpty() && stk.peek() == b[i] && count == 1000) { // System.out.println("5"); } else if (!stk.isEmpty() && stk.peek() == b[i] && count > 0) { // System.out.println("6"); } } // System.out.println("##############"); Integer sd[] = stk.toArray(new Integer[stk.size()]); for (int i = 0; i < sd.length; i++) { System.out.print((char) (int) (sd[i]) + ""); } // System.out.println("\n##############"); } public static void main(String[] args) throws IOException { new C211C().solve(); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 6
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
f26e32c67e00008a66be7a57f8c94cc6
train_000.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.io.PrintWriter; import java.util.*; public class c { public static void main(String[] args) { Scanner input = new Scanner(System.in); String s = input.next(); int n = s.length(); PrintWriter out = new PrintWriter(System.out); ArrayList<Character> list = new ArrayList<Character>(); for(int i = 0; i<n; i++) { char c = s.charAt(i); boolean triple = list.size() >= 2 && c == list.get(list.size()-1) && c == list.get(list.size()-2); boolean double2 = list.size() >= 3 && c == list.get(list.size()-1) && list.get(list.size()-2) == list.get(list.size()-3); if(triple || double2) continue; list.add(c); } for(char c: list) out.print(c); out.close(); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 6
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
c37f4d212be4aaa7f81c53c27a040ea3
train_000.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
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.ArrayList; import java.util.Locale; import java.util.StringTokenizer; public class ProblemC { InputReader in; PrintWriter out; private void runIO() throws IOException { // in = new InputReader(new File("file.in")); // out = new PrintWriter(new File("file.out")); in = new InputReader(System.in); out = new PrintWriter(System.out); } private void closeIO() { out.close(); } class InputReader { BufferedReader bf; StringTokenizer st; InputReader(File f) throws FileNotFoundException { bf = new BufferedReader(new FileReader(f)); } InputReader(InputStream s) { bf = new BufferedReader(new InputStreamReader(s)); } private String next() throws IOException { while (st == null || !st.hasMoreElements()) { String s; try { s = bf.readLine(); } catch (IOException e) { return null; } if (s == null) return null; st = new StringTokenizer(s); } return st.nextToken(); } private int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } private long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } private double nextDouble() throws NumberFormatException, IOException { return Double.parseDouble(next()); } } public static void main(String[] S) throws IOException { // long startTime = System.currentTimeMillis(); Locale.setDefault(Locale.US); new ProblemC().run(); // System.out.println("Time used: "+(System.currentTimeMillis()-startTime)+" ms."); } private void run() throws IOException { runIO(); solve(); closeIO(); } String input; int N; private void solve() throws IOException { input = in.next(); N = input.length(); int i=0; int counterbefore =-1; while(i<N){ char key = input.charAt(i++); int counter = 1; while(i<N&&input.charAt(i)==key){ i++; counter = 2; } if (counterbefore==2&&counter==2) counter--; for (int j=0;j<counter;j++) out.print(key); counterbefore = counter; } } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 6
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
7eb54dd058023dc24558acd8dc762ead
train_000.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class Main implements Runnable{ private static String filename; public static void main(String[] args) { if (args.length > 0 && args[0].equals("f")) filename = "input.txt"; else filename = ""; new Thread(new Main()).start(); } private static void debug(Object ... str){ for (Object s : str) System.out.print(s + ", "); System.out.println(); } public void run() { try { MyScanner in; Locale.setDefault(Locale.US); if (filename.length() > 0) in = new MyScanner(filename); else in = new MyScanner(System.in); PrintWriter out = new PrintWriter(System.out); String string = in.nextString(); int n = string.length(); boolean del[] = new boolean[n]; int index = 1; boolean waspair = false; while (index < n) { if (del[index]) { ++index; continue; } if (string.charAt(index) == string.charAt(index - 1)) { int index0 = index; ++index; while (index < n && string.charAt(index) == string.charAt(index - 1)) { del[index] = true; ++index; } if (waspair) { waspair = false; del[index0] = true; } else { waspair = true; } } else waspair = false; ++index; } StringBuilder ans = new StringBuilder(); for (int i = 0; i < n; ++i) if (!del[i]) ans.append(string.charAt(i)); out.println(ans); out.close(); in.close(); } catch (Exception e) { e.printStackTrace(); } } } class MyScanner{ BufferedReader in; StringTokenizer st; MyScanner(String file){ try{ in = new BufferedReader(new FileReader(new File(file))); }catch(Exception e){ e.printStackTrace(); } } MyScanner(InputStream inp){ try{ in = new BufferedReader(new InputStreamReader(inp)); }catch (Exception e){ e.printStackTrace(); } } void skipLine(){ st = null; } boolean hasMoreTokens(){ String s = null; try{ while ((st==null || !st.hasMoreTokens())&& (s=in.readLine()) != null) st = new StringTokenizer(s); if ((st==null || !st.hasMoreTokens())&& s==null) return false; }catch(IOException e){ e.printStackTrace(); } return true; } String nextToken(){ if (hasMoreTokens()){ return st.nextToken(); } return null; } int nextInt(){ return Integer.parseInt(nextToken()); } long nextLong(){ return Long.parseLong(nextToken()); } double nextDouble(){ return Double.parseDouble(nextToken()); } String nextString(){ return nextToken(); } void close(){ try{ in.close(); }catch(IOException e){ e.printStackTrace(); } } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 6
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
42b593abd2cd59d234f82c3ff3ca6765
train_000.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class Test { public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); char[] letters = br.readLine().toCharArray(); boolean[] toRemove = new boolean[letters.length]; int count = 1; for (int i = 1; i < letters.length; i++) { if(letters[i] == letters[i - 1]){ count ++; if(count > 2) toRemove[i] = true; } else count = 1; } boolean is2DigBefore = false; boolean cuurrEq = false; int prevInd = -1; for (int i = 0; i < letters.length; i++) { if(toRemove[i]) continue; if(prevInd != -1){ if(letters[i] == letters[prevInd]){ if(is2DigBefore){ toRemove[i] = true; continue; } cuurrEq = true; } else{ is2DigBefore = cuurrEq; cuurrEq = false; } } prevInd = i; } StringBuilder sb = new StringBuilder(letters.length); for (int i = 0; i < letters.length; i++) { if( !toRemove[i]) sb.append(letters[i]); } System.out.println(sb.toString()); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 6
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
78e4d935feece21317afdf63c389b478
train_000.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; /** * * 28691 28312 * * @author pttrung */ public class C { // public static long x, y, gcd; public static int Mod = 1000000007; public static PrintWriter out; public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(); out = new PrintWriter(System.out); // System.out.println(Integer.MAX_VALUE); //PrintWriter out = new PrintWriter(new FileOutputStream(new File("output.txt"))); String val = in.next(); ArrayList<Integer> list = new ArrayList(); int count = 0; char last = ' '; int result = 0; for (int i = 0; i < val.length(); i++) { if (val.charAt(i) != last) { if (count > 0) { if (count > 2) { result += count - 2; count = 2; } list.add(count); } count = 1; last = val.charAt(i); } else { count++; } } if (count > 2) { result += count - 2; count = 2; } list.add(count); int []data = new int[list.size()]; for(int i = 0; i < list.size(); i++){ data[i] = list.get(i); } for(int i = 1; i < data.length; i++){ if(data[i] == 2 && data[i - 1] == 2){ data[i] = 1; result++; } } int index = 0; for(int i = 0; i < val.length(); i++ ){ if(i == 0 || val.charAt(i) != val.charAt(i - 1)){ for(int j = 0; j < data[index]; j++){ out.print(val.charAt(i)); } index++; } } out.close(); } public static Point horizon(Point p, int n, int m) { Point result = new Point(p.x, m - p.y + 1); return result; } public static int cross(Point a, Point b) { int val = a.x * b.y - a.y * b.x; return val; } public static long pow(long a, long b) { if (b == 0) { return 1; } if (b == 1) { return a; } long val = pow(a, b / 2); if (b % 2 == 0) { return val * val; } else { return val * val * a; } } public static int gcd(int a, int b) { if (b == 0) { return a; } return gcd(b, a % b); } public static class Point implements Comparable<Point> { int x, y; public Point(int x, int y) { this.x = x; this.y = y; } @Override public int compareTo(Point o) { if (x != o.x) { return x - o.x; } else { return y - o.y; } } } // public static void extendEuclid(long a, long b) { // if (b == 0) { // x = 1; // y = 0; // gcd = a; // return; // } // extendEuclid(b, a % b); // long x1 = y; // long y1 = x - (a / b) * y; // x = x1; // y = y1; // // } public static class FT { int[] data; FT(int n) { data = new int[n]; } public void update(int index, int value) { while (index < data.length) { data[index] += value; index += (index & (-index)); } } public int get(int index) { int result = 0; while (index > 0) { result += data[index]; index -= (index & (-index)); } return result; } } static class Scanner { BufferedReader br; StringTokenizer st; public Scanner() throws FileNotFoundException { // System.setOut(new PrintStream(new BufferedOutputStream(System.out), true)); br = new BufferedReader(new InputStreamReader(System.in)); //br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt")))); } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { throw new RuntimeException(); } } return st.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } public double nextDouble() { return Double.parseDouble(next()); } public String nextLine() { st = null; try { return br.readLine(); } catch (Exception e) { throw new RuntimeException(); } } public boolean endLine() { try { String next = br.readLine(); while (next != null && next.trim().isEmpty()) { next = br.readLine(); } if (next == null) { return true; } st = new StringTokenizer(next); return st.hasMoreTokens(); } catch (Exception e) { throw new RuntimeException(); } } } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 6
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
2da980667b3e36b6631b555cfcb1c5d9
train_000.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; public class Main { public static void main(String[] args) throws IOException { FastScanner s = new FastScanner(System.in); String word = s.nextString(); char array[] = word.toCharArray(); ArrayList<CH> ch = new ArrayList<CH>(); CH c = new CH(array[0]); ch.add(c); int j = 0; for (int i = 1; i < array.length; i++) { if (array[i] == array[i - 1]) { ch.get(j).increase(); } else { ch.add(new CH(array[i])); j++; } } CH c1 = ch.get(0); while (c1.count / 3 >= 1) { c1.count = (c1.count / 3)*2 + (c1.count % 3); } for (int i = 1; i <= j; i++) { CH cc = ch.get(i); while (cc.count / 3 >= 1) { cc.count = (cc.count / 3)*2 + (cc.count % 3); } if (c1.count == 2 && cc.count == 2) { cc.count = 1; } c1 = cc; } for (int i = 0; i <= j; i++) { CH cc = ch.get(i); for (int k = 0; k < cc.count; k++) { System.out.print(cc.ch); } } } } class CH { public char ch; public int count; public CH(char ch) { this.ch = ch; this.count = 1; } public void increase() { this.count++; } public String toString() { return (ch + "" + count); } } class FastScanner { InputStream is; byte buff[] = new byte[1024]; int currentChar = -1; int buffChars = 0; public FastScanner(InputStream inputStream) { is = inputStream; } public boolean hasNext() throws IOException { return buffChars >= 0; } public int nextChar() throws IOException { //if we already have that next char read, just return else input if (currentChar == -1 || currentChar >= buffChars) { currentChar = 0; buffChars = is.read(buff); } if (buffChars <= 0) { return -1; } return (char) buff[currentChar++]; } public String nextString() throws IOException { StringBuilder bldr = new StringBuilder(); int ch; while (isSpace(ch = nextChar())) ; do { bldr.append((char) ch); } while (!isSpace(ch = nextChar())); return bldr.toString(); } public int nextInt() throws IOException { //considering ASCII files--> 8 bit chars, unicode files has 16 bit chars (byte1 then byte2) int result = 0; int sign = 1; int ch; while (isSpace(ch = nextChar())) ; if (ch == '-') { sign = -1; ch = nextChar(); } do { if (ch < '0' || ch > '9') { throw new NumberFormatException("Found '" + ch + "' while parsing for int."); } result *= 10; result += ch - '0'; } while (!isSpace(ch = nextChar())); return sign * result; } public long nextLong() throws IOException { //considering ASCII files--> 8 bit chars, unicode files has 16 bit chars (byte1 then byte2) long result = 0; int sign = 1; int ch; while (isSpace(ch = nextChar())) ; if (ch == '-') { sign = -1; ch = nextChar(); } do { if (ch < '0' || ch > '9') { throw new NumberFormatException("Found '" + ch + "' while parsing for int."); } result *= 10; result += ch - '0'; } while (!isSpace(ch = nextChar())); return sign * result; } private boolean isSpace(int ch) { return ch == '\n' || ch == ' ' || ch == '\t' || ch == '\r' || ch == -1; } public void close() throws IOException { is.close(); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 6
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
15ac5c2d4ca6a05e01bc1ff3175e6104
train_000.jsonl
1384156800
Many modern text editors automatically check the spelling of the user's text. Some editors even suggest how to correct typos.In this problem your task to implement a small functionality to correct two types of typos in a word. We will assume that three identical letters together is a typo (for example, word "helllo" contains a typo). Besides, a couple of identical letters immediately followed by another couple of identical letters is a typo too (for example, words "helloo" and "wwaatt" contain typos).Write a code that deletes the minimum number of letters from a word, correcting described typos in the word. You are allowed to delete letters from both ends and from the middle of the word.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; import java.math.BigDecimal; import java.math.BigInteger; public class palin { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(System.out); Scanner scan = new Scanner(System.in); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { String str = in.next(); boolean f = false, f2 = false; char[] c = str.toCharArray(); for (int i = 0; i < c.length - 2; i++) { if (c[i] == c[i + 1] && c[i] == c[i + 2]) { c[i] = ' '; } } boolean f3 = false; for (int i = 0; i < c.length - 1; i++) { int j = i + 1; while (true) { if (j == c.length) { f3 = true; break; } if (c[j] == ' ') { j++; i++; } else { break; } } if (f3) { break; } if (c[i] == c[j] && c[i] != ' ') { f2 = true; if (f) { c[i] = ' '; f2 = false; } f = true; } else { if (!f2) { f = false; } f2 = false; } } for (int i = 0; i < c.length; i++) { if (c[i] != ' ') { out.print(c[i]); } } } } class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public float nextFloat() { return Float.parseFloat(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["helloo", "woooooow"]
1 second
["hello", "woow"]
NoteThe second valid answer to the test from the statement is "heloo".
Java 6
standard input
[ "implementation", "greedy" ]
31d803d886c47fe681bdcfbe6c74f090
The single line of the input contains word s, its length is from 1 to 200000 characters. The given word s consists of lowercase English letters.
1,400
Print such word t that it doesn't contain any typos described in the problem statement and is obtained from s by deleting the least number of letters. If there are multiple solutions, print any of them.
standard output
PASSED
37da96b044ad6fcc2f87b37b5ff4b692
train_000.jsonl
1397749200
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { new Thread(null, new Runnable() { public void run() { try { long prevTime = System.currentTimeMillis(); new Main().run(); System.err.println("Total time: " + (System.currentTimeMillis() - prevTime) + " ms"); System.err.println("Memory status: " + memoryStatus()); } catch (IOException e) { e.printStackTrace(); } } }, "1", 1L << 24).start(); } void run() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); Object o = solve(); if (o != null) out.println(o); out.close(); in.close(); } private Object solve() throws IOException { int n = ni(); int k = ni(); if(n<=k) return -1; int[] count = new int[n]; List<int[]> show = new ArrayList<int[]>(); for(int i =0;i<n;i++){ for(int j=i+1;j<n;j++) if(count[i]<k){ show.add(new int[]{i+1,j+1}); count[i]++; }else{ if(count[j]<k){ show.add(new int[]{j+1,i+1}); count[j]++; } } } int N = n*k; if(show.size()!=N) return -1; pln(show.size()); for(int[] arr : show) pln(arr[0]+" "+arr[1]); return null; } BufferedReader in; PrintWriter out; StringTokenizer strTok = new StringTokenizer(""); String nextToken() throws IOException { while (!strTok.hasMoreTokens()) strTok = new StringTokenizer(in.readLine()); return strTok.nextToken(); } int ni() throws IOException { return Integer.parseInt(nextToken()); } long nl() throws IOException { return Long.parseLong(nextToken()); } double nd() throws IOException { return Double.parseDouble(nextToken()); } int[] nia(int size) throws IOException { int[] ret = new int[size]; for (int i = 0; i < size; i++) ret[i] = ni(); return ret; } long[] nla(int size) throws IOException { long[] ret = new long[size]; for (int i = 0; i < size; i++) ret[i] = nl(); return ret; } double[] nda(int size) throws IOException { double[] ret = new double[size]; for (int i = 0; i < size; i++) ret[i] = nd(); return ret; } String nextLine() throws IOException { strTok = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!strTok.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; strTok = new StringTokenizer(s); } return false; } void printRepeat(String s, int count) { for (int i = 0; i < count; i++) out.print(s); } void printArray(int[] array) { for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(long[] array) { for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array) { for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.print(array[i]); } out.println(); } void printArray(double[] array, String spec) { for (int i = 0; i < array.length; i++) { if (i > 0) out.print(' '); out.printf(Locale.US, spec, array[i]); } out.println(); } void printArray(Object[] array) { boolean blank = false; for (Object x : array) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } @SuppressWarnings("rawtypes") void printCollection(Collection collection) { boolean blank = false; for (Object x : collection) { if (blank) out.print(' '); else blank = true; out.print(x); } out.println(); } static String memoryStatus() { return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() >> 20) + "/" + (Runtime.getRuntime().totalMemory() >> 20) + " MB"; } public void pln() { out.println(); } public void pln(int arg) { out.println(arg); } public void pln(long arg) { out.println(arg); } public void pln(double arg) { out.println(arg); } public void pln(String arg) { out.println(arg); } public void pln(boolean arg) { out.println(arg); } public void pln(char arg) { out.println(arg); } public void pln(float arg) { out.println(arg); } public void pln(Object arg) { out.println(arg); } public void p(int arg) { out.print(arg); } public void p(long arg) { out.print(arg); } public void p(double arg) { out.print(arg); } public void p(String arg) { out.print(arg); } public void p(boolean arg) { out.print(arg); } public void p(char arg) { out.print(arg); } public void p(float arg) { out.print(arg); } public void p(Object arg) { out.print(arg); } }
Java
["3 1"]
1 second
["3\n1 2\n2 3\n3 1"]
null
Java 7
standard input
[ "constructive algorithms", "implementation", "graphs" ]
14570079152bbf6c439bfceef9816f7e
The first line contains two integers — n and k (1 ≤ n, k ≤ 1000).
1,400
In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1.
standard output
PASSED
943112566a2f2364db95e26d78d0c90b
train_000.jsonl
1397749200
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
256 megabytes
import static java.lang.Math.*; import static java.lang.System.currentTimeMillis; import static java.lang.System.exit; import static java.lang.System.arraycopy; import static java.util.Arrays.sort; import static java.util.Arrays.binarySearch; import static java.util.Arrays.fill; import java.util.*; import java.io.*; public class Main { public static void main(String[] args) throws IOException { new Main().run(); } BufferedReader in; PrintWriter out; StringTokenizer st = new StringTokenizer(""); private void run() throws IOException { if (new File("input.txt").exists()) in = new BufferedReader(new FileReader("input.txt")); else in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); in.close(); out.close(); } private void solve() throws IOException { int n = nextInt(); int k = nextInt(); int a[][] = new int[n][n]; if (n * k * 2 > n * (n - 1)) { out.println(-1); return; } for (int i = 0; i < n; i++) { int cnt = 0; int j = 0; while (cnt < k) { if (a[i][j] == 0 && i != j) { a[i][j] = 1; a[j][i] = -1; cnt++; } j++; } } out.println((n * k)); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) if (a[i][j] == 1) out.println((i + 1) + " " + (j + 1)); } void chk(boolean b) { if (b) return; System.out.println(new Error().getStackTrace()[1]); exit(999); } void deb(String fmt, Object... args) { System.out.printf(Locale.US, fmt + "%n", args); } String nextToken() throws IOException { while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } String nextLine() throws IOException { st = new StringTokenizer(""); return in.readLine(); } boolean EOF() throws IOException { while (!st.hasMoreTokens()) { String s = in.readLine(); if (s == null) return true; st = new StringTokenizer(s); } return false; } }
Java
["3 1"]
1 second
["3\n1 2\n2 3\n3 1"]
null
Java 7
standard input
[ "constructive algorithms", "implementation", "graphs" ]
14570079152bbf6c439bfceef9816f7e
The first line contains two integers — n and k (1 ≤ n, k ≤ 1000).
1,400
In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1.
standard output
PASSED
1e918cb8e3932698a3bc4798929955da
train_000.jsonl
1397749200
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.*; public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); //int t = in.nextInt(); //for (int i = 0; i < t; i++) { solver.solve(1, in, out); //} out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { int N = in.nextInt(); int K = in.nextInt(); if (K > (N-1)/2) { out.println("-1"); return; } out.println(N*K); for (int i = 1; i <= N; i++) { for (int j = 0; j < K; j++) { int loser = (i+j+1); if (loser > N) loser -= N; out.println(i + " " + loser); } } } } class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); 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
["3 1"]
1 second
["3\n1 2\n2 3\n3 1"]
null
Java 7
standard input
[ "constructive algorithms", "implementation", "graphs" ]
14570079152bbf6c439bfceef9816f7e
The first line contains two integers — n and k (1 ≤ n, k ≤ 1000).
1,400
In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1.
standard output
PASSED
6bd6751c2a2eba3bb545342c9cfe6b6c
train_000.jsonl
1397749200
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
256 megabytes
import java.io.PrintStream; import java.util.Scanner; /** * Created by Poison. */ public class Football { private static int teamsCount; private static int winsCount; private static final String SPACE = " "; private static final char ENDL = '\n'; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); /*Football aProblem = new Football(); aProblem.readData(scanner); aProblem.findSolution(); aProblem.printSolution(System.out);*/ readData(scanner); printSolution(System.out); } private static void readData(Scanner scanner) { String data = scanner.nextLine(); String[] iData = data.split(SPACE); teamsCount = Integer.valueOf(iData[0]); winsCount = Integer.valueOf(iData[1]); } private void findSolution() { } private static void printSolution(PrintStream out) { if (winsCount+winsCount >= teamsCount) { out.println(-1); return; } out.println(teamsCount * winsCount); StringBuilder b = new StringBuilder(teamsCount*3); for (int fT = 1; fT <= teamsCount; fT++) { int iWin = 0, sT = fT + 1; while (iWin++ < winsCount) { if (sT > teamsCount) sT = 1; b.append(fT).append(SPACE).append(sT).append(ENDL); sT++; } } out.print(b.toString()); } }
Java
["3 1"]
1 second
["3\n1 2\n2 3\n3 1"]
null
Java 7
standard input
[ "constructive algorithms", "implementation", "graphs" ]
14570079152bbf6c439bfceef9816f7e
The first line contains two integers — n and k (1 ≤ n, k ≤ 1000).
1,400
In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1.
standard output
PASSED
bfc51239ca9715fc6e0c7d215fd01cfe
train_000.jsonl
1397749200
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
256 megabytes
import java.io.IOException; import java.io.InputStreamReader; import java.util.InputMismatchException; import java.io.BufferedReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author izban */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; Scanner in = new Scanner(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); int k = in.nextInt(); if (k * 2 >= n) { out.println(-1); return; } out.println(n * k); for (int i = 0; i < n; i++) { for (int j = 1; j <= k; j++) { out.println(i + 1 + " " + ((i + j) % n + 1)); } } } } class Scanner { BufferedReader in; StringTokenizer tok; public Scanner(InputStream in) { this.in = new BufferedReader(new InputStreamReader(in)); tok = new StringTokenizer(""); } private String tryReadNextLine() { try { return in.readLine(); } catch (Exception e) { throw new InputMismatchException(); } } public String nextToken() { while (!tok.hasMoreTokens()) { tok = new StringTokenizer(next()); } return tok.nextToken(); } public String next() { String newLine = tryReadNextLine(); if (newLine == null) throw new InputMismatchException(); return newLine; } public int nextInt() { return Integer.parseInt(nextToken()); } }
Java
["3 1"]
1 second
["3\n1 2\n2 3\n3 1"]
null
Java 7
standard input
[ "constructive algorithms", "implementation", "graphs" ]
14570079152bbf6c439bfceef9816f7e
The first line contains two integers — n and k (1 ≤ n, k ≤ 1000).
1,400
In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1.
standard output
PASSED
57e50d633c492568307e160e53269d5f
train_000.jsonl
1397749200
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
256 megabytes
import java.io.*; import java.util.*; public class Main implements Runnable { public void _main() throws IOException { int n = nextInt(); int k = nextInt(); if (k > (n - 1) / 2) { out.println(-1); return; } out.println(n * k); for (int i = 0; i < n; i++) { for (int j = 0; j < k; j++) { int a = i; int b = (i + j + 1) % n; out.println((a + 1) + " " + (b + 1)); } } } private BufferedReader in; private PrintWriter out; private StringTokenizer st; private String next() throws IOException { while (st == null || !st.hasMoreTokens()) { String rl = in.readLine(); if (rl == null) return null; st = new StringTokenizer(rl); } return st.nextToken(); } private int nextInt() throws IOException { return Integer.parseInt(next()); } private long nextLong() throws IOException { return Long.parseLong(next()); } private double nextDouble() throws IOException { return Double.parseDouble(next()); } public static void main(String[] args) { Locale.setDefault(Locale.UK); new Thread(new Main()).start(); } public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); //in = new BufferedReader(new FileReader("a.in")); //out = new PrintWriter(new FileWriter("a.out")); _main(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(202); } } }
Java
["3 1"]
1 second
["3\n1 2\n2 3\n3 1"]
null
Java 7
standard input
[ "constructive algorithms", "implementation", "graphs" ]
14570079152bbf6c439bfceef9816f7e
The first line contains two integers — n and k (1 ≤ n, k ≤ 1000).
1,400
In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1.
standard output
PASSED
5bfa5c6445232d684b0ed33d648c29a3
train_000.jsonl
1397749200
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
256 megabytes
import java.io.*; import java.util.*; public class GPL implements Runnable { public static void main(String[] args) { new Thread(new GPL()).run(); } BufferedReader br; StringTokenizer in; PrintWriter out; public String nextToken() throws IOException { while (in == null || !in.hasMoreTokens()) { in = new StringTokenizer(br.readLine()); } return in.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 void solve() throws IOException { int n = nextInt(); int k = nextInt(); if (n < 2 * k + 1) { out.println(-1); return; } out.println(k * n); for (int i = 0; i < n; i++) { for (int j = 0; j < k; j++) { int next = (i + j + 1) % n; out.println((i + 1) + " " + (next + 1)); } } } public void run() { try { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } catch (IOException e) { e.printStackTrace(); System.exit(1); } } }
Java
["3 1"]
1 second
["3\n1 2\n2 3\n3 1"]
null
Java 7
standard input
[ "constructive algorithms", "implementation", "graphs" ]
14570079152bbf6c439bfceef9816f7e
The first line contains two integers — n and k (1 ≤ n, k ≤ 1000).
1,400
In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1.
standard output
PASSED
9db1561215a4519d7a71147cbc68a307
train_000.jsonl
1397749200
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
256 megabytes
//package rcc.warmup; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.InputMismatchException; public class A { InputStream is; PrintWriter out; String INPUT = ""; void solve() { int n = ni(), K = ni(); if(K*n > n*(n-1)/2){ out.println(-1); return; } int[][] a = new int[n][n]; for(int i = 1;i <= K;i++){ for(int j = 0, k = j+i;j < n;j++,k++){ if(k == n)k = 0; if(a[j][k] != 0){ out.println(-1); return; } a[j][k] = 1; a[k][j] = -1; } } out.println(K*n); for(int i = 0;i < n;i++){ for(int j = 0;j < n;j++){ if(a[i][j] == 1){ out.println((i+1) + " " + (j+1)); } } } } void run() throws Exception { is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes()); out = new PrintWriter(System.out); long s = System.currentTimeMillis(); solve(); out.flush(); tr(System.currentTimeMillis()-s+"ms"); } public static void main(String[] args) throws Exception { new A().run(); } private byte[] inbuf = new byte[1024]; private int lenbuf = 0, ptrbuf = 0; private int readByte() { if(lenbuf == -1)throw new InputMismatchException(); if(ptrbuf >= lenbuf){ ptrbuf = 0; try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); } if(lenbuf <= 0)return -1; } return inbuf[ptrbuf++]; } private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; } private double nd() { return Double.parseDouble(ns()); } private char nc() { return (char)skip(); } private String ns() { int b = skip(); StringBuilder sb = new StringBuilder(); while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } private char[] ns(int n) { char[] buf = new char[n]; int b = skip(), p = 0; while(p < n && !(isSpaceChar(b))){ buf[p++] = (char)b; b = readByte(); } return n == p ? buf : Arrays.copyOf(buf, p); } private char[][] nm(int n, int m) { char[][] map = new char[n][]; for(int i = 0;i < n;i++)map[i] = ns(m); return map; } private int[] na(int n) { int[] a = new int[n]; for(int i = 0;i < n;i++)a[i] = ni(); return a; } private int ni() { int num = 0, b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private long nl() { long num = 0; int b; boolean minus = false; while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')); if(b == '-'){ minus = true; b = readByte(); } while(true){ if(b >= '0' && b <= '9'){ num = num * 10 + (b - '0'); }else{ return minus ? -num : num; } b = readByte(); } } private boolean oj = System.getProperty("ONLINE_JUDGE") != null; private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); } }
Java
["3 1"]
1 second
["3\n1 2\n2 3\n3 1"]
null
Java 7
standard input
[ "constructive algorithms", "implementation", "graphs" ]
14570079152bbf6c439bfceef9816f7e
The first line contains two integers — n and k (1 ≤ n, k ≤ 1000).
1,400
In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1.
standard output
PASSED
d16c328f1b1ffbfb2a5a25dab0bb0499
train_000.jsonl
1397749200
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Queue; import java.util.Set; import java.util.SortedSet; import java.util.Stack; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.LinkedBlockingQueue; public class Main { public static void main(String[] argv) { MainRun mainSolve = new MainRun(); mainSolve.run(0, 0); } } class Task { public void solve(InputReader in, PrintWriter out) { int n = in.nextInt(); int k = in.nextInt(); int q = n * k; if ((n * (n - 1)) / 2 < q) { out.println("-1"); return; } out.println(q); for (int i = 1; i <= n; i++) { int d = i; for (int l = 0; l < k; l++) { d = (d + 1) > n ? 1 : (d + 1); out.println(i + " " + d); } } } } class MainRun { void run(int inF, int outF) { // inF = outF = 0; String input = "input.txt"; // String input = "robot.in"; String output = "output.txt"; // String output = "robot.out"; InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in; PrintWriter out; if (inF == 1) in = new InputReader(input); else in = new InputReader(inputStream); if (outF == 1) out = getPrintWriter(output); else out = getPrintWriter(outputStream); Task solver = new Task(); solver.solve(in, out); out.close(); } public static PrintWriter getPrintWriter(OutputStream stream) { return new PrintWriter(stream); } public static PrintWriter getPrintWriter(String f) { try { return new PrintWriter(new File(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } return null; } } class InputReader { BufferedReader reader; StringTokenizer tokenizer; InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } InputReader(String f) { try { reader = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } 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 String getLine() { try { return (String)reader.readLine(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ""; } public int nextInt() { return Integer.parseInt(next()); } public char nextChar() { return next().charAt(0); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } public int[] nextIntArray(int n) { int a[] = new int[n + 2]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } }
Java
["3 1"]
1 second
["3\n1 2\n2 3\n3 1"]
null
Java 7
standard input
[ "constructive algorithms", "implementation", "graphs" ]
14570079152bbf6c439bfceef9816f7e
The first line contains two integers — n and k (1 ≤ n, k ≤ 1000).
1,400
In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1.
standard output
PASSED
2bed15c1ea2643e27dcdaf4bc566591b
train_000.jsonl
1397749200
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
256 megabytes
//package main; import java.util.*; import java.io.*; import java.math.BigInteger; public class Main { FastScanner scan; PrintWriter out; BufferedReader in; static BigInteger fact(BigInteger b) { BigInteger p =BigInteger.ONE; for (BigInteger i = BigInteger.ONE; i.compareTo(b.add(BigInteger.ONE))==-1; i=i.add(BigInteger.ONE)) { p = p.multiply(i); } return p; } static boolean isPrime(long n) { for (int i=2; i<=Math.sqrt((double)n); i++) { if(n%i==0) { return false; } } return true; } static boolean isPal(String s) { int l =0 ; int r = s.length()-1; while(l<=r) { if(s.charAt(l)!=s.charAt(r)) { return false; } l++; r--; } return true; } public void solve() throws Exception { int n = scan.nextInt(),m = scan.nextInt(); if(2*m>=n) { out.println("-1"); return; } out.println(n*m); for (int i=0; i<n; i++) { for (int j=1; j<=m; j++) { int next = (i+j)%n; out.println((i+1)+" "+(next+1)); } } } static Throwable uncaught; public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); scan = new FastScanner(in); solve(); } catch (Throwable uncaught) { Main.uncaught = uncaught; } finally { out.close(); } } class FastScanner { BufferedReader in; StringTokenizer st; FastScanner(BufferedReader in) { this.in = in; } String next() throws IOException { while (st == null || !st.hasMoreTokens()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public long nextLong() throws Exception { return Long.parseLong(next()); } public double nextDouble() throws Exception { return Double.parseDouble(next()); } int nextInt() throws IOException { return Integer.parseInt(next()); } BigInteger nextBig() throws IOException { return new BigInteger(next()); } } public static void main(String[] arg) { new Main().run(); } }
Java
["3 1"]
1 second
["3\n1 2\n2 3\n3 1"]
null
Java 7
standard input
[ "constructive algorithms", "implementation", "graphs" ]
14570079152bbf6c439bfceef9816f7e
The first line contains two integers — n and k (1 ≤ n, k ≤ 1000).
1,400
In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1.
standard output
PASSED
7c8e83fb706a64c98e5a9b5ff4bbe555
train_000.jsonl
1397749200
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Shamir14 ([email protected]) */ 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); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, OutputWriter out) { boolean can = true; int n = in.readInt(); int k = in.readInt(); if(k>(n-1)/2) can = false; if(!can) out.printLine(-1); else{ out.printLine(k*n); for (int i = 0; i < n; i++) { for (int j = 0; j < k; j++) { out.printLine((i+1) + " " + ((i+j+1)%n+1)); } } } } } class InputReader { // this IO reading - writing is provided by Egor Kulikov private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new UnknownError(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new UnknownError(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public boolean hasNext(){ return peek()!=-1; } 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 readInt() { 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 UnknownError(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long readLong() { 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 UnknownError(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private String readLine0() { StringBuffer buf = new StringBuffer(); 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(readString()); } catch (NumberFormatException e) { throw new UnknownError(); } } public char readCharacter() { int c = read(); while (isSpaceChar(c)) c = read(); return (char) c; } public double readDouble() { 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, readInt()); if (c < '0' || c > '9') throw new UnknownError(); 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, readInt()); if (c < '0' || c > '9') throw new UnknownError(); 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 readString(); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(outputStream); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void printLine(Object...objects) { print(objects); writer.println(); } public void printLine(char[] array) { writer.println(array); } public void printFormat(String format, Object...objects) { writer.printf(format, objects); } public void close() { writer.close(); } public void flush() { writer.flush(); } }
Java
["3 1"]
1 second
["3\n1 2\n2 3\n3 1"]
null
Java 7
standard input
[ "constructive algorithms", "implementation", "graphs" ]
14570079152bbf6c439bfceef9816f7e
The first line contains two integers — n and k (1 ≤ n, k ≤ 1000).
1,400
In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1.
standard output
PASSED
4988384f63f2c00b14e23d55bb3f1e1b
train_000.jsonl
1397749200
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
256 megabytes
import java.io.*; import java.util.*; public class C418A { private static StringTokenizer st; public static void nextLine(BufferedReader br) throws IOException { st = new StringTokenizer(br.readLine()); } public static int nextInt() { return Integer.parseInt(st.nextToken()); } public static String next() { return st.nextToken(); } public static long nextLong() { return Long.parseLong(st.nextToken()); } public static double nextDouble() { return Double.parseDouble(st.nextToken()); } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); nextLine(br); int n = nextInt(); int k = nextInt(); if (k >= n || (n * k) > (n * (n - 1)) / 2) { System.out.println(-1); return; } HashSet<Integer>[] tables = new HashSet[n]; for (int i = 0; i < n; i++) { tables[i] = new HashSet<Integer>(); } StringBuffer sb = new StringBuffer(); int total = 0; for (int i = 0; i < n; i++) { int count = k; for (int j = 0; j < n; j++) { if (i == j) continue; if (tables[j].contains(i)) continue; tables[j].add(i); tables[i].add(j); sb.append((i+1) + " " + (j+1) + "\n"); total++; count--; if (count <= 0) break; } } System.out.println(total); System.out.print(sb.toString()); } }
Java
["3 1"]
1 second
["3\n1 2\n2 3\n3 1"]
null
Java 7
standard input
[ "constructive algorithms", "implementation", "graphs" ]
14570079152bbf6c439bfceef9816f7e
The first line contains two integers — n and k (1 ≤ n, k ≤ 1000).
1,400
In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1.
standard output
PASSED
c55ed7363006af5859c4d25810decaa1
train_000.jsonl
1397749200
One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.The appointed Judge was the most experienced member — Pavel. But since he was the wisest of all, he soon got bored of the game and fell asleep. Waking up, he discovered that the tournament is over and the teams want to know the results of all the matches.Pavel didn't want anyone to discover about him sleeping and not keeping an eye on the results, so he decided to recover the results of all games. To do this, he asked all the teams and learned that the real winner was friendship, that is, each team beat the other teams exactly k times. Help Pavel come up with chronology of the tournir that meets all the conditions, or otherwise report that there is no such table.
256 megabytes
import java.io.*; import java.util.*; public class Task{ public static void main(String[] args) throws IOException{ new Task().run(); } StreamTokenizer in; Scanner ins; PrintWriter out; int nextInt() throws IOException{ in.nextToken(); return (int)in.nval; } long nextLong() throws IOException{ in.nextToken(); return (long)in.nval; } double nextDouble() throws IOException{ in.nextToken(); return in.nval; } char nextChar() throws IOException{ in.nextToken(); return (char)in.ttype; } boolean isNextChar() throws IOException{ in.nextToken(); return in.ttype != StreamTokenizer.TT_NUMBER; } int getReadedInt(){ return (int) in.nval; } String nextString() throws IOException{ in.nextToken(); return in.sval; } private static final String INPUT = "g.in"; Stack<Integer>[] tabels; void run() throws IOException{ in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in))); ins = new Scanner(System.in); out = new PrintWriter(System.out); try{ if(System.getProperty("xDx") != null){ in = new StreamTokenizer(new BufferedReader(new FileReader("input.txt"))); ins = new Scanner(new FileReader("input.txt")); out = new PrintWriter(new FileWriter("output.txt")); }else{ // in = new StreamTokenizer(new BufferedReader(new FileReader(INPUT))); // ins = new Scanner(new FileReader(INPUT)); // out = new PrintWriter(System.out); } }catch(Exception e){ // in = new StreamTokenizer(new BufferedReader(new FileReader(INPUT))); // ins = new Scanner(new FileReader(INPUT)); // out = new PrintWriter(System.out); } int n = nextInt(), k = nextInt(); if(k*n > n*(n - 1)/2){ out.print(-1); }else{ resolve(n, k); } out.close(); } private void resolve(int n, int k) { out.println(n*k); for(int i = 0; i < n; i++){ for(int j = 0; j < k; j++){ out.println((i + 1) + " " + ((i + j + 1)%n + 1)); } } } }
Java
["3 1"]
1 second
["3\n1 2\n2 3\n3 1"]
null
Java 7
standard input
[ "constructive algorithms", "implementation", "graphs" ]
14570079152bbf6c439bfceef9816f7e
The first line contains two integers — n and k (1 ≤ n, k ≤ 1000).
1,400
In the first line print an integer m — number of the played games. The following m lines should contain the information about all the matches, one match per line. The i-th line should contain two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi). The numbers ai and bi mean, that in the i-th match the team with number ai won against the team with number bi. You can assume, that the teams are numbered from 1 to n. If a tournir that meets the conditions of the problem does not exist, then print -1.
standard output