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
listlengths
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
749a7d824e7ad2e8fa6234c3bbd24aea
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
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.*; import java.io.*; /** * * @author TRUE */ public class Main { public static void main(String[] args) { Scanner cin = new Scanner(System.in); PrintStream cout = System.out; String s= cin.next(); int ans=0, man=0; int n = s.length(); for(int i=0; i<n; i++) { if(s.charAt(i) == 'F') { if(man>0) { ans=ans+1; if(ans<man) ans=man; } }else { man=man+1; } } cout.println(ans); } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
05696eb7ce4485cc1d9941a015e42d60
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
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 * * @author Abhas Jain */ 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); DQueue solver = new DQueue(); solver.solve(1, in, out); out.close(); } static class DQueue { public void solve(int testNumber, InputReader in, PrintWriter out) { String x = in.next(); int n = x.length(); int stp = 0; int m = 0; int i = 0; while (i < n && x.charAt(i) == 'F') i++; for (; i < n; ++i) { if (x.charAt(i) == 'M') m++; else { stp = stp - m + 1; if (stp < 0) stp = 0; m = 0; } } int male = 0; for (i = 0; i < n; ++i) if (x.charAt(i) == 'M') male++; for (i = n - 1; i >= 0; --i) { if (x.charAt(i) == 'M') male--; else break; } out.print(male + stp); } } 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(); } } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
78484e5d6fe5630dc1b8ccc54440bd08
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.awt.List; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.math.BigInteger; 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.Iterator; import java.util.LinkedList; import java.util.Map.Entry; import java.util.Queue; import java.util.Scanner; import java.util.Set; import java.util.Stack; import java.util.*; public class cool { private static InputStream stream; private static PrintWriter pw; // static int a; // static int b; // static int f = 0; static int n; static int m; // static int[][] arr; // static char[][] arr; static int Arr[]; static int size[]; static int time = 0; static int[][] dir = {{-1,0},{0,1},{1,0},{0,-1}}; static int visited[][]; static Stack<Integer> stack; // static ArrayList<Integer> ans; // static int arr[][]; // static int arr[]; static char[][] arr; // static int[][] visited; // static int c; // static int d[]; // static int arr[][]; static ArrayList[] adj; // static ArrayList<Integer> ans; // static int f; static int parent[]; static int color[]; // static ArrayList<Integer> comp[]; static int f = 0; static int k = 0; static int count = 0; static int ini[]; static ArrayList<Node> list; static ArrayList<Integer> ind; static int ans[]; public static void main(String[] args){ //InputReader(System.in); pw = new PrintWriter(System.out); Scanner in = new Scanner(System.in); String s = in.nextLine(); int t = s.length(); long ans = 0; int m = 0; int f = 0; for(int i = 0;i<t;i++){ if(s.charAt(i) == 'M'){ m++; if(f > 0){ f--; } }else{ if(m > 0){ ans = Math.max(ans, m+f); f++; } } } System.out.println(ans); pw.close(); } static int ceilSearch(int arr[], int low, int high, int x) { int mid; /* If x is smaller than or equal to the first element, then return the first element */ if(x <= arr[low]) return low; /* If x is greater than the last element, then return -1 */ if(x > arr[high]) return -1; /* get the index of middle element of arr[low..high]*/ mid = (low + high)/2; /* low + (high - low)/2 */ /* If x is same as middle element, then return mid */ if(arr[mid] == x) return mid; /* If x is greater than arr[mid], then either arr[mid + 1] is ceiling of x or ceiling lies in arr[mid+1...high] */ else if(arr[mid] < x) { if(mid + 1 <= high && x <= arr[mid+1]) return mid + 1; else return ceilSearch(arr, mid+1, high, x); } /* If x is smaller than arr[mid], then either arr[mid] is ceiling of x or ceiling lies in arr[mid-1...high] */ else { if(mid - 1 >= low && x > arr[mid-1]) return mid; else return ceilSearch(arr, low, mid - 1, x); } } public static int prev(int i,boolean[] arr){ while(arr[i]){ if(i == 0){ if(arr[i]){ return -1; }else{ return 0; } } i--; } return i; } public static int next(int i,boolean[] arr){ while(arr[i]){ if(i == arr.length-1){ if(arr[i]){ return -1; }else{ return 0; } } i++; } return i; } private static Map<String, Integer> sortByValue(Map<String, Integer> unsortMap) { // 1. Convert Map to List of Map LinkedList<Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>(unsortMap.entrySet()); // 2. Sort list with Collections.sort(), provide a custom Comparator // Try switch the o1 o2 position for a different order Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() { public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { return (o1.getValue()).compareTo(o2.getValue()); } }); // 3. Loop the sorted list and put it into a new insertion order Map LinkedHashMap Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>(); for (Map.Entry<String, Integer> entry : list) { sortedMap.put(entry.getKey(), entry.getValue()); } /* //classic iterator example for (Iterator<Map.Entry<String, Integer>> it = list.iterator(); it.hasNext(); ) { Map.Entry<String, Integer> entry = it.next(); sortedMap.put(entry.getKey(), entry.getValue()); }*/ return sortedMap; } public static ArrayList<Integer> Range(int[] numbers, int target) { int low = 0, high = numbers.length - 1; // get the start index of target number int startIndex = -1; while (low <= high) { int mid = (high - low) / 2 + low; if (numbers[mid] > target) { high = mid - 1; } else if (numbers[mid] == target) { startIndex = mid; high = mid - 1; } else low = mid + 1; } // get the end index of target number int endIndex = -1; low = 0; high = numbers.length - 1; while (low <= high) { int mid = (high - low) / 2 + low; if (numbers[mid] > target) { high = mid - 1; } else if (numbers[mid] == target) { endIndex = mid; low = mid + 1; } else low = mid + 1; } ArrayList<Integer> list = new ArrayList<Integer>(); int c = 0; if (startIndex != -1 && endIndex != -1){ for(int i = startIndex;i<=endIndex;i++){ list.add(i); } } return list; } private static int root(int Arr[],int i) { while(Arr[ i ] != i) //chase parent of current element until it reaches root { Arr[ i ] = Arr[ Arr[ i ] ] ; i = Arr[ i ]; } return i; } private static void union(int Arr[],int size[],int A,int B) { int root_A = root(Arr,A); int root_B = root(Arr,B); System.out.println(root_A + " " + root_B); if(root_A != root_B){ if(size[root_A] < size[root_B ]) { Arr[ root_A ] = Arr[root_B]; size[root_B] += size[root_A]; } else { Arr[ root_B ] = Arr[root_A]; size[root_A] += size[root_B]; } } } private static boolean find(int A,int B) { if( root(Arr,A)==root(Arr,B) ) //if A and B have the same root, it means that they are connected. return true; else return false; } // // public static void bfs(int i){ // // Queue<Integer> q=new LinkedList<Integer>(); // q.add(i); // // visited[i] = 1; // c++; // nodes++; // while(!q.isEmpty()){ // int top=q.poll(); // // Iterator<Integer> it= arr[top].listIterator(); // while(it.hasNext()){ // int next =it.next(); // // if(visited[next] == 0){ // nodes++; // visited[next] = 1; // q.add(next); // } // // } // } // // } // public static void dfs(int i){ // // // if(visited[i] == 1){ // return; // } // // visited[i] = 1; // con[c].add(i); // //System.out.print(i + " "); // for(int j = 0;j<arr[i].size();j++){ // dfs(arr[i].get(j)); // } // // } // // // public static void dfss(int i){ // if(visited[i] == 1){ // return; // } // // visited[i] = 1; // // for(int j = 0;j<arr[i].size();j++){ // dfss(arr[i].get(j)); // } // // System.out.println(i); // stack.push(i); // } // // public static void reverse(){ // ArrayList[] temp = new ArrayList[n]; // // for(int i = 0;i<n;i++){ // temp[i] = new ArrayList(); // } // // for(int i = 0;i<n;i++){ // for(int j = 0;j<arr[i].size();j++){ // temp[arr[i].get(j)].add(i); // } // } // // arr = temp; // // } // // public 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; } // union code starts // union code ends // // Segment tree code begins // // // static void build(int node,int start,int end) // { // if(start==end) // tree[node]=a[start]; // else // { // int mid=(start+end)/2; // build(2*node,start,mid); // build(2*node+1,mid+1,end); // if(tree[2*node]<tree[2*node+1]) // tree[node]=tree[2*node]; // else // tree[node]=tree[2*node+1]; // } // } // // // static void update(int node,int start,int end,int idx,int val) // { // if(start==end) // { // a[idx]=val; // tree[node]=val; // } // else // { // int mid=(start+end)/2; // if(idx>=start&&idx<=mid) // update(2*node,start,mid,idx,val); // else // update(2*node+1,mid+1,end,idx,val); // if(tree[2*node]<tree[2*node+1]) // tree[node]=tree[2*node]; // else // tree[node]=tree[2*node+1]; // } // } // // static int query(int node,int start,int end,int l,int r) // { // if(l>end||start>r) // return 100005; // if(l<=start&&r>=end) // return tree[node]; // int p1,p2; // int mid=(start+end)/2; // p1=query(2*node,start,mid,l,r); // p2=query(2*node+1,mid+1,end,l,r); // if(p1<p2) // return p1; // else // return p2; // } // // // //} } class Node{ point a; int b; } class point{ int a; int b; } class MyComp2 implements Comparator<Node>{ @Override public int compare(Node o1, Node o2) { // if((o1.b - o2.b) < 0.00000001){ // return 0; // }else if(o1.b == o2.b){ return 0; }else if( o1.b > o2.b){ return 1; }else if( o2.b > o1.b){ return -1; } return 0; } } class Card implements Comparable<Card> { int a,b; public Card(int w,int h) { this.a=w; this.b=h; } public int compareTo(Card that) { return this.a-that.a; } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
a9a59b5e71396017aa4ba14584e3dcfb
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Codechef { public static void main (String[] args) throws java.lang.Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s; s = br.readLine(); int finale = 0; int last = 0; if(s.indexOf('F') ==-1 || s.indexOf('M')==-1){ System.out.println(0); return; } s = s.substring(s.indexOf('M')); for(int i =0 ;i<s.length();i++){ if(s.charAt(i) == 'F') { if(i-finale > last) { last = i-finale; } else { last++; } finale++; } } System.out.println(last); } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
45c609f61ae476a88375ab4325ca3033
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { public static class FastReader { BufferedReader br; StringTokenizer root; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (root == null || !root.hasMoreTokens()) { try { root = new StringTokenizer(br.readLine()); } catch (Exception addd) { addd.printStackTrace(); } } return root.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 addd) { addd.printStackTrace(); } return str; } } public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out)); public static FastReader sc = new FastReader(); static int mod = (int) (1e9+7),MAX=(int) (2e5); static List<Integer>[] edges; public static int col = 19; public static int[][] table; public static void main(String[] args){ char[] s = sc.next().toCharArray(); boolean found = false; int last = 0,st = 0; for(int i=0;i<s.length;++i) { if(!found && s[i] == 'F') continue; if(s[i] == 'F') { if(i - st > last) last = i - st; else ++last; ++st; }else if(!found) { found = true; st = i; } } out.print(last); out.close(); } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
e739ec1ebb996e3c8a82a5b13b5b304d
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; public class CF205_Queue { static char c[]; static int n; static int slow(char c[]) { char m[] = new char[c.length]; int need = 0; for(int i = 0 ; i < c.length ; ++i) m[i] = c[i]; boolean same = false; while(!same) { same = true; char tmp[] = new char[m.length]; for(int i = 0 ; i < m.length ; ++i) tmp[i] = m[i]; for(int i = 0 ; i < m.length - 1; ++i) { if(m[i] == 'M' && m[i + 1] == 'F') { same = false; tmp[i] = 'F'; tmp[i + 1] ='M'; } } if(!same) ++need; for(int i = 0 ; i < m.length ; ++i) m[i] = tmp[i]; } return need; } static class Girl { int ans; int pos; int goal; public Girl(int pos,int goal) { this.pos = pos; this.goal = goal; } } public static void main(String[]args)throws Throwable { Scanner sc = new Scanner(System.in); c = sc.next().toCharArray(); int dest = 0; ArrayList<Girl> girls = new ArrayList(); boolean hasMale = false; for(int i = 0 ; i < c.length ; ++i) { if(c[i] == 'F') { girls.add(new Girl(i,dest++)); } } int ans = 0; if(girls.size() != 0) { Girl g = girls.get(0); g.ans = g.pos - g.goal; ans = g.ans; } for(int i = 1 ; i < girls.size() ; ++i) { Girl right = girls.get(i); Girl left = girls.get(i - 1); if( (left.ans < right.pos - right.goal) || left.ans == 0) right.ans = right.pos - right.goal; else right.ans = left.ans + 1; //System.out.println(right.ans); ans = Math.max(right.ans, ans); } //System.out.println(ans+" "+slow(c)); System.out.println(ans); } static class Scanner { BufferedReader br; StringTokenizer st; Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public Scanner(String s) throws FileNotFoundException{ br = new BufferedReader(new FileReader(s));} String next() throws IOException { while(st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
a808615eaa1186fee77ee29486b3ed58
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String [] args)throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine(); int max = 0; int pos = str.length(); for(int i = 0;i < str.length();i++){ if(str.charAt(i) == 'F')continue; pos = i; break; } int cnt = pos; for(int i = pos;i < str.length();i++){ if(str.charAt(i) == 'M')continue; cnt++; if(i + 1 - cnt >= max + 1){ max = i + 1 - cnt; } else{ max++; } //System.out.println(cnt + " " + i + " " + max); } System.out.print(max); } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
37881032c313b706981f112642b522e3
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class Template implements Runnable { BufferedReader in; PrintWriter out; StringTokenizer tok = new StringTokenizer(""); void init() throws FileNotFoundException { try { in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } catch (Exception e) { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); } } class GraphBuilder { int n, m; int[] x, y; int index; int[] size; GraphBuilder(int n, int m) { this.n = n; this.m = m; x = new int[m]; y = new int[m]; size = new int[n]; } void add(int u, int v) { x[index] = u; y[index] = v; size[u]++; size[v]++; index++; } int[][] build() { int[][] graph = new int[n][]; for (int i = 0; i < n; i++) { graph[i] = new int[size[i]]; } for (int i = index - 1; i >= 0; i--) { int u = x[i]; int v = y[i]; graph[u][--size[u]] = v; graph[v][--size[v]] = u; } return graph; } } String readString() throws IOException { while (!tok.hasMoreTokens()) { try { tok = new StringTokenizer(in.readLine()); } catch (Exception e) { return null; } } return tok.nextToken(); } int readInt() throws IOException { return Integer.parseInt(readString()); } int[] readIntArray(int size) throws IOException { int[] res = new int[size]; for (int i = 0; i < size; i++) { res[i] = readInt(); } return res; } long[] readLongArray(int size) throws IOException { long[] res = new long[size]; for (int i = 0; i < size; i++) { res[i] = readLong(); } return res; } long readLong() throws IOException { return Long.parseLong(readString()); } double readDouble() throws IOException { return Double.parseDouble(readString()); } <T> List<T>[] createGraphList(int size) { List<T>[] list = new List[size]; for (int i = 0; i < size; i++) { list[i] = new ArrayList<>(); } return list; } public static void main(String[] args) { new Template().run(); // new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start(); } long timeBegin, timeEnd; void time() { timeEnd = System.currentTimeMillis(); System.err.println("Time = " + (timeEnd - timeBegin)); } long memoryTotal, memoryFree; void memory() { memoryFree = Runtime.getRuntime().freeMemory(); System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10) + " KB"); } public void run() { try { timeBegin = System.currentTimeMillis(); memoryTotal = Runtime.getRuntime().freeMemory(); init(); solve(); out.close(); if (System.getProperty("ONLINE_JUDGE") == null) { time(); memory(); } } catch (Exception e) { e.printStackTrace(); System.exit(-1); } } void solve() throws IOException { char[] s = readString().toCharArray(); int boys = 0; int slowestGirl = 0; for (int i = 0; i < s.length; i++) { if (s[i] == 'M') { boys++; } else { if (boys == 0) continue; slowestGirl = Math.max(boys, slowestGirl + 1); } } out.println(slowestGirl); //System.err.println(slowestGirl); //System.err.println(naive(s)); } int naive(char[] a) { int res = 0; while (true) { boolean smth = false; for (int i = 0; i < a.length - 1; i++) { if (a[i] == 'M' && a[i + 1] == 'F') { char t = a[i]; a[i] = a[i + 1]; a[i + 1] = t; i++; smth = true; } } if (!smth) break; res++; } return res; } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
e929274e94f144c78e7ce300f04ccd7f
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Queue_353D { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); char[] s = sc.next().toCharArray(); int n = s.length; int st = 0; while (st < n && s[st] == 'F') st++; int males = 0; int ans = 0; for (int i = st; i < n; i++) { if (s[i] == 'M') males++; else ans = Math.max(males, ans + 1); } System.out.println(ans); } 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 double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
bb07d925c56db152f8185b3d57258f47
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Queue_353D { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); char[] s = sc.next().toCharArray(); int n = s.length; int st = 0; while(st < n && s[st] == 'F') st++; int males = 0; int ans = 0; for(int i=st;i<n;i++) { if(s[i] == 'M') males++; else { ans = Math.max(males, ans + 1); i++; while(i < n && s[i] == 'F') { ans = ans+ 1; i++; } i--; } } System.out.println(ans); } 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 double nextDouble() throws IOException { return Double.parseDouble(next()); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
cb88049fc55f7aef5845ba35fb89b496
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.util.*; import java.io.*; public class D { Reader in; PrintWriter out; int i = 0, j = 0; void solve() { //START// char[] cc = in.next().toCharArray(); int cnt = 0, max = 0, del = 0; for (i = 0; i < cc.length; i++) { if (cc[i] == 'M') { cnt++; if (del > 0) del--; } else { if (cnt > 0) { max = Math.max(max, cnt+del); del++; } } } out.println(max); //END } void runIO() { in = new Reader(); out = new PrintWriter(System.out, false); solve(); out.close(); } public static void main(String[] args) { new D().runIO(); } // input/output 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 final String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.append((char) c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public int nextInt() { 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() { 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() { 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; } public int[] readIntArray(int size) { int[] arr = new int[size]; for (int i = 0; i < size; i++) arr[i] = nextInt(); return arr; } public long[] readLongArray(int size) { long[] arr = new long[size]; for (int i = 0; i < size; i++) arr[i] = nextInt(); return arr; } private void fillBuffer() { try { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); } catch (IOException e) { } if (bytesRead == -1) buffer[0] = -1; } private byte read() { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
c84e82cbb2502c289a1c4c53dab4d2d1
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.text.DecimalFormat; import java.text.NumberFormat; public class Main { int mod = 1000000007; public void solve() throws IOException{ char[] s = in.next().toCharArray(); int m = 0; int ans = 0; for(int i = 0; i < s.length; i++){ if(s[i] == 'M'){ m++; }else{ if(m > 0){ ans = Math.max(ans + 1, m); } } } out.println(ans); return; } public long exp(int b, int e){ if(e == 0){ return 1; }else if(e % 2 == 1){ long r = exp(b, e / 2); return r * r % mod * b % mod; }else if(e % 2 == 0){ long r = exp(b, e / 2); return r * r % mod; } return 1; } FastScanner in; PrintWriter out; static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } String nextLine() throws IOException { if (st == null || !st.hasMoreTokens()) return br.readLine(); StringBuilder result = new StringBuilder(st.nextToken()); while (st.hasMoreTokens()) { result.append(" "); result.append(st.nextToken()); } return result.toString(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } } void run() throws IOException { in = new FastScanner(System.in); out = new PrintWriter(System.out, false); solve(); out.close(); } public static void main(String[] args) throws IOException{ new Main().run(); } public void printArr(int[] arr){ for(int i = 0; i < arr.length; i++){ out.print(arr[i] + " "); } out.println(); } public long gcd(long a, long b){ if(a == 0) return b; return gcd(b % a, a); } public boolean isPrime(long num){ if(num == 0 || num == 1){ return false; } for(int i = 2; i * i <= num; i++){ if(num % i == 0){ return false; } } return true; } public class Pair<A, B>{ public A x; public B y; Pair(A x, B y){ this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Pair<?, ?> pair = (Pair<?, ?>) o; if (!x.equals(pair.x)) return false; return y.equals(pair.y); } @Override public int hashCode() { int result = x.hashCode(); result = 31 * result + y.hashCode(); return result; } } class Tuple{ int x; int y; int z; Tuple(int ix, int iy, int iz){ x = ix; y = iy; z = iz; } } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
9ba9e06c0efd2694037513b5f61ced17
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
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.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author Jenish */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; ScanReader in = new ScanReader(inputStream); PrintWriter out = new PrintWriter(outputStream); DQueue solver = new DQueue(); solver.solve(1, in, out); out.close(); } static class DQueue { public void solve(int testNumber, ScanReader in, PrintWriter out) { char arr[] = in.scanString().toCharArray(); int n = arr.length; ArrayList<Integer> arrayList = new ArrayList<>(); for (int i = 0; i < n; i++) if (arr[i] == 'F') arrayList.add(i); int fe = 0; for (int i = 0; i < n; i++) { if (arr[i] == 'M') break; else fe++; } if (arrayList.size() == 0 || fe == arrayList.size()) { out.println(0); return; } long dp[] = new long[arrayList.size()]; dp[fe] = dis(arrayList.get(fe), fe); for (int i = fe + 1; i < arrayList.size(); i++) dp[i] = Math.max(dp[i - 1] + 1, dis(arrayList.get(i), i)); out.println(dp[arrayList.size() - 1]); } long dis(int cur, int f_n) { return cur - f_n; } } 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 String scanString() { int c = scan(); while (isWhiteSpace(c)) c = scan(); StringBuilder RESULT = new StringBuilder(); do { RESULT.appendCodePoint(c); c = scan(); } while (!isWhiteSpace(c)); return RESULT.toString(); } private boolean isWhiteSpace(int n) { if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true; else return false; } } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
722c6d23a1786d35570b4ed5b2606feb
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
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. */ /** * * @author dipankar12 */ import java.io.*; import java.util.*; public class r205d { public static void main(String args[]) { fastio in=new fastio(System.in); PrintWriter pw=new PrintWriter(System.out); String str=in.readString(); int len=str.length(); int cnt=0,delay=0,max=0; for(int i=0;i<str.length();i++) { if(str.charAt(i)=='M') { cnt++; if(delay>0) delay--; } else { if(cnt>0) { max=Math.max(max, cnt+delay); delay++; } } } pw.println(max); pw.close(); } static class fastio { private final InputStream stream; private final byte[] buf = new byte[8192]; private int cchar, snchar; private SpaceCharFilter filter; public fastio(InputStream stream) { this.stream = stream; } public int nxt() { if (snchar == -1) throw new InputMismatchException(); if (cchar >= snchar) { cchar = 0; try { snchar = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snchar <= 0) return -1; } return buf[cchar++]; } public int nextInt() { int c = nxt(); while (isSpaceChar(c)) { c = nxt(); } int sgn = 1; if (c == '-') { sgn = -1; c = nxt(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = nxt(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = nxt(); while (isSpaceChar(c)) { c = nxt(); } int sgn = 1; if (c == '-') { sgn = -1; c = nxt(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = nxt(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = nxt(); while (isSpaceChar(c)) { c = nxt(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = nxt(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = nxt(); while (isSpaceChar(c)) c = nxt(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = nxt(); } while (!isEndOfLine(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; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
fa2c3560fa390c544bede60e021e5b33
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main (String[] args)throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String s = in.readLine(); int n = s.length(); int count = 0; int last = 0; int flag = 0; for(int i=0;i<n;i++) { char ch = s.charAt(i); if(ch == 'M') { flag = 1; continue; } else if(flag == 1) { last = (i - count > last? i - count:last + 1); } count++; } System.out.println(last); } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
701e889e972511b9981d20b268467f97
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class _35_Queue { public static void main(String[] args) { Scanner scn = new Scanner(System.in); String s = scn.next(); int time = 0; int updated = 0; int v = 0; int sl = 0; while (sl < s.length()) { if (s.charAt(sl) == 'F') { break; } sl++; } int []previous=new int[s.length()]; Arrays.fill(previous, -1); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (ch == 'F') { if (i!=0&&s.charAt(i - 1) == 'F') { previous[i] = previous[i - 1] + 1; } else { previous[i] = 0; } sl = i; } } boolean vs = false; while (v < s.length()) { if (s.charAt(v) == 'M') { break; } v++; } while (v < s.length()) { if (s.charAt(v) == 'F') { vs = true; break; } v++; } if (vs == false) { System.out.println(0); return; } int[] tm = new int[s.length()]; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == 'F') { if (previous[i] == i) { updated++; continue; } if(updated==0){ tm[updated]=Math.max(1, i-updated); }else{ tm[updated]=Math.max(tm[updated-1]+1, i-updated);} updated++; } } System.out.println(tm[updated-1]); } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
dd49953ad742d119d28f6eb739ea4beb
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
// ONE DAY, YOU WILL BE BEYOND THE REACH OF SPACE AND TIME. // // UNTIL THEN, STAY LOW AND CODE HARD. // // Author :- Saurabh// //BIT MESRA, RANCHI// import java.io.*; import java.util.*; import java.util.Queue; import static java.lang.Math.*; public class DQueue { static void Bolo_Jai_Mata_Di() { char ch[]=ns().toCharArray(); long t=0,ans=0; tsc(); for(int i=0;i<ch.length;i++){ if(ch[i]=='M')t++; else if(t!=0) ans=max(ans+1,t); } pl(ans); flush(); } static class three{ int x,y,z; three(int x, int y, int z){ this.x=x;this.y=y;this.z=z; } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //THE DON'T CARE ZONE BEGINS HERE...// static Calendar ts, te; //For time calculation static int mod9 = 1000000007; static int n, m, k, t, mod = 998244353; static Lelo input = new Lelo(System.in); static PrintWriter pw = new PrintWriter(System.out, true); public static void main(String[] args) { //threading has been used to increase the stack size. new Thread(null, null, "BlackRise", 1 << 25) //the last parameter is stack size desired., { public void run() { try { Bolo_Jai_Mata_Di(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } }.start(); } static class Lelo { //Lelo class for fast input private InputStream ayega; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public Lelo(InputStream ayega) { this.ayega = ayega; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = ayega.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); } } // functions to take input// static int ni() { return input.nextInt(); } static long nl() { return input.nextLong(); } static double nd() { return input.nextDouble(); } static String ns() { return input.readString(); } //functions to give output static void pl() { pw.println(); } static void p(Object o) { pw.print(o + " "); } static void pws(Object o) { pw.print(o + ""); } static void pl(Object o) { pw.println(o); } static void tsc() //calculates the starting time of execution { ts = Calendar.getInstance(); ts.setTime(new Date()); } static void tec() //calculates the ending time of execution { te = Calendar.getInstance(); te.setTime(new Date()); } static void pwt() //prints the time taken for execution { pw.printf("\nExecution time was :- %f s\n", (te.getTimeInMillis() - ts.getTimeInMillis()) / 1000.00); } static void sort(int ar[], int n) { for (int i = 0; i < n; i++) { int ran = (int) (Math.random() * n); int temp = ar[i]; ar[i] = ar[ran]; ar[ran] = temp; } Arrays.sort(ar); } static void sort(long ar[], int n) { for (int i = 0; i < n; i++) { int ran = (int) (Math.random() * n); long temp = ar[i]; ar[i] = ar[ran]; ar[ran] = temp; } Arrays.sort(ar); } static void sort(char ar[], int n) { for (int i = 0; i < n; i++) { int ran = (int) (Math.random() * n); char temp = ar[i]; ar[i] = ar[ran]; ar[ran] = temp; } Arrays.sort(ar); } static void flush() { tec(); //ending time of execution //pwt(); //prints the time taken to execute the program pw.flush(); pw.close(); } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
9737b4962b21826cb6f3d3cb6d81ddad
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.util.*; import java.lang.*; import java.math.*; import java.io.*; /* spar5h */ public class cf4 implements Runnable{ static void bfc(int x) { char[] ch = Integer.toBinaryString(x).toCharArray(); int n = ch.length; char[] a = new char[n]; for(int i = 0; i < n; i++) a[i] = ch[i]; int res2 = 0; while(true) { int count = 0; for(int i = 0; i < n; i++) if(a[i] == '1') System.out.print('M'); else System.out.print('F'); System.out.println(); for(int i = 1; i < n; i++) { if(a[i] == '0' && a[i - 1] == '1') { a[i] = '1'; a[i - 1] = '0'; i++; count++; } } if(count == 0) break; res2++; } int[] mc = new int[n]; if(ch[0] == '1') mc[0] = 1; int[] wait = new int[n]; int[] dp = new int[n]; int j = 0, res = 0; for(int i = 1; i < n; i++) { mc[i] += mc[i - 1]; if(ch[i] == '1') { mc[i]++; continue; } if(dp[j] > 0) wait[i] = Math.max(wait[j] - (i - j - 1) + 1, 0); dp[i] = wait[i] + mc[i]; res = Math.max(dp[i], res); j = i; } System.out.println(x + " " + res + " " + res2); } public void run() { InputReader s = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); /* for(int i = 0; i < (1 << 7); i++) bfc(i); */ char[] ch = s.next().toCharArray(); int n = ch.length; int[] mc = new int[n]; if(ch[0] == 'M') mc[0] = 1; int[] wait = new int[n]; int[] dp = new int[n]; int j = 0, res = 0; for(int i = 1; i < n; i++) { mc[i] += mc[i - 1]; if(ch[i] == 'M') { mc[i]++; continue; } if(dp[j] > 0) wait[i] = Math.max(wait[j] - (i - j - 1) + 1, 0); dp[i] = wait[i] + mc[i]; res = Math.max(dp[i], res); j = i; } w.println(res); w.close(); } 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); } } public static void main(String args[]) throws Exception { new Thread(null, new cf4(),"cf4",1<<26).start(); } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
3a2654bca9dc63b6870eb0079d1ac9e4
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.io.*; import java.util.*; public class D implements Runnable{ public static void main (String[] args) {new Thread(null, new D(), "_cf", 1 << 28).start();} public void run() { FastScanner fs = new FastScanner(); PrintWriter out = new PrintWriter(System.out); System.err.println("Go!"); char[] str = fs.next().toCharArray(); int res = 0, n = str.length; int lastF = -1, curF = 0; int[] moves = new int[n]; for(int i = 0; i < n; i++) { if(str[i] == 'F') { if(lastF >= curF) { if(Math.abs(lastF - curF) < moves[lastF]) { moves[i] = Math.max(1 + moves[lastF], Math.abs(i - (curF))); } else { moves[i] = Math.abs(i - (curF)); } } else { moves[i] = Math.abs(i - (curF)); } curF++; lastF = i; } } for(int i = 0; i < n; i++) res = Math.max(res, moves[i]); out.println(res); out.close(); } class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(""); } public String next() { if(st.hasMoreTokens()) return st.nextToken(); else { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) {} } return next(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
7a2ed4282c2d60c6149a1b568f282897
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
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); DQueue solver = new DQueue(); solver.solve(1, in, out); out.close(); } static class DQueue { public void solve(int testNumber, ScanReader in, PrintWriter out) { char[] ar = in.scanString().toCharArray(); int ff = 0; int last = 0; boolean flag = true; for (int i = 0; i < ar.length; i++) { if (flag && ar[i] == 'F') continue; if (ar[i] == 'F') { if (i - ff > last) last = i - ff; else last = last + 1; ff++; } else if (flag) { flag = false; ff = i; } } out.println(last); } } 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 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
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
a2dea75536bedc08d451cf4f6db13296
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
/* Keep solving problems. */ import java.util.*; import java.io.*; public class CFA { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; private static final long MOD = 1000L * 1000L * 1000L + 7; private static final int[] dx = {0, -1, 0, 1}; private static final int[] dy = {1, 0, -1, 0}; private static final String yes = "Yes"; private static final String no = "No"; char[] arr; int n; void solve() throws IOException { String str = nextString(); int idx = -1; for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == 'M') { idx = i; break; } } if (idx == -1) { outln(0); return; } arr = str.substring(idx).toCharArray(); n = arr.length; List<Integer> girls = new ArrayList<>(); int g = 0; for (int i = 0; i < n; i++) { char c = arr[i]; if (c == 'F') { g++; girls.add(i); } } if (g == 0 || g == n || girls.get(g - 1) == g - 1) { outln(0); return; } int[] T = new int[n]; T[0] = girls.get(0); for (int i = 1; i < g; i++) { T[i] = Math.max(T[i - 1] + 1, girls.get(i) - i); } outln(T[g - 1]); } void shuffle(int[] a) { int n = a.length; for(int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n - i)); int tmp = a[i]; a[i] = a[r]; a[r] = tmp; } } long gcd(long a, long b) { while(a != 0 && b != 0) { long c = b; b = a % b; a = c; } return a + b; } private void outln(Object o) { out.println(o); } private void out(Object o) { out.print(o); } private void formatPrint(double val) { System.out.format("%.9f%n", val); } public CFA() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); solve(); out.close(); } public static void main(String[] args) throws IOException { new CFA(); } public long[] nextLongArr(int n) throws IOException{ long[] res = new long[n]; for(int i = 0; i < n; i++) res[i] = nextLong(); return res; } public int[] nextIntArr(int n) throws IOException { int[] res = new int[n]; for(int i = 0; i < n; i++) res[i] = nextInt(); return res; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { eof = true; return null; } } return st.nextToken(); } public String nextString() { try { return br.readLine(); } catch (IOException e) { eof = true; return null; } } 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()); } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
75c66f0274229a5555fb9cee79155d45
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
//package c205; import java.util.Scanner; public class q4 { public static void main(String args[]) { Scanner s=new Scanner(System.in); String in=s.nextLine(); int []ans=new int[in.length()]; int[] m=new int[in.length()]; int[] w=new int[in.length()]; int max=0; for(int i=0;i<in.length();i++) { if(i==0) { if(in.charAt(i)=='M') m[0]=1; w[0]=-1; } else { if(in.charAt(i)=='M') { if(w[i-1]>=0) w[i]=w[i-1]-1; else w[i]=w[i-1]; m[i]=1+m[i-1]; } else { m[i]=m[i-1]; if(m[i]!=0) w[i]=w[i-1]+1; if((w[i]+m[i])>=max && m[i]!=0 ) { max=w[i]+m[i]; //System.out.println(i+" "+w[i]+" "+m[i]+" "+max); } } } } System.out.println(max); } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
723acc48a9381c6eeb0459b01f250ff6
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.util.*; import java.io.*; public class codeforces { static long n; static int m; public static void main(String args[]) { Scanner sc=new Scanner(System.in); String s=sc.next(); int counter=0; int store=0,sum=-1; for(int i=0;i<s.length();i++) { if(s.charAt(i)=='F') { if(i!=store) { sum=Math.max(sum+1,i-store); } store++; } } System.out.println(Math.max(0,sum)); } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
5475e36e8637bbff1dd309211949803d
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.util.*; import java.io.*; import static java.lang.System.in; public class Main { public static void main(String[] args)throws IOException { Scanner sc = new Scanner(System.in); char[] s = sc.next().toCharArray(); long ans = 0, man = 0; for(char w:s){ if(w=='M') man++; else{ if(man>0) ans = Math.max(ans+1,man); } } System.out.println(ans); } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
b920e974400f11d29077322fdbeee3b2
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
/** * Created by Martin on 2/5/2017. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; import java.io.PrintWriter; public class Main { public static void main(String[]args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PrintWriter pw = new PrintWriter(System.out); String cl = br.readLine(); int N = cl.length(); int v[] = new int[N]; int w[] = new int[N]; int zc = 0; for (int i = 0; i < N; i++) { int c = cl.charAt(i)=='M' ? 0 : 1; if (c == 0) { zc++; v[i] = i > 0 ? v[i - 1] : 0; w[i] = i > 0 ? w[i - 1] : 0; } else { if (zc == 0) continue; int d = zc - (i > 0 ? v[i - 1] : 0); int nw = Math.max(0, (i > 0 ? w[i - 1] : 0) - d + 1); v[i] = zc; w[i] = nw; } } //debug(v); //debug(w); long res = v[N-1]; res += w[N - 1]; pw.println(res); pw.flush(); } public static void debug(Object...args) { System.out.println(Arrays.deepToString(args)); } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
4340c8af6f52c52ea8584f901ab88e51
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.io.*; import java.util.*; public class ProblemD { InputReader in; PrintWriter out; void solve() { String s = in.next(); int mCount = 0; int wait = 0; int ans = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == 'M') { mCount++; if (wait > 0) { wait--; } } else { if (mCount > 0) { ans = Math.max(ans, mCount + wait); wait++; } } } out.println(ans); } ProblemD(){ boolean oj = System.getProperty("ONLINE_JUDGE") != null; try { if (oj) { in = new InputReader(System.in); out = new PrintWriter(System.out); } else { Writer w = new FileWriter("output.txt"); in = new InputReader(new FileReader("input.txt")); out = new PrintWriter(w); } } catch(Exception e) { throw new RuntimeException(e); } solve(); out.close(); } public static void main(String[] args){ new ProblemD(); } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream)); tokenizer = null; } public InputReader(FileReader fr) { reader = new BufferedReader(fr); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
277cf0eb073e87c226b7fa784fbb475f
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import javafx.scene.layout.Priority; import java.io.*; import java.lang.reflect.Array; import java.net.Inet4Address; import java.util.*; import java.lang.*; import java.util.HashMap; import java.util.PriorityQueue; public class templ implements Runnable{ static class pair implements Comparable { int f; int s; pair(int fi,int se) { f=fi; s=se; } public int compareTo(Object o) { pair pr=(pair)o; if(s>pr.s) return 1; if(s==pr.s) { if(f<pr.f) return 1; else return -1; } else return -1; } public boolean equals(Object o) { pair ob=(pair)o; int ff; int ss; if(o!=null) { ff=ob.f; ss=ob.s; if((ff==this.f)&&(ss==this.s)) return true; } return false; } public int hashCode() { return (this.f+" "+this.s).hashCode(); } } public class triplet implements Comparable { int f,t; int s; triplet(int f,int s,int t) { this.f=f; this.s=s; this.t=t; } public boolean equals(Object o) { triplet ob=(triplet)o; int ff; int ss; int tt; if(o!=null) { ff=ob.f; ss=ob.s; tt=ob.t; if((ff==this.f)&&(ss==this.s)&&(tt==this.t)) return true; } return false; } public int hashCode() { return (this.f+" "+this.s+" "+this.t).hashCode(); } public int compareTo(Object o) { triplet tr=(triplet)o; if(t>tr.t) return 1; else return -1; } } public static void main(String args[])throws Exception { new Thread(null,new templ(),"templ",1<<27).start(); } public void run() { try { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); String s=in.nextLine(); int n=s.length(); ArrayList<Integer>al=new ArrayList<>(); for(int i=0;i<n;i++) { char c=s.charAt(i); if(c=='F') al.add(i+1); } ArrayList<Integer>al1=new ArrayList<>(); ArrayList<Integer>w=new ArrayList<>(); if(al.size()!=0) al1.add(al.get(0)-1); w.add(0); for(int i=1;i<al.size();i++) { int x=al.get(i); int y=x-1-i; if(y==0) { al1.add(0); w.add(0); continue; } int z=al.get(i-1)-x+2; int wait=Math.max(0,z+w.get(i-1)); al1.add(wait+y); w.add(wait); } /*for(int i=0;i<al.size();i++) out.println(al.get(i)+" "+w.get(i)+" "+al1.get(i));*/ if(al.size()==0) out.println(0); else out.println(al1.get(al1.size()-1)); out.close(); } catch(Exception e){ return; } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int ni() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nl() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = ni(); } return a; } 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 String nextLine() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isEndOfLine(c)); return res.toString(); } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
0c6eb7e37a8891d3d56e2e0b56485a8e
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
// package Practice.CF347; import java.io.*; import java.util.*; public class CF353D { static FastReader s; static PrintWriter out; static String INPUT = "MFMMMMMF\n"; public static void main(String[] args) { long time = System.currentTimeMillis(); boolean oj = System.getProperty("ONLINE_JUDGE") != null; out = new PrintWriter(System.out); s = new FastReader(oj); int cnt = 0, delay = 0, max = 0; String str = s.next(); char[] cc = str.toCharArray(); for (int i = 0; i < cc.length; i++) if (cc[i] == 'M') { cnt++; if (delay > 0) delay--; } else { if (cnt > 0) { max = Math.max(max, cnt + delay); delay++; } } out.println(max); // out.println(cnt); if (!oj) { System.out.println(Arrays.deepToString(new Object[]{System.currentTimeMillis() - time + " ms"})); } out.flush(); } private static class Maths { static ArrayList<Long> printDivisors(long n) { // Note that this loop runs till square root ArrayList<Long> list = new ArrayList<>(); for (long i = 1; i <= Math.sqrt(n); i++) { if (n % i == 0) { if (n / i == i) { list.add(i); } else { list.add(i); list.add(n / i); } } } return list; } // GCD - Using Euclid theorem. private static long gcd(long a, long b) { if (b == 0) { return a; } return gcd(b, a % b); } // Extended euclidean algorithm // Used to solve equations of the form ax + by = gcd(a,b) // return array [d, a, b] such that d = gcd(p, q), ap + bq = d static long[] extendedEuclidean(long p, long q) { if (q == 0) return new long[]{p, 1, 0}; long[] vals = extendedEuclidean(q, p % q); long d = vals[0]; long a = vals[2]; long b = vals[1] - (p / q) * vals[2]; return new long[]{d, a, b}; } // X ^ y mod p static long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if ((y & 1) == 1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; } // Returns modulo inverse of a // with respect to m using extended // Euclid Algorithm. Refer below post for details: // https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/ static long inv(long a, long m) { long m0 = m, t, q; long x0 = 0, x1 = 1; if (m == 1) return 0; // Apply extended Euclid Algorithm while (a > 1) { q = a / m; t = m; m = a % m; a = t; t = x0; x0 = x1 - q * x0; x1 = t; } // Make x1 positive if (x1 < 0) x1 += m0; return x1; } // k is size of num[] and rem[]. // Returns the smallest number // x such that: // x % num[0] = rem[0], // x % num[1] = rem[1], // .................. // x % num[k-2] = rem[k-1] // Assumption: Numbers in num[] are pairwise // coprime (gcd for every pair is 1) static long findMinX(long num[], long rem[], long k) { int prod = 1; for (int i = 0; i < k; i++) prod *= num[i]; int result = 0; for (int i = 0; i < k; i++) { long pp = prod / num[i]; result += rem[i] * inv(pp, num[i]) * pp; } return result % prod; } } private static class BS { // Binary search private static int binarySearch(int[] arr, int ele) { int low = 0; int high = arr.length - 1; while (low <= high) { int mid = (low + high) / 2; if (arr[mid] == ele) { return mid; } else if (ele < arr[mid]) { high = mid - 1; } else { low = mid + 1; } } return -1; } // First occurence using binary search private static int binarySearchFirstOccurence(int[] arr, int ele) { int low = 0; int high = arr.length - 1; int ans = -1; while (low <= high) { int mid = (low + high) / 2; if (arr[mid] == ele) { ans = mid; high = mid - 1; } else if (ele < arr[mid]) { high = mid - 1; } else { low = mid + 1; } } return ans; } // Last occurenece using binary search private static int binarySearchLastOccurence(int[] arr, int ele) { int low = 0; int high = arr.length - 1; int ans = -1; while (low <= high) { int mid = (low + high) / 2; if (arr[mid] == ele) { ans = mid; low = mid + 1; } else if (ele < arr[mid]) { high = mid - 1; } else { low = mid + 1; } } return ans; } } private static class arrays { // Merge sort static void merge(int arr[], int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int L[] = new int[n1]; int R[] = new int[n2]; for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } static void sort(int arr[], int l, int r) { if (l < r) { int m = (l + r) / 2; sort(arr, l, m); sort(arr, m + 1, r); merge(arr, l, m, r); } } static void sort(int[] arr) { sort(arr, 0, arr.length - 1); } } private static class UnionFindDisjointSet { int[] parent; int[] size; int n; int size1; public UnionFindDisjointSet(int n) { this.n = n; this.parent = new int[n]; this.size = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; } for (int i = 0; i < n; i++) { size[i] = 1; } this.size1 = n; } private int numDisjointSets() { System.out.println(size1); return size1; } private boolean find(int a, int b) { int rootA = root(a); int rootB = root(b); if (rootA == rootB) { return true; } return false; } private int root(int b) { while (parent[b] != b) { parent[b] = parent[parent[b]]; b = parent[b]; } return b; } private void union(int a, int b) { int rootA = root(a); int rootB = root(b); if (rootA == rootB) { return; } if (size[rootA] < size[rootB]) { parent[rootA] = parent[rootB]; size[rootB] += size[rootA]; } else { parent[rootB] = parent[rootA]; size[rootA] += size[rootB]; } size1--; System.out.println(Arrays.toString(parent)); } } private static class SegTree { int[] st; int[] arr; public SegTree(int[] arr) { this.arr = arr; int size = (int) Math.ceil(Math.log(arr.length) / Math.log(2)); st = new int[(int) ((2 * Math.pow(2, size)) - 1)]; buildSegmentTree(1, 0, arr.length - 1); } //**********JUST CALL THE CONSTRUCTOR, THIS FUNCTION WILL BE CALLED AUTOMATICALLY****** private void buildSegmentTree(int index, int L, int R) { if (L == R) { st[index] = arr[L]; return; } buildSegmentTree(index * 2, L, (L + R) / 2); buildSegmentTree(index * 2 + 1, (L + R) / 2 + 1, R); // Replace this line if you want to change the function of the Segment tree. st[index] = Math.min(st[index * 2], st[index * 2 + 1]); } //***********We have to use this function ************** private int Query(int queL, int queR) { return Query1(1, 0, arr.length - 1, queL, queR); } //This is a helper function. //************* DO NOT USE THIS **************** private int Query1(int index, int segL, int segR, int queL, int queR) { if (queL > segR || queR < segL) { return -1; } if (queL <= segL && queR >= segR) { return st[index]; } int ans1 = Query1(index * 2, segL, (segL + segR) / 2, queL, queR); int ans2 = Query1(index * 2 + 1, (segL + segR) / 2 + 1, segR, queL, queR); if (ans1 == -1) { return ans2; } if (ans2 == -1) { return ans1; } // Segment tree implemented for range minimum query. Change the below line to change the function. return Math.min(ans1, ans2); } private void update(int idx, int val) { update1(1, 0, arr.length - 1, idx, val); } private void update1(int node, int queL, int queR, int idx, int val) { // idx - index to be updated in the array // node - index to be updated in the seg tree if(queL == queR) { // Leaf node arr[idx] += val; st[node] += val; } else { int mid = (queL + queR) / 2; if(queL <= idx && idx <= mid){ // If idx is in the left child, recurse on the left child update1(2*node, queL, mid, idx, val); }else{ // if idx is in the right child, recurse on the right child update1(2*node+1, mid+1, queR, idx, val); } // Internal node will have the min of both of its children st[node] = Math.min(st[2*node],st[2*node+1]); } } } private static class FastReader { InputStream is; public FastReader(boolean onlineJudge) { is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes()); } byte[] inbuf = new byte[1024]; public int lenbuf = 0, ptrbuf = 0; 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++]; } boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); } int skip() { int b; while ((b = readByte()) != -1 && isSpaceChar(b)) ; return b; } double nextDouble() { return Double.parseDouble(next()); } char nextChar() { return (char) skip(); } String next() { int b = skip(); StringBuilder sb = new StringBuilder(); while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } String nextLine() { int b = skip(); StringBuilder sb = new StringBuilder(); while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ') sb.appendCodePoint(b); b = readByte(); } return sb.toString(); } char[] next(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); } int nextInt() { 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(); } } long nextLong() { 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(); } } char[][] nextMatrix(int n, int m) { char[][] map = new char[n][]; for (int i = 0; i < n; i++) map[i] = next(m); return map; } int[] nextIntArray(int n) { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } long[] nextLongArray(int n) { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } int[][] next2DInt(int n, int m) { int[][] arr = new int[n][]; for (int i = 0; i < n; i++) { arr[i] = nextIntArray(m); } return arr; } long[][] next2DLong(int n, int m) { long[][] arr = new long[n][]; for (int i = 0; i < n; i++) { arr[i] = nextLongArray(m); } return arr; } int[] shuffle(int[] arr) { Random r = new Random(); for (int i = 1, j; i < arr.length; i++) { j = r.nextInt(i); arr[i] = arr[i] ^ arr[j]; arr[j] = arr[i] ^ arr[j]; arr[i] = arr[i] ^ arr[j]; } return arr; } int[] uniq(int[] arr) { Arrays.sort(arr); int[] rv = new int[arr.length]; int pos = 0; rv[pos++] = arr[0]; for (int i = 1; i < arr.length; i++) { if (arr[i] != arr[i - 1]) { rv[pos++] = arr[i]; } } return Arrays.copyOf(rv, pos); } } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 8
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
478daefb9c979ffc06a24fb179ddf077
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.util.*; public class P353D { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String line = sc.next(); int N = line.length(); int[] dp = new int[N]; int k; for (k = 0; k < N; k++) { if (line.charAt(k) == 'F') { dp[0] = k; break; } } if (k == N) { System.out.println(0); return; } int i = 1; for (k = dp[0] + 1; k < N; k++) { if (line.charAt(k) == 'F') { int l = k - i; dp[i] = Math.max(l, (dp[i-1] == 0 ? 0 : dp[i-1] + 1)); i++; } } System.out.println(dp[i-1]); } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 6
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
8fcb273a1cfe0de810d7637e4049537b
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.util.LinkedList; import java.util.Scanner; public class B { public static void main(String[] args) { Scanner in = new Scanner(System.in); char[] s = in.next().toCharArray(); int last = 0; int i = 0; int m = 0; while (i<s.length&&s[i] == 'F'){ i++; last--; m--; } for (; i < s.length; i++) if (s[i] == 'F') break; if (i == s.length) { System.out.println(0); System.exit(0); } last += i; m += i; i++; for (; i < s.length; i++) { if (s[i] == 'F') { last = Math.max(last + 1, m); } else { m++; } } System.out.println(last); } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 6
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
cd93f90596c461d588992af88c10dc3e
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Queue { public static void main(String[] args) throws IOException{ BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(System.in)); String m = reader.readLine(); int l = m.length(); int max = 0; int countM = 0; int countF = 0; for(int i=0;i<l;i++){ char c = m.charAt(i); if(c=='M'){ countM++; if(countF > 0) countF--; }else{ if(countM > 0){ if(countM+countF > max){ max = countM+countF; } countF++; } } } System.out.println(max); } finally { if(reader != null) reader.close(); } } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 6
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
3322c7e34e7a51f6604da4fa57fa8d58
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; public class D { public static void main(String[] args)throws Exception{ // TODO Auto-generated method stub new D().run(); } int[] getArray(String line){ String[] array=line.split(" "); int[] res=new int[array.length]; for(int i=0;i<res.length;i++) res[i]=Integer.parseInt(array[i]); return res; } void run() throws Exception{ BufferedReader reader=new BufferedReader(new InputStreamReader(System.in)); String line=reader.readLine(); System.out.println(howLong(line)); System.out.flush(); reader.close(); } long howLong(String q){ int i=0; while(i<q.length() && q.charAt(i)=='F'){ i++; } int goal=i; long merkeLast=0; long lastCanBe=-1; for(;i<q.length();i++){ if(q.charAt(i)=='F'){ merkeLast=Math.max(lastCanBe+1, i-goal); lastCanBe=merkeLast; goal++; } } return merkeLast; } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 6
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
9b5ab20069306f378c1eb7e744016af1
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class R205D { BufferedReader reader; StringTokenizer tokenizer; PrintWriter out; public void solve() throws IOException { char[] S = reader.readLine().toCharArray(); int cnt = 0; int max = 0; int target = 0; int first = -1; for(int i = 0; i < S.length; i++){ if(S[i] == 'M'){ cnt++; if(first == -1) first = i; } else{ target++; if(first != -1) cnt--; max = Math.max(max, cnt); } } if(target == S.length) out.println(0); else out.println( (target-first) + max); } /** * @param args */ public static void main(String[] args) { new R205D().run(); } public void run() { try { reader = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; out = new PrintWriter(System.out); solve(); reader.close(); out.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(); } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 6
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
af3ce332cf1d23501b72de71a54e1354
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String str = scan.nextLine(); int m = 0; int n = 0; int i = 0; while (str.charAt(i) == 'F') { i++; if (str.length() == i){ System.out.println(0); return;} } for (int j = i; j < str.length(); j++) { if (str.charAt(j) == 'M') { m++; } if (str.charAt(j) == 'F') { n = Math.max(n + 1, m); } } System.out.println(n); } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 6
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
d6024f4a32a3ced909ce0fb735ac6ed3
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.io.*; import java.util.*; public class B { public static void main(String[] args) { new B().run(); } float[] x; float[] y; float[][] d; int n; long count = 0; private void solve() throws Exception { String input = in.readLine(); char[] chs = input.toCharArray(); //in.close(); int n = chs.length; for(int i = 0; i < chs.length; i++){ if(chs[i] == 'F'){ chs[i] = ' '; }else{ break; } } for(int i = n-1; i >= 0; i--){ if(chs[i] == 'M'){ chs[i] = ' '; }else{ break; } } input = new String(chs); input = input.trim(); chs = input.toCharArray(); LinkedList<Integer> valuesList = new LinkedList<Integer>(); n = chs.length; int state = 0; int count = 0; for(int i = 0; i < n; i++){ if(chs[i] == 'M'){ if(state == 0){ count++; }else{ valuesList.add(count); count = 1; state = 0; } }else{ if(state == 1){ count++; }else{ valuesList.add(count); count = 1; state = 1; } } } valuesList.add(count); Integer[] values = valuesList.toArray(new Integer[0]); n = values.length; int last = n-1; while(last > 1){ int M = last-1; int F = last-2; if(values[M] > values[F]){ values[last-3] += values[M]; if(last > 3){ values[last-4] += values[F]; } values[F] = values[last]; }else{ values[F] += values[last]; } last -= 2; } if(input.isEmpty()) System.out.println(0); else System.out.println(values[0]+values[1]-1); } private BufferedReader in; private PrintWriter out; private StringTokenizer tokenizer; public void run() { try { in = new BufferedReader(new InputStreamReader(System.in)); tokenizer = null; out = new PrintWriter(System.out); solve(); in.close(); out.close(); } catch (Exception e) { e.printStackTrace(); System.exit(1); } } private int nextInt() throws IOException { return Integer.parseInt(nextToken()); } private long nextLong() throws IOException { return Long.parseLong(nextToken()); } private float nextFloat() throws IOException { return Float.parseFloat(nextToken()); } private String nextLine() throws IOException { return new String(in.readLine()); } private String nextToken() throws IOException { while (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(in.readLine()); } return tokenizer.nextToken(); } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 6
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
f34fb35982cd16a921c80ee23da86f5f
train_003.jsonl
1381419000
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes.Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy.Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more.Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing.
256 megabytes
import java.util.*; public class d { public static void main(String[] args) { Scanner input = new Scanner(System.in); String s = input.next(); int n = s.length(); int ms = 0, totms = 0, res = 0, max = 0, totfs = 0, last = 0; for(int i = 0; i<n; i++) { char c = s.charAt(i); if(c == 'M') { totms++; } else { if(totfs == 0) { max = last = i; totfs++; continue; } if(totms == 0 || i - totfs > last) last = i - totfs; else last++; max = last; totfs++; } } System.out.println(max+res); } }
Java
["MFM", "MMFF", "FFMMM"]
1 second
["1", "3", "0"]
NoteIn the first test case the sequence of changes looks as follows: MFM  →  FMM.The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF  →  MFMF  →  FMFM  →  FFMM.
Java 6
standard input
[ "dp", "constructive algorithms" ]
8423f334ef789ba1238d34f70e7cbbc8
The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position.
2,000
Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0.
standard output
PASSED
1f965387abce4c56990e2fad6d7e2bea
train_003.jsonl
1305299400
Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical.Valera absolutely accidentally got a piece of ancient parchment on which an array of numbers was written. He immediately thought that the numbers in this array were not random. As a result of extensive research Valera worked out a wonderful property that a magical array should have: an array is defined as magic if its minimum and maximum coincide.He decided to share this outstanding discovery with you, but he asks you for help in return. Despite the tremendous intelligence and wit, Valera counts very badly and so you will have to complete his work. All you have to do is count the number of magical subarrays of the original array of numbers, written on the parchment. Subarray is defined as non-empty sequence of consecutive elements.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(in.readLine()); int[] a = new int[n]; String q[] = in.readLine().split(" "); for (int i = 0; i < a.length; i++) { a[i] = Integer.parseInt(q[i]); } long cont = 0; for (int i = 0; i < a.length; i++) { long c = 1; for (int j = (int)c; j < a.length - i; j++) { if (a[i] == a[i + (int)c]) { c++; } else { break; } } i--; i += c; cont+=c*(c+1)/2; } System.out.println(cont); } }
Java
["4\n2 1 1 4", "5\n-2 -2 -2 0 1"]
2 seconds
["5", "8"]
NoteNotes to sample tests:Magical subarrays are shown with pairs of indices [a;b] of the beginning and the end.In the first sample: [1;1], [2;2], [3;3], [4;4], [2;3].In the second sample: [1;1], [2;2], [3;3], [4;4], [5;5], [1;2], [2;3], [1;3].
Java 7
standard input
[ "combinatorics", "implementation" ]
0b229ddf583949d43d6f1728e38c3cad
The first line of the input data contains an integer n (1 ≀ n ≀ 105). The second line contains an array of original integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109).
1,300
Print on the single line the answer to the problem: the amount of subarrays, which are magical. Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is recommended to use cin, cout streams (you can also use the %I64d specificator).
standard output
PASSED
ed95d5f5270db243db89d90b15054662
train_003.jsonl
1305299400
Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical.Valera absolutely accidentally got a piece of ancient parchment on which an array of numbers was written. He immediately thought that the numbers in this array were not random. As a result of extensive research Valera worked out a wonderful property that a magical array should have: an array is defined as magic if its minimum and maximum coincide.He decided to share this outstanding discovery with you, but he asks you for help in return. Despite the tremendous intelligence and wit, Valera counts very badly and so you will have to complete his work. All you have to do is count the number of magical subarrays of the original array of numbers, written on the parchment. Subarray is defined as non-empty sequence of consecutive elements.
256 megabytes
/* * @author Sane */ import java.util.*; import java.util.Scanner; import java.io.File; import java.io.PrintWriter; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.OutputStreamWriter; import java.math.BigDecimal; import java.math.BigInteger; import javax.management.StringValueExp; public class TheMain { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); long ans = n; int[] a = new int[n]; for (int i = 0; i < n; ++i) a[i] = sc.nextInt(); int pos = 0; while (pos < n) { long len = 1; while (pos + 1 < n && a[pos+1] == a[pos]) { ++len; ++pos; } ++pos; ans += len*(len-1)/2; } System.out.println(ans); } }
Java
["4\n2 1 1 4", "5\n-2 -2 -2 0 1"]
2 seconds
["5", "8"]
NoteNotes to sample tests:Magical subarrays are shown with pairs of indices [a;b] of the beginning and the end.In the first sample: [1;1], [2;2], [3;3], [4;4], [2;3].In the second sample: [1;1], [2;2], [3;3], [4;4], [5;5], [1;2], [2;3], [1;3].
Java 7
standard input
[ "combinatorics", "implementation" ]
0b229ddf583949d43d6f1728e38c3cad
The first line of the input data contains an integer n (1 ≀ n ≀ 105). The second line contains an array of original integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109).
1,300
Print on the single line the answer to the problem: the amount of subarrays, which are magical. Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is recommended to use cin, cout streams (you can also use the %I64d specificator).
standard output
PASSED
558babac2bd56d0386fea40599d06138
train_003.jsonl
1305299400
Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical.Valera absolutely accidentally got a piece of ancient parchment on which an array of numbers was written. He immediately thought that the numbers in this array were not random. As a result of extensive research Valera worked out a wonderful property that a magical array should have: an array is defined as magic if its minimum and maximum coincide.He decided to share this outstanding discovery with you, but he asks you for help in return. Despite the tremendous intelligence and wit, Valera counts very badly and so you will have to complete his work. All you have to do is count the number of magical subarrays of the original array of numbers, written on the parchment. Subarray is defined as non-empty sequence of consecutive elements.
256 megabytes
import java.util.*; import java.io.*; public class Main{ BufferedReader in; StringTokenizer str = null; PrintWriter out; private String next() throws Exception{ while (str == null || !str.hasMoreElements()) str = new StringTokenizer(in.readLine()); return str.nextToken(); } private int nextInt() throws Exception{ return Integer.parseInt(next()); } public void run() throws Exception{ in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int n = nextInt(); int []a = new int[n]; for(int i = 0; i < n; ++i) a[i] = nextInt(); //Arrays.sort(a); long r = 0, c = 1; for(int i = 0; i + 1 < n; ++i){ if (a[i] == a[i + 1]){ c++; }else { r+=c*(c+1)/2; c = 1; } } r+=c*(c+1)/2; out.println(r); out.close(); } public static void main(String args[]) throws Exception{ new Main().run(); } }
Java
["4\n2 1 1 4", "5\n-2 -2 -2 0 1"]
2 seconds
["5", "8"]
NoteNotes to sample tests:Magical subarrays are shown with pairs of indices [a;b] of the beginning and the end.In the first sample: [1;1], [2;2], [3;3], [4;4], [2;3].In the second sample: [1;1], [2;2], [3;3], [4;4], [5;5], [1;2], [2;3], [1;3].
Java 7
standard input
[ "combinatorics", "implementation" ]
0b229ddf583949d43d6f1728e38c3cad
The first line of the input data contains an integer n (1 ≀ n ≀ 105). The second line contains an array of original integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109).
1,300
Print on the single line the answer to the problem: the amount of subarrays, which are magical. Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is recommended to use cin, cout streams (you can also use the %I64d specificator).
standard output
PASSED
969290e8aff56b7f76bc15fa0f458a41
train_003.jsonl
1305299400
Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical.Valera absolutely accidentally got a piece of ancient parchment on which an array of numbers was written. He immediately thought that the numbers in this array were not random. As a result of extensive research Valera worked out a wonderful property that a magical array should have: an array is defined as magic if its minimum and maximum coincide.He decided to share this outstanding discovery with you, but he asks you for help in return. Despite the tremendous intelligence and wit, Valera counts very badly and so you will have to complete his work. All you have to do is count the number of magical subarrays of the original array of numbers, written on the parchment. Subarray is defined as non-empty sequence of consecutive elements.
256 megabytes
import java.util.Scanner; public class MagicArray { public static void main(String[] args) { Scanner flujo = new Scanner(System.in); int a = flujo.nextInt(); int[] arr = new int[a]; long cont = 0; arr[0] = flujo.nextInt(); int act = arr[0]; long oc = 1; for (int i = 1; i < a; i++) { arr[i] = flujo.nextInt(); if (act != arr[i]) { cont += oc * (oc + 1) / 2; act = arr[i]; oc = 1; } else { oc++; } } cont += oc * (oc + 1) / 2; oc = 1; System.out.println(cont); } }
Java
["4\n2 1 1 4", "5\n-2 -2 -2 0 1"]
2 seconds
["5", "8"]
NoteNotes to sample tests:Magical subarrays are shown with pairs of indices [a;b] of the beginning and the end.In the first sample: [1;1], [2;2], [3;3], [4;4], [2;3].In the second sample: [1;1], [2;2], [3;3], [4;4], [5;5], [1;2], [2;3], [1;3].
Java 7
standard input
[ "combinatorics", "implementation" ]
0b229ddf583949d43d6f1728e38c3cad
The first line of the input data contains an integer n (1 ≀ n ≀ 105). The second line contains an array of original integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109).
1,300
Print on the single line the answer to the problem: the amount of subarrays, which are magical. Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is recommended to use cin, cout streams (you can also use the %I64d specificator).
standard output
PASSED
84f70f43be01090817d5cbe474b1c64c
train_003.jsonl
1305299400
Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical.Valera absolutely accidentally got a piece of ancient parchment on which an array of numbers was written. He immediately thought that the numbers in this array were not random. As a result of extensive research Valera worked out a wonderful property that a magical array should have: an array is defined as magic if its minimum and maximum coincide.He decided to share this outstanding discovery with you, but he asks you for help in return. Despite the tremendous intelligence and wit, Valera counts very badly and so you will have to complete his work. All you have to do is count the number of magical subarrays of the original array of numbers, written on the parchment. Subarray is defined as non-empty sequence of consecutive elements.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner flujo = new Scanner(System.in); int a = flujo.nextInt(); int[] arr = new int[a]; long cont = 0; arr[0] = flujo.nextInt(); int act = arr[0]; long oc = 1; for (int i = 1; i < a; i++) { arr[i] = flujo.nextInt(); if (act != arr[i]) { cont += oc * (oc + 1) / 2; act = arr[i]; oc = 1; } else { oc++; } } cont += oc * (oc + 1) / 2; oc = 1; System.out.println(cont); } }
Java
["4\n2 1 1 4", "5\n-2 -2 -2 0 1"]
2 seconds
["5", "8"]
NoteNotes to sample tests:Magical subarrays are shown with pairs of indices [a;b] of the beginning and the end.In the first sample: [1;1], [2;2], [3;3], [4;4], [2;3].In the second sample: [1;1], [2;2], [3;3], [4;4], [5;5], [1;2], [2;3], [1;3].
Java 7
standard input
[ "combinatorics", "implementation" ]
0b229ddf583949d43d6f1728e38c3cad
The first line of the input data contains an integer n (1 ≀ n ≀ 105). The second line contains an array of original integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109).
1,300
Print on the single line the answer to the problem: the amount of subarrays, which are magical. Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is recommended to use cin, cout streams (you can also use the %I64d specificator).
standard output
PASSED
87dc91c885051526eec21fb770a17510
train_003.jsonl
1305299400
Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical.Valera absolutely accidentally got a piece of ancient parchment on which an array of numbers was written. He immediately thought that the numbers in this array were not random. As a result of extensive research Valera worked out a wonderful property that a magical array should have: an array is defined as magic if its minimum and maximum coincide.He decided to share this outstanding discovery with you, but he asks you for help in return. Despite the tremendous intelligence and wit, Valera counts very badly and so you will have to complete his work. All you have to do is count the number of magical subarrays of the original array of numbers, written on the parchment. Subarray is defined as non-empty sequence of consecutive elements.
256 megabytes
import java.awt.geom.Ellipse2D; import java.awt.geom.Rectangle2D; import java.io.IOException; import java.io.PrintWriter; import java.util.*; import java.math.*; import java.io.InputStream; public class main { static final long mod = 1000000007; public static void main(String[] args) { InputReader in = new InputReader(System.in); //Scanner in = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); int n = in.readInt(); int [] a = new int[n]; long ans = 0; for(int i = 0; i < n; ++i) { a[i] = in.readInt(); } for(int i = 0; i < n; ++i) { int cnt = 0; while (i + cnt < n && a[i] == a[i + cnt]) ++cnt; ans += ((long)cnt * (cnt + 1)) / 2; i += cnt - 1; } out.println(ans); out.flush(); } } class InputReader { private final InputStream stream; private final byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int 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 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 interface SpaceCharFilter { public boolean isSpaceChar(int ch); } }
Java
["4\n2 1 1 4", "5\n-2 -2 -2 0 1"]
2 seconds
["5", "8"]
NoteNotes to sample tests:Magical subarrays are shown with pairs of indices [a;b] of the beginning and the end.In the first sample: [1;1], [2;2], [3;3], [4;4], [2;3].In the second sample: [1;1], [2;2], [3;3], [4;4], [5;5], [1;2], [2;3], [1;3].
Java 7
standard input
[ "combinatorics", "implementation" ]
0b229ddf583949d43d6f1728e38c3cad
The first line of the input data contains an integer n (1 ≀ n ≀ 105). The second line contains an array of original integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109).
1,300
Print on the single line the answer to the problem: the amount of subarrays, which are magical. Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is recommended to use cin, cout streams (you can also use the %I64d specificator).
standard output
PASSED
6ef7b964cb840a72434638eef1f8b4d1
train_003.jsonl
1305299400
Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical.Valera absolutely accidentally got a piece of ancient parchment on which an array of numbers was written. He immediately thought that the numbers in this array were not random. As a result of extensive research Valera worked out a wonderful property that a magical array should have: an array is defined as magic if its minimum and maximum coincide.He decided to share this outstanding discovery with you, but he asks you for help in return. Despite the tremendous intelligence and wit, Valera counts very badly and so you will have to complete his work. All you have to do is count the number of magical subarrays of the original array of numbers, written on the parchment. Subarray is defined as non-empty sequence of consecutive elements.
256 megabytes
//package codeforces; 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.StreamTokenizer; public class CodeForces { public static void main(String[] args) throws FileNotFoundException, IOException { MyScanner sc = new MyScanner(System.in); int n = sc.nextInt(); long[] sum = new long[n + 1]; for (int i = 1; i < n + 1; i++) { sum[i] = sum[i - 1] + i; } long all = 0; int now = 1; int prev = sc.nextInt(); for (int i = 0; i < n - 1; i++) { int num = sc.nextInt(); if (num == prev) { now++; } else { all += sum[now]; now = 1; prev = num; } } all += sum[now]; System.out.println(all); } } class MyScanner { StreamTokenizer st; public MyScanner(InputStream is) { st = new StreamTokenizer(is); } public MyScanner(File f) throws FileNotFoundException { BufferedReader in = new BufferedReader(new FileReader(f)); st = new StreamTokenizer(in); } public int nextInt() throws IOException { st.nextToken(); return ((int) st.nval); } public double nextDouble() throws IOException { st.nextToken(); return (st.nval); } public String nextString() throws IOException { st.nextToken(); return (st.sval); } }
Java
["4\n2 1 1 4", "5\n-2 -2 -2 0 1"]
2 seconds
["5", "8"]
NoteNotes to sample tests:Magical subarrays are shown with pairs of indices [a;b] of the beginning and the end.In the first sample: [1;1], [2;2], [3;3], [4;4], [2;3].In the second sample: [1;1], [2;2], [3;3], [4;4], [5;5], [1;2], [2;3], [1;3].
Java 7
standard input
[ "combinatorics", "implementation" ]
0b229ddf583949d43d6f1728e38c3cad
The first line of the input data contains an integer n (1 ≀ n ≀ 105). The second line contains an array of original integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109).
1,300
Print on the single line the answer to the problem: the amount of subarrays, which are magical. Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is recommended to use cin, cout streams (you can also use the %I64d specificator).
standard output
PASSED
215bf5c2414c3b0b4c7bd8fbbf186454
train_003.jsonl
1305299400
Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical.Valera absolutely accidentally got a piece of ancient parchment on which an array of numbers was written. He immediately thought that the numbers in this array were not random. As a result of extensive research Valera worked out a wonderful property that a magical array should have: an array is defined as magic if its minimum and maximum coincide.He decided to share this outstanding discovery with you, but he asks you for help in return. Despite the tremendous intelligence and wit, Valera counts very badly and so you will have to complete his work. All you have to do is count the number of magical subarrays of the original array of numbers, written on the parchment. Subarray is defined as non-empty sequence of consecutive elements.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class Solution { private BufferedReader in; private PrintWriter out; private StringTokenizer st; public String next() throws Exception { if (st == null || !st.hasMoreElements()) { st = new StringTokenizer(in.readLine()); } return st.nextToken(); } public int nextInt() throws Exception { return Integer.parseInt(next()); } public long nextLong() throws Exception { return Long.parseLong(next()); } public double nextDouble() throws Exception { return Double.parseDouble(next()); } public void run() throws Exception { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); int n = nextInt(); int[] a = new int[n]; for (int i = 0; i < n; ++i) { a[i] = nextInt(); } long ans = 0; for (int i = 0; i < n; ++i) { long c = 1; while(i + 1 < n && a[i] == a[i + 1]) { ++i; ++c; } ans += c * (c + 1) / 2; } out.println(ans); out.close(); } public static void main(String[] args) throws Exception { new Solution().run(); } }
Java
["4\n2 1 1 4", "5\n-2 -2 -2 0 1"]
2 seconds
["5", "8"]
NoteNotes to sample tests:Magical subarrays are shown with pairs of indices [a;b] of the beginning and the end.In the first sample: [1;1], [2;2], [3;3], [4;4], [2;3].In the second sample: [1;1], [2;2], [3;3], [4;4], [5;5], [1;2], [2;3], [1;3].
Java 7
standard input
[ "combinatorics", "implementation" ]
0b229ddf583949d43d6f1728e38c3cad
The first line of the input data contains an integer n (1 ≀ n ≀ 105). The second line contains an array of original integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109).
1,300
Print on the single line the answer to the problem: the amount of subarrays, which are magical. Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is recommended to use cin, cout streams (you can also use the %I64d specificator).
standard output
PASSED
d14124cca5e70f4dd8ec0e81288e23aa
train_003.jsonl
1305299400
Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical.Valera absolutely accidentally got a piece of ancient parchment on which an array of numbers was written. He immediately thought that the numbers in this array were not random. As a result of extensive research Valera worked out a wonderful property that a magical array should have: an array is defined as magic if its minimum and maximum coincide.He decided to share this outstanding discovery with you, but he asks you for help in return. Despite the tremendous intelligence and wit, Valera counts very badly and so you will have to complete his work. All you have to do is count the number of magical subarrays of the original array of numbers, written on the parchment. Subarray is defined as non-empty sequence of consecutive elements.
256 megabytes
import java.io.InputStreamReader; import java.io.IOException; import java.util.Arrays; 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 nasko */ 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } } class TaskB { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int[] arr = new int[n]; for(int i = 0; i < n; ++i) { arr[i] = in.nextInt(); } long[] len = new long[100001]; Arrays.fill(len,0); len[2] = 1; int last = 2; long res = 0; res += n; for(int i = 3; i <= 100000; ++i) { len[i] = len[i-1] + last; ++last; } int cnt = 1; for(int i = 0; i < n-1; ++i) { if(arr[i] == arr[i+1]) { ++cnt; } else { if(cnt > 1) res += len[cnt]; cnt = 1; } } if(cnt > 1) res += len[cnt]; out.println(res); } } 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
["4\n2 1 1 4", "5\n-2 -2 -2 0 1"]
2 seconds
["5", "8"]
NoteNotes to sample tests:Magical subarrays are shown with pairs of indices [a;b] of the beginning and the end.In the first sample: [1;1], [2;2], [3;3], [4;4], [2;3].In the second sample: [1;1], [2;2], [3;3], [4;4], [5;5], [1;2], [2;3], [1;3].
Java 7
standard input
[ "combinatorics", "implementation" ]
0b229ddf583949d43d6f1728e38c3cad
The first line of the input data contains an integer n (1 ≀ n ≀ 105). The second line contains an array of original integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109).
1,300
Print on the single line the answer to the problem: the amount of subarrays, which are magical. Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is recommended to use cin, cout streams (you can also use the %I64d specificator).
standard output
PASSED
55c46398acab75ca6b2d2d44586595de
train_003.jsonl
1305299400
Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical.Valera absolutely accidentally got a piece of ancient parchment on which an array of numbers was written. He immediately thought that the numbers in this array were not random. As a result of extensive research Valera worked out a wonderful property that a magical array should have: an array is defined as magic if its minimum and maximum coincide.He decided to share this outstanding discovery with you, but he asks you for help in return. Despite the tremendous intelligence and wit, Valera counts very badly and so you will have to complete his work. All you have to do is count the number of magical subarrays of the original array of numbers, written on the parchment. Subarray is defined as non-empty sequence of consecutive elements.
256 megabytes
import java.util.*; import static java.lang.Math.*; import java.awt.Point; import java.io.*; public class A { static Scanner sc = new Scanner(new BufferedInputStream(System.in)); public static void main(String[] args) { int n = ni(); long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nl(); long l = a[0]; long c = 0; long an = 0; for (int i = 0; i < n; i++) { long cr = a[i]; if (l == cr) { c++; // System.out.println("i: " + i + " " + l + " " + cr); } else { // System.out.println(cr + "--" + l); an += c(c); c = 1; l = cr; } if(i == n -1) an += c(c); } System.out.println(an); } private static long c(long c) { if (c == 1) { return 1; } long x = 0; long cop = c; while (c > 0) { // System.out.println(cop + " "+ c); x += cop -c + 1; // System.out.println("X: " + x); c--; } // System.out.println(cop + " CPOP " + x); return x; } // private static long f(long cop) { // long a = 1; // while (cop > 1) { // a *= cop; // cop--; // } //// System.out.println("F: " + a); // return a; // } static String n() { return sc.next(); } static int ni() { return Integer.valueOf(n()).intValue(); } static long nl() { return Long.valueOf(n()).longValue(); } }
Java
["4\n2 1 1 4", "5\n-2 -2 -2 0 1"]
2 seconds
["5", "8"]
NoteNotes to sample tests:Magical subarrays are shown with pairs of indices [a;b] of the beginning and the end.In the first sample: [1;1], [2;2], [3;3], [4;4], [2;3].In the second sample: [1;1], [2;2], [3;3], [4;4], [5;5], [1;2], [2;3], [1;3].
Java 7
standard input
[ "combinatorics", "implementation" ]
0b229ddf583949d43d6f1728e38c3cad
The first line of the input data contains an integer n (1 ≀ n ≀ 105). The second line contains an array of original integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109).
1,300
Print on the single line the answer to the problem: the amount of subarrays, which are magical. Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is recommended to use cin, cout streams (you can also use the %I64d specificator).
standard output
PASSED
fa74e4d131e55ae8bc46c830de500efa
train_003.jsonl
1305299400
Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical.Valera absolutely accidentally got a piece of ancient parchment on which an array of numbers was written. He immediately thought that the numbers in this array were not random. As a result of extensive research Valera worked out a wonderful property that a magical array should have: an array is defined as magic if its minimum and maximum coincide.He decided to share this outstanding discovery with you, but he asks you for help in return. Despite the tremendous intelligence and wit, Valera counts very badly and so you will have to complete his work. All you have to do is count the number of magical subarrays of the original array of numbers, written on the parchment. Subarray is defined as non-empty sequence of consecutive elements.
256 megabytes
import java.io.BufferedInputStream; import java.io.IOException; import java.io.PrintWriter; import java.math.BigInteger; 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.InputMismatchException; import java.util.LinkedList; import java.util.Map.Entry; import java.util.PriorityQueue; import java.util.Queue; import java.util.Random; import java.util.Set; import java.util.SortedSet; import java.util.Stack; import java.util.TreeMap; import java.util.TreeSet; public class Main { /********************************************** a list of common variables **********************************************/ private MyScanner scan = new MyScanner(); private PrintWriter out = new PrintWriter(System.out); private final double PI = Math.acos(-1.0); private final int SIZEN = (int)(1e5); private final int MOD = (int)(1e9 + 7); private final int[] DX = {0, 1, 0, -1}, DY = {-1, 0, 1, 0}; private ArrayList<Integer>[] edge; public void foo() { int n = scan.nextInt(); int[] a = new int[n]; for(int i = 0;i < n;++i) { a[i] = scan.nextInt(); } long ans = 0; int i = 0; while(i < n) { int j = i + 1; while(j < n) { if(a[i] != a[j]) { break; } ++j; } ans += (long)(j - i) * (j - i + 1); i = j; } out.println(ans / 2); } public static void main(String[] args) { Main m = new Main(); m.foo(); m.out.close(); } /********************************************** a list of common algorithms **********************************************/ /** * 1---Get greatest common divisor * @param a : first number * @param b : second number * @return greatest common divisor */ public long gcd(long a, long b) { return 0 == b ? a : gcd(b, a % b); } /** * 2---Get the distance from a point to a line * @param x1 the x coordinate of one endpoint of the line * @param y1 the y coordinate of one endpoint of the line * @param x2 the x coordinate of the other endpoint of the line * @param y2 the y coordinate of the other endpoint of the line * @param x the x coordinate of the point * @param y the x coordinate of the point * @return the distance from a point to a line */ public double getDist(long x1, long y1, long x2, long y2, long x, long y) { long a = y2 - y1; long b = x1 - x2; long c = y1 * (x2 - x1) - x1 * (y2 - y1); return Math.abs(a * x + b * y + c) / Math.sqrt(a * a + b * b); } /** * 3---Get the distance from one point to a segment (not a line) * @param x1 the x coordinate of one endpoint of the segment * @param y1 the y coordinate of one endpoint of the segment * @param x2 the x coordinate of the other endpoint of the segment * @param y2 the y coordinate of the other endpoint of the segment * @param x the x coordinate of the point * @param y the y coordinate of the point * @return the distance from one point to a segment (not a line) */ public double ptToSeg(long x1, long y1, long x2, long y2, long x, long y) { double cross = (x2 - x1) * (x - x1) + (y2 - y1) * (y - y1); if(cross <= 0) { return (x - x1) * (x - x1) + (y - y1) * (y - y1); } double d = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1); if(cross >= d) { return (x - x2) * (x - x2) + (y - y2) * (y - y2); } double r = cross / d; double px = x1 + (x2 - x1) * r; double py = y1 + (y2 - y1) * r; return (x - px) * (x - px) + (y - py) * (y - py); } /** * 4---KMP match, i.e. kmpMatch("abcd", "bcd") = 1, kmpMatch("abcd", "bfcd") = -1. * @param s: String to match. * @param t: String to be matched. * @return if can match, first index; otherwise -1. */ public int[] kmpMatch(char[] s, char[] t) { int n = s.length; int m = t.length; int[] next = new int[m + 1]; next[0] = -1; int j = -1; for(int i = 1;i < m;++i) { while(j >= 0 && t[i] != t[j + 1]) { j = next[j]; } if(t[i] == t[j + 1]) { ++j; } next[i] = j; } int[] left = new int[n + 1]; j = -1; for(int i = 0;i < n;++i) { while(j >= 0 && s[i] != t[j + 1]) { j = next[j]; } if(s[i] == t[j + 1]) { ++j; } if(j == m - 1) { left[i + 1] = i - m + 2; j = next[j]; } } for(int i = 1;i <= n;++i) { if(0 == left[i]) { left[i] = left[i - 1]; } } return left; } class MyScanner { private byte[] buf = new byte[1024]; private int curChar; private int numChars; BufferedInputStream bis = new BufferedInputStream(System.in); public int read() { if (-1 == numChars) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = bis.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int nextInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public 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 & 15; 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 & 15) * m; c = read(); } } return res * sgn; } public String next() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } private boolean isSpaceChar(int c) { return ' ' == c || '\n' == c || '\r' == c || '\t' == c || -1 == c; } } }
Java
["4\n2 1 1 4", "5\n-2 -2 -2 0 1"]
2 seconds
["5", "8"]
NoteNotes to sample tests:Magical subarrays are shown with pairs of indices [a;b] of the beginning and the end.In the first sample: [1;1], [2;2], [3;3], [4;4], [2;3].In the second sample: [1;1], [2;2], [3;3], [4;4], [5;5], [1;2], [2;3], [1;3].
Java 7
standard input
[ "combinatorics", "implementation" ]
0b229ddf583949d43d6f1728e38c3cad
The first line of the input data contains an integer n (1 ≀ n ≀ 105). The second line contains an array of original integers a1, a2, ..., an ( - 109 ≀ ai ≀ 109).
1,300
Print on the single line the answer to the problem: the amount of subarrays, which are magical. Please do not use the %lld specificator to read or write 64-bit numbers in C++. It is recommended to use cin, cout streams (you can also use the %I64d specificator).
standard output
PASSED
93c56392201b7f5dc9c6deab3e4a6c5a
train_003.jsonl
1427387400
Pasha got a very beautiful string s for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |s| from left to right, where |s| is the length of the given string.Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent m days performing the following transformations on his stringΒ β€”Β each day he chose integer ai and reversed a piece of string (a segment) from position ai to position |s| - ai + 1. It is guaranteed that 2Β·ai ≀ |s|.You face the following task: determine what Pasha's string will look like after m days.
256 megabytes
import java.util.Scanner; public class B { public static void main(String[] args) { Scanner in = new Scanner(System.in); String str = in.nextLine(); if (str == null || str.isEmpty()) { System.out.println(str); return; } char[] chars = str.toCharArray(); int n = chars.length; int days = in.nextInt(); int[] swaps = new int[n / 2]; for (int i = 0; i < days; i++) { int pos = in.nextInt(); swaps[pos - 1] += 1; } int count = 0; for (int i = 0; i < n / 2; i++) { swaps[i] += count; if (swaps[i] > count) count+=swaps[i]-count; } for (int i = 0; i < n / 2; i++) { if ((swaps[i] & 1) == 1) swap(chars, i, n - i - 1); } System.out.println(new String(chars)); } private static void swap(char[] chars, int i, int j) { char temp = chars[i]; chars[i] = chars[j]; chars[j] = temp; } }
Java
["abcdef\n1\n2", "vwxyz\n2\n2 2", "abcdef\n3\n1 2 3"]
2 seconds
["aedcbf", "vwxyz", "fbdcea"]
null
Java 8
standard input
[ "constructive algorithms", "greedy", "math", "strings" ]
9d46ae53e6dc8dc54f732ec93a82ded3
The first line of the input contains Pasha's string s of length from 2 to 2Β·105 characters, consisting of lowercase Latin letters. The second line contains a single integer m (1 ≀ m ≀ 105)Β β€”Β  the number of days when Pasha changed his string. The third line contains m space-separated elements ai (1 ≀ ai; 2Β·ai ≀ |s|)Β β€”Β the position from which Pasha started transforming the string on the i-th day.
1,400
In the first line of the output print what Pasha's string s will look like after m days.
standard output
PASSED
cec429a7f0c40539d26a3d71a0136453
train_003.jsonl
1427387400
Pasha got a very beautiful string s for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |s| from left to right, where |s| is the length of the given string.Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent m days performing the following transformations on his stringΒ β€”Β each day he chose integer ai and reversed a piece of string (a segment) from position ai to position |s| - ai + 1. It is guaranteed that 2Β·ai ≀ |s|.You face the following task: determine what Pasha's string will look like after m days.
256 megabytes
import java.io.*; import java.util.*; public class B { public static void main(String[] args)throws IOException { BufferedReader ob = new BufferedReader(new InputStreamReader(System.in)); StringBuffer sb=new StringBuffer(); char s[]=ob.readLine().toCharArray(); int m=Integer.parseInt(ob.readLine()); String str[]=ob.readLine().split(" "); int a[]=new int[m]; int vis[]=new int[s.length+1]; for(int i=0;i<m;i++) { a[i]=Integer.parseInt(str[i])-1; vis[a[i]]++; vis[s.length-(a[i])]--; } int sum=0; for(int i=0;i<s.length;i++) { sum+=vis[i]; sb.append(sum%2==0?s[i]:s[s.length-1-i]); } System.out.println(sb); } }
Java
["abcdef\n1\n2", "vwxyz\n2\n2 2", "abcdef\n3\n1 2 3"]
2 seconds
["aedcbf", "vwxyz", "fbdcea"]
null
Java 8
standard input
[ "constructive algorithms", "greedy", "math", "strings" ]
9d46ae53e6dc8dc54f732ec93a82ded3
The first line of the input contains Pasha's string s of length from 2 to 2Β·105 characters, consisting of lowercase Latin letters. The second line contains a single integer m (1 ≀ m ≀ 105)Β β€”Β  the number of days when Pasha changed his string. The third line contains m space-separated elements ai (1 ≀ ai; 2Β·ai ≀ |s|)Β β€”Β the position from which Pasha started transforming the string on the i-th day.
1,400
In the first line of the output print what Pasha's string s will look like after m days.
standard output
PASSED
b01b613595871c4d13029eebf23ba77d
train_003.jsonl
1427387400
Pasha got a very beautiful string s for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |s| from left to right, where |s| is the length of the given string.Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent m days performing the following transformations on his stringΒ β€”Β each day he chose integer ai and reversed a piece of string (a segment) from position ai to position |s| - ai + 1. It is guaranteed that 2Β·ai ≀ |s|.You face the following task: determine what Pasha's string will look like after m days.
256 megabytes
//package merofeev.contests.codeforces.rnd297; import java.util.Scanner; import java.util.stream.Stream; /** * @author m-erofeev * @since 26.03.15 */ public class B { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str = scanner.nextLine(); String days = scanner.nextLine(); String changes = scanner.nextLine(); String sol = solution(str, changes); System.out.println(sol); } public static String solution(String str, String changes) { char[] chars = str.toCharArray(); boolean[] reverse = new boolean[chars.length]; int[] changesAi = Stream.of(changes.split(" ")).mapToInt(Integer::valueOf).sorted().toArray(); boolean rev = false; for (int i = 0, changeI = 0; i < reverse.length; ) { if (changeI == changesAi.length) { reverse[i] = rev; i++; } else if (changesAi[changeI] - 1 == i) { rev = !rev; reverse[i] = rev; changeI++; } else { reverse[i] = rev; i++; } } for (int i = 0, j = chars.length - 1; i < j; i++, j--) { if (reverse[i]) { char t = chars[i]; chars[i] = chars[j]; chars[j] = t; } } return new String(chars); } }
Java
["abcdef\n1\n2", "vwxyz\n2\n2 2", "abcdef\n3\n1 2 3"]
2 seconds
["aedcbf", "vwxyz", "fbdcea"]
null
Java 8
standard input
[ "constructive algorithms", "greedy", "math", "strings" ]
9d46ae53e6dc8dc54f732ec93a82ded3
The first line of the input contains Pasha's string s of length from 2 to 2Β·105 characters, consisting of lowercase Latin letters. The second line contains a single integer m (1 ≀ m ≀ 105)Β β€”Β  the number of days when Pasha changed his string. The third line contains m space-separated elements ai (1 ≀ ai; 2Β·ai ≀ |s|)Β β€”Β the position from which Pasha started transforming the string on the i-th day.
1,400
In the first line of the output print what Pasha's string s will look like after m days.
standard output
PASSED
a810f77bac92af31f34faa0baf1794f3
train_003.jsonl
1427387400
Pasha got a very beautiful string s for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |s| from left to right, where |s| is the length of the given string.Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent m days performing the following transformations on his stringΒ β€”Β each day he chose integer ai and reversed a piece of string (a segment) from position ai to position |s| - ai + 1. It is guaranteed that 2Β·ai ≀ |s|.You face the following task: determine what Pasha's string will look like after m days.
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. */ /** * * @author Alex */ import java.io.*; import java.util.*; public class JavaApplication2 { /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Scanner in=new Scanner(System.in); char[] c=in.next().toCharArray(); int slen=c.length; int m = in.nextInt();//Integer.parseInt(br.readLine()); int clen=(int)Math.ceil(slen/2); int[] changes = new int[clen]; int a, j,i; for (i=0;i<m;i++) { a= in.nextInt(); changes[a-1]++; } char ctmp; int sum=0; for ( i = 0; i < clen; i++) { sum+=changes[i]; if ((sum%2)==1) { ctmp = c[i]; c[i]=c[slen-i-1]; c[slen-i-1]=ctmp; } } System.out.print(c); // TODO code application logic here } }
Java
["abcdef\n1\n2", "vwxyz\n2\n2 2", "abcdef\n3\n1 2 3"]
2 seconds
["aedcbf", "vwxyz", "fbdcea"]
null
Java 8
standard input
[ "constructive algorithms", "greedy", "math", "strings" ]
9d46ae53e6dc8dc54f732ec93a82ded3
The first line of the input contains Pasha's string s of length from 2 to 2Β·105 characters, consisting of lowercase Latin letters. The second line contains a single integer m (1 ≀ m ≀ 105)Β β€”Β  the number of days when Pasha changed his string. The third line contains m space-separated elements ai (1 ≀ ai; 2Β·ai ≀ |s|)Β β€”Β the position from which Pasha started transforming the string on the i-th day.
1,400
In the first line of the output print what Pasha's string s will look like after m days.
standard output
PASSED
020c0874c85488d063e25c50333885b3
train_003.jsonl
1427387400
Pasha got a very beautiful string s for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |s| from left to right, where |s| is the length of the given string.Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent m days performing the following transformations on his stringΒ β€”Β each day he chose integer ai and reversed a piece of string (a segment) from position ai to position |s| - ai + 1. It is guaranteed that 2Β·ai ≀ |s|.You face the following task: determine what Pasha's string will look like after m days.
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. */ /** * * @author Alex */ import java.util.Scanner; public class JavaApplication2 { /** * @param args the command line arguments */ public static void main(String[] args) { Scanner in=new Scanner(System.in); char[] c=in.next().toCharArray(); int m = in.nextInt(); int[] changes = new int[(int)Math.ceil(c.length/2)]; for (int i=0;i<m;i++) { int a= in.nextInt(); changes[a-1]++; } int sum=0; for (int i = 0; i < changes.length; i++) { sum+=changes[i]; if ((sum%2)==1) { char ctmp = c[i]; c[i]=c[c.length-i-1]; c[c.length-i-1]=ctmp; } } System.out.print(c); } }
Java
["abcdef\n1\n2", "vwxyz\n2\n2 2", "abcdef\n3\n1 2 3"]
2 seconds
["aedcbf", "vwxyz", "fbdcea"]
null
Java 8
standard input
[ "constructive algorithms", "greedy", "math", "strings" ]
9d46ae53e6dc8dc54f732ec93a82ded3
The first line of the input contains Pasha's string s of length from 2 to 2Β·105 characters, consisting of lowercase Latin letters. The second line contains a single integer m (1 ≀ m ≀ 105)Β β€”Β  the number of days when Pasha changed his string. The third line contains m space-separated elements ai (1 ≀ ai; 2Β·ai ≀ |s|)Β β€”Β the position from which Pasha started transforming the string on the i-th day.
1,400
In the first line of the output print what Pasha's string s will look like after m days.
standard output
PASSED
3ac60a37e8e3c9e0acc8fabf067bcf34
train_003.jsonl
1427387400
Pasha got a very beautiful string s for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |s| from left to right, where |s| is the length of the given string.Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent m days performing the following transformations on his stringΒ β€”Β each day he chose integer ai and reversed a piece of string (a segment) from position ai to position |s| - ai + 1. It is guaranteed that 2Β·ai ≀ |s|.You face the following task: determine what Pasha's string will look like after m days.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Arrays; import java.util.StringTokenizer; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////SOLUTION /////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public class Main { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); public static void main(String[] args) throws IOException{ new Main().solve(); }//void main void solve() throws IOException{ char[] get=in.next().toCharArray(); int lk=get.length; boolean[] as=new boolean[lk]; int m=in.nextInt(),n=0; for(int i=0; i < m; i++){ n=in.nextInt()-1; as[n]=!as[n]; } for(int i=0;i<lk/2;i++){ if(as[i+1]) as[i+1] = !as[i]; else as[i+1] = as[i]; } char swap; for(int i=0; i < lk/2; i++){ if(as[i]){ swap=get[lk-i-1]; get[lk-i-1]=get[i]; get[i]=swap; } } out.println(String.valueOf(get)); in.close(); out.close(); } }//class Main /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////// FASTSCANNER ///////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class FastScanner { BufferedReader reader; StringTokenizer tokenizer; public FastScanner(InputStream stream) { this.reader = new BufferedReader(new InputStreamReader(stream)); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public int[] nextIntegerArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < a.length; i++) { a[i] = nextInt(); } return a; } public long[] nextLongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < a.length; i++) { a[i] = nextLong(); } return a; } public int nextInt(int radix) throws IOException { return Integer.parseInt(next(), radix); } public long nextLong() throws IOException { return Long.parseLong(next()); } public long nextLong(int radix) throws IOException { return Long.parseLong(next(), radix); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public BigInteger nextBigInteger() throws IOException { return new BigInteger(next()); } public BigInteger nextBigInteger(int radix) throws IOException { return new BigInteger(next(), radix); } public String next() throws IOException { if (tokenizer == null || !tokenizer.hasMoreTokens()) { tokenizer = new StringTokenizer(reader.readLine()); return this.next(); } return tokenizer.nextToken(); } public void close() throws IOException { this.reader.close(); } }
Java
["abcdef\n1\n2", "vwxyz\n2\n2 2", "abcdef\n3\n1 2 3"]
2 seconds
["aedcbf", "vwxyz", "fbdcea"]
null
Java 8
standard input
[ "constructive algorithms", "greedy", "math", "strings" ]
9d46ae53e6dc8dc54f732ec93a82ded3
The first line of the input contains Pasha's string s of length from 2 to 2Β·105 characters, consisting of lowercase Latin letters. The second line contains a single integer m (1 ≀ m ≀ 105)Β β€”Β  the number of days when Pasha changed his string. The third line contains m space-separated elements ai (1 ≀ ai; 2Β·ai ≀ |s|)Β β€”Β the position from which Pasha started transforming the string on the i-th day.
1,400
In the first line of the output print what Pasha's string s will look like after m days.
standard output
PASSED
38e5d93ed9f0353a869a07ecd597ace4
train_003.jsonl
1427387400
Pasha got a very beautiful string s for his birthday, the string consists of lowercase Latin letters. The letters in the string are numbered from 1 to |s| from left to right, where |s| is the length of the given string.Pasha didn't like his present very much so he decided to change it. After his birthday Pasha spent m days performing the following transformations on his stringΒ β€”Β each day he chose integer ai and reversed a piece of string (a segment) from position ai to position |s| - ai + 1. It is guaranteed that 2Β·ai ≀ |s|.You face the following task: determine what Pasha's string will look like after m days.
256 megabytes
import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); String s = sc.nextLine(); int days = sc.nextInt(); int length = s.length(); int[] ar = new int[length]; for(int i=0;i<days;i++){ int index = sc.nextInt(); ar[index-1]++; } int sum = 0; char[] res = s.toCharArray(); for(int j = 0;j<length/2;j++){ sum += ar[j]; if(sum % 2!=0){ char tmp=res[j]; res[j] = res[length-j-1]; res[length-j-1]=tmp; } } System.out.println(res); sc.close(); } }
Java
["abcdef\n1\n2", "vwxyz\n2\n2 2", "abcdef\n3\n1 2 3"]
2 seconds
["aedcbf", "vwxyz", "fbdcea"]
null
Java 8
standard input
[ "constructive algorithms", "greedy", "math", "strings" ]
9d46ae53e6dc8dc54f732ec93a82ded3
The first line of the input contains Pasha's string s of length from 2 to 2Β·105 characters, consisting of lowercase Latin letters. The second line contains a single integer m (1 ≀ m ≀ 105)Β β€”Β  the number of days when Pasha changed his string. The third line contains m space-separated elements ai (1 ≀ ai; 2Β·ai ≀ |s|)Β β€”Β the position from which Pasha started transforming the string on the i-th day.
1,400
In the first line of the output print what Pasha's string s will look like after m days.
standard output
PASSED
4756d1477712af5e27d05f36e2a444e9
train_003.jsonl
1560955500
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; public class Email { static Scanner sc = new Scanner(System.in); static PrintWriter pw = new PrintWriter(System.out), pw2 = new PrintWriter(System.out); public static void main(String[] args) throws IOException { int q=sc.nextInt(); loop:while(q-->0){ String s=sc.next(),t=sc.next(); int i=0,j=0; char last='?'; while(i<s.length()&&j<t.length()){ if(s.charAt(i)==t.charAt(j)) { last=s.charAt(i); i++;j++; continue; } else { while(j<t.length()&&t.charAt(j)==last) j++; if(j>=t.length()||s.charAt(i)!=t.charAt(j)){ System.out.println("NO"); continue loop; }else{ last=s.charAt(i); i++; j++; } } } boolean f=true; while(j<t.length()){ if(t.charAt(j)!=last) f=false; j++; } if(i==s.length()&&f) System.out.println("YES"); else System.out.println("NO"); } } public static <E> void print2D(E[][] arr) { for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr[i].length; j++) { pw.println(arr[i][j]); } } } public static int digitSum(String s) { int toReturn = 0; for (int i = 0; i < s.length(); i++) toReturn += Integer.parseInt(s.charAt(i) + " "); return toReturn; } public static boolean isPrime(long n) { if (n <= 1) return false; if (n <= 3) return true; if (n % 2 == 0 || n % 3 == 0) return false; for (long i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } public static long pow(long a, long pow) { return pow == 0 ? 1 : pow % 2 == 0 ? pow(a * a, pow >> 1) : a * pow(a * a, pow >> 1); } public static long sumNum(long a) { return a * (a + 1) / 2; } public static int gcd(int n1, int n2) { return n2 == 0 ? n1 : gcd(n2, n1 % n2); } public static long factorial(long a) { return a == 0 || a == 1 ? 1 : a * factorial(a - 1); } public static void sort(int arr[]) { shuffle(arr); Arrays.sort(arr); } public static void shuffle(int arr[]) { Random rnd = new Random(); for (int i = arr.length - 1; i > 0; i--) { int index = rnd.nextInt(i + 1); int temp = arr[index]; arr[index] = arr[i]; arr[i] = temp; } } public static Double[] solveQuadratic(double a, double b, double c) { double result = (b * b) - 4.0 * a * c; double r1; if (result > 0.0) { r1 = ((double) (-b) + Math.pow(result, 0.5)) / (2.0 * a); double r2 = ((double) (-b) - Math.pow(result, 0.5)) / (2.0 * a); return new Double[]{r1, r2}; } else if (result == 0.0) { r1 = (double) (-b) / (2.0 * a); return new Double[]{r1, r1}; } else { return new Double[]{null, null}; } } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(FileReader r) { br = new BufferedReader(r); } public Scanner(InputStream s) { br = new BufferedReader(new InputStreamReader(s)); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } static class pair<E1, E2> implements Comparable<pair> { E1 x; E2 y; pair(E1 x, E2 y) { this.x = x; this.y = y; } @Override public int compareTo(pair o) { return x.equals(o.x) ? (Integer) y - (Integer) o.y : (Integer) x - (Integer) o.x; } @Override public String toString() { return x + " " + y; } public double pointDis(pair p1) { return Math.sqrt(((Integer) y - (Integer) p1.y) * ((Integer) y - (Integer) p1.y) + ((Integer) x - (Integer) p1.x) * ((Integer) x - (Integer) p1.x)); } } }
Java
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
null
Java 8
standard input
[ "implementation", "strings" ]
6709c8078cd29e69cf1be285071b2527
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
1,200
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
standard output
PASSED
db64cfb471b6b953b6cc59e4b7b56c09
train_003.jsonl
1560955500
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
256 megabytes
import java.util.*; public class Main{ public static void main(String [] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); l: for(int i=0;i<n;i++){ String a = in.next(); String b = in.next(); if(a.length()>b.length()){ System.out.println("NO"); continue; } char prev = a.charAt(0); int count = 0; for(int z=0;z<b.length();z++){ if(count!=a.length()&&b.charAt(z)==a.charAt(count)){ prev = a.charAt(count); count++; } else if(b.charAt(z)!=prev){ System.out.println("NO"); continue l; } } System.out.println(count==a.length() ? "YES" : "NO"); } } }
Java
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
null
Java 8
standard input
[ "implementation", "strings" ]
6709c8078cd29e69cf1be285071b2527
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
1,200
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
standard output
PASSED
c9e68484c5cc36168d9dfae556c20e91
train_003.jsonl
1560955500
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; public class AA{ public static void main(String[] args){ InputStream inputStream = System.in; InputReader in = new InputReader(inputStream); OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); Solver s = new Solver(); s.solve(in,out); out.close(); } static class Solver{ private boolean check(String s,String t){ int sl = s.length(); int tl = t.length(); if(tl<sl) return false; int i =0, j=0; while(i<sl && j<tl){ if(s.charAt(i)!=t.charAt(j)){ // Systemstem.out.println(""+s.charAt(i)+" "+t.charAt(j)); return false; } int sf = 1; for(int k=i+1;k<sl;k++){ if(s.charAt(k)==s.charAt(i)){ sf++; if(k==sl-1) i=sl-1; } else{ i = k-1; break; } } // System.out.println("sf="+sf); int tf = 1; for(int k=j+1;k<tl;k++){ if(t.charAt(k)==t.charAt(j)){ tf++; if(k==tl-1) j=k; } else{ j = k-1; break; } } // System.out.println("tf="+tf); if(sf>tf) return false; i++;j++; } if(i==sl && j==tl) return true; return false; } private void solve(InputReader in, PrintWriter out){ int n = in.nextInt(); while(n-->0){ String s = in.next(); String t = in.next(); if(check(s,t)) out.println("YES"); else out.println("NO"); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public long nextLong() { return Long.parseLong(next()); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
null
Java 8
standard input
[ "implementation", "strings" ]
6709c8078cd29e69cf1be285071b2527
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
1,200
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
standard output
PASSED
e2e2a3fda49f96596f4ab90a4fea2405
train_003.jsonl
1560955500
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.HashMap; import java.util.TreeMap; import java.util.Map; import java.util.Arrays; import java.util.Set; import java.util.HashSet; import java.util.Iterator; import java.util.Collections; import java.util. LinkedList; /* * * @author Riddle * */ public final class Email { final static long MOD = (long)1e9+7; static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String args[]) { FastReader reader = new FastReader(); PrintWriter out = new PrintWriter(System.out); int test = reader.nextInt(); for(int t =0;t<test;t++) { String a = reader.next(); String b = reader.next(); TreeMap<Character, Integer> map = new TreeMap(); TreeMap<Character, Integer> map2 = new TreeMap(); if(a.equals(b)) { out.println("YES"); continue; } for(char c : a.toCharArray()) { if(map.containsKey(c)) { map.put(c, map.get(c)+1); } else { map.put(c,1); } } for(char c : b.toCharArray()) { if(map2.containsKey(c)) { map2.put(c, map2.get(c)+1); } else { map2.put(c,1); } } ArrayList<Character> list1 = new ArrayList(map.keySet()); ArrayList<Character> list2 = new ArrayList(map2.keySet()); if(!list1.equals(list2)) { out.println("NO"); continue; } boolean result = false; char c1[] = a.toCharArray(); char c2[] = b.toCharArray(); if(c1[0]!=c2[0]||c1[c1.length-1]!=c2[c2.length-1]) { out.println("NO"); continue; } int i=0; int j=0; while(true&&i<c1.length&&j<c2.length) { char ca = c1[i]; char cb = c2[j]; int count1 = 0; int count2 = 0; while(i<c1.length) { if(c1[i]!=ca) { break; } i++; count1++; } while(j<c2.length) { if(c2[j]!=cb) { break; } j++; count2++; } if(cb!=ca) { result = true; break; } if(count2<count1) { result = true; break; } if((i<c1.length&&(!(j<c2.length)))||(j<c2.length&&(!(i<c1.length)))) { result = true; break; } } if(result) { out.println("NO"); } else { out.println("YES"); } } out.flush(); out.close(); } }
Java
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
null
Java 8
standard input
[ "implementation", "strings" ]
6709c8078cd29e69cf1be285071b2527
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
1,200
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
standard output
PASSED
aee71b054f23839cfb46ebfd0f4705f3
train_003.jsonl
1560955500
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
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 el-Bishoy */ 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); div21185BEmailFromPolycarp solver = new div21185BEmailFromPolycarp(); solver.solve(1, in, out); out.close(); } static class div21185BEmailFromPolycarp { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); StringBuilder stringBuilder = new StringBuilder(); String s1, s2; int arr[] = new int[2]; while (n-- > 0) { s1 = in.nextString(); s2 = in.nextString(); if (s2.length() < s1.length()) { stringBuilder.append("NO\n"); continue; } if (s2.length() == s1.length() && s1.equals(s2)) { stringBuilder.append("YES\n"); continue; } boolean good = true; int j = 0; int ii = 0; for (; ii < s1.length(); ) { char cuurent = s1.charAt(ii++); if (j == s2.length()) { good = false; break; } if (cuurent != s2.charAt(j++)) { good = false; break; } int cnts1 = 1; int cnts2 = 1; for (; ii < s1.length() && cuurent == s1.charAt(ii); ii++) { cnts1++; } for (; j < s2.length() && cuurent == s2.charAt(j); j++) { cnts2++; } if (cnts2 < cnts1) { good = false; break; } } if (good && j == s2.length()) stringBuilder.append("YES\n"); else stringBuilder.append("NO\n"); } out.print(stringBuilder); } } 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 print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void close() { writer.close(); } } 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 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 String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
null
Java 8
standard input
[ "implementation", "strings" ]
6709c8078cd29e69cf1be285071b2527
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
1,200
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
standard output
PASSED
472bb4c245e8f5771caf35287bf09b36
train_003.jsonl
1560955500
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
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 boolean check(String a,String b) { char[] s=a.toCharArray(); char[] t=b.toCharArray(); if(t.length<s.length||s[0]!=t[0]) return false; int i=0; int j=0; while(i<s.length&&j<t.length) { if(s[i]==t[j]) { i++; j++; } else if(i>0&&s[i-1]==t[j]) j++; else return false; } if(i!=s.length) return false; while(j<t.length) { if(t[j]==s[i-1]) j++; else return false; } return true; } public void solve(int testNumber, InputReader sc, PrintWriter out) { int n=sc.nextInt(); for(int i=0;i<n;i++) { String a=sc.next(); String b=sc.next(); if(check(a,b)) System.out.println("YES"); else System.out.println("NO"); } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } }
Java
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
null
Java 8
standard input
[ "implementation", "strings" ]
6709c8078cd29e69cf1be285071b2527
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
1,200
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
standard output
PASSED
e773f9c569e680e6e28379b9fcd32d4c
train_003.jsonl
1560955500
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
256 megabytes
/*package whatever //do not write package name here */ import java.io.*; import java.util.*; public class GFG { static Scanner sc=new Scanner(System.in); public static void main (String[] args) { int T=sc.nextInt(); while(T>0){ T--; String a=sc.next(); String b=sc.next(); int i=0,j=0,flag=0; if(a.length()>b.length()){ flag=1; } else{ int n=a.length(); int m=b.length(); while(i<n&&j<m){ if(a.charAt(i)==b.charAt(j)){ i++;j++; } else if(i==0){ flag=1;break;} else if(b.charAt(j)==b.charAt(j-1))j++; else {flag=1;break;} } if(j==m && i<n){flag=1;} j--; if(flag==0){ for(int l=j+1;l<m;l++){ if(b.charAt(l)!=b.charAt(j)) {flag=1;break;} } } } if(flag==0)System.out.println("YES"); else System.out.println("NO"); } } }
Java
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
null
Java 8
standard input
[ "implementation", "strings" ]
6709c8078cd29e69cf1be285071b2527
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
1,200
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
standard output
PASSED
19076f82d7fe7dab7ca6f0e79b19a279
train_003.jsonl
1560955500
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
256 megabytes
import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class Main implements Runnable { static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private SpaceCharFilter filter; private BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars==-1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if(numChars <= 0) return -1; } return buf[curChar++]; } public String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } public int nextInt() { int c = read(); while(isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if(c<'0'||c>'9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public double nextDouble() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } double res = 0; while (!isSpaceChar(c) && c != '.') { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } if (c == '.') { c = read(); double m = 1; while (!isSpaceChar(c)) { if (c == 'e' || c == 'E') return res * Math.pow(10, nextInt()); if (c < '0' || c > '9') throw new InputMismatchException(); m /= 10; res += (c - '0') * m; c = read(); } } return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } public static void main(String args[]) throws Exception { new Thread(null, new Main(),"Main",1<<26).start(); } public void run() { InputReader sc = new InputReader(System.in); PrintWriter w = new PrintWriter(System.out); int n=sc.nextInt(); while(n-->0) { char arr1[]=sc.next().toCharArray(); char arr2[]=sc.next().toCharArray(); if(arr1.length>arr2.length) { w.println("NO"); } else { int j=0; boolean flag=true; int count=0; while(j<arr2.length && arr1[0]==arr2[j]) { count++; j++; } if(count==0) { w.println("NO"); } else{ for(int i=1;i<arr1.length;i++) { if(arr1[i]==arr1[i-1]) { count--; } else { count=0; } while(j<arr2.length && arr2[j]==arr1[i]) { count++; j++; } if(count==0) { flag=false; break; } } while(flag && j<arr2.length) { if(arr1[arr1.length-1]!=arr2[j]) { flag=false; } j++; } if(flag) { w.println("YES"); } else { w.println("NO"); } } } } w.close(); } }
Java
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
null
Java 8
standard input
[ "implementation", "strings" ]
6709c8078cd29e69cf1be285071b2527
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
1,200
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
standard output
PASSED
0d6e6e7f809c67c666e7f6a1818fafd0
train_003.jsonl
1560955500
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
256 megabytes
import java.io.*; import java.util.*; public class Codeforces { public static void main(String[] args) throws IOException { BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); int t=Integer.parseInt(bf.readLine()); String[] outputs=new String[t]; for(int i=0;i<t;i++) { char[] a = bf.readLine().toCharArray(); char[] b = bf.readLine().toCharArray(); if (a.length > b.length) { outputs[i] = "NO"; } else { int s_a = 0; int s_b = 0; boolean match = true; while (s_a < a.length && s_b < b.length) { if (a[s_a] != b[s_b]) { if (s_a == 0) { match = false; break; } else { if (b[s_b] == b[s_b - 1]) { s_b += 1; } else { match = false; break; } } } else { s_a += 1; s_b += 1; } } if(s_a<a.length){ match=false; } if(match) { while (s_b < b.length) { if (b[s_b] != b[s_b - 1]){ match=false; break; } s_b++; } } if (match) { outputs[i] = "YES"; } else { outputs[i] = "NO"; } } } for(String output:outputs)System.out.println(output); } }
Java
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
null
Java 8
standard input
[ "implementation", "strings" ]
6709c8078cd29e69cf1be285071b2527
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
1,200
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
standard output
PASSED
0a209327ee41acf0310f596fb2117360
train_003.jsonl
1560955500
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
256 megabytes
import java.util.*; import java.io.*; import java.lang.*; public class Main{ public static void main(String[] args){ Scanner in = new Scanner(System.in); int n= in.nextInt(); for(int i=0;i<n;i++){ String str1 = in.next(); String str2 = in.next(); int k=0,flag =0; int l1 = str1.length(),l2 = str2.length(); for(int j=0;j<l2;j++){ if(k<l1&&str1.charAt(k)==str2.charAt(j)) k++; else if(j==0||str2.charAt(j)!=str2.charAt(j-1)) flag = 1; } if ((k==l1)&&(flag==0)) System.out.println("YES"); else System.out.println("NO"); } } }
Java
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
null
Java 8
standard input
[ "implementation", "strings" ]
6709c8078cd29e69cf1be285071b2527
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
1,200
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
standard output
PASSED
ef23e24c51a5534f3855a809f44435c2
train_003.jsonl
1560955500
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.IOException; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author caoash */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; FastScanner in = new FastScanner(inputStream); PrintWriter out = new PrintWriter(outputStream); BEmailFromPolycarp solver = new BEmailFromPolycarp(); solver.solve(1, in, out); out.close(); } static class BEmailFromPolycarp { public void solve(int testNumber, FastScanner br, PrintWriter pw) { int n = br.nextInt(); String[] s = new String[2 * n]; for (int i = 0; i < 2 * n; i++) { s[i] = br.nextString(); } for (int i = 0; i < 2 * n; i += 2) { String initString = s[i]; String newS = s[i + 1]; StringBuilder comp = new StringBuilder(); StringBuilder compInit = new StringBuilder(); int[] freqNew = new int[26]; int[] freqInit = new int[26]; comp.append(newS.charAt(0)); int cnt = 1; int[] cter = new int[Math.max(initString.length(), newS.length())]; int ind = 0; ; for (int j = 1; j < newS.length(); j++) { freqNew[newS.charAt(j) - 'a']++; if (newS.charAt(j) == newS.charAt(j - 1)) { cnt++; continue; } else { cter[ind] = cnt; ind++; cnt = 1; comp.append(newS.charAt(j)); } } cter[ind] = cnt; compInit.append(initString.charAt(0)); ind = 0; cnt = 1; boolean found = false; for (int j = 1; j < initString.length(); j++) { freqInit[initString.charAt(j) - 'a']++; if (initString.charAt(j) == initString.charAt(j - 1)) { cnt++; continue; } else { if (cter[ind] < cnt) { pw.println("NO"); found = true; break; } ind++; cnt = 1; compInit.append(initString.charAt(j)); } } if (!found) { if (cter[ind] < cnt) { pw.println("NO"); found = true; } } if (!found) { for (int it = 0; it < 26; it++) { if (freqNew[it] < freqInit[it]) { pw.println("NO"); found = true; break; } } if (!found) { if (comp.toString().equals(compInit.toString())) { pw.println("YES"); } else { pw.println("NO"); } } } } } } static class FastScanner { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private FastScanner.SpaceCharFilter filter; public FastScanner(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 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 String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
null
Java 8
standard input
[ "implementation", "strings" ]
6709c8078cd29e69cf1be285071b2527
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
1,200
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
standard output
PASSED
24d8169257ac12fdc5dfca97d80f4ca9
train_003.jsonl
1560955500
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class B { public static void main(String[] arg) throws IOException{ Reader.init(System.in); int n=Reader.nextInt(); while(n-->0) { String a1=Reader.next(); String a2=Reader.next(); int[] count=new int[26]; for(int i=0;i<a1.length();i++) { count[a1.charAt(i)-'a']+=1; } int i=0; for(i=0;i<a2.length();i++) { count[a2.charAt(i)-'a']-=1; } for(i=0;i<26;i++) { if(count[i]>=1) { System.out.println("NO"); break; } } if(i!=26) { continue; } int j=0; for(i=0;i<a1.length();i++) { char a=a1.charAt(i); if(j<a2.length() && a2.charAt(j)==a) { j++; if(i+1<a1.length() && a1.charAt(i+1)!=a) { while(j<a2.length() && a2.charAt(j)==a) { j++; // System.out.println(j); } } } else { System.out.println("NO"); break; } } if(i!=a1.length()) { continue; } char a=a1.charAt(a1.length()-1); while(j<a2.length() && a2.charAt(j)==a) { j++; } if(j!=a2.length()) { System.out.println("NO"); } else { System.out.println("YES"); } } } } class Reader { static BufferedReader reader; static StringTokenizer tokenizer; static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static long nextLong() throws IOException { return Long.parseLong(next()); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } }
Java
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
null
Java 8
standard input
[ "implementation", "strings" ]
6709c8078cd29e69cf1be285071b2527
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
1,200
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
standard output
PASSED
2d66a7f43d7857be3a1307e3e6d29e2d
train_003.jsonl
1560955500
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
256 megabytes
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); InputReader.OutputWriter out = new InputReader.OutputWriter(outputStream); int n = in.nextInt(); for (int i = 0; i < n; i++) { String a = in.next(); String b = in.next(); int [] freqA = freq(a); int [] freqB = freq(b); if(!check(freqA,freqB)) { out.println("NO"); } else { char [] aa = a.toCharArray(); char [] bb = b.toCharArray(); if(!firstCheck(aa,bb)) { out.println("NO"); } else { String sa = numRepresentation(aa); String sb = numRepresentation(bb); String[] ssa = sa.split("#"); String[] ssb = sb.split("#"); boolean flag = false; for (int j = 0; j < ssa.length; j++) { int num1 = Integer.parseInt(ssa[j]); int num2 = Integer.parseInt(ssb[j]); if (num2 < num1) { flag = true; out.println("NO"); break; } } if (!flag) { out.println("YES"); } } } } out.flush(); } private static boolean firstCheck(char [] aa, char [] bb) { char current = aa[0]; StringBuilder sa = new StringBuilder(); sa.append(current); for (int j = 1; j < aa.length; j++) { if(aa[j]!=current) { sa.append(aa[j]); current = aa[j]; } } StringBuilder sb = new StringBuilder(); current = bb[0]; sb.append(current); for (int j = 1; j < bb.length; j++) { if(bb[j]!=current) { sb.append(bb[j]); current = bb[j]; } } String saa = sa.toString(); String sbb = sb.toString(); return saa.equals(sbb); } private static String numRepresentation(char [] aa) { StringBuilder sa = new StringBuilder(); int current = aa[0]; int count = 1; for (int j = 1; j < aa.length; j++) { if(current!=aa[j]) { sa.append(count+"#"); current = aa[j]; count = 1; } else { count++; } } sa.append(count); return sa.toString(); } private static boolean check(int [] a, int [] b) { for (int i = 0; i < a.length; i++) { if(a[i] == 0 && b[i]!=0) return false; if(b[i]<a[i]) return false; } return true; } private static int[] freq(String s) { int [] f = new int[26]; for(char c : s.toCharArray()) { f[c-'a']++; } return f; } public static String maxRepeatedCharacters (String s, int max) { StringBuilder sb = new StringBuilder(); char last = ' '; int count = 0; for(char c : s.toCharArray()) { if(c != last) { count = 1; last = c; } else { count++; } if(count <= max) { sb.append(c); } } return sb.toString(); } private static int [] mergeTwoArrays(int [] a, int [] b) { int [] res = new int[a.length + b.length]; int i = 0; int j = 0; int index = 0; while (i<a.length && j<b.length) { if(a[i]<b[j]) { res[index++] = a[i++]; } else { res[index++] = b[j++]; } } System.out.println(i + " " + j); if(j == b.length - 1) { while (i<a.length) { res[index++] = a[i++]; } } else { while (j<b.length) { res[index++] = b[j++]; } } return res; } } class Point { private int i; private int j; public int getI() { return i; } public int getJ() { return j; } public Point(int i, int j) { this.i = i; this.j = j; } public String toString() { return i + " " + j; } } class InputReader extends BufferedReader { StringTokenizer tokenizer; public InputReader(InputStream inputStream) { super(new InputStreamReader(inputStream), 32768); } public InputReader(String filename) { super(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(filename))); } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(readLine()); } catch (IOException e) { throw new RuntimeException(); } } return tokenizer.nextToken(); } public Integer nextInt() { return Integer.valueOf(next()); } public Long nextLong() {return Long.valueOf(next());} static class OutputWriter extends PrintWriter { public OutputWriter(OutputStream outputStream) { super(outputStream); } public OutputWriter(Writer writer) { super(writer); } public OutputWriter(String filename) throws FileNotFoundException { super(filename); } public void close() { super.close(); } } }
Java
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
null
Java 8
standard input
[ "implementation", "strings" ]
6709c8078cd29e69cf1be285071b2527
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
1,200
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
standard output
PASSED
7b96dbba47413cf27a0f757f33ad1e6b
train_003.jsonl
1560955500
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
256 megabytes
import java.io.*; import java.util.*; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader in=new FastReader(); int t=in.nextInt(); for(int q=0;q<t;++q) { int i,j; int f=0,f1=0,f2=0; long cnt1=0,cnt=0,cnt3=0; int max=Integer.MIN_VALUE; int min=Integer.MAX_VALUE; String s1=in.next(); String s2=in.next(); int l1=s1.length(); int l2=s2.length(); char c5=s1.charAt(0); char c6=s2.charAt(0); if(c6!=c5) f=1; else { for(i=1,j=1;i<l1&&j<l2;) { char c1=s1.charAt(i); char c2=s2.charAt(j); char c3=s1.charAt(i-1); if(c1==c2) { ++i; ++j; } else { if(c2==c3) { ++j; } else { f=1; break; } } if(i==l1&&j<l2) f1=1; if(i<l1&&j==l2) f2=1; } if(f==0) { if(f2==1) f=1; if(j==l2&&i<l1) f=1; if(f1==1||(i==l1&&j<l2)) { for(int k=j;k<l2;++k) { char c1=s1.charAt(l1-1); char c2=s2.charAt(k); if(c1!=c2) { f=1; break; } } } } } if(f==1) System.out.println("NO"); else System.out.println("YES"); } } }
Java
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
null
Java 8
standard input
[ "implementation", "strings" ]
6709c8078cd29e69cf1be285071b2527
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
1,200
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
standard output
PASSED
514122b59f22b398a2c2497b230183a1
train_003.jsonl
1560955500
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.stream.Collectors; import java.util.regex.*; public class Program { private static PrintWriter out; private static <T> void mprintln(T ... ar){ for(T i: ar) out.print(i + " "); out.println(); } public static void main(String[] args) throws FileNotFoundException{ // Input from file // File inputFile = new File("JavaFile.txt"); // File outputFile = new File("JavaOutputFile.txt"); // FileReader fileReader = new FileReader(inputFile); // Here it ends MyScanner sc = new MyScanner(); // MyScanner sc = new MyScanner(fileReader); out = new PrintWriter(new BufferedOutputStream(System.out)); // Output to console // out = new PrintWriter(new PrintStream(outputFile)); // Output to file getAns(sc); out.close(); } // Global Variables private static void getAns(MyScanner sc){ int t = sc.ni(); testcase: while(t-- > 0){ char[] ar = sc.nn().toCharArray(), br = sc.nn().toCharArray(); ArrayList<Node> mapA = new ArrayList(), mapB = new ArrayList(); int count = 1; for(int i = 1; i < ar.length; i++){ if(ar[i] == ar[i - 1]) ++count; else{ mapA.add(new Node(ar[i - 1], count)); count = 1; } } mapA.add(new Node(ar[ar.length - 1], count)); count = 1; for(int i = 1; i < br.length; i++){ if(br[i] == br[i - 1]) ++count; else{ mapB.add(new Node(br[i - 1], count)); count = 1; } } mapB.add(new Node(br[br.length - 1], count)); // out.println(mapA); // out.println(mapB); if(mapA.size() != mapB.size()){ out.println("NO"); continue; } int i = 0; while(i < mapA.size()){ if(mapA.get(i).ch != mapB.get(i).ch || mapA.get(i).count > mapB.get(i).count){ out.println("NO"); continue testcase; } ++i; } out.println("YES"); } } static class Node{ char ch; int count; Node(char ch, int count){ this.ch = ch; this.count = count; } @Override public String toString(){ return ch + " " + count; } } static class MyScanner{ BufferedReader br; StringTokenizer st; MyScanner(FileReader fileReader){ br = new BufferedReader(fileReader); } MyScanner(){ br = new BufferedReader(new InputStreamReader(System.in)); } String nn(){ while(st == null || !st.hasMoreElements()){ try{ st = new StringTokenizer(br.readLine()); }catch(IOException e){ e.printStackTrace(); } } return st.nextToken(); } String nextLine(){ String ans = ""; try { ans = br.readLine(); } catch (IOException ex) { ex.printStackTrace(); } return ans; } char nc(){ return nn().charAt(0); } int ni(){ return Integer.parseInt(nn()); } long nl(){ return Long.parseLong(nn()); } double nd(){ return Double.parseDouble(nn()); } int[] niArr0(int n){ int[] ar = new int[n]; for(int i = 0; i < n; i++) ar[i] = ni(); return ar; } int[] niArr1(int n){ int[] ar = new int[n + 1]; for(int i = 1; i <= n; i++) ar[i] = ni(); return ar; } long[] nlArr0(int n){ long[] ar = new long[n]; for(int i = 0; i < n; i++) ar[i] = nl(); return ar; } long[] nlArr1(int n){ long[] ar = new long[n + 1]; for(int i = 1; i <= n; i++) ar[i] = nl(); return ar; } } }
Java
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
null
Java 8
standard input
[ "implementation", "strings" ]
6709c8078cd29e69cf1be285071b2527
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
1,200
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
standard output
PASSED
e1c5576b83eae828b165b3829b905b0a
train_003.jsonl
1560955500
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
256 megabytes
//package com.company; //import java.io.file.Paths; import java.util.*; public class Main { public static void main(String[] args) { // write your code here Scanner s=new Scanner(System.in); int n=s.nextInt(); while(n-->0){ char[] a=s.next().toCharArray(); char[] b=s.next().toCharArray(); int g=0;int ca=1;int i=1;int j=0;int cb=0;int flag=0; while(true){if(i==a.length) break;if(j==b.length){ flag=1;break; } if(g==0&&a[i]==a[i-1]) { ca++;i++;continue; }else g=1; if(a[i-1]==b[j]){ cb++;j++; }else{ if(cb<ca){ flag=1;break; }g=0;ca=1;cb=0; i++; if(i==a.length){ break; } }} if(flag==0){ for(int k=j;k<b.length;k++){ if(b[k]!=a[a.length-1]){ flag=1;break; }else cb++; }if(flag==0&&cb>=ca) System.out.println("YES"); else System.out.println("NO"); }else System.out.println("NO"); } } }
Java
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
null
Java 8
standard input
[ "implementation", "strings" ]
6709c8078cd29e69cf1be285071b2527
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
1,200
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
standard output
PASSED
cbdc0eab9c40c829c80fc1d07656b7be
train_003.jsonl
1560955500
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
256 megabytes
import java.io.*; import java.util.*; public class R568B { public static void main(String[] args) { JS scan = new JS(); int t = scan.nextInt(); PrintWriter out = new PrintWriter(System.out); loop:while(t-->0){ String a = scan.next(); String b = scan.next(); if(b.length()<a.length()){ System.out.println("NO"); continue; } int idx = 0; for(int i = 0;i<a.length();){ if(idx>=b.length()){ System.out.println("NO"); continue loop; } if(a.charAt(i)==b.charAt(idx)){ if(i<a.length()-1 && idx<b.length()-1){ if(a.charAt(i+1) == a.charAt(i) && b.charAt(idx+1) ==b.charAt(idx)){ idx++; i++; continue; } } if(idx<b.length()-1){ if(b.charAt(idx+1) == b.charAt(idx)){ idx++; continue; } } i++; idx++; continue; }else{ System.out.println("NO"); continue loop; } } if(idx==b.length()){ System.out.println("YES"); } else System.out.println("NO"); } } /* 1 ccccbbbb cccbbbbbbb 1 abb aaaab 1 amcmcmc ammmmmccccccmmmmcmcccccmmmm */ static class JS{ public int BS = 1<<16; public char NC = (char)0; byte[] buf = new byte[BS]; int bId = 0, size = 0; char c = NC; double num = 1; BufferedInputStream in; public JS() { in = new BufferedInputStream(System.in, BS); } public JS(String s) throws FileNotFoundException { in = new BufferedInputStream(new FileInputStream(new File(s)), BS); } public char nextChar(){ while(bId==size) { try { size = in.read(buf); }catch(Exception e) { return NC; } if(size==-1)return NC; bId=0; } return (char)buf[bId++]; } public int nextInt() { return (int)nextLong(); } public long nextLong() { num=1; boolean neg = false; if(c==NC)c=nextChar(); for(;(c<'0' || c>'9'); c = nextChar()) { if(c=='-')neg=true; } long res = 0; for(; c>='0' && c <='9'; c=nextChar()) { res = (res<<3)+(res<<1)+c-'0'; num*=10; } return neg?-res:res; } public double nextDouble() { double cur = nextLong(); return c!='.' ? cur:cur+nextLong()/num; } public String next() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c>32) { res.append(c); c=nextChar(); } return res.toString(); } public String nextLine() { StringBuilder res = new StringBuilder(); while(c<=32)c=nextChar(); while(c!='\n') { res.append(c); c=nextChar(); } return res.toString(); } public boolean hasNext() { if(c>32)return true; while(true) { c=nextChar(); if(c==NC)return false; else if(c>32)return true; } } } }
Java
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
null
Java 8
standard input
[ "implementation", "strings" ]
6709c8078cd29e69cf1be285071b2527
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
1,200
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
standard output
PASSED
bf91e439b1efbc49a72d8b25dd5673d7
train_003.jsonl
1560955500
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class B { public static void main(String[] args) throws IOException { Reader2.init(System.in); int Testcases=Reader2.nextInt(); while(Testcases!=0) { Testcases--; String ActualWord=Reader2.next(); String KeyboardedWord=Reader2.next(); int j=0; int k=0; int LenAW=ActualWord.length(); int LenKW=KeyboardedWord.length(); int bigger=0; if(LenAW>LenKW) { System.out.println("NO"); } else { boolean Flag=false; while(k!=LenKW) { if(((j)< LenAW )&& (ActualWord.charAt(j)==KeyboardedWord.charAt(k))) { j++; k++; } else if(((j-1)< LenAW && ((j-1)>=0) )&& (ActualWord.charAt(j-1)==KeyboardedWord.charAt(k))){ //j++; k++; } else { Flag=true; System.out.println("NO"); break; } } if(Flag==false && j==LenAW) { System.out.println("YES"); } else if(Flag==false){ System.out.println("NO"); } } } } } class Reader2 { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialise 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 long nextLong() throws IOException{ return Long.parseLong(next()); } static double nextDouble() throws IOException { return Double.parseDouble(next()); } }
Java
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
null
Java 8
standard input
[ "implementation", "strings" ]
6709c8078cd29e69cf1be285071b2527
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
1,200
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
standard output
PASSED
241ebd933ae6eea61070b99970bf83bd
train_003.jsonl
1560955500
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(reader.readLine()); for(int i = 0 ;i < N;i++){ String str1 = reader.readLine(); String str2 = reader.readLine(); System.out.println(request(str1,str2)); } } public static String request(String str1, String str2){ if(str2.length() >= str1.length()){ char[] arr1 = str1.toCharArray(); char[] arr2 = str2.toCharArray(); int i = 0; int j = 0; for(; j < arr1.length && (arr1.length - j <= arr2.length - i);j++){ if(arr2[i] != arr1[j]){ return "NO"; } else{ while(i < arr2.length && arr2[i] == arr1[j]){ if(j != arr1.length - 1){ if(arr2[i] != arr1[j+1]) i++; else{ i++; break; } }else{ i++; break; } } } } if(arr1.length - j <= arr2.length - i){ while(arr2.length - i > 0){ if(arr1[j-1] == arr2[i])i++; else return "NO"; } if(arr1[arr1.length - 1] == arr2[arr2.length - 1]) return "YES"; else return "NO"; } else{ return "NO"; } } else{ return "NO"; } } }
Java
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
null
Java 8
standard input
[ "implementation", "strings" ]
6709c8078cd29e69cf1be285071b2527
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
1,200
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
standard output
PASSED
4a4270135d9adf830dc1994031291464
train_003.jsonl
1560955500
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
256 megabytes
import java.util.*; public class q2568 { public static void main(String ... args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); String res[]=new String[n]; for(int i=0;i<n;i++) { String s1=sc.next(); String s2=sc.next(); if(s1==null && s2==null) { res[i]="YES"; continue; } else if(s1.length()==0 && s2.length()==0) { res[i]="YES"; continue; } else if(s1.length()==0 || s2.length()==0) { res[i]="NO"; continue; } if(s2.length()<s1.length()) { res[i]="NO"; continue; } int s2_ptr=0; int flag=0; for(int j=0;j<s1.length();j++) { char x=s1.charAt(j); int count=1; int k=j+1; for(k=j+1;k<s1.length();k++) { if(s1.charAt(k)==x) count++; else break; } char temp=s2.charAt(s2_ptr); if(temp!=x) { res[i]="NO"; flag=1; break; } int count1=0; while(s2_ptr<s2.length() && s2.charAt(s2_ptr)==x) { s2_ptr++; count1++; } if(s2_ptr>=s2.length() && k<s1.length()) { res[i]="NO"; flag=1; break; } if(count1<count) { res[i]="NO"; flag=1; break; } j=k-1; } if(s2_ptr<s2.length()) { res[i]="NO"; } else if(flag==0) res[i]="YES"; } for(int i=0;i<n;i++) System.out.println(res[i]); } }
Java
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
null
Java 8
standard input
[ "implementation", "strings" ]
6709c8078cd29e69cf1be285071b2527
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
1,200
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
standard output
PASSED
b595c16add7edd920b9335fc8e681a56
train_003.jsonl
1560955500
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
256 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.*; import java.lang.StringBuilder; public class codechef1 { 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[10000000]; // 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(); } } public static void main(String[] args) throws IOException { Scanner sc=new Scanner(System.in); Reader s=new Reader(); int n=sc.nextInt(); sc.nextLine(); outer: for(int t=0;t<n;t++) { String input = sc.nextLine(); String output = sc.nextLine(); char a[] = input.toCharArray(); char b[] = output.toCharArray(); char ch[]=new char[a.length]; int count[]=new int[a.length]; char current=a[0]; int temp=1; int pointer=0; for(int i=1;i<a.length;i++){ if(a[i]==current) temp++; else { ch[pointer]=current; count[pointer++]=temp; current=a[i]; temp=1; } } ch[pointer]=current; count[pointer++]=temp; int max=pointer; current = b[0]; temp=1; pointer=0; for(int i=1;i<b.length;i++){ if(b[i]==current) temp++; else { if(pointer==max){ System.out.println("NO"); continue outer; } char next=ch[pointer]; int val=count[pointer++]; if(next!=current || temp<val) { System.out.println("NO"); continue outer; } current=b[i]; temp=1; } } if(pointer==max){ System.out.println("NO"); continue outer; } char next=ch[pointer]; int val=count[pointer++]; if(next!=current || temp<val) { System.out.println("NO"); continue outer; } if(pointer!=max){ System.out.println("NO"); continue outer; } System.out.println("YES"); } } }
Java
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
null
Java 8
standard input
[ "implementation", "strings" ]
6709c8078cd29e69cf1be285071b2527
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
1,200
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
standard output
PASSED
78f7ce3c638ac8cb05d5432976eedae2
train_003.jsonl
1560955500
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
256 megabytes
// 21/8/20 10:40 AM Aug 2020 import java.util.*; public class _1185B { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while (t-- > 0) { String s1=sc.next(); String s2=sc.next(); boolean check=true; int i=0,j=0; while(i<s1.length() && j<s2.length()) { char ch1 = s1.charAt(i), ch2 = s2.charAt(j); int count1 = 0, count2 = 0; while (i < s1.length() && s1.charAt(i) == ch1) { count1++; i++; } while (j < s2.length() && s2.charAt(j) == ch2) { count2++; j++; } if (ch1 != ch2|| count2 < count1) { check = false; break; } else check=(i==s1.length() && j==s2.length()); } System.out.println(check?"YES":"NO"); } } }
Java
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
null
Java 8
standard input
[ "implementation", "strings" ]
6709c8078cd29e69cf1be285071b2527
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
1,200
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
standard output
PASSED
8a7dcf4092c45d1b608b056a0b99603d
train_003.jsonl
1560955500
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
256 megabytes
import java.util.Scanner; public class ProblemB { public static void main(String [] args) { Scanner scanner = new Scanner(System.in); int a = scanner.nextInt(); for(int i = 0; i < a; i++) { String s = scanner.next(); String z = scanner.next(); int k = 0; char cur = s.charAt(0); char last = z.charAt(0); if(last != cur || s.length() > z.length()) { System.out.println("NO"); continue; } boolean flag = true; for(int j = 1; j < z.length(); j++) { if(k < s.length() - 1){ k++; } cur = s.charAt(k); last = z.charAt(j); if(cur == last) { continue; }else if(last == z.charAt(j - 1)){ k--; }else { flag = false; break; } //System.out.println(cur + " " + last + k); } if(!flag || k != s.length() - 1) { System.out.println("NO"); }else { System.out.println("YES"); } } } }
Java
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
null
Java 8
standard input
[ "implementation", "strings" ]
6709c8078cd29e69cf1be285071b2527
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
1,200
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
standard output
PASSED
86d316995b8126c4cd63747c6bc7bc2d
train_003.jsonl
1560955500
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
256 megabytes
import java.util.Scanner; public final class EmailFromPolycarp { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); for (int i = 0; i < n; ++i) { boolean works = true; String correct = in.next(); String incorrect = in.next(); int correctIndex = 0; int incorrectIndex = 0; while (correctIndex < correct.length()) { char c = correct.charAt(correctIndex); int nb = nbOfSameLetter(correct, correctIndex, c); correctIndex += nb; int nbIncorrect = nbOfSameLetter(incorrect, incorrectIndex, c); incorrectIndex += nbIncorrect; if (nbIncorrect < nb) { works = false; } } if (incorrectIndex != incorrect.length()) { works = false; } System.out.println(works ? "YES" : "NO"); } in.close(); } private static int nbOfSameLetter(String s, int index, char c) { if (s.length() <= index) { return 0; } int i = 0; while (index + i < s.length() && s.charAt(index + i) == c) { ++i; } return i; } }
Java
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
null
Java 8
standard input
[ "implementation", "strings" ]
6709c8078cd29e69cf1be285071b2527
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
1,200
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
standard output
PASSED
10c6ec3825ef7f356c6913c853cb77fe
train_003.jsonl
1560955500
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; public class pre214 { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static class Data { char a; int n; Data(char a,int n) { this.a = a; this.n = n; } } public static void main(String args[]) { FastReader obj = new FastReader(); int tc = obj.nextInt(); while(tc--!=0) { String s1 = obj.next(),s2 = obj.next(); int s1i[] = new int[26],s0i[] = new int[26]; if(s2.length()>=s1.length()) { ArrayList<Data> con1 = new ArrayList<>(),con2 = new ArrayList<>(); char a1 = s1.charAt(0),a2 = s2.charAt(0); int count1 = 1,count2 = 1; for(int i=1;i<s1.length()-1;i++) { if(a1==s1.charAt(i)) count1++; else { con1.add(new Data(a1,count1)); a1 = s1.charAt(i); count1 = 1; } } if(a1==s1.charAt(s1.length()-1)) con1.add(new Data(a1,count1+1));else {con1.add(new Data(a1,count1));con1.add(new Data(s1.charAt(s1.length()-1),1));} for(int i=1;i<s2.length()-1;i++) { if(a2==s2.charAt(i)) count2++; else { con2.add(new Data(a2,count2)); a2 = s2.charAt(i); count2 = 1; } } if(a2==s2.charAt(s2.length()-1)) con2.add(new Data(a2,count2+1));else {con2.add(new Data(a2,count2));con2.add(new Data(s2.charAt(s2.length()-1),1));} if(con1.size()==con2.size()) { boolean flag = true; for(int i=0;i<con1.size();i++) if(con1.get(i).a!=con2.get(i).a || con1.get(i).n>con2.get(i).n) { flag = false; break; } System.out.println((flag)?"YES":"NO"); } else System.out.println("NO"); } else System.out.println("NO"); } } }
Java
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
null
Java 8
standard input
[ "implementation", "strings" ]
6709c8078cd29e69cf1be285071b2527
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
1,200
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
standard output
PASSED
4c41bd92acdc41d5bda557a3cc02b5bd
train_003.jsonl
1560955500
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
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 Sid */ 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); EmailFromPolycarp solver = new EmailFromPolycarp(); solver.solve(1, in, out); out.close(); } static class EmailFromPolycarp { public void solve(int testNumber, InputReader in, OutputWriter out) { int n = in.nextInt(); while (n-- > 0) { String str1 = in.nextString(); String str2 = in.nextString(); int start = str2.length() - 1; int pos = str1.length() - 1; while (pos <= start && str1.charAt(pos) == str2.charAt(start)) { if (pos != 0 && str2.charAt(start - 1) == str1.charAt(pos - 1)) { pos--; start--; } else { start--; } } if (pos == 0 && start == -1) { out.println("YES"); } else { out.println("NO"); } } } } 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 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 String nextString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } 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 print(Object... objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) { writer.print(' '); } writer.print(objects[i]); } } public void println(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } }
Java
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
null
Java 8
standard input
[ "implementation", "strings" ]
6709c8078cd29e69cf1be285071b2527
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
1,200
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
standard output
PASSED
8e9dd39fb081a2097304cc4c844ff1d2
train_003.jsonl
1560955500
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
256 megabytes
import java.util.*; import java.io.*; public class Exam { public static long mod = (long) Math.pow(10, 9)+7 ; public static InputReader sc = new InputReader(System.in); public static PrintWriter pw = new PrintWriter(System.out); public static int check2(int b4,int b3,int b2,int b1,String a[],String s,int x,int y){ int m=check(b4,b3,b2,b1,a,s,x,y); m+=check(b4,b3,b1,b2,a,s,x,y); m+=check(b4,b2,b3,b1,a,s,x,y); m+=check(b4,b2,b1,b3,a,s,x,y); m+=check(b4,b1,b2,b3,a,s,x,y); m+=check(b4,b1,b3,b2,a,s,x,y); return m; } public static int check(int a3,int a2,int a1,int a0,String a[],String s,int x,int y){ a3--; a2--; a1--; a0--; int k=0; int n=a.length; int m=a[0].length(); for(int i=0;i<s.length();i++){ if(s.charAt(i)=='3'){ x+=getx(a3); y+=gety(a3); } else if(s.charAt(i)=='2'){ x+=getx(a2); y+=gety(a2); } else if(s.charAt(i)=='1'){ x+=getx(a1); y+=gety(a1); } else if(s.charAt(i)=='0'){ x+=getx(a0); y+=gety(a0); } if(x>=0&&x<n&&y>=0&&y<m){ if(a[x].charAt(y)=='E') return 1; else if(a[x].charAt(y)=='#') return 0; else continue; } else return 0; } return 0; } public static int getx(int a){ if(a==0) return 1; else if(a==1) return -1; else return 0; } public static int gety(int a){ if(a==2) return 1; else if(a==3) return -1; else return 0; } void te(){ int z=sc.nextInt(); while(z-->0){ int n=sc.nextInt(); String s=sc.nextLine(); int st[]=new int[s.length()]; int t=-1; st[++t]=s.charAt(0); int xor[]=new int[n+1]; xor[t+1]=s.charAt(0); int l=s.charAt(0); for(int i=1;i<s.length();i++){ if(t>=0&&st[t]<s.charAt(i)){ t--; } else{ st[++t]=s.charAt(i); xor[t+1]=s.charAt(i)^xor[t]; } l+=xor[t+1]; } pw.println(l); } } public static int dp[][]=new int[500+1][500+1]; static{ for(int i=0;i<501;i++){ Arrays.fill(dp[i], -1); } } public static int color(int start,int end,int a[]){ int min=(int)1e9; if(dp[start][end]!=-1){ return dp[start][end]; } if(start==end){ dp[start][end]=1; return 1; } if(start+1==end&&a[start]==a[end]){ dp[start][end]=0; return 0; } min=color(start, end-1, a)+1; for(int i=start;i<end;i++){ if(a[i]==a[end]){ if(i-1>=start&&i+1<=end-1) min=Math.min(color(start,i-1,a)+color(i+1,end-1,a), min); else if(i-1>=start) min=Math.min(color(start,i-1,a), min); else if(i+1<=end-1) min=Math.min(color(i+1,end-1,a), min); else min=0; } } dp[start][end]=min; return min; } public static void main(String[] args) { // Code starts.. int z=sc.nextInt(); while(z-->0){ String a=sc.nextLine(); String b=sc.nextLine(); int f=0; if(a.length()>b.length()){ f=1; } int t=0,last=0; for(int i=0;i<b.length();i++){ if(t<a.length()&&a.charAt(t)==b.charAt(i)){ last=a.charAt(t); t++; } else if(b.charAt(i)!=last){ f=1; break; } } if(t!=a.length()) f=1; if(f==0) pw.println("YES"); else pw.println("NO"); } // Code ends... pw.flush(); pw.close(); } public static void shortestPathDfs(int a[][]){ StringBuilder out = new StringBuilder(); int n=a.length-1; int st[]=new int[n+1]; int t=0; st[t]=1; int w=0; int vi[]=new int[n+1]; Arrays.fill(vi, 1); int vis[]=new int[n+1]; vis[1]=1; ArrayList<Integer> r=new ArrayList<>(); int minw=(int)1e9; while(t!=-1){ int f=0; for(int i=vi[st[t]];i<=n;i++){ if(a[st[t]][i]!=0&&vis[i]==0){ w+=a[st[t]][i]; vi[st[t]]=i+1; st[++t]=i; f=1; vis[i]=1; if(st[t]==n){ f=0; if(w<minw){ minw=w; r=new ArrayList<>(); for(int j=0;j<=t;j++){ r.add(st[j]); } } } break; } } if(f==0){ vis[st[t]]=0; vi[st[t]]=1; if(t>0) w=w-a[st[t-1]][st[t]]; t--; } } if(r.size()!=0) for(int i=0;i<r.size();i++){ out.append(r.get(i)+" "); } else out.append("-1"); pw.println(out); } public static String reverseString(String s){ StringBuilder input1 = new StringBuilder(); input1.append(s); input1 = input1.reverse(); return input1.toString(); } public static int[] scanArray(int n){ int a[]=new int [n]; for(int i=0;i<n;i++) a[i]=sc.nextInt(); return a; } public static long[] scanLongArray(int n){ long a[]=new long [n]; for(int i=0;i<n;i++) a[i]=sc.nextLong(); return a; } public static String [] scanStrings(int n){ String a[]=new String [n]; for(int i=0;i<n;i++) a[i]=sc.nextLine(); return a; } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; private SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int snext() { if (snumChars == -1) throw new InputMismatchException(); if (curChar >= snumChars) { curChar = 0; try { snumChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (snumChars <= 0) return -1; } return buf[curChar++]; } public int nextInt() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public long nextLong() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } int sgn = 1; if (c == '-') { sgn = -1; c = snext(); } long res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = snext(); } while (!isSpaceChar(c)); return res * sgn; } public int[] nextIntArray(int n) { int a[] = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } public String readString() { int c = snext(); while (isSpaceChar(c)) { c = snext(); } StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isSpaceChar(c)); return res.toString(); } public String nextLine() { int c = snext(); while (isSpaceChar(c)) c = snext(); StringBuilder res = new StringBuilder(); do { res.appendCodePoint(c); c = snext(); } while (!isEndOfLine(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; } private boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } }
Java
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
null
Java 8
standard input
[ "implementation", "strings" ]
6709c8078cd29e69cf1be285071b2527
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
1,200
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
standard output
PASSED
1e98351bf0db011d93e3e99e0ea4c75a
train_003.jsonl
1560955500
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).For example, as a result of typing the word "hello", the following words could be printed: "hello", "hhhhello", "hheeeellllooo", but the following could not be printed: "hell", "helo", "hhllllooo".Note, that when you press a key, the corresponding symbol must appear (possibly, more than once). The keyboard is broken in a random manner, it means that pressing the same key you can get the different number of letters in the result.For each word in the letter, Methodius has guessed what word Polycarp actually wanted to write, but he is not sure about it, so he asks you to help him.You are given a list of pairs of words. For each pair, determine if the second word could be printed by typing the first one on Polycarp's keyboard.
256 megabytes
import javax.swing.*; import java.io.*; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import java.util.concurrent.LinkedBlockingQueue; public class Main { private static AWriter writer = new AWriter(System.out); private static AReader reader = new AReader(System.in); private static final int INF=0X3F3F3F3F; private static int MAXN; private static int MAXM=4000+5; private static int n,m,q,x,y; private static int[] mode={4,8,15,16,23,42}; private static int[] a,b,cnt; private static Map<Character,Integer> map=new HashMap<>(); public static void main(String[] args) throws IOException{ n=reader.nextInt(); for(int i=0;i<n;i++){ char[] a=reader.next().toCharArray(); char[] b=reader.next().toCharArray(); int tot=0; int j=0,k=0; boolean flag=true; while(j<a.length&&k<b.length){ int cnt1=0,cnt2=0; if(a[j]!=b[k]) { flag=false; break; } int mode=a[j]; while(j<a.length&&a[j]==mode) { j++; cnt1++; } while(k<b.length&&b[k]==mode) { k++; cnt2++; } if(cnt1>cnt2) flag=false; } if(j!=a.length||k!=b.length||!flag) writer.println("NO"); else writer.println("YES"); } writer.close(); reader.close(); } } class AReader implements Closeable { private BufferedReader reader; private StringTokenizer tokenizer; public AReader(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); tokenizer = new StringTokenizer(""); } private String innerNextLine() { try { return reader.readLine(); } catch (IOException ex) { return null; } } public boolean hasNext() { while (!tokenizer.hasMoreTokens()) { String nextLine = innerNextLine(); if (nextLine == null) { return false; } tokenizer = new StringTokenizer(nextLine); } return true; } public String nextLine() { tokenizer = new StringTokenizer(""); return innerNextLine(); } public String next() { hasNext(); return tokenizer.nextToken(); } public int nextInt() { return Integer.valueOf(next()); } public long nextLong() { return Long.valueOf(next()); } public double nextDouble() { return Double.valueOf(next()); } public BigDecimal nextBigDecimal(){ return new BigDecimal(next()); } public BigInteger nextBigInteger() { return new BigInteger(next()); } @Override public void close() throws IOException { reader.close(); } } // Fast writer for ACM By Azure99 class AWriter implements Closeable { private BufferedWriter writer; public AWriter(OutputStream outputStream) { writer = new BufferedWriter(new OutputStreamWriter(outputStream)); } public void print(Object object) throws IOException { writer.write(object.toString()); } public void println(Object object) throws IOException { writer.write(object.toString()); writer.write("\n"); } @Override public void close() throws IOException { writer.close(); } }
Java
["4\nhello\nhello\nhello\nhelloo\nhello\nhlllloo\nhello\nhelo", "5\naa\nbb\ncodeforces\ncodeforce\npolycarp\npoolycarpp\naaaa\naaaab\nabcdefghijklmnopqrstuvwxyz\nzabcdefghijklmnopqrstuvwxyz"]
3 seconds
["YES\nYES\nNO\nNO", "NO\nNO\nYES\nNO\nNO"]
null
Java 8
standard input
[ "implementation", "strings" ]
6709c8078cd29e69cf1be285071b2527
The first line of the input contains one integer $$$n$$$ ($$$1 \le n \le 10^5$$$) β€” the number of pairs to check. Further input contains $$$n$$$ descriptions of pairs. The first line of each description contains a single non-empty word $$$s$$$ consisting of lowercase Latin letters. The second line of the description contains a single non-empty word $$$t$$$ consisting of lowercase Latin letters. The lengths of both strings are not greater than $$$10^6$$$. It is guaranteed that the total length of all words $$$s$$$ in the input is not greater than $$$10^6$$$. Also, it is guaranteed that the total length of all words $$$t$$$ in the input is not greater than $$$10^6$$$.
1,200
Output $$$n$$$ lines. In the $$$i$$$-th line for the $$$i$$$-th pair of words $$$s$$$ and $$$t$$$ print YES if the word $$$t$$$ could be printed by typing the word $$$s$$$. Otherwise, print NO.
standard output
PASSED
99795d864d742bc0938573609c041a87
train_003.jsonl
1409061600
Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Map; import java.util.StringTokenizer; import java.util.TreeMap; public class CF_462_B_APPLEMAN_AND_CARD_GAME { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); long n = sc.nextInt(); long m = sc.nextInt(); String s = sc.next(); TreeMap<Character, Long> map = new TreeMap<>(); TreeMap<Long, Long> res = new TreeMap<>(); for (int i = 0; i < n; i++) map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0L) + 1L); for (Map.Entry<Character, Long> e : map.entrySet()) res.put(-e.getValue(), res.getOrDefault(-e.getValue(), 0L) + 1L); long ans = 0; outer:for (Map.Entry<Long, Long> e : res.entrySet()) { long key = -e.getKey(); long value = key; long count = e.getValue(); while (count-- > 0) { if (value < m) ans += (value * value); else { ans += (m * m); break outer; } m -= value; } } System.out.println(ans); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream fileReader) { br = new BufferedReader(new InputStreamReader(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 long nextLong() throws IOException { return Long.parseLong(next()); } public String nextLine() throws IOException { return br.readLine(); } public double nextDouble() throws IOException { String x = next(); StringBuilder sb = new StringBuilder("0"); double res = 0, f = 1; boolean dec = false, neg = false; int start = 0; if (x.charAt(0) == '-') { neg = true; start++; } for (int i = start; i < x.length(); i++) if (x.charAt(i) == '.') { res = Long.parseLong(sb.toString()); sb = new StringBuilder("0"); dec = true; } else { sb.append(x.charAt(i)); if (dec) f *= 10; } res += Long.parseLong(sb.toString()) / f; return res * (neg ? -1 : 1); } public boolean ready() throws IOException { return br.ready(); } } }
Java
["15 10\nDZFDFZDFDDDDDDF", "6 4\nYJSNPI"]
1 second
["82", "4"]
NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin.
Java 8
standard input
[ "greedy" ]
480defc596ee5bc800ea569fd76dc584
The first line contains two integers n and k (1 ≀ k ≀ n ≀ 105). The next line contains n uppercase letters without spaces β€” the i-th letter describes the i-th card of the Appleman.
1,300
Print a single integer – the answer to the problem.
standard output
PASSED
ef550d61e5c5b4e1cf67ce0389984947
train_003.jsonl
1409061600
Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class B462 { public static void main(String args[]){ Scanner in = new Scanner(System.in); int n=in.nextInt(); long k= in.nextInt(); String s=in.next(); long a[]=new long[30]; for(int i=0;i<n;i++){ a[s.charAt(i)-'A']++; } Arrays.sort(a); long sum=0; for(int i=29;i>0 && k>0;i--){ if(a[i]<=k){ sum+=a[i]*a[i]; k-=a[i];} else{ sum+=k*k; k=0; } } System.out.println(sum); } }
Java
["15 10\nDZFDFZDFDDDDDDF", "6 4\nYJSNPI"]
1 second
["82", "4"]
NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin.
Java 8
standard input
[ "greedy" ]
480defc596ee5bc800ea569fd76dc584
The first line contains two integers n and k (1 ≀ k ≀ n ≀ 105). The next line contains n uppercase letters without spaces β€” the i-th letter describes the i-th card of the Appleman.
1,300
Print a single integer – the answer to the problem.
standard output
PASSED
0cd45b6c5213da55484e5c7ac093f98d
train_003.jsonl
1409061600
Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?
256 megabytes
import java.util.*; import java.io.*; import java.math.*; public class mmm { static class InputReader { public BufferedReader br; public StringTokenizer token; public InputReader(InputStream stream) { br=new BufferedReader(new InputStreamReader(stream),32768); token=null; } public String next() { while(token==null || !token.hasMoreTokens()) { try { token=new StringTokenizer(br.readLine()); } catch(IOException e) { throw new RuntimeException(e); } } return token.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } } static class card{ char ch; int i; public card(char ch,int i) { this.ch=ch; this.i=i; } } static class sort implements Comparator<card> { public int compare(card o1,card o2) { if(o1.i!=o2.i) return (o1.i-o2.i)*-1; else return (o1.i-o2.i)*-1; } } /*static void shuffle(long a[]) { List<Long> l=new ArrayList<>(); for(int i=0;i<a.length;i++) l.add(a[i]); Collections.shuffle(l); for(int i=0;i<a.length;i++) a[i]=l.get(i); } static long gcd(long a,long b) { if(b==0) return a; else return gcd(b,a%b); } static int ans1=Integer.MAX_VALUE,ans2=Integer.MAX_VALUE,ans3=Integer.MAX_VALUE,ans4=Integer.MAX_VALUE; static boolean v[]=new boolean[101]; static void dfs(Integer so,Set<Integer> s[]){ if(!v[so.intValue()]) { v[so]=true; for(Integer h:s[so.intValue()]) { if(!v[h.intValue()]) dfs(h,s); } } } static class Print{ public PrintWriter out; Print(OutputStream o) { out=new PrintWriter(o); } } static int CeilIndex(int A[], int l, int r, int key) { while (r - l > 1) { int m = l + (r - l) / 2; if (A[m] >= key) r = m; else l = m; } return r; } static int LongestIncreasingSubsequenceLength(int A[], int size) { // Add boundary case, when array size is one int[] tailTable = new int[size]; int len; // always points empty slot tailTable[0] = A[0]; len = 1; for (int i = 1; i < size; i++) { if (A[i] < tailTable[0]) // new smallest value tailTable[0] = A[i]; else if (A[i] > tailTable[len - 1]) // A[i] wants to extend largest subsequence tailTable[len++] = A[i]; else // A[i] wants to be current end candidate of an existing // subsequence. It will replace ceil value in tailTable tailTable[CeilIndex(tailTable, -1, len - 1, A[i])] = A[i]; } return len; }*/ /*static int binary(int n) { int s=1; while(n>0) { s=s<<1; n--; } return s-1; } static StringBuilder bin(int i,int n) { StringBuilder s=new StringBuilder(); while(i>0) { s.append(i%2); i=i/2; } while(s.length()!=n) { s.append(0); } return s.reverse(); }*/ public static void main(String[] args) { InputReader sc=new InputReader(System.in); int n=sc.nextInt(); long k=sc.nextLong(); char ch[]=sc.next().toCharArray(); long a[]=new long[26]; for(int i=0;i<n;i++) { a[ch[i]-'A']++; } Arrays.sort(a); long sum=0; for(int i=25;i>=0;i--) { if(k==0) break; if(a[i]>=k) { sum+=k*k; k=0; } else { sum+=a[i]*a[i]; k=k-a[i]; } } System.out.println(sum); } }
Java
["15 10\nDZFDFZDFDDDDDDF", "6 4\nYJSNPI"]
1 second
["82", "4"]
NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin.
Java 8
standard input
[ "greedy" ]
480defc596ee5bc800ea569fd76dc584
The first line contains two integers n and k (1 ≀ k ≀ n ≀ 105). The next line contains n uppercase letters without spaces β€” the i-th letter describes the i-th card of the Appleman.
1,300
Print a single integer – the answer to the problem.
standard output
PASSED
c358339dbac036c3745d25d3a809430d
train_003.jsonl
1409061600
Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.PriorityQueue; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author neuivn */ 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, InputReader in, PrintWriter out) { int N = in.nextInt(); int K = in.nextInt(); int[] cnt = new int[26]; String s = in.nextLine(); for (int i = 0; i < s.length(); ++i) { cnt[(s.charAt(i) - 'A') % 26]++; } PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() { public int compare(Integer o1, Integer o2) { return o2 - o1; } }); for (int i = 0; i < 26; ++i) { if (cnt[i] > 0) { pq.offer(cnt[i]); } } long ret = 0; while (K > 0) { int top = pq.poll(); if (top <= K) { ret += (long) top * (long) top; K -= top; } else { ret += (long) K * (long) K; break; } } out.println(ret); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } } }
Java
["15 10\nDZFDFZDFDDDDDDF", "6 4\nYJSNPI"]
1 second
["82", "4"]
NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin.
Java 8
standard input
[ "greedy" ]
480defc596ee5bc800ea569fd76dc584
The first line contains two integers n and k (1 ≀ k ≀ n ≀ 105). The next line contains n uppercase letters without spaces β€” the i-th letter describes the i-th card of the Appleman.
1,300
Print a single integer – the answer to the problem.
standard output
PASSED
d3ed4e8e8fbcde8dbfa4a8e61e5f70b7
train_003.jsonl
1409061600
Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.PriorityQueue; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; import java.io.BufferedReader; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author neuivn */ 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); TaskB solver = new TaskB(); solver.solve(1, in, out); out.close(); } static class TaskB { public void solve(int testNumber, InputReader in, PrintWriter out) { int N = in.nextInt(); int K = in.nextInt(); int[] cnt = new int[26]; String line = in.nextLine(); for (int j = 0; j < line.length(); ++j) { cnt[(line.charAt(j) - 'A') % 26]++; } PriorityQueue<Integer> pq = new PriorityQueue<Integer>(1, new Comparator<Integer>() { public int compare(Integer o1, Integer o2) { return o2 - o1; } }); long ret = 0; for (int i = 0; i < 26; ++i) { if (cnt[i] > 0) { pq.offer(cnt[i]); } } while (K > 0 && pq.size() > 0) { int v = pq.poll(); if (K >= v) { ret += (long) v * (long) v; K -= v; } else if (v > K) { ret += (long) K * (long) K; K = 0; } } out.println(ret); } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public String nextLine() { try { return reader.readLine(); } catch (IOException e) { e.printStackTrace(); } return null; } } }
Java
["15 10\nDZFDFZDFDDDDDDF", "6 4\nYJSNPI"]
1 second
["82", "4"]
NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin.
Java 8
standard input
[ "greedy" ]
480defc596ee5bc800ea569fd76dc584
The first line contains two integers n and k (1 ≀ k ≀ n ≀ 105). The next line contains n uppercase letters without spaces β€” the i-th letter describes the i-th card of the Appleman.
1,300
Print a single integer – the answer to the problem.
standard output
PASSED
9a3e7d96aaaaea6bd4d5bcb58642c113
train_003.jsonl
1409061600
Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Code462B { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); char[] cards = new char[n]; int[] alpha = new int[26]; br.read(cards); for (char c : cards) { alpha[c - 'A']++; } Arrays.sort(alpha); long sum = 0; int kk = k; for(int i = alpha.length - 1; kk > 0; i--) { long m = kk > alpha[i] ? alpha[i] : kk; sum += (m * m); kk -= m; } if(sum == 0) sum += k; else if(sum < 0) System.out.println(kk); System.out.println(sum); } }
Java
["15 10\nDZFDFZDFDDDDDDF", "6 4\nYJSNPI"]
1 second
["82", "4"]
NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin.
Java 8
standard input
[ "greedy" ]
480defc596ee5bc800ea569fd76dc584
The first line contains two integers n and k (1 ≀ k ≀ n ≀ 105). The next line contains n uppercase letters without spaces β€” the i-th letter describes the i-th card of the Appleman.
1,300
Print a single integer – the answer to the problem.
standard output
PASSED
ec625e578da493ac5daa42dc61b54f3d
train_003.jsonl
1409061600
Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class B462 { public static void main(String args[]){ Scanner in = new Scanner(System.in); int n=in.nextInt(); long k= in.nextInt(); String s=in.next(); long a[]=new long[30]; for(int i=0;i<n;i++){ a[s.charAt(i)-'A']++; } Arrays.sort(a); long sum=0; for(int i=29;i>0 && k>0;i--){ if(a[i]<=k){ sum+=a[i]*a[i]; k-=a[i];} else{ sum+=k*k; k=0; } } System.out.println(sum); } }
Java
["15 10\nDZFDFZDFDDDDDDF", "6 4\nYJSNPI"]
1 second
["82", "4"]
NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin.
Java 8
standard input
[ "greedy" ]
480defc596ee5bc800ea569fd76dc584
The first line contains two integers n and k (1 ≀ k ≀ n ≀ 105). The next line contains n uppercase letters without spaces β€” the i-th letter describes the i-th card of the Appleman.
1,300
Print a single integer – the answer to the problem.
standard output
PASSED
d2f981517edb3f59cdbf04cbd1610f68
train_003.jsonl
1409061600
Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; import java.util.ArrayList; import java.util.Scanner; public class main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static final int mod = 1000000007; static final int mod1 = 1073741824; public static int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a); } static boolean prime[] = new boolean[1000001]; public static void sieve() { int n = 1000000; Arrays.fill(prime, true); for (int j = 2; j * j <= n; j++) { if (prime[j] == true) { for (int i = j * j; i <= n; i += j) { prime[i] = false; } } } /*for(int j=2;j<=n;j++) { if(prime[j]==true) System.out.println(j); }*/ } public static void main(String[] args) { FastReader sc = new FastReader(); int n=sc.nextInt(); int k=sc.nextInt(); long a[]=new long[26]; //System.out.println(n+" "+k); //sc.next(); String s=sc.nextLine(); //System.out.println(s); for(int j=0;j<n;j++) { a[s.charAt(j)-'A']++; } Arrays.sort(a); long ans=0; for(int j=25;j>=0;j--) { if(k>a[j]) { ans+=(long)Math.pow(a[j],2); k-=a[j]; } else { ans+=(long)Math.pow(k,2); break; } } System.out.println(ans); } }
Java
["15 10\nDZFDFZDFDDDDDDF", "6 4\nYJSNPI"]
1 second
["82", "4"]
NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin.
Java 8
standard input
[ "greedy" ]
480defc596ee5bc800ea569fd76dc584
The first line contains two integers n and k (1 ≀ k ≀ n ≀ 105). The next line contains n uppercase letters without spaces β€” the i-th letter describes the i-th card of the Appleman.
1,300
Print a single integer – the answer to the problem.
standard output
PASSED
8caf4ab6fc5be4052d8b2bdf2c75eb4b
train_003.jsonl
1409061600
Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?
256 megabytes
import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Scanner; public class CF462B { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); String [] na = in.nextLine().split(" "); int n = Integer.parseInt(na[0]); long k = Long.parseLong(na[1]); String s = in.nextLine(); HashSet<Character> op = new HashSet<Character>(); for(int i=0;i<n;++i){ op.add(s.charAt(i)); } Character [] c = new Character[op.size()]; c = op.toArray(c); Long [] ar = new Long[op.size()]; for(int i=0;i<c.length;++i){ char t = c[i]; long count =0; for(int j=0;j<n;++j){ if(t==s.charAt(j)){ count++; } } ar[i] = count; } Arrays.sort(ar,Collections.reverseOrder()); long ans =0; for(int i=0;i<ar.length;++i){ if(k-ar[i]>=0){ ans += (ar[i] * ar[i]); k -= ar[i]; } else{ ans += (k * k); break; } } System.out.println(ans); in.close(); } }
Java
["15 10\nDZFDFZDFDDDDDDF", "6 4\nYJSNPI"]
1 second
["82", "4"]
NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin.
Java 8
standard input
[ "greedy" ]
480defc596ee5bc800ea569fd76dc584
The first line contains two integers n and k (1 ≀ k ≀ n ≀ 105). The next line contains n uppercase letters without spaces β€” the i-th letter describes the i-th card of the Appleman.
1,300
Print a single integer – the answer to the problem.
standard output
PASSED
ef547fc2db291038acc03b6030848b4a
train_003.jsonl
1409061600
Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?
256 megabytes
import java.util.Arrays; import java.util.Comparator; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; import java.util.TreeMap; public class Tree { static int[] dx = {-1, 1, 0, 0}; static int[] dy = {0, 0, 1, -1}; public static void main(String[] args) { Scanner in = new Scanner(System.in); String[] l = in.nextLine().split(" "); int n = Integer.parseInt(l[0]); int k = Integer.parseInt(l[1]); Integer[] arr = new Integer[30]; for(int i=0; i<arr.length; i++) arr[i] = new Integer(0); for(char c : in.nextLine().toCharArray()) { arr[c - 'A']++; } Arrays.sort(arr, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { // TODO Auto-generated method stub return Integer.compare(o2, o1); } }); long mon = 0; for(int e : arr) { if(e > k) { mon += (k * (long)k); break; } else { mon += (e* (long)e); k -= (e); } } System.out.println(mon); } } class Q { public Q(char let, int freq) { super(); this.let = let; this.freq = freq; } char let; int freq; }
Java
["15 10\nDZFDFZDFDDDDDDF", "6 4\nYJSNPI"]
1 second
["82", "4"]
NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin.
Java 8
standard input
[ "greedy" ]
480defc596ee5bc800ea569fd76dc584
The first line contains two integers n and k (1 ≀ k ≀ n ≀ 105). The next line contains n uppercase letters without spaces β€” the i-th letter describes the i-th card of the Appleman.
1,300
Print a single integer – the answer to the problem.
standard output
PASSED
1ac49ed945e4809ed6a7b006e27f37e2
train_003.jsonl
1409061600
Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?
256 megabytes
import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; public class Cards { public static void main(String[] args){ Scanner scanner = new Scanner(System.in); String[] nInput = scanner.nextLine().split(" "); int toastCards = Integer.parseInt(nInput[1]); List<String> cards = Arrays.asList(scanner.nextLine().split("")); Collections.sort(cards); Map<String, Integer> frequencyMap = new HashMap<String, Integer>(); for(int i = 0; i < cards.size(); i++){ String card = cards.get(i); int freq = Collections.frequency(cards, card); frequencyMap.put(cards.get(i), freq); i += freq - 1; } long coins = 0L; while(toastCards > 0){ Entry maxEntry = findMax(frequencyMap); int maxCards = frequencyMap.get(maxEntry.getKey()); if(toastCards - maxCards < 0){ coins += (long)toastCards * (long)toastCards; break; } coins += (long)maxCards * (long)maxCards; frequencyMap.remove(maxEntry.getKey()); toastCards -= maxCards; } System.out.print((long)coins); scanner.close(); } public static Entry<String, Integer> findMax(Map<String, Integer> map){ Map.Entry<String, Integer> maxEntry = null; for(Map.Entry<String, Integer> entry : map.entrySet()){ if(maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0){ maxEntry = entry; } } return maxEntry; } }
Java
["15 10\nDZFDFZDFDDDDDDF", "6 4\nYJSNPI"]
1 second
["82", "4"]
NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin.
Java 8
standard input
[ "greedy" ]
480defc596ee5bc800ea569fd76dc584
The first line contains two integers n and k (1 ≀ k ≀ n ≀ 105). The next line contains n uppercase letters without spaces β€” the i-th letter describes the i-th card of the Appleman.
1,300
Print a single integer – the answer to the problem.
standard output
PASSED
dbee6c5efffa88e479d4744a1321e669
train_003.jsonl
1409061600
Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?
256 megabytes
import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Scanner; public class Cards { public static void main(String[] args){ Scanner scanner = new Scanner(System.in); String[] nInput = scanner.nextLine().split(" "); int toastCards = Integer.parseInt(nInput[1]); List<String> cards = Arrays.asList(scanner.nextLine().split("")); Collections.sort(cards); Map<String, Integer> frequencyMap = new HashMap<String, Integer>(); for(int i = 0; i < cards.size(); i++){ String card = cards.get(i); int freq = Collections.frequency(cards, card); frequencyMap.put(cards.get(i), freq); i += freq - 1; } long coins = 0L; while(toastCards > 0){ Entry maxEntry = findMax(frequencyMap); int maxCards = frequencyMap.get(maxEntry.getKey()); if(toastCards - maxCards < 0){ coins += (long)toastCards * (long)toastCards; break; } coins += (long)maxCards * (long)maxCards; frequencyMap.remove(maxEntry.getKey()); toastCards -= maxCards; } System.out.print((long)coins); scanner.close(); } public static Entry<String, Integer> findMax(Map<String, Integer> map){ Map.Entry<String, Integer> maxEntry = null; for(Map.Entry<String, Integer> entry : map.entrySet()){ if(maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0){ maxEntry = entry; } } return maxEntry; } }
Java
["15 10\nDZFDFZDFDDDDDDF", "6 4\nYJSNPI"]
1 second
["82", "4"]
NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin.
Java 8
standard input
[ "greedy" ]
480defc596ee5bc800ea569fd76dc584
The first line contains two integers n and k (1 ≀ k ≀ n ≀ 105). The next line contains n uppercase letters without spaces β€” the i-th letter describes the i-th card of the Appleman.
1,300
Print a single integer – the answer to the problem.
standard output
PASSED
c2130d1a50bab2d38f3a0bf76f9a994e
train_003.jsonl
1409061600
Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?
256 megabytes
import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner input = new Scanner(System.in); long n = input.nextInt(); long k = input.nextInt(); String s =input.next(); long res=0; char arr[]=s.toCharArray(); long freq[] = new long[(int) n]; int p=0; Arrays.sort(arr); char temp=arr[0]; int counter=1; for(int i=1;i<arr.length;i++){ //System.out.print(arr[i]); if(arr[i]==temp) counter++; else { freq[p]=counter; counter=1; p++; temp=arr[i]; } if(i==arr.length-1){ freq[p]=counter; } } Arrays.sort(freq); for(int i=1;i<freq.length;i++){ if(freq[freq.length-i]==1) break; else if(freq[freq.length-i]>k){ res+=k*k; k=0; } else { k-=freq[freq.length-i]; res+=freq[freq.length-i]*freq[freq.length-i]; } } if(k!=0) { res+=k; } System.out.println(res); input.close(); } }
Java
["15 10\nDZFDFZDFDDDDDDF", "6 4\nYJSNPI"]
1 second
["82", "4"]
NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin.
Java 8
standard input
[ "greedy" ]
480defc596ee5bc800ea569fd76dc584
The first line contains two integers n and k (1 ≀ k ≀ n ≀ 105). The next line contains n uppercase letters without spaces β€” the i-th letter describes the i-th card of the Appleman.
1,300
Print a single integer – the answer to the problem.
standard output
PASSED
07b7453796a988acdd1314f589cbcac3
train_003.jsonl
1409061600
Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?
256 megabytes
import java.util.Scanner; import java.util.Collections; import java.util.Arrays; public class C462B { public static void main(String[] args) { Scanner in = new Scanner(System.in); long n, k; n = in.nextLong(); k = in.nextLong(); String str; str = in.next(); long [] hash = new long [26]; for (int i = 0; i < n; i++) { hash[(int)(str.charAt(i) - 'A')]++; } Arrays.sort(hash); long res = 0; for (int i = 25; i >= 0; i--) { if (k > hash[i]) { res += (hash[i]*hash[i]); k -= hash[i]; } else { res += k*k; k = 0; break; } } System.out.print(res); } }
Java
["15 10\nDZFDFZDFDDDDDDF", "6 4\nYJSNPI"]
1 second
["82", "4"]
NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin.
Java 8
standard input
[ "greedy" ]
480defc596ee5bc800ea569fd76dc584
The first line contains two integers n and k (1 ≀ k ≀ n ≀ 105). The next line contains n uppercase letters without spaces β€” the i-th letter describes the i-th card of the Appleman.
1,300
Print a single integer – the answer to the problem.
standard output
PASSED
a4ad94d7aea7f1a9f0e3284e9e87c693
train_003.jsonl
1409061600
Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?
256 megabytes
import java.util.Scanner; import java.util.Collections; import java.util.Arrays; public class C462B { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n, k; n = in.nextInt(); k = in.nextInt(); String str; str = in.next(); long [] hash = new long [26]; for (int i = 0; i < n; i++) { hash[(int)(str.charAt(i) - 'A')]++; } Arrays.sort(hash); long res = 0; for (int i = 25; i >= 0; i--) { if (k > hash[i]) { res += ((long)hash[i])*((long)hash[i]); k -= hash[i]; } else { res += ((long)k)*((long)k); k = 0; break; } } System.out.print(res); } }
Java
["15 10\nDZFDFZDFDDDDDDF", "6 4\nYJSNPI"]
1 second
["82", "4"]
NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin.
Java 8
standard input
[ "greedy" ]
480defc596ee5bc800ea569fd76dc584
The first line contains two integers n and k (1 ≀ k ≀ n ≀ 105). The next line contains n uppercase letters without spaces β€” the i-th letter describes the i-th card of the Appleman.
1,300
Print a single integer – the answer to the problem.
standard output
PASSED
5aa4591e9810766ae963cb58d728e72f
train_003.jsonl
1409061600
Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.*; /** * Created by spss on 1/11/16. */ public class Problem462B { public static class MyScanner{ static BufferedReader br; static StringTokenizer st; MyScanner(){ br = new BufferedReader(new InputStreamReader(System.in)); st = null; } String next() throws IOException { while(st == null || !st.hasMoreElements()){ st = new StringTokenizer(br.readLine()); } return st.nextToken(); } int nextInt() throws IOException{ return Integer.parseInt(next()); } } public static void main(String[] args) throws IOException{ MyScanner scan = new MyScanner(); int n,k; String letters; n = scan.nextInt(); k = scan.nextInt(); letters = scan.next(); Map<Character, Long> charMap = new HashMap<>(); for(int i=0;i<letters.length();i++){ char c = letters.charAt(i); charMap.put(c, charMap.getOrDefault(c,0L) + 1); } ArrayList<Long> X = new ArrayList<>(charMap.values()); Collections.sort(X,(n1,n2) -> Long.compare(n2,n1)); BigInteger S = new BigInteger("0"); long K = k; for(int i=0;i<X.size();i++){ long x = X.get(i); if(x >= K){ S = S.add(new BigInteger(Long.toString(K*K))); break; } else { K -= x; S = S.add(new BigInteger(Long.toString(x*x))); } } System.out.println(S); } }
Java
["15 10\nDZFDFZDFDDDDDDF", "6 4\nYJSNPI"]
1 second
["82", "4"]
NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin.
Java 8
standard input
[ "greedy" ]
480defc596ee5bc800ea569fd76dc584
The first line contains two integers n and k (1 ≀ k ≀ n ≀ 105). The next line contains n uppercase letters without spaces β€” the i-th letter describes the i-th card of the Appleman.
1,300
Print a single integer – the answer to the problem.
standard output
PASSED
abd7572a9eaa350428726ac5de8b2e5c
train_003.jsonl
1409061600
Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?
256 megabytes
import java.util.Scanner; public class B462 { static Scanner sc = new Scanner(System.in); static int n, k, ind; static long ans, cur; static String s; static int[] a; public static void main(String[] args) { n = sc.nextInt(); k = sc.nextInt(); s = sc.next(); a = new int[26]; for (int i = 0; i < s.length(); i++) { a[s.charAt(i) - 'A']++; } for (int i = 0; i < 26 && k > 0; i++) { for (int j = 0; j < 26; j++) { if (a[j] > a[ind]) { ind = j; } } cur = Math.min(a[ind], k); k -= a[ind]; ans += (cur * cur); a[ind] = 0; } System.out.println(ans); } }
Java
["15 10\nDZFDFZDFDDDDDDF", "6 4\nYJSNPI"]
1 second
["82", "4"]
NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin.
Java 8
standard input
[ "greedy" ]
480defc596ee5bc800ea569fd76dc584
The first line contains two integers n and k (1 ≀ k ≀ n ≀ 105). The next line contains n uppercase letters without spaces β€” the i-th letter describes the i-th card of the Appleman.
1,300
Print a single integer – the answer to the problem.
standard output
PASSED
aaec09a0ce70ec1faf36a43fcbc44277
train_003.jsonl
1409061600
Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on ith, then sum up all these quantities, such a number of coins Appleman should give to Toastman.Given the description of Appleman's cards. What is the maximum number of coins Toastman can get?
256 megabytes
import java.util.*; public class codfo { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(), k = s.nextInt(); String st = s.next(); int count[] = new int[26]; for (int i = 0; i < st.length(); i++) { int index = st.charAt(i) - 65; count[index]++; } Arrays.sort(count); int i = 25; long ans = 0; while (k > 0) { long min = Math.min(k, count[i]); ans += (min * min); k -= min; i--; } System.out.println(ans); } }
Java
["15 10\nDZFDFZDFDDDDDDF", "6 4\nYJSNPI"]
1 second
["82", "4"]
NoteIn the first test example Toastman can choose nine cards with letter D and one additional card with any letter. For each card with D he will get 9 coins and for the additional card he will get 1 coin.
Java 8
standard input
[ "greedy" ]
480defc596ee5bc800ea569fd76dc584
The first line contains two integers n and k (1 ≀ k ≀ n ≀ 105). The next line contains n uppercase letters without spaces β€” the i-th letter describes the i-th card of the Appleman.
1,300
Print a single integer – the answer to the problem.
standard output