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
f157eabcb2e0cd02d56c277cc98ff158
train_001.jsonl
1561559700
This problem is a version of problem D from the same contest with some additional constraints and tasks.There are $$$n$$$ candies in a candy box. The type of the $$$i$$$-th candy is $$$a_i$$$ ($$$1 \le a_i \le n$$$). You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all distinct (i. e. for example, a gift having two candies of type $$$1$$$ and two candies of type $$$2$$$ is bad).It is possible that multiple types of candies are completely absent from the gift. It is also possible that not all candies of some types will be taken to a gift.You really like some of the candies and don't want to include them into the gift, but you want to eat them yourself instead. For each candy, a number $$$f_i$$$ is given, which is equal to $$$0$$$ if you really want to keep $$$i$$$-th candy for yourself, or $$$1$$$ if you don't mind including it into your gift. It is possible that two candies of the same type have different values of $$$f_i$$$.You want your gift to be as large as possible, but you don't want to include too many of the candies you want to eat into the gift. So, you want to calculate the maximum possible number of candies that can be included into a gift, and among all ways to choose maximum number of candies, you want to maximize the number of candies having $$$f_i = 1$$$ in your gift.You have to answer $$$q$$$ independent queries.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
256 megabytes
import java.io.*; import java.math.*; import java.text.*; import java.util.*; import java.util.regex.*; public class Solution { public static class pair implements Comparable<pair> { int f0,f1; pair(int a0,int a1) { f0 = a0; f1 = a1; } public int compareTo(pair p1) { // if(this.f1+this.f0 == p1.f1+p1.f0) // { return(p1.f1-this.f1); // } // return(((p1.f1+p1.f0)-(this.f0+this.f1))); } } public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); PrintWriter w = new PrintWriter(System.out); int q = Integer.parseInt(in.readLine()); for(int x=0;x<q;x++) { int n = Integer.parseInt(in.readLine()); ArrayList<pair> pr = new ArrayList<pair>(); int[] cns = new int[n+1]; for(int i=0;i<=n;i++) { pr.add(new pair(0,0)); } for(int i=0;i<n;i++) { String[] s1 = in.readLine().trim().split("\\s+"); int type = Integer.parseInt(s1[0]); int f = Integer.parseInt(s1[1]); pair pq = pr.get(type); pq.f0 = pq.f0-(f-1); pq.f1 = pq.f1+f; pr.set(type,pq); cns[type]++; } Collections.sort(pr); Arrays.sort(cns); int prev = 10000000; int count = 0; int f1count = 0; ArrayList<Integer> take = new ArrayList<Integer>(); for(int i=n;i>=0;i--) { int fr = cns[i]; if(prev<=0) break; count += (int)Math.min(prev-1,fr); take.add((int)Math.min(prev-1,fr)); prev = (int)Math.min(prev-1,fr); } int ix = 0; for(int i=0;i<take.size();i++) { int total = take.get(i); int index = i; int maxf1s = Integer.MIN_VALUE; for(int j=0;j<pr.size();j++) { if(pr.get(j).f1+pr.get(j).f0>=total) { if(maxf1s<pr.get(j).f1) { maxf1s = pr.get(j).f1; index = j; } } } f1count += (int)Math.min(maxf1s,total); pr.remove(index); } w.println(count+" "+f1count); } w.close(); } }
Java
["3\n8\n1 0\n4 1\n2 0\n4 1\n5 1\n6 1\n3 0\n2 0\n4\n1 1\n1 1\n2 1\n2 1\n9\n2 0\n2 0\n4 1\n4 1\n4 1\n7 0\n7 1\n7 0\n7 1"]
2 seconds
["3 3\n3 3\n9 5"]
NoteIn the first query, you can include two candies of type $$$4$$$ and one candy of type $$$5$$$. All of them have $$$f_i = 1$$$ and you don't mind giving them away as part of the gift.
Java 8
standard input
[ "implementation", "sortings", "greedy" ]
bcde53a1671a66eb16a37139380f4ae5
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) β€” the number of queries. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of candies. Then $$$n$$$ lines follow, each containing two integers $$$a_i$$$ and $$$f_i$$$ ($$$1 \le a_i \le n$$$, $$$0 \le f_i \le 1$$$), where $$$a_i$$$ is the type of the $$$i$$$-th candy, and $$$f_i$$$ denotes whether you want to keep the $$$i$$$-th candy for yourself ($$$0$$$ if you want to keep it, $$$1$$$ if you don't mind giving it away). It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2 \cdot 10^5$$$.
2,000
For each query print two integers: the maximum number of candies in a gift you can compose, according to the constraints in the statement; the maximum number of candies having $$$f_i = 1$$$ in a gift you can compose that contains the maximum possible number of candies.
standard output
PASSED
52ff90ed94741a06ff4296a03ef160d7
train_001.jsonl
1561559700
This problem is a version of problem D from the same contest with some additional constraints and tasks.There are $$$n$$$ candies in a candy box. The type of the $$$i$$$-th candy is $$$a_i$$$ ($$$1 \le a_i \le n$$$). You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all distinct (i. e. for example, a gift having two candies of type $$$1$$$ and two candies of type $$$2$$$ is bad).It is possible that multiple types of candies are completely absent from the gift. It is also possible that not all candies of some types will be taken to a gift.You really like some of the candies and don't want to include them into the gift, but you want to eat them yourself instead. For each candy, a number $$$f_i$$$ is given, which is equal to $$$0$$$ if you really want to keep $$$i$$$-th candy for yourself, or $$$1$$$ if you don't mind including it into your gift. It is possible that two candies of the same type have different values of $$$f_i$$$.You want your gift to be as large as possible, but you don't want to include too many of the candies you want to eat into the gift. So, you want to calculate the maximum possible number of candies that can be included into a gift, and among all ways to choose maximum number of candies, you want to maximize the number of candies having $$$f_i = 1$$$ in your gift.You have to answer $$$q$$$ independent queries.If you are Python programmer, consider using PyPy instead of Python when you submit your code.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.PriorityQueue; import java.util.AbstractSet; import java.util.InputMismatchException; import java.util.Random; import java.util.Map; import java.io.OutputStreamWriter; import java.util.NoSuchElementException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Iterator; import java.io.BufferedWriter; import java.util.Collection; import java.util.Set; import java.io.IOException; import java.util.AbstractMap; import java.io.Writer; import java.util.Map.Entry; import java.util.Queue; import java.util.Comparator; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * * @author aryssoncf */ 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); TaskG solver = new TaskG(); int testCount = Integer.parseInt(in.next()); for (int i = 1; i <= testCount; i++) solver.solve(i, in, out); out.close(); } static class TaskG { public void solve(int testNumber, InputReader in, OutputWriter out) { try { int n = in.readInt(); Counter<Integer> all = new Counter<>(), good = new Counter<>(); for (int i = 0; i < n; i++) { int a = in.readInt(), f = in.readInt(); all.add(a); if (f == 1) { good.add(a); } } Queue<LongLongPair> pq = new PriorityQueue<>(Comparator.reverseOrder()); for (int type : all.keySet()) { pq.add(new LongLongPair(all.get(type), good.get(type))); } long resAll = 0, resGood = 0; while (!pq.isEmpty()) { LongLongPair pair = pq.poll(); resAll += pair.first; resGood += pair.second; while (!pq.isEmpty() && pq.peek().first == pair.first) { LongLongPair npair = pq.poll(); long first = npair.first - 1, second = Math.min(npair.second, first); if (first > 0) { pq.add(new LongLongPair(first, second)); } } } out.printLine(resAll, resGood); } catch (Exception e) { e.printStackTrace(); } } } static class EHashMap<E, V> extends AbstractMap<E, V> { private static final int[] shifts = new int[10]; private int size; private EHashMap.HashEntry<E, V>[] data; private int capacity; private Set<Entry<E, V>> entrySet; static { Random random = new Random(System.currentTimeMillis()); for (int i = 0; i < 10; i++) { shifts[i] = 1 + 3 * i + random.nextInt(3); } } public EHashMap() { this(4); } private void setCapacity(int size) { capacity = Integer.highestOneBit(4 * size); //noinspection unchecked data = new EHashMap.HashEntry[capacity]; } public EHashMap(int maxSize) { setCapacity(maxSize); entrySet = new AbstractSet<Entry<E, V>>() { public Iterator<Entry<E, V>> iterator() { return new Iterator<Entry<E, V>>() { private EHashMap.HashEntry<E, V> last = null; private EHashMap.HashEntry<E, V> current = null; private EHashMap.HashEntry<E, V> base = null; private int lastIndex = -1; private int index = -1; public boolean hasNext() { if (current == null) { for (index++; index < capacity; index++) { if (data[index] != null) { base = current = data[index]; break; } } } return current != null; } public Entry<E, V> next() { if (!hasNext()) { throw new NoSuchElementException(); } last = current; lastIndex = index; current = current.next; if (base.next != last) { base = base.next; } return last; } public void remove() { if (last == null) { throw new IllegalStateException(); } size--; if (base == last) { data[lastIndex] = last.next; } else { base.next = last.next; } } }; } public int size() { return size; } }; } public EHashMap(Map<E, V> map) { this(map.size()); putAll(map); } public Set<Entry<E, V>> entrySet() { return entrySet; } public void clear() { Arrays.fill(data, null); size = 0; } private int index(Object o) { return getHash(o.hashCode()) & (capacity - 1); } private int getHash(int h) { int result = h; for (int i : shifts) { result ^= h >>> i; } return result; } public V remove(Object o) { if (o == null) { return null; } int index = index(o); EHashMap.HashEntry<E, V> current = data[index]; EHashMap.HashEntry<E, V> last = null; while (current != null) { if (current.key.equals(o)) { if (last == null) { data[index] = current.next; } else { last.next = current.next; } size--; return current.value; } last = current; current = current.next; } return null; } public V put(E e, V value) { if (e == null) { return null; } int index = index(e); EHashMap.HashEntry<E, V> current = data[index]; if (current != null) { while (true) { if (current.key.equals(e)) { V oldValue = current.value; current.value = value; return oldValue; } if (current.next == null) { break; } current = current.next; } } if (current == null) { data[index] = new EHashMap.HashEntry<>(e, value); } else { current.next = new EHashMap.HashEntry<>(e, value); } size++; if (2 * size > capacity) { EHashMap.HashEntry<E, V>[] oldData = data; setCapacity(size); for (EHashMap.HashEntry<E, V> entry : oldData) { while (entry != null) { EHashMap.HashEntry<E, V> next = entry.next; index = index(entry.key); entry.next = data[index]; data[index] = entry; entry = next; } } } return null; } public V get(Object o) { if (o == null) { return null; } int index = index(o); EHashMap.HashEntry<E, V> current = data[index]; while (current != null) { if (current.key.equals(o)) { return current.value; } current = current.next; } return null; } public boolean containsKey(Object o) { if (o == null) { return false; } int index = index(o); EHashMap.HashEntry<E, V> current = data[index]; while (current != null) { if (current.key.equals(o)) { return true; } current = current.next; } return false; } public int size() { return size; } private static class HashEntry<E, V> implements Entry<E, V> { private final E key; private V value; private EHashMap.HashEntry<E, V> next; private HashEntry(E key, V value) { this.key = key; this.value = value; } public E getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { V oldValue = this.value; this.value = value; return oldValue; } } } static class Counter<K> extends EHashMap<K, Long> { public Counter() { super(); } public Counter(int capacity) { super(capacity); } public long add(K key) { long result = get(key); put(key, result + 1); return result + 1; } public Long get(Object key) { if (containsKey(key)) { return super.get(key); } return 0L; } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; private InputReader.SpaceCharFilter filter; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) { throw new InputMismatchException(); } if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) { return -1; } } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) { c = read(); } int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) { c = read(); } StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) { res.appendCodePoint(c); } c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) { return filter.isSpaceChar(c); } return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { boolean isSpaceChar(int ch); } } static class LongLongPair implements Comparable<LongLongPair> { public final long first; public final long second; public LongLongPair(long first, long second) { this.first = first; this.second = second; } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LongLongPair pair = (LongLongPair) o; return first == pair.first && second == pair.second; } public int hashCode() { int result = Long.hashCode(first); result = 31 * result + Long.hashCode(second); return result; } public String toString() { return "(" + first + "," + second + ")"; } public int compareTo(LongLongPair o) { int value = Long.compare(first, o.first); if (value != 0) { return value; } return Long.compare(second, o.second); } } 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 printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } } }
Java
["3\n8\n1 0\n4 1\n2 0\n4 1\n5 1\n6 1\n3 0\n2 0\n4\n1 1\n1 1\n2 1\n2 1\n9\n2 0\n2 0\n4 1\n4 1\n4 1\n7 0\n7 1\n7 0\n7 1"]
2 seconds
["3 3\n3 3\n9 5"]
NoteIn the first query, you can include two candies of type $$$4$$$ and one candy of type $$$5$$$. All of them have $$$f_i = 1$$$ and you don't mind giving them away as part of the gift.
Java 8
standard input
[ "implementation", "sortings", "greedy" ]
bcde53a1671a66eb16a37139380f4ae5
The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 2 \cdot 10^5$$$) β€” the number of queries. The first line of each query contains one integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) β€” the number of candies. Then $$$n$$$ lines follow, each containing two integers $$$a_i$$$ and $$$f_i$$$ ($$$1 \le a_i \le n$$$, $$$0 \le f_i \le 1$$$), where $$$a_i$$$ is the type of the $$$i$$$-th candy, and $$$f_i$$$ denotes whether you want to keep the $$$i$$$-th candy for yourself ($$$0$$$ if you want to keep it, $$$1$$$ if you don't mind giving it away). It is guaranteed that the sum of $$$n$$$ over all queries does not exceed $$$2 \cdot 10^5$$$.
2,000
For each query print two integers: the maximum number of candies in a gift you can compose, according to the constraints in the statement; the maximum number of candies having $$$f_i = 1$$$ in a gift you can compose that contains the maximum possible number of candies.
standard output
PASSED
e8cdcd33e2036047b7cdef7fb0376f9a
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; /* * 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 Andy Phan */ public class p196a { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); char[] s = in.readLine().toCharArray(); int[] last = new int[s.length+1]; last[s.length] = s.length; last[s.length-1] = s.length-1; for(int i = s.length-2; i >= 0; i--) { if(s[i] >= s[last[i+1]]) last[i] = i; else last[i] = last[i+1]; } PrintWriter out = new PrintWriter(System.out); int ind = last[0]; while(ind < s.length) { out.print(s[ind]); ind = last[ind+1]; } out.println(); out.close(); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
18ae16ab9888f46d52216d5c599841b1
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; public class LexMaxSubSeq { private static int binarySearch(char[] maxSubSeq, int start, int end, char key){ int low = start, high = end; while(low<=high){ int mid = (low+high)/2; if(maxSubSeq[mid]<key){ high = mid-1; }else{ low = mid+1; } } return low; } public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // BufferedReader br = new BufferedReader(new FileReader("testip.txt")); PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out)); String str = br.readLine(); int len = str.length(); if (len <= 1) { pw.println(str); } else { char[] maxSubSeq = new char[len]; maxSubSeq[0] = str.charAt(0); int maxSubSeqLen = 1; for (int i = 1; i < len; ++i) { char currentChar = str.charAt(i); int pos = binarySearch(maxSubSeq, 0, maxSubSeqLen-1, currentChar); maxSubSeq[pos] = currentChar; maxSubSeqLen = pos+1; } for(int i=0; i<maxSubSeqLen; ++i){ pw.print(maxSubSeq[i]); } pw.println(); } br.close(); pw.flush(); pw.close(); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
14c7f2b700ab7807ae566e8dad42a556
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.*; import java.util.*; public class A { public static void solution(BufferedReader reader, PrintWriter writer) throws IOException { In in = new In(reader); Out out = new Out(writer); char[] s = in.next().toCharArray(); int n = s.length; char[] max = new char[n]; max[n - 1] = s[n - 1]; for (int i = n - 2; i >= 0; i--) max[i] = s[i] > max[i + 1] ? s[i] : max[i + 1]; StringBuffer sb = new StringBuffer(); for (int i = 0; i < n; i++) if (s[i] == max[i]) sb.append(s[i]); out.println(sb.toString()); } public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader( new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter( new BufferedWriter(new OutputStreamWriter(System.out))); solution(reader, writer); writer.close(); } protected static class In { private BufferedReader reader; private StringTokenizer tokenizer = new StringTokenizer(""); public In(BufferedReader reader) { this.reader = reader; } public String next() throws IOException { while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine()); return tokenizer.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public int[] nextIntArray1(int n) throws IOException { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } public int[] nextIntArraySorted(int n) throws IOException { int[] a = nextIntArray(n); Random r = new Random(); for (int i = 0; i < n; i++) { int j = i + r.nextInt(n - i); int t = a[i]; a[i] = a[j]; a[j] = t; } Arrays.sort(a); return a; } public long[] nextLongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public long[] nextLongArray1(int n) throws IOException { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } public long[] nextLongArraySorted(int n) throws IOException { long[] a = nextLongArray(n); Random r = new Random(); for (int i = 0; i < n; i++) { int j = i + r.nextInt(n - i); long t = a[i]; a[i] = a[j]; a[j] = t; } Arrays.sort(a); return a; } } protected static class Out { private PrintWriter writer; private static boolean local = System .getProperty("ONLINE_JUDGE") == null; public Out(PrintWriter writer) { this.writer = writer; } public void print(char c) { writer.print(c); } public void print(int a) { writer.print(a); } public void printb(int a) { writer.print(a); writer.print(' '); } public void println(Object a) { writer.println(a); } public void println(Object[] os) { for (int i = 0; i < os.length; i++) { writer.print(os[i]); writer.print(' '); } writer.println(); } public void println(int[] a) { for (int i = 0; i < a.length; i++) { writer.print(a[i]); writer.print(' '); } writer.println(); } public void println(long[] a) { for (int i = 0; i < a.length; i++) { writer.print(a[i]); writer.print(' '); } writer.println(); } public void flush() { writer.flush(); } public static void db(Object... objects) { if (local) System.out.println(Arrays.deepToString(objects)); } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
1de78593ec62f1be5a3cbe541b10a6fc
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
/** * Created by Karan Jobanputra on 29-05-2017. */ import java.util.Scanner; import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class Main { public static void main(String args[]) throws Exception { InputReader sc = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); char arr[] = sc.next().toCharArray(); int first[] = new int[26]; int last[] = new int[26]; Arrays.fill(first,-1); Arrays.fill(last,-1); for(int i=0;i<arr.length;i++) { if(first[arr[i]-'a']==-1) { first[arr[i]-'a'] = i; } last[arr[i]-'a'] = i; } int prevIndex = -1; StringBuffer str = new StringBuffer(""); for(char i='z';i>='a';i--) { int firstIndex = first[i-'a']; int lastIndex = last[i-'a']; if(firstIndex!=-1 && lastIndex>prevIndex) { for(int j=prevIndex+1;j<=lastIndex;j++) { if(arr[j]==i) { str.append(i); } } prevIndex = lastIndex; } } pw.println(str); pw.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); } } static class Node implements Comparable<Node> { int v; int w; Node(int v, int w) { this.v = v; this.w = w; } public int compareTo(Node node) { if (w == node.w) return Integer.compare(v, node.v); return (-1) * Integer.compare(w, node.w); } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
8334ead995706d79e93987500bf5ce3d
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
/** * Created by Karan Jobanputra on 29-05-2017. */ import java.util.Scanner; import java.io.*; import java.util.*; import java.math.*; import java.lang.*; import static java.lang.Math.*; public class Main { public static void main(String args[]) throws Exception { InputReader sc = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); char arr[] = sc.next().toCharArray(); int first[] = new int[26]; int last[] = new int[26]; Arrays.fill(first,-1); Arrays.fill(last,-1); for(int i=0;i<arr.length;i++) { if(first[arr[i]-'a']==-1) { first[arr[i]-'a'] = i; } last[arr[i]-'a'] = i; } int prevIndex = -1; StringBuffer str = new StringBuffer(""); for(char i='z';i>='a';i--) { int firstIndex = first[i-'a']; int lastIndex = last[i-'a']; if(firstIndex!=-1 && lastIndex>prevIndex) { for(int j=prevIndex+1;j<=lastIndex;j++) { if(arr[j]==i) { str.append(i); } } prevIndex = lastIndex; } if(prevIndex == arr.length-1) { break; } } pw.println(str); pw.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); } } static class Node implements Comparable<Node> { int v; int w; Node(int v, int w) { this.v = v; this.w = w; } public int compareTo(Node node) { if (w == node.w) return Integer.compare(v, node.v); return (-1) * Integer.compare(w, node.w); } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
83c47fe9a30d502ae9a64af84d20a8a0
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; import java.util.StringTokenizer; import java.util.TreeSet; public class A { static final long MOD = 1L << 30; public static void main(String[] args) throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); String str = in.next(); TreeSet<Integer>[] ts = new TreeSet[26]; for(int i=0;i<ts.length;i++) ts[i] = new TreeSet<>(); for(int i=0;i<str.length();i++) { ts[str.charAt(i)-'a'].add(i); } StringBuilder ans = new StringBuilder(); int ptr = 0; while(ptr < str.length()) { int letter = 25; while(ts[letter].ceiling(ptr) == null) letter--; ans.append((char)(letter+'a')); ptr = ts[letter].ceiling(ptr)+1; } out.println(ans.toString()); out.close(); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } public String next() throws IOException { while(st == null || !st.hasMoreElements()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
e5691101568b9223d2aa0a04df700f04
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; import java.util.StringTokenizer; import java.util.TreeSet; public class A { static final long MOD = 1L << 30; public static void main(String[] args) throws IOException { FastScanner in = new FastScanner(System.in); PrintWriter out = new PrintWriter(System.out); String str = in.next(); TreeSet<Integer>[] ts = new TreeSet[26]; for(int i=0;i<ts.length;i++) ts[i] = new TreeSet<>(); for(int i=0;i<str.length();i++) { ts[str.charAt(i)-'a'].add(i); } StringBuilder ans = new StringBuilder(); int ptr = 0; int letter = 25; while(ptr < str.length()) { while(ts[letter].ceiling(ptr) == null) letter--; ans.append((char)(letter+'a')); ptr = ts[letter].ceiling(ptr)+1; } out.println(ans.toString()); out.close(); } static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } public String next() throws IOException { while(st == null || !st.hasMoreElements()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public long nextLong() throws IOException { return Long.parseLong(next()); } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
39e0e438dbf0b68b00cb988cdbb82aa8
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); char[] s = sc.next().toCharArray(); StringBuilder sb = new StringBuilder(); int idx = 0; for(char c = 'z'; idx < s.length && c >= 'a'; --c) for(int i = idx; i < s.length; ++i) if(s[i] == c) { sb.append(c); idx = i + 1; } out.println(sb); out.flush(); out.close(); } 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 { 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
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
80800818c31b2a317b15ed1cbbc7d4a4
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class SolutionA{ public static void main(String[] args){ new SolutionA().run(); } void solve(){ char c[] = in.next().toCharArray(); int n = c.length; int pos = 0; StringBuilder sb = new StringBuilder(); for(char t='z'; t>='a'; t--){ for(int j = pos; j<n; j++){ if(c[j] == t){ pos = j+1; sb.append(t); } } } out.println(sb); } class Pair implements Comparable<Pair>{ int x, y; Pair(int x, int y){ this.x = x; this.y = y; } @Override public int compareTo(Pair o) { if(o.x == x) return ((Integer) y).compareTo(o.y); return ((Integer) x).compareTo(o.x); } } FastScanner in; PrintWriter out; void run(){ in = new FastScanner(System.in); out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); out.close(); } void runIO(){ try{ in = new FastScanner(new File("expr.in")); out = new PrintWriter(new FileWriter(new File("expr.out"))); solve(); out.close(); }catch(Exception ex){ ex.printStackTrace(); } } class FastScanner{ BufferedReader bf; StringTokenizer st; public FastScanner(File f){ try{ bf = new BufferedReader(new FileReader(f)); } catch(IOException ex){ ex.printStackTrace(); } } public FastScanner(InputStream is){ bf = new BufferedReader(new InputStreamReader(is)); } String next(){ while(st == null || !st.hasMoreTokens()){ try{ st = new StringTokenizer(bf.readLine()); } catch(IOException ex){ ex.printStackTrace(); } } return st.nextToken(); } int nextInt(){ return Integer.parseInt(next()); } double nextDouble(){ return Double.parseDouble(next()); } float nextFloat(){ return Float.parseFloat(next()); } String nextLine(){ try{ return bf.readLine(); } catch(Exception ex){ ex.printStackTrace(); } return ""; } long nextLong(){ return Long.parseLong(next()); } BigInteger nextBigInteger(){ return new BigInteger(next()); } BigDecimal nextBigDecimal(){ return new BigDecimal(next()); } int[] nextIntArray(int n){ int a[] = new int[n]; for(int i = 0; i < n; i++) a[i] = Integer.parseInt(next()); return a; } long[] nextLongArray(int n){ long a[] = new long[n]; for(int i = 0; i < n; i++) a[i] = Long.parseLong(next()); return a; } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
b82c7758239a5e5908ca51e41e958fe0
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class CF196A { public static void main(String []args) { MyScanner in = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); //Start your solution from here. String text = in.next(); int used[] = new int[26]; for (int i = 0; i < text.length(); i++) used[text.charAt(i) - 'a']++; int alpha = 25; for (int i = 0; i < text.length(); i++) { while (used[alpha] == 0) alpha--; used[text.charAt(i) - 'a']--; if (text.charAt(i) - 'a' == alpha) out.print(text.charAt(i)); } //End your solution here. out.close(); } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } char nextChar() { return next().charAt(0); } int [] nextIntAr(int [] ar){ for(int i=0;i<ar.length;++i){ ar[i] = Integer.parseInt(next()); } return ar; } long [] nextLongAr(long [] ar){ for(int i=0;i<ar.length;++i){ ar[i] = Long.parseLong(next()); } return ar; } double [] nextDoubleAr(double [] ar){ for(int i=0;i<ar.length;++i){ ar[i] = Double.parseDouble(next()); } return ar; } String [] nextStringAr(String [] ar){ for(int i=0;i<ar.length;++i){ ar[i] = next(); } return ar; } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
ea9792fbe5040ab9123d2157d04daa25
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.*; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); char[] x = sc.next().toCharArray(); int n = x.length; int[] cnt = new int[26]; for (int c : x) cnt[c - 'a']++; StringBuilder ans = new StringBuilder(); int p = 25; int i = 0; while (p >= 0) { while (cnt[p] > 0) { if (x[i] - 'a' == p) { ans.append((char) (p + 'a')); } cnt[x[i] - 'a']--; i++; } p--; } out.println(ans); out.flush(); out.close(); } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream system) { br = new BufferedReader(new InputStreamReader(system)); } public Scanner(String s) throws FileNotFoundException { br = new BufferedReader(new FileReader(new File(s))); } public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine() throws IOException { return br.readLine(); } public int nextInt() throws IOException { return Integer.parseInt(next()); } public double nextDouble() throws IOException { return Double.parseDouble(next()); } public char nextChar() throws IOException { return next().charAt(0); } public Long nextLong() throws IOException { return Long.parseLong(next()); } public boolean ready() throws IOException { return br.ready(); } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public long[] nextLongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public Integer[] nextIntegerArray(int n) throws IOException { Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public double[] nextDoubleArray(int n) throws IOException { double[] ans = new double[n]; for (int i = 0; i < n; i++) ans[i] = nextDouble(); return ans; } public short nextShort() throws IOException { return Short.parseShort(next()); } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
8c623bcdb80bd25b7ebc21c3dd16912d
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.util.*; import java.util.Map.Entry; import java.lang.*; import java.math.*; import java.text.*; import java.io.*; public final class Solution { static PrintWriter out = new PrintWriter(System.out); static void flush() { out.flush(); } static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } static boolean isPalindrome(String str1, String str2) { String str3 = str1+str2; int i = 0, j = str3.length()-1; while(i < j) { char a = str3.charAt(i), b = str3.charAt(j); if(a != b) return false; i++;j--; } return true; } static boolean isPalindrome(String str) { int i = 0, j = str.length()-1; while(i < j) { char a = str.charAt(i), b = str.charAt(j); if(a != b) return false; i++;j--; } return true; } 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());} static int fact(int n) { if(n == 1) return 1; return n * fact(n-1); } public int[] readIntArray(int n) { int[] arr = new int[n]; for(int i=0; i<n; ++i) arr[i]=nextInt(); return arr; } public int[][] readIntArray(int m, int n){ int[][] arr = new int[m][n]; for(int i = 0;i<m;i++) for(int j = 0;j<n;j++) arr[i][j] = nextInt(); return arr; } public String[] readStringArray(int n) { String[] arr = new String[n]; for(int i=0; i<n; ++i) arr[i]= nextLine(); return arr; } static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } double nextDouble() {return Double.parseDouble(next());} String nextLine() { String str = ""; try{str = br.readLine();} catch (IOException e) {e.printStackTrace();} return str;} } static void solve(char[] ch) { int[] arr = new int[26]; for(int i = 0;i<ch.length;i++) { ++arr[ch[i] - 'a']; } StringBuilder sb = new StringBuilder(); for(int i = 0;i<ch.length;i++) { int fl = 0; for(int j = ch[i] - 'a' + 1;j<26;j++) { if(arr[j] > 0) { fl = 1; break; } } if(fl == 0) { sb.append(ch[i]); } --arr[ch[i] - 'a']; } out.println(sb.toString()); } public static void main(String args[]) throws Exception { FastReader sc = new FastReader(); long start = System.currentTimeMillis(); char[] ch = sc.nextLine().toCharArray(); solve(ch); flush(); long end = System.currentTimeMillis(); NumberFormat formatter = new DecimalFormat("#0.00000"); //System.out.print("Execution time is " + formatter.format((end - start) / 1000d) + " seconds"); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
50bbaf98c119c78baddd1748f9482f19
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
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.PriorityQueue; import java.util.Random; import java.util.StringTokenizer; public class C { static class Pair implements Comparable<Pair> { int idx; char c; Pair(int i, char c) { idx = i; this.c = c; } @Override public int compareTo(Pair o) { if (c == o.c) return idx - o.idx; return o.c - c; } } public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); String s = sc.next(); PriorityQueue<Pair> pq = new PriorityQueue<Pair>(); for (int i = 0; i < s.length(); i++) pq.add(new Pair(i, s.charAt(i))); StringBuilder ans = new StringBuilder(); int prev = -1; while (!pq.isEmpty()) { Pair cur = pq.remove(); if (cur.idx > prev) { ans.append(cur.c); prev = cur.idx; } } 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(); } public int[] nextIntArray(int n) throws IOException { int[] a = new int[n]; for (int i = 0; i < n; i++) a[i] = nextInt(); return a; } public int[] nextIntArray1(int n) throws IOException { int[] a = new int[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextInt(); return a; } public int[] nextIntArraySorted(int n) throws IOException { int[] a = nextIntArray(n); Random r = new Random(); for (int i = 0; i < n; i++) { int j = i + r.nextInt(n - i); int t = a[i]; a[i] = a[j]; a[j] = t; } Arrays.sort(a); return a; } public long[] nextLongArray(int n) throws IOException { long[] a = new long[n]; for (int i = 0; i < n; i++) a[i] = nextLong(); return a; } public long[] nextLongArray1(int n) throws IOException { long[] a = new long[n + 1]; for (int i = 1; i <= n; i++) a[i] = nextLong(); return a; } public long[] nextLongArraySorted(int n) throws IOException { long[] a = nextLongArray(n); Random r = new Random(); for (int i = 0; i < n; i++) { int j = i + r.nextInt(n - i); long t = a[i]; a[i] = a[j]; a[j] = t; } Arrays.sort(a); return a; } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
2a5344434071401d9925ab6057499e0b
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Practice { public static void main(String args[]) throws IOException { Scanner sc = new Scanner(System.in); String input = sc.nextLine(); StringBuilder out = new StringBuilder(""); int ch = input.charAt(input.length()-1) -1; for(int i = input.length()-1; i >= 0; i--) { if(ch <= input.charAt(i) ) { out = out.append(input.charAt(i)); ch = input.charAt(i); } } System.out.println(out.reverse().toString()); } 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
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
54f0c243d9770a799cc9c51c9fb23730
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Stack; import java.util.StringTokenizer; public class Code { public static void main(String[] args) { // Use the Scanner class MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); String s = sc.nextLine(); Stack<Character> st = new Stack<>(); for (char c : s.toCharArray()) { while (!st.isEmpty() && st.peek() < c) { st.pop(); } st.push(c); } StringBuilder sb = new StringBuilder(); while(!st.isEmpty()) { sb.append(st.pop()); } System.out.println(sb.reverse().toString()); } public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
1af6446c62763e6d8f6ff101e5fd8161
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.*; import java.util.*; import static java.lang.Math.*; public class Main extends PrintWriter { BufferedReader in; StringTokenizer stok; final Random rand = new Random(31); final int inf = (int) 1e9; final long linf = (long) 1e18; final static String IO = "_std"; void solve() throws IOException { char[] s = next().toCharArray(); int n = s.length; List<Integer>[] p = createAdjacencyList(26); for (int i = 0; i < n; i++) { p[s[i] - 'a'].add(i); } List<Integer> ans = new ArrayList<>(); int last = -1; for (int i = 25; i >= 0; i--) { for (Integer j : p[i]) { if (j > last) { ans.add(last = j); } } } for (Integer i : ans) { print(s[i]); } } Main() { super(System.out); in = new BufferedReader(new InputStreamReader(System.in)); } Main(String fileIn, String fileOut) throws IOException { super(fileOut); in = new BufferedReader(new FileReader(fileIn)); } public static void main(String[] args) throws IOException { Main main; if ("_std".equals(IO)) { main = new Main(); } else if ("_iodef".equals(IO)) { main = new Main("input.txt", "output.txt"); } else { main = new Main(IO + ".in", IO + ".out"); } main.solve(); main.close(); } String next() throws IOException { while (stok == null || !stok.hasMoreTokens()) { String s = in.readLine(); if (s == null) { return null; } stok = new StringTokenizer(s); } return stok.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } int[] nextIntArray(int len) throws IOException { int[] a = new int[len]; for (int i = 0; i < len; i++) { a[i] = nextInt(); } return a; } int[] nextIntArraySorted(int len) throws IOException { int[] a = nextIntArray(len); shuffle(a); Arrays.sort(a); return a; } void shuffle(int[] a) { for (int i = 1; i < a.length; i++) { int x = rand.nextInt(i + 1); int _ = a[i]; a[i] = a[x]; a[x] = _; } } void shuffleAndSort(int[] a) { shuffle(a); Arrays.sort(a); } boolean nextPermutation(int[] p) { for (int a = p.length - 2; a >= 0; --a) { if (p[a] < p[a + 1]) for (int b = p.length - 1; ; --b) if (p[b] > p[a]) { int t = p[a]; p[a] = p[b]; p[b] = t; for (++a, b = p.length - 1; a < b; ++a, --b) { t = p[a]; p[a] = p[b]; p[b] = t; } return true; } } return false; } <T> List<T>[] createAdjacencyList(int n) { List<T>[] res = new List[n]; for (int i = 0; i < n; i++) { res[i] = new ArrayList<>(); } return res; } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
d84e8542444c272a16e5166da9574c58
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.*; import java.util.*; public class Main { FastReader scn; PrintWriter out; String INPUT = ""; void solve() { char[] arr = scn.next().toCharArray(); int n = arr.length; int[] fr = new int[26]; for(char ch : arr) { fr[ch - 'a']++; } int[][] pos = new int[26][]; for(int i = 0; i < 26; i++) { pos[i] = new int[fr[i]]; } for(int i = 0; i < n; i++) { pos[arr[i] - 'a'][--fr[arr[i] - 'a']] = i; } for(int i = 0; i < 26; i++) { pos[i] = scn.shuffle(pos[i]); Arrays.sort(pos[i]); } StringBuilder sb = new StringBuilder(); int curr = -1; while(curr != n - 1) { for(int i = 25; i >= 0; i--) { if(pos[i].length == 0) { continue; } int l = 0, r = pos[i].length - 1, ind = -1; while(l <= r) { int m = (l + r) >> 1; if(pos[i][m] > curr) { ind = m; r = m - 1; } else { l = m + 1; } } if(ind == -1) { continue; } sb.append((char)('a' + i)); curr = pos[i][ind]; break; } } out.println(sb); } void run() throws Exception { StringBuilder sb = new StringBuilder(); for(int i = 0; i < 1e5; i++) { sb.append('a'); } INPUT = sb.toString(); long time = System.currentTimeMillis(); boolean oj = System.getProperty("ONLINE_JUDGE") != null; out = new PrintWriter(System.out); scn = new FastReader(oj); solve(); out.flush(); if (!oj) { System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" })); } } public static void main(String[] args) throws Exception { new Main().run(); } 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; } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
7ce3ff3cc66af77063c117213263eff0
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.FileReader; import java.io.FileWriter; //import java.lang.StringBuilder; import java.util.StringTokenizer; //import java.lang.Comparable; //import java.util.Arrays; //import java.util.HashMap; //import java.util.ArrayList; //import java.util.LinkedList; public class LexicographicallyMaximumSubsequence { static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); static PrintWriter out = new PrintWriter(System.out); static StringBuilder sb = new StringBuilder(); public static void main(String[] args) throws IOException { //StringTokenizer st = new StringTokenizer(in.readLine()); //BufferedReader in = new BufferedReader(new FileReader("input.txt")); //PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt"))); char[] c = in.readLine().toCharArray(); boolean[] b = new boolean[c.length]; char max = c[c.length-1]; for(int i = c.length-1; i > -1; i--) { if(c[i] >= max) { max = c[i]; b[i] = true; } } for(int i = 0; i < c.length; i++) { if(b[i]) { sb.append(c[i]); } } out.print(sb); out.close(); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
4a4c31297efe93664a9c924537899c83
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Deque; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; public class Main { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); StringBuilder res = new StringBuilder(); ArrayList<Integer> pos [] = new ArrayList[26]; char [] arr = sc.next().toCharArray(); for (int i = 0 ; i < 26 ; ++ i) pos[i] = new ArrayList<>(); for (int i = 0 ; i < arr.length ; ++ i) pos[arr[i] - 'a'].add(i); int last = - 1; for (int i = 25 ; i >= 0 ; -- i) { if (pos[i].size() == 0) continue; int lo = 0 , hi = pos[i].size() - 1 , best = pos[i].size(); for (int cnt = 0 ; cnt <= 30 ; ++ cnt) { int mid = lo + ((hi - lo) >> 1); if (pos[i].get(mid) > last) { best = mid; hi = Math.max(lo, mid - 1); } else lo = Math.min(hi , mid + 1); } if (best == pos[i].size()) continue; last = pos[i].get(best); while (best < pos[i].size()) { res.append((char)(i + 'a')); last = pos[i].get(best); best ++ ; } } out.println(res); out.flush(); out.close(); } 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 { 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(); } public boolean nextEmpty() throws IOException { String s = nextLine(); st = new StringTokenizer(s); return s.isEmpty(); } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
aee809fee74ff50f9104121408986e57
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; 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.HashMap; import java.util.HashSet; import java.util.PriorityQueue; public class a { public static class Pair implements Comparable<Pair> { int f, s; public Pair(int f, int s) { this.f = f; this.s = s; } @Override public int compareTo(Pair o) { if (o.s < s) return 1; else if (o.s > s) return -1; return 0; } }; public static long gcd(int x, int y) { if (y == 0) return x; return gcd(y, x % y); } public static void main(String[] args) throws IOException { PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String y = in.readLine(); int a[][] = new int[26][100005]; int p[] = new int[26]; for (int i = 0; i < 26; i++) Arrays.fill(a[i], Integer.MAX_VALUE); for (int i = 0; i < y.length(); i++) { int k = y.charAt(i) - 'a'; a[k][p[k]++] = i; } int last = 0; for (int i = 25; i >= 0; i--) { if (p[i] != 0) { int t = Arrays.binarySearch(a[i], last); if (t < 0) { t *= -1; t--; } for (int j = t; j < p[i]; j++) { out.print((char) (i + 'a')); } last = Math.max(last, a[i][p[i] - 1] + 1); // System.out.println(last); } } out.close(); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
def671eb037a710b185b0612764ef268
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.StringTokenizer; public class A196{ public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskG solver = new TaskG(); solver.solve(1, in, out); out.close(); } static class TaskG { public void solve(int testNumber, InputReader in, PrintWriter out) { String texte =in.next(); int len = texte.length(); char lettre; String lettre1; String[] alpha=new String[26]; char m; HashMap<String,Integer> indiceLast=new HashMap<String,Integer>(); for(int indiceChar=0;indiceChar<26;indiceChar++){ m=(char)(97+indiceChar); alpha[indiceChar]=m+""; } for(int i = 0; i<len;i++){ lettre=texte.charAt(i); lettre1=alpha[lettre-'a']; indiceLast.put(lettre1,i); } int indicedebut=0; int indiceend; String tocomp; String res=""; for(int indiceChar=25 ; indiceChar>=0;indiceChar--){ String model=alpha[indiceChar]; if(indiceLast.containsKey(alpha[indiceChar])){ indiceend=indiceLast.get(alpha[indiceChar]); for(int j=indicedebut;j<=indiceend;j++){ lettre=texte.charAt(j); lettre1=alpha[lettre-'a']; if(model==lettre1){ out.print(lettre1);; } } if(indiceend>indicedebut) indicedebut=indiceend; } } } } static class InputReader { public BufferedReader reader; public StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
a8b089f57318202230e739f4fdaada75
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
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.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } static class TaskA { public void solve(int testNumber, InputReader in, PrintWriter out) { String s = in.next(); ArrayList<Character> ans = new ArrayList<>(); gen(s, ans); for (char c : ans) out.print(c); } void gen(String s, ArrayList ans) { if (s.length() > 0) { int maxC = s.charAt(0); for (int i = 1; i < s.length(); i++) maxC = Math.max(maxC, s.charAt(i)); int lastMaxC = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == maxC) { ans.add(s.charAt(i)); lastMaxC = i; } } gen(s.substring(lastMaxC + 1), ans); } } } static class InputReader { private StringTokenizer tokenizer; private BufferedReader reader; public InputReader(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream)); } private void fillTokenizer() { if (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (Exception e) { throw new RuntimeException(e); } } } public String next() { fillTokenizer(); return tokenizer.nextToken(); } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
85cca28cf6cc2483920d64c4cc5eedf0
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.util.*; import static java.lang.Math.*; import java.io.*; public class SolutionB { public static void main(String args[])throws IOException{ Scanner sc = new Scanner(System.in); String s = sc.next(); int N = s.length(); Stack<Character> st = new Stack<Character>(); int max = 0; for(int i = N-1; i >= 0; i--){ char c = s.charAt(i); if(c - 'a' >= max){ max = c - 'a'; st.push(c); } } while(!st.isEmpty()) System.out.print(st.pop()); System.out.println(); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
d46f89ac56ff8b78d8c2185c5a578a43
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.util.*; import static java.lang.Math.*; import java.io.*; public class SolutionB { public static void main(String args[])throws IOException{ Scanner sc = new Scanner(System.in); String s = sc.next(); int N = s.length(); List<Integer> d[] = new ArrayList[26]; for(int i = 0; i < N; i++){ int c = s.charAt(i) - 'a'; if(d[c] == null)d[c] = new ArrayList<Integer>(); d[c].add(i); } int curr = 0; StringBuilder sb = new StringBuilder(); for(int i = 25; i >= 0; i--){ if(d[i] != null){ for(int a : d[i]){ if(a >= curr){ sb.append((char)(i + 'a')); curr = a; } } } } System.out.println(sb.toString()); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
d7cab854d56ab4fee28d8c89de1f8138
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
/* package codechef; // don't place package name! */ import java.util.*; 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 { // your code goes here MyScanner sc = new MyScanner(); String s = sc.nextLine(); ArrayList<ArrayList<Integer>> pos = new ArrayList<ArrayList<Integer>>(); int len = s.length(); for (int i = 0; i < 26; ++i){ pos.add(new ArrayList<Integer>()); } for (int i = 0; i < len; ++i){ pos.get((int) (s.charAt(i) - 'a')).add(i); } ArrayList<Character> res = new ArrayList<Character>(); int index = -1; while (index < len){ // System.out.println(index); boolean found = false; for (int i = 25; i >= 0; --i){ if (pos.get(i).size() == 0) continue; int lo = 0, hi = pos.get(i).size() - 1; int best = -1; while (lo <= hi){ int mid = lo + (hi - lo) / 2; if (pos.get(i).get(mid) > index){ best = mid; hi = mid - 1; }else{ lo = mid + 1; } } if (best != -1){ res.add((char) (i + 'a')); // System.out.println((char) (i + 'a')); index = pos.get(i).get(best); found = true; break; } } if (!found) break; } out = new PrintWriter(new BufferedOutputStream(System.out)); for (int i = 0; i < res.size(); ++i){ out.print(res.get(i)); } out.close(); } private static boolean Ok(int n, int[] arr, int[] need, ArrayList<ArrayList<Integer>> pos, int mid){ int free = 0; int[] count = new int [pos.size()]; int okCount = 0; // System.out.println(mid); for (int i = 0; i <= mid; ++i){ // System.out.println(arr[i]); if (arr[i] != 0){ ArrayList<Integer> po = pos.get(arr[i]); // System.out.println(" --- " + count[arr[i]] + " " + po.get(count[arr[i]]) + " " + free); if (po.size() - 1 > count[arr[i]] && po.get(count[arr[i]] + 1) <= mid){ count[arr[i]]++; free++; }else{ if (free < need[arr[i]]){ return false; }else{ free-= need[arr[i]]; okCount++; } } }else{ free++; } } // System.out.println("okCount = " + okCount); return okCount == pos.size() - 1; } //-----------PrintWriter for faster output--------------------------------- public static PrintWriter out; //-----------MyScanner class for faster input---------- public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine(){ String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
fb713d224760ff347304b058994d4590
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.function.Consumer; public class LMS { public static void main(String[] args) { try (BufferedReader reader = new BufferedReader(new InputStreamReader( System.in))) { char[] seq = reader.readLine().toCharArray(); char prev; LinkedList<Character> list = new LinkedList<>(); list.add(seq[seq.length - 1]); prev = seq[seq.length - 1]; for (int i = seq.length - 2; i >= 0; i--) { if (seq[i] >= prev) { list.addFirst(seq[i]); prev = seq[i]; } } list.forEach(new Consumer<Character>() { @Override public void accept(Character arg0) { System.out.print(arg0); } }); } catch (Exception e) { e.printStackTrace(); } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
e56942246a60b7c014690bee0742980c
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.StringTokenizer; public class CF124A { public static void main(String[] args) throws IOException { Scanner sc=new Scanner (System.in); String s=sc.next(); StringBuilder out=new StringBuilder(""); char last='a'; for(int i=s.length()-1; i>=0; i--){ if(s.charAt(i)>=last){ out.append(s.charAt(i)); last=s.charAt(i); } } System.out.println(out.reverse().toString()); } 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
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
40f1fc1a8cf2e1d3a2f56d256cb6ee59
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; public class LMS { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream(new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') break; buf[cnt++] = (byte) c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void main(String args[])throws IOException { Scanner sc=new Scanner(System.in); String s=sc.next(); int l=s.length(); int max=(s.charAt(l-1)-97); int ar[]=new int[26]; ar[max]++; for(int x=l-2;x>=0;x--) { int ch=s.charAt(x)-97; if(ch>=max) { max=ch; ar[max]++; } } for(int x=25;x>=0;x--) { for(int y=1;y<=ar[x];y++) { System.out.print((char)(x+97)); } } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
29b2b85fa3eaf663a4af046bb2466097
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.*; import java.util.*; public class cf5 { public static void main(String args[]) { Scanner s=new Scanner(System.in); String str=s.next(); StringBuffer sb=new StringBuffer(); int max=0; for(int i=str.length()-1;i>=0;i--) { char ch=str.charAt(i); if((int)ch>=max) { max=(int)ch; sb.append(ch); } } sb.reverse(); System.out.println(sb.toString()); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
858ba47a02b2d41feb1be4dc0696ae89
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.util.*; import java.io.*; public class Div1A { public static void main(String[] args) throws IOException { new Div1A().run(); } FastScanner in; PrintWriter out; void run() throws IOException { in = new FastScanner(System.in); out = new PrintWriter(System.out, true); solve(); out.close(); } void solve() throws IOException { String text = in.next(); int used[] = new int[26]; for (int i = 0; i < text.length(); i++) used[text.charAt(i) - 'a']++; int alpha = 25; for (int i = 0; i < text.length(); i++) { while (used[alpha] == 0) alpha--; used[text.charAt(i) - 'a']--; if (text.charAt(i) - 'a' == alpha) out.print(text.charAt(i)); } } 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()); } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
c2aaff38673e35f3b39e60f349694f7b
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class LexicographicallyMaximumSubsequence { public static void main(String[] args) { PrintWriter pw = new PrintWriter(System.out); reader(System.in); String s = n(); int[] arr = new int[26]; int i = 0; for (i = 0; i < s.length(); i++) arr[s.charAt(i) - 'a']++; i = 25; StringBuilder sb = new StringBuilder(); int l = 0; while (i >= 0) { if (arr[i] != 0) { for (int j = 0; j < arr[i]; j++) sb.append((char) (i + 'a')); l = s.lastIndexOf((char) (i + 'a')); arr = new int[26]; for (int j = l + 1; j < s.length(); j++) arr[s.charAt(j) - 'a']++; } i--; } pw.println(sb); pw.close(); } private static BufferedReader br; private static StringTokenizer st; static void reader(InputStream stream) { try { br = new BufferedReader(new InputStreamReader(stream)); } catch (Exception e) { e.printStackTrace(); } } static String n() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } static int nI() { return Integer.parseInt(n()); } static long nL() { return Long.parseLong(n()); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
5dc4a1784c31b41539ca3504d9eefcdf
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.*; import java.util.*; public final class code // class code // public class Solution { static void solve()throws IOException { String s=nextLine(); int n=s.length(); s=" "+s; Stack<Character> stack=new Stack<>(); stack.push(s.charAt(n)); int curr=s.charAt(n); for(int i=n-1;i>=1;i--) { if(s.charAt(i)>=curr) { curr=s.charAt(i); stack.push((char)curr); } } while(stack.isEmpty()==false) { out.print(stack.pop()); } } /////////////////////////////////////////////////////////// static final long mod=(long)(1e9+7); static final int inf=(int)(1e9); // static final long inf=(long)(1e18); static class Pair implements Comparable<Pair> { int first,second; Pair(int a,int b) { first=a; second=b; } public int compareTo(Pair p) { if(this.second==p.second) return p.first-this.first; return this.second-p.second; } } static void debug(Object ... a) { System.out.print("> "); for(int i=0;i<a.length;i++) System.out.print(a[i]+" "); System.out.println(); } static void debuga(int a[]) { System.out.print("> "); for(int i=0;i<a.length;i++) System.out.print(a[i]+" "); System.out.println(); } static Random random; static BufferedReader br; static StringTokenizer st; static PrintWriter out; static String nextToken()throws IOException { while(st==null || !st.hasMoreTokens()) st=new StringTokenizer(br.readLine()); return st.nextToken(); } static String nextLine()throws IOException { return br.readLine(); } static int nextInt()throws IOException { return Integer.parseInt(nextToken()); } static long nextLong()throws IOException { return Long.parseLong(nextToken()); } static double nextDouble()throws IOException { return Double.parseDouble(nextToken()); } public static void main(String args[])throws IOException { br=new BufferedReader(new InputStreamReader(System.in)); out=new PrintWriter(new BufferedOutputStream(System.out)); random=new Random(); solve(); // int t=nextInt(); // for(int i=1;i<=t;i++) // { // // out.print("Case #"+i+": "); // solve(); // } out.close(); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
b388d6724720fb5d256a40d9521aade6
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.StringTokenizer; public class C { public static void main(String[] args) throws Exception{ Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); char[] a = sc.next().toCharArray(); ArrayList<Integer>[] L = new ArrayList[27]; for(int i = 0; i < 27; i++) L[i] = new ArrayList<>(); for(int i = 0; i < a.length; i++) L[a[i] - 'a'].add(i); int cur = 0; for(int i = 26; i >= 0; i--) if(L[i].size() > 0) { int idx = BS(L[i], cur); if(idx == -1) continue; for(int j = idx; j < L[i].size(); j++) out.print((char)(i + 'a')); cur = L[i].get(L[i].size()-1); } out.flush(); out.close(); } static int BS(ArrayList<Integer> L, int t) { int lo = 0, hi = L.size()-1, ans = -1; while(lo <= hi) { int mid = (lo + hi) / 2; if(L.get(mid) >= t) hi = (ans = mid) - 1; else lo = mid + 1; } return ans; } static class Scanner { StringTokenizer st; BufferedReader br; public Scanner(InputStream System){br = new BufferedReader(new InputStreamReader(System));} public String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine()); return st.nextToken(); } public String nextLine()throws IOException{return br.readLine();} public int nextInt() throws IOException {return Integer.parseInt(next());} public double nextDouble() throws IOException {return Double.parseDouble(next());} public char nextChar()throws IOException{return next().charAt(0);} public Long nextLong()throws IOException{return Long.parseLong(next());} public boolean ready() throws IOException{return br.ready();} public void waitForInput(){for(long i = 0; i < 3e9; i++);} } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
7a4c58076d97410c138810989850bf4d
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.*; import java.util.*; import java.lang.*; public class templ { public static void main(String[] args) throws FileNotFoundException { try { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); int i,j,last=-1; String str=in.nextLine(); StringBuilder sb = new StringBuilder(); for(i=25;i>=0;i--) { if(str.contains(""+(char)(97+i))) for(j=last+1;j<str.length();j++) { if(str.charAt(j)==(char)(97+i)) { sb.append(str.charAt(j)); last=j; } } } out.println(sb.toString()); out.close(); } catch(Exception e){ } } public 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++; } } public 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 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 nextInt() { 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 nextLong() { 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] = nextInt(); } 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
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
b53df8984be5afabd305d976338dae18
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.IOException; import java.io.OutputStreamWriter; import java.io.BufferedWriter; import java.util.InputMismatchException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.NoSuchElementException; import java.io.Writer; import java.math.BigInteger; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author Alex */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, OutputWriter out) { char[] input = in.next().toCharArray(); int curindex = 0; for (char i = 'z'; i >= 'a'; i--) { for (int j = 0; j < input.length; j++) { if (j >= curindex && input[j] == i) { out.print(i); curindex = j; } } } } } 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 readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuilder res = new StringBuilder(); do { if (Character.isValidCodePoint(c)) res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public boolean isSpaceChar(int c) { if (filter != null) return filter.isSpaceChar(c); return isWhitespace(c); } public static boolean isWhitespace(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } public String next() { return readString(); } public interface SpaceCharFilter { public boolean isSpaceChar(int ch); } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream))); } public void print(char i) { writer.print(i); } public void close() { writer.close(); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
8c469b09a24ee97a28aadd9dbac2b83f
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.*; import java.util.*; public class lexi { public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); int length = s.length(); char max = s.charAt(length-1); Deque<Character> deque = new ArrayDeque<Character>(100000); //String finals = String.valueOf(s.charAt(length-1)); deque.push(max); for(int i=length-2;i>=0;i--){ char current = s.charAt(i); //System.out.println(current); if(current >= max){ max = current; //finals = String.valueOf(current) + finals; deque.push(current); }/* else if(current == max){ cs.push(current); //finals = String.valueOf(current) + finals; }*/ } for(Character c : deque){ System.out.printf("%c",c); } // System.out.println(finals); System.out.printf("\n"); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
e14bf63adc60b802a8f0cb6db72b403f
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.*; public class Main { static final int INF = Integer.MAX_VALUE; static int mergeSort(int[] a,int [] c, int begin, int end) { int inversion=0; if(begin < end) { inversion=0; int mid = (begin + end) >>1; inversion+= mergeSort(a,c, begin, mid); inversion+=mergeSort(a, c,mid + 1, end); inversion+=merge(a,c, begin, mid, end); } return inversion; } ///////////////////////////////////////////////////// static int merge(int[] a,int[]c, int b, int mid, int e) { int n1 = mid - b + 1; int n2 = e - mid; int[] L = new int[n1+1], R = new int[n2+1]; int[] L1 = new int[n1+1], R1 = new int[n2+1]; //inversion int inversion=0; for(int i = 0; i < n1; i++) { L[i] = a[b + i]; L1[i] = c[b + i]; } for(int i = 0; i < n2; i++) { R[i] = a[mid + 1 + i]; R1[i] = c[mid + 1 + i]; } L[n1] = R[n2] = INF; for(int k = b, i = 0, j = 0; k <= e; k++) if(L[i] <= R[j]){ a[k] = L[i]; c[k] = L1[i++]; } else { a[k] = R[j]; c[k] = R1[j++]; inversion=inversion+(n1-i); } return inversion; } ////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// static int[]dx={-1,1,0,0}; static int[]dy={0,0,1,-1}; static char[][]a; static int n; static void dfs(int r,int c){ if (r<0||r>=n||c<0||c>=n||a[r][c]=='1'||a[r][c]=='2')return ; a[r][c]='2'; for (int i = 0; i < 4; i++) { dfs(r+dx[i],c+dy[i]); } } static void dfs2(int r,int c){ if (r<0||r>=n||c<0||c>=n||a[r][c]=='1'||a[r][c]=='3')return ; a[r][c]='3'; for (int i = 0; i < 4; i++) { dfs2(r+dx[i],c+dy[i]); } } public static void main(String[] args) throws IOException { Scanner in = new Scanner(System.in); try (PrintWriter or = new PrintWriter(System.out)) { char[] a= in.next().toCharArray(); Set<Character> set= new TreeSet<>(Collections.reverseOrder()); ArrayList<Integer>[]list = new ArrayList[26]; for (int i = 0; i < 26; i++) list[i]= new ArrayList<>(); for (int i = 0; i <a.length ; i++) { set.add(a[i]); list[a[i]-'a'].add(i); } for (char i:set) { int y=list[i-'a'].get(list[i-'a'].size()-1); for (int j = 0; j <y ; j++) { if (a[j]=='.'||a[j]==i)continue; if (a[j]<i)a[j]='.'; } } for(char i:a)if(i!='.')or.print(i); } } 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 { 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(); } } } class Triple{ int r,c; public Triple(int r, int c) { this.r = r; this.c = c; } public boolean between(int x){ return x>=r&&x<=c; } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
3595cddf1ec793831d204b9b336d35be
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.PriorityQueue; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws FileNotFoundException { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); TaskB solver = new TaskB(); solver.solve(1, in, out); out.flush(); out.close(); } } class Pair implements Comparable<Pair> { int first; long second; int train; Pair(int first, long second, int train) { this.first = first; this.second = second; this.train = train; } @Override public int compareTo(Pair e) { if (second != e.second) return Long.compare(second, e.second); return train - e.train; } } class TaskB { long INF = (long) 1e18 + 7; int MAX_N = (int) 1e5 + 5; long mod = (long) 1e8; ArrayList<Pair> edges[]; boolean processed[]; ArrayList<Integer> topSort; long distTo[]; ArrayList<Pair> trains; int used[]; void dijkstra(int s) { PriorityQueue<Pair> queue = new PriorityQueue<>(); queue.offer(new Pair(0, 0, 0)); while (!queue.isEmpty()) { Pair temp = queue.poll(); int u = temp.first; long weight = temp.second; int isTrain = temp.train; if (processed[u]) { continue; } processed[u] = true; used[u] = isTrain; for (Pair x : edges[u]) { int v = x.first; if (weight + x.second < distTo[v]) { distTo[v] = weight + x.second; queue.offer(new Pair(x.first, distTo[v], x.train)); } } } } void solve(int testNumber, InputReader in, PrintWriter pw) { char arr[] = in.next().toCharArray(); int cnt[] = new int[26]; for (int i = 0; i < arr.length; i++) { cnt[arr[i] - 'a']++; } int index = -1; int n = arr.length; StringBuilder ans = new StringBuilder(); for (int i = 25; i >= 0; i--) { for (int j = index + 1; j < n; j++) { if (cnt[i] == 0) { break; } else { if (arr[j] == (char) (i + 'a')) { ans.append(arr[j]); cnt[arr[j] - 'a']--; index = j; } } } } pw.println(ans); } long gcd(long a, long b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } int[] shrink(int a[]) { int n = a.length; long b[] = new long[n]; for (int i = 0; i < n; i++) { b[i] = ((long) (a[i] << 32)) | i; } Arrays.sort(b); int ret[] = new int[n]; int p = 0; for (int i = 0; i < n; i++) { if (i > 0 && (b[i] ^ b[i - 1]) >> 32 != 0) { p++; } ret[(int) b[i]] = p; } return ret; } int sum(int ft[], int i) { int sum = 0; for (int j = i; j >= 1; j -= (j & -j)) { sum += ft[j]; // System.out.println(sum); } return sum; } void add(int ft[], int i, int x) { for (int j = i; j < ft.length; j += (j & -j)) { // System.out.println(j); ft[j] += x; } } boolean isValid(int i, int j, char arr[][]) { if (i >= arr[0].length || j >= arr[0].length) { return false; } if (arr[i][j] == '*') { return false; } return true; } long pow(long m, long k) { long prod = 1; for (int i = 0; i < k; i++) { prod = (prod * m) % INF; } return prod % INF; } // int sum(int k) { // int sum=0; // for(int i=k;i>=1;i) { // sum+=ft[k]; // } // } long fib(int N) { long fib[] = new long[N + 1]; fib[0] = 1; fib[1] = 1; for (int i = 2; i <= N; i++) { fib[i] = (fib[i - 1] + fib[i - 2]) % mod; } return fib[N] % mod; } long sum(int i, int j, long arr[]) { long sum = 0; for (int k = i; k <= j; k++) { sum += arr[k]; } return sum; } int __gcd(int a, int b) { if (b == 0) return a; return __gcd(b, a % b); } public int getInt(int num) { int ret = -1; switch (num) { case 0: ret = 6; break; case 1: ret = 2; break; case 2: ret = 5; break; case 3: ret = 5; break; case 4: ret = 4; break; case 5: ret = 5; break; case 6: ret = 6; break; case 7: ret = 3; break; case 8: ret = 7; break; case 9: ret = 6; break; } return ret; } public int isPow(long num) { int count = 0; while (num > 0) { num /= 2; count++; } return count; } } class InputReader { BufferedReader br; StringTokenizer st; public InputReader(InputStream in) { br = new BufferedReader(new InputStreamReader(in)); st = null; } public String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } public long nextLong() { return Long.parseLong(next()); } public double nextDouble() { return Double.parseDouble(next()); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
ff7b9109a3cfbd2c04f245258d0e445b
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.math.BigInteger; import java.util.Random; import java.util.StringTokenizer; public class LexicographicallyMaximumSubsequence { static BufferedReader in; static PrintWriter out; static StringTokenizer tok; static void solve() throws Exception { char[] c = next().toCharArray(); char max = c[c.length - 1]; StringBuilder sb = new StringBuilder(); sb.append(max); for (int i = c.length - 2; i >= 0; i--) if (c[i] >= max) { max = c[i]; sb.append(max); } out.println(sb.reverse()); } public static void main(String args[]) { try { in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); solve(); in.close(); out.close(); } catch (Throwable e) { e.printStackTrace(); System.exit(1); } } static int nextInt() throws IOException { return Integer.parseInt(next()); } static int[] nextIntArray(int len, int start) throws IOException { int[] a = new int[len]; for (int i = start; i < len; i++) a[i] = nextInt(); return a; } static long nextLong() throws IOException { return Long.parseLong(next()); } static long[] nextLongArray(int len, int start) throws IOException { long[] a = new long[len]; for (int i = start; i < len; i++) a[i] = nextLong(); return a; } static double nextDouble() throws IOException { return Double.parseDouble(next()); } static double[] nextDoubleArray(int len, int start) throws IOException { double[] a = new double[len]; for (int i = start; i < len; i++) a[i] = nextDouble(); return a; } static BigInteger nextBigInteger() throws IOException { return new BigInteger(next()); } static String next() throws IOException { while (tok == null || !tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); } return tok.nextToken(); } static String nextLine() throws IOException { tok = new StringTokenizer(""); return in.readLine(); } static void shuffleArray(long[] array) { Random random = new Random(); for (int i = array.length - 1; i > 0; i--) { int index = random.nextInt(i + 1); long temp = array[index]; array[index] = array[i]; array[i] = temp; } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
89e98181534b64bae55bfdfe33661445
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
//package Mssolved; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; public class lexMaxSub { static class pair{ int occ,start,end; public pair(int start, int end){ this.end=end; this.start=start; occ=1; } } public static void main(String[] args) throws IOException{ BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); String x=in.readLine(); PrintWriter out=new PrintWriter(System.out); int max=(int)'a'; int idx=-1; int last=0; pair [] let=new pair[28]; for (int i = 0; i < x.length(); i++) { int id=x.charAt(i)-'a'; if(let[id]==null){ let[id]=new pair(i,i); }else{ let[id].end=i; let[id].occ++; } } int start=-1; for (int i = let.length-1; i >=0;i--) { if(let[i]==null) continue; char c=(char)('a'+i); if(start==-1) for (int j = 0; j < let[i].occ; j++) { out.print(c); } else { // System.out.println(start); for (int j = start; j <=let[i].end; j++) { if(x.charAt(j)==c){ out.print(c); } }} if(let[i].end>=start) start=let[i].end; } out.flush(); out.close(); // System.out.println(out); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
afef933973b7ff5b9a3061ffac501073
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
/* * * @Author Ajudiya_13(Bhargav Girdharbhai Ajudiya) * Dhirubhai Ambani Institute of Information And Communication Technology * */ import java.util.*; import java.io.*; import java.lang.*; public class Code198 { 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); } } public static long mod = 1000000007; public static int d; public static int p; public static int q; public static int[] suffle(int[] a,Random gen) { int n = a.length; for(int i=0;i<n;i++) { int ind = gen.nextInt(n-i)+i; int temp = a[ind]; a[ind] = a[i]; a[i] = temp; } return a; } public static void swap(int a, int b){ int temp = a; a = b; b = temp; } public static ArrayList<Integer> primeFactorization(int n) { ArrayList<Integer> a =new ArrayList<Integer>(); for(int i=2;i*i<=n;i++) { while(n%i==0) { a.add(i); n/=i; } } if(n!=1) a.add(n); return a; } public static void sieve(boolean[] isPrime,int n) { for(int i=1;i<n;i++) isPrime[i] = true; isPrime[0] = false; isPrime[1] = false; for(int i=2;i*i<n;i++) { if(isPrime[i] == true) { for(int j=(2*i);j<n;j+=i) isPrime[j] = false; } } } public static int GCD(int a,int b) { if(b==0) return a; else return GCD(b,a%b); } public static long GCD(long a,long b) { if(b==0) return a; else return GCD(b,a%b); } public static void extendedEuclid(int A,int B) { if(B==0) { d = A; p = 1 ; q = 0; } else { extendedEuclid(B, A%B); int temp = p; p = q; q = temp - (A/B)*q; } } public static long LCM(long a,long b) { return (a*b)/GCD(a,b); } public static int LCM(int a,int b) { return (a*b)/GCD(a,b); } public static int binaryExponentiation(int x,int n) { int result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static long binaryExponentiation(long x,long n) { long result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static int modularExponentiation(int x,int n,int M) { int result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x*x)%M; n=n/2; } return result; } public static long modularExponentiation(long x,long n,long M) { long result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x*x)%M; n=n/2; } return result; } public static int modInverse(int A,int M) { return modularExponentiation(A,M-2,M); } public static long modInverse(long A,long M) { return modularExponentiation(A,M-2,M); } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) { if (n%i == 0 || n%(i+2) == 0) return false; } return true; } static class pair implements Comparable<pair> { Integer x, y; pair(int x,int y) { this.x=x; this.y=y; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } } public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); char[] s = in.nextLine().toCharArray(); ArrayList<Character> ans = new ArrayList<>(); ans.add(s[s.length-1]); for(int i=s.length-2;i>=0;i--) { if(s[i]>=ans.get(ans.size()-1)) ans.add(s[i]); } for(int i=ans.size()-1;i>=0;i--) pw.print(ans.get(i)); pw.flush(); pw.close(); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
69b0a0d904b5814e301909e85aa625fc
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.util.*; import java.io.*; public class abc { static void print(Object o){ System.out.println(o); } static String getch(int i){ switch(i){ case (0): return "a"; case (1): return "b"; case (2): return "c"; case (3): return "d"; case (4): return "e"; case (5): return "f"; case (6): return "g"; case (7): return "h"; case (8): return "i"; case (9): return "j"; case (10): return "k"; case (11): return "l"; case (12): return "m"; case (13): return "n"; case (14): return "o"; case (15): return "p"; case (16): return "q"; case (17): return "r"; case (18): return "s"; case (19): return "t"; case (20): return "u"; case (21): return "v"; case (22): return "w"; case (23): return "x"; case (24): return "y"; case (25): return "z"; } return "h"; } public static void main (String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); LinkedList<Integer> l[]; l = new LinkedList[26]; for(int i=0;i<26;i++){ l[i] = new LinkedList<Integer>(); } int len = s.length(); for(int i=0;i<len;i++){ l[s.charAt(i)-'a'].add(i); } int start = 0; int n = 0; int temp = 0; for(int i=25;i>=0;i--){ Iterator<Integer> k = l[i].listIterator(); while (k.hasNext()) { n = k.next(); if (n>=start){ //print(n + " "+ start); System.out.print(getch(i)); temp = n; } } start = temp; } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
b7a98f5e8c0d0b93b3a577917e7b735d
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.*; import java.util.*; import java.text.*; import java.lang.*; import java.lang.reflect.Array; import java.math.BigInteger; import java.util.regex.*; public class Myclass { public static ArrayList a[]=new ArrayList[300001]; public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); char []s=in.nextLine().toCharArray(); for(int i=0;i<26;i++) { a[i]=new ArrayList<Integer>(); } for(int i=0;i<s.length;i++) { a[s[i]-'a'].add(i); } Vector<Character>ans=new Vector<>(); int end=-1; for(int i=25;i>=0;i--) { for(int j=0;j<a[i].size();j++) { int idx=(int) a[i].get(j); if(idx>end) { end=idx; ans.add((char)(i+'a')); } } } for(int i=0;i<ans.size();i++) { pw.print(ans.get(i)); } pw.flush(); pw.close(); } 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; } static class tri implements Comparable<tri> { int p, c, l; tri(int p, int c, int l) { this.p = p; this.c = c; this.l = l; } public int compareTo(tri o) { return Integer.compare(l, o.l); } } 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); } } public static long mod = 1000000007; public static int d; public static int p; public static int q; public static int[] suffle(int[] a,Random gen) { int n = a.length; for(int i=0;i<n;i++) { int ind = gen.nextInt(n-i)+i; int temp = a[ind]; a[ind] = a[i]; a[i] = temp; } return a; } public static void swap(int a, int b){ int temp = a; a = b; b = temp; } public static HashSet<Integer> primeFactorization(int n) { HashSet<Integer> a =new HashSet<Integer>(); for(int i=2;i*i<=n;i++) { while(n%i==0) { a.add(i); n/=i; } } if(n!=1) a.add(n); return a; } public static void sieve(boolean[] isPrime,int n) { for(int i=1;i<n;i++) isPrime[i] = true; isPrime[0] = false; isPrime[1] = false; for(int i=2;i*i<n;i++) { if(isPrime[i] == true) { for(int j=(2*i);j<n;j+=i) isPrime[j] = false; } } } public static int GCD(int a,int b) { if(b==0) return a; else return GCD(b,a%b); } public static long GCD(long a,long b) { if(b==0) return a; else return GCD(b,a%b); } public static void extendedEuclid(int A,int B) { if(B==0) { d = A; p = 1 ; q = 0; } else { extendedEuclid(B, A%B); int temp = p; p = q; q = temp - (A/B)*q; } } public static long LCM(long a,long b) { return (a*b)/GCD(a,b); } public static int LCM(int a,int b) { return (a*b)/GCD(a,b); } public static int binaryExponentiation(int x,int n) { int result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static long binaryExponentiation(long x,long n) { long result=1; while(n>0) { if(n % 2 ==1) result=result * x; x=x*x; n=n/2; } return result; } public static int modularExponentiation(int x,int n,int M) { int result=1; while(n>0) { if(n % 2 ==1) result=(result * x)%M; x=(x%M*x)%M; n=n/2; } return result; } public static long modularExponentiation(long x,long n,long M) { long result=1; while(n>0) { if(n % 2 ==1) result=(result%M * x%M)%M; x=(x%M * x%M)%M; n=n/2; } return result; } public static long modInverse(int A,int M) { return modularExponentiation(A,M-2,M); } public static long modInverse(long A,long M) { return modularExponentiation(A,M-2,M); } public static boolean isPrime(int n) { if (n <= 1) return false; if (n <= 3) return true; if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) { if (n%i == 0 || n%(i+2) == 0) return false; } return true; } public static long[] shuffle(long[] a, Random gen){ for(int i = 0, n = a.length;i < n;i++){ int ind = gen.nextInt(n-i)+i; long d = a[i]; a[i] = a[ind]; a[ind] = d; } return a; } static class pair implements Comparable<pair> { Long x; Long y; pair(long a,long sum) { this.x=a; this.y=sum; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } public String toString() { return x+" "+y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair)o; return p.x == x && p.y == y ; } return false; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode(); } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
fd51021ce4bc3accd0385e3ddffa124e
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.*; import java.util.*; public class Lexico{ public static void main(String[] args) { Scanner sc=new Scanner(System.in); String s=sc.next(); char arr[]=s.toCharArray(); int last=-1; for(int i=122;i>=97;i--){ for(int j=0;j<arr.length;j++){ if(arr[j]==(char)i && j>last){System.out.print((char)i);arr[j]='#';last=j;} } } // end of i loop } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
6dcf6c2d1f0a7586e536b7a8fb1607ce
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
//package codeforces; import java.io.BufferedReader; import java.io.Closeable; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeSet; public class A implements Closeable { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter writer = new PrintWriter(System.out); A() throws IOException { // reader = new BufferedReader(new FileReader("input.txt")); // writer = new PrintWriter(new FileWriter("output.txt")); } StringTokenizer stringTokenizer; String next() throws IOException { while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) { stringTokenizer = new StringTokenizer(reader.readLine()); } return stringTokenizer.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } final int MOD = 1000 * 1000 * 1000 + 7; int sum(int a, int b) { a += b; return a >= MOD ? a - MOD : a; } int product(int a, int b) { return (int) (1l * a * b % MOD); } int pow(int x, int k) { int result = 1; while (k > 0) { if (k % 2 == 1) { result = product(result, x); } x = product(x, x); k /= 2; } return result; } int inv(int x) { return pow(x, MOD - 2); } void solve() throws IOException { String s = next(); int si = 0; StringBuilder answer = new StringBuilder(); for(char c = 'z'; c >= 'a'; c--) { int li = s.substring(si).lastIndexOf(c); if(li == -1) { continue; } li += si; for(int i = si; i <= li; i++) { if(s.charAt(i) == c) { answer.append(c); } } si = li; } writer.println(answer); } public static void main(String[] args) throws IOException { try (A a = new A()) { a.solve(); } } @Override public void close() throws IOException { reader.close(); writer.close(); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
e7006b8cfaf0d6645628cf8506a292b4
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.util.*; import java.io.*; public class codeforces { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); String s = in.nextLine(); int n = s.length(); Stack<Character> stack = new Stack<>(); for(int i=n-1;i>=0;i--) { if(stack.isEmpty()) stack.push(s.charAt(i)); else { if(s.charAt(i) - stack.peek() >= 0) stack.add(s.charAt(i)); } } for(int i=stack.size()-1;i>=0;i--) pw.print(stack.get(i)); pw.flush(); pw.close(); } public static long GCD(long a,long b) { if(b==0) return a; else return GCD(b,a%b); } static class pair implements Comparable<pair> { Long x, y; pair(long x,long y) { this.x=x; this.y=y; } public int compareTo(pair o) { int result = x.compareTo(o.x); if(result==0) result = y.compareTo(o.y); return result; } public String toString() { return x+" "+y; } public boolean equals(Object o) { if (o instanceof pair) { pair p = (pair)o; return p.x - x == 0 && p.y - y == 0 ; } return false; } public int hashCode() { return new Long(x).hashCode()*31 + new Long(y).hashCode(); } } 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); } } static class CodeX { public static void sort(long arr[]) { merge_sort(arr, 0, arr.length - 1); } private static void merge_sort(long A[], long start, long end) { if (start < end) { long mid = (start + end) / 2; merge_sort(A, start, mid); merge_sort(A, mid + 1, end); merge(A, start, mid, end); } } private static void merge(long A[], long start,long mid, long end) { long p = start, q = mid + 1; long Arr[] = new long[(int)(end - start + 1)]; long k = 0; for (int i = (int)start; i <= end; i++) { if (p > mid) Arr[(int)k++] = A[(int)q++]; else if (q > end) Arr[(int)k++] = A[(int)p++]; else if (A[(int)p] < A[(int)q]) Arr[(int)k++] = A[(int)p++]; else Arr[(int)k++] = A[(int)q++]; } for (int i = 0; i < k; i++) { A[(int)start++] = Arr[i]; } } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
345dc6f699368872877b67a9db63c169
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; public class C124 { public static void main(String[] args) { MyScanner scan = new MyScanner(); String s = scan.next(); StringBuilder sol = new StringBuilder(); int N = s.length(); int[] last = new int[26]; Arrays.fill(last, -1); for(int i=0;i<N;i++){ last[s.charAt(i)-'a']=i; } int idx = 25; for(int i=0;i<N;i++){ while(idx>=0&&last[idx]<i){ idx--; } if(idx==-1)break; if(s.charAt(i)==idx+'a'){ sol.append((char)(idx+'a')); } } PrintWriter out = new PrintWriter(System.out); out.println(sol); out.close(); } private static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() {br = new BufferedReader(new InputStreamReader(System.in));} String next(){ while(st==null||!st.hasMoreElements()){ try{st = new StringTokenizer(br.readLine());} catch(IOException e){e.printStackTrace();} }return st.nextToken(); } int nextInt() {return Integer.parseInt(next());} long nextLong(){return Long.parseLong(next());} double nextDouble(){return Double.parseDouble(next());} } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
464def1e3bc540a6adbca73be62925c2
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.util.Scanner; public class A196 { public static void main(String[] args) { Scanner in = new Scanner(System.in); char[] S = in.next().toCharArray(); int lastIdx = 0; StringBuilder sb = new StringBuilder(); for (char c = 'z'; c >= 'a'; c--) { for (int i=lastIdx; i<S.length; i++) { if (S[i] == c) { sb.append(c); lastIdx = i; } } } System.out.println(sb); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
e0acf4ce1f02e1bd82e85db3a233b0ef
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.*; import java.util.*; public class simplex3 { public static void main(String args[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String str=br.readLine(); HashMap<Character,Integer> map=new HashMap<Character,Integer>(); for(int i=0;i<str.length();i++) { char c=str.charAt(i); if(map.containsKey(c)) map.put(c, map.get(c)+1); else map.put(c, 1); } boolean first=true; StringBuilder sb=new StringBuilder(); int l=0; for(char c='z';c>='a';c--) { if(map.containsKey(c)) { if(first) { int f=map.get(c); for(int i=0;i<f;i++) sb.append(c); l=str.lastIndexOf(c); first=false; } for(int i=l+1;i<str.length();i++) { if(str.charAt(i)==c) { sb.append(c); l=i; } } } } System.out.println(sb.toString()); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
394d8b90042c3d22e3bf82f7cf4691f4
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.util.*; public class cf{ public static void main(String args[]){ Scanner sc=new Scanner(System.in); char[] a=sc.next().toCharArray(); int n=a.length; char curr=a[n-1]; ArrayList<Character> s=new ArrayList<>(); s.add(curr); for(int i=n-2;i>=0;i--){ if(a[i]>=curr){ curr=a[i]; s.add(curr); } } for(int i=s.size()-1;i>=0;i--) System.out.print(s.get(i)); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
193850a722515334bc3eba6e52fd2008
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
/* Keep solving problems. */ import java.util.*; import java.io.*; public class CFA { BufferedReader br; PrintWriter out; StringTokenizer st; boolean eof; final long MOD = 1000L * 1000L * 1000L + 7; int[] dx = {0, -1, 0, 1}; int[] dy = {1, 0, -1, 0}; void solve() throws IOException { char[] arr = nextString().toCharArray(); StringBuilder sb = new StringBuilder(); int start = -1; for (char c = 'z'; c >= 'a'; c--) { int end = start + 1; for (int i = end; i < arr.length; i++) { if (arr[i] == c) { sb.append(c); start = i; } } } out(sb.toString()); } 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); } 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
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
9e05c17aa593c3fb37cc68acd2c1947c
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.PrintWriter; import java.util.ArrayList; import java.util.Scanner; public class Lexicographicallymaximum { public static void main(String[] args) { // TODO Auto-generated method stub Scanner input = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); String s = input.next(); String z = ""; int j=-1; //int i=0; ArrayList<Character> list = new ArrayList<Character>(); char curr = s.charAt(s.length()-1); list.add(curr); for(int i=s.length()-2;i>=0;i--){ if(s.charAt(i)>=curr){ list.add(s.charAt(i)); curr = s.charAt(i); } // System.out.println(z); } for(int i=list.size()-1;i>=0;i--)out.print(list.get(i)); //out.println(z); out.flush(); out.close(); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
6cd23754bd2999ac37de1aa700e7b612
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.util.*; import java.io.*; public class Main { public static void main(String[] args) { InputReader in = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); String s= in.readString(); int max=0; int[] nums = new int[26]; StringBuilder a = new StringBuilder(); for (int i =0;i<s.length();i++) { nums[s.charAt(i)-97]++; max=Math.max(max,s.charAt(i)-97); } for (int i=0;i<s.length();i++) { if (max>=0) { if (s.charAt(i)-97==max) { a.append(s.charAt(i)); } nums[s.charAt(i)-97]--; if (nums[max]==0) { while (max >= 0 && nums[max] == 0) { max--; } } } } out.printLine(a.toString()); out.flush(); } static void MergeSort(int[] a, int[] b, int p, int r) { if (p < r) { int q = (r + p) / 2; MergeSort(a, b, p, q); MergeSort(a, b, q + 1, r); Merge(a, b, p, q, r); } } static void Merge(int[] a, int[] b, int p, int q, int r) { int n1 = q - p + 1; int n2 = r - q; int[] R = new int[n1 + 1]; int[] L = new int[n2 + 1]; int[] R1 = new int[n1]; int[] L1 = new int[n2]; for (int i = 0; i < n1; i++) { R[i] = a[p + i]; R1[i] = b[p + i]; } R[n1] = Integer.MAX_VALUE; for (int i = 0; i < n2; i++) { L[i] = a[q + i + 1]; L1[i] = b[q + i + 1]; } L[n2] =Integer.MAX_VALUE; int n = a.length; int j = 0; int k = 0; for (int i = p; i <= r; i++) { if (L[j] < R[k]) { a[i] = L[j]; b[i] = L1[j]; j++; } else { a[i] = R[k]; b[i] = R1[k]; k++; } } } } class Graph { int n; ArrayList<Integer>[] adjList; public Graph(int n) { this.n = n; adjList = new ArrayList[n]; for (int i = 0; i < n; i++) adjList[i] = new ArrayList<>(); } } 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 nextInt() { 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 nextLong() { 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] = nextInt(); } 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; } } 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 printLine(Object... objects) { print(objects); writer.println(); } public void close() { writer.close(); } public void flush() { writer.flush(); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
f4a2a6889e0a59f7eafec56ab8b1d99e
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.*; import java.util.*; public class Main { 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()), n1 = Integer.parseInt(st.nextToken()), n2 = Integer.parseInt(st.nextToken()); char[] arr = br.readLine().toCharArray(); TreeMap<Character, Integer> tm = new TreeMap<>(); int max = 0; for(int i=0; i<arr.length; i++) { if(tm.get(arr[i]) == null) tm.put(arr[i],1); else tm.put(arr[i],tm.get(arr[i]) + 1); max = Math.max(arr[i], max); } StringBuilder ans = new StringBuilder(); for(int i=0; i<arr.length; i++) { if(arr[i] == max) { ans.append("" + arr[i]); if(tm.get(arr[i]) == 1) { tm.remove(arr[i]); try { max = tm.lastKey(); } catch (Exception e) { max = 0; } } else tm.put(arr[i],tm.get(arr[i]) - 1); } else { if(tm.get(arr[i]) == 1) { tm.remove(arr[i]); try { max = tm.lastKey(); } catch (Exception e) { max = 0; } } else tm.put(arr[i],tm.get(arr[i]) - 1); } } System.out.println(ans); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
20b71f3d41726303df074915be27d3fa
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.ArrayList; import java.util.StringTokenizer; public class Abood2B { public static void main(String[] args) throws IOException { Scanner sc = new Scanner(System.in); PrintWriter out = new PrintWriter(System.out); String s = sc.next(); ArrayList<Character> ans = new ArrayList<>(); ans.add(s.charAt(s.length() - 1)); char max = s.charAt(s.length() - 1); for (int i = s.length() - 2; i >= 0; i--) if(s.charAt(i) >= max) { ans.add(s.charAt(i)); max = s.charAt(i); } for (int i = ans.size() - 1; i >= 0; i--) out.print(ans.get(i)); out.println(); out.flush(); } 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 { 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
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
e70853f71d86578a315a9e9bdc344129
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.awt.AWTException; import java.awt.Robot; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.math.BigInteger; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import java.util.Queue; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.text.html.parser.Entity; public class Main { public static void main(String[] args) throws InterruptedException, AWTException { InputStream inputStream = System.in; OutputStream outputStream = System.out; PrintWriter out = new PrintWriter(outputStream); InputReader in = new InputReader(inputStream); char[] a = in.next().toCharArray(); char[] max = new char[a.length]; max[a.length - 1] = a[a.length - 1]; for(int i = a.length - 2; i >= 0; i--) { max[i] = (char)Math.max(a[i], max[i + 1]); } for(int i = 0; i < a.length; i++) { if(max[i] == a[i]) out.print(a[i]); } out.println(); out.close(); } static class InputReader { BufferedReader reader; StringTokenizer tokenizer; public InputReader(InputStream inputStream) { reader = new BufferedReader(new InputStreamReader(inputStream), 32624); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) { try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } private long nextLong() { return Long.parseLong(next()); } private BigInteger nextBigInteger() { return new BigInteger(next()); } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
34e972989cc5655cdd2e1c1e6f19fbc6
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Scanner; import java.util.StringTokenizer; import java.util.*; public class lmse { //By shwetank_verma static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader(new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } static int mod=1000000007; static boolean primes[]=new boolean[1000007]; static boolean seive(int n){ Arrays.fill(primes,true); primes[0]=primes[1]=false; for(int i=2;i*i<=n;i++){ if(primes[i]==true){ for(int p=i*i;p<=n;p+=i){ primes[p]=false; } } } if(n<1000007){ return primes[n]; } return false; } static int gcd(int a,int b){ if(b==0) return a; return gcd(b,a%b); } static long GCD(long a,long b){ if(b==0) return a; return GCD(b,a%b); } public static void main(String[] args) { FastReader sc=new FastReader(); try{ String s=sc.next(); int l=s.length(); int a[]=new int[26]; int max=-1; int p=0; for(int i=0;i<l;i++) { char ch=s.charAt(i); if(ch-97>=max) { max=ch-97; } } while(max!=-1) { for(int j=p;j<l;j++) { if(max==s.charAt(j)-97) { p=j; a[max]++; } } max--; } for(int i=25;i>=0;i--) { for(int j=0;j<a[i];j++) { System.out.print((char)(i+97)); } } }catch(Exception e){ return; } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 8
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
b0ff245a47dc5e1f91b0a1c2c7e583a3
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.*; import java.util.*; public class CodeForces { static boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null; void runCase(int caseNum) throws IOException { String str = next(); char[] ret = new char[str.length()]; int len = 0; char cur = 'z'; int pos = 0; while (true) { boolean find = false; for (int i = pos; i < str.length(); ++i) if (str.charAt(i) == cur) { find = true; pos = i + 1; ret[len++] = cur; break; } if (!find) --cur; if (cur < 'a') break; } // out.print("Case #" + caseNum + ":"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; ++i) sb.append(ret[i]); out.println(sb.toString()); } public static void main(String[] args) throws IOException { if (ONLINE_JUDGE){ System.out.println(); in = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(System.out); }else{ in = new BufferedReader(new FileReader("input.txt")); out = new PrintWriter("output.txt"); } new CodeForces().runIt(); out.flush(); out.close(); return; } static BufferedReader in; private StringTokenizer st; static PrintWriter out; String next() throws IOException { while (!st.hasMoreTokens()) { String line = in.readLine(); if (line == null) { return null; } st = new StringTokenizer(line); } String ret = st.nextToken(); if (ret == null || ret.length() == 0) return next(); return ret; } int nextInt() throws IOException { return Integer.parseInt(next()); } double nextDouble() throws IOException { return Double.parseDouble(next()); } long nextLong() throws IOException { return Long.parseLong(next()); } void runIt() throws IOException { st = new StringTokenizer(""); // int N = nextInt(); // for (int i = 0; i < N; i++) { // runCase(i + 1); // } runCase(0); out.flush(); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
5dcfcea8ff5abc4b419fc07451d67ec8
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class C { static long[][] a; static long[][] adj; public static void main(String[] args) throws IOException { InputReader in = new InputReader(); char[] s = in.next().toCharArray(); int[] f = new int[26]; int[] t = new int[26]; for (int i = 0; i < t.length; i++) t[i] = -1; for (int i = 0; i < t.length; i++) f[i] = 1 << 25; for (int i = 0; i < s.length; i++) { f[s[i] - 'a'] = Math.min(f[s[i] - 'a'], i); t[s[i] - 'a'] = Math.max(t[s[i] - 'a'], i); } int at = 0; StringBuilder sb = new StringBuilder(); for (int i = 25; i >= 0; i--) { if (t[i] != -1) { at = Math.max(at, f[i]); while (at <= t[i]) { if (s[at] == (i + 'a')) sb.append((char) (i + 'a')); at++; } } } System.out.println(sb); } static class InputReader { BufferedReader in; StringTokenizer st; public InputReader() throws IOException { in = new BufferedReader(new InputStreamReader(System.in)); st = new StringTokenizer(in.readLine()); } public String next() throws IOException { while (!st.hasMoreElements()) st = new StringTokenizer(in.readLine()); return st.nextToken(); } public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); } public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); } } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
84fbcd151da8f4e366f74f2db4d97b29
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.util.Scanner; public class LexicographicallyMaximumSubsequence { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String x = sc.next(); StringBuilder sb = new StringBuilder(); int len = x.length(); char max = 'a'; for(int i = len-1; i >= 0; i--) { if(x.charAt(i) >= max) { sb.append(x.charAt(i)); max = x.charAt(i); } } System.out.println(sb.reverse()); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
9bcbbd128f61cd0e59ae91989dc23fe9
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.*; public class Main { public static void main(String[] args) throws Exception { char[] s = inB.readLine().toCharArray(); int pos = 0; StringBuilder ans = new StringBuilder(); for(char c = 'z'; c >= 'a'; c--){ for(int i = pos; i < s.length; i++){ if(s[i] == c){ pos = i; ans.append(s[i]); } } } exit(ans); } private static PrintWriter out = new PrintWriter(System.out);; private static BufferedReader inB = new BufferedReader(new InputStreamReader(System.in)); private static StreamTokenizer in = new StreamTokenizer(inB); private static void exit(Object o) throws Exception { out.println(o); out.flush(); System.exit(0); } private static void println(Object o) throws Exception{ out.println(o); out.flush(); } private static void print(Object o) throws Exception{ out.print(o); out.flush(); } private static int nextInt() throws Exception { in.nextToken(); return (int)in.nval; } private static String nextString() throws Exception { in.nextToken(); return in.sval; } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
95aedb63ad02fb6f8b336f544a43985a
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class Solution { void solve() throws IOException { String s = nextToken();//, res = ""; final int inf = 1000000000; int[] fpos = new int[300], lpos = new int[300]; Arrays.fill(fpos, inf); Arrays.fill(lpos, -1); char maxc = 'a', minc = 'z'; for (int i = 0; i < s.length(); ++i) { if (s.charAt(i) > maxc) { maxc = s.charAt(i); } if (s.charAt(i) < minc) { minc = s.charAt(i); } fpos[s.charAt(i)] = Math.min(fpos[s.charAt(i)], i); lpos[s.charAt(i)] = Math.max(lpos[s.charAt(i)], i); } int last = 0, cnt = 0; char[] res = new char[100010]; for (char i = maxc; i >= minc; --i) { for (int j = Math.max(fpos[i], last); j <= lpos[i]; ++j) { if (s.charAt(j) == i) { res[cnt++] = i; } } last = Math.max(last, lpos[i] + 1); } for (int i = 0; i < cnt; ++i) { System.out.print(res[i]); } } BufferedReader br; StringTokenizer st; String nextToken() throws IOException { while (st == null || !st.hasMoreTokens()) { String s = br.readLine(); if (s == null) { return "-1"; } st = new StringTokenizer(s); } return st.nextToken(); } int nextInt() throws IOException { return Integer.parseInt(nextToken()); } long nextLong() throws IOException { return Long.parseLong(nextToken()); } double nextDouble() throws IOException { return Double.parseDouble(nextToken()); } void run() throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); solve(); br.close(); } public static void main(String[] args) throws IOException { new Solution().run(); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
8976076b299ebb2493139145bd798b99
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.OutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.InputMismatchException; import java.io.Writer; import java.io.InputStream; /** * Built using CHelper plug-in * Actual solution is at the top * @author emotionalBlind */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); OutputWriter out = new OutputWriter(outputStream); TaskA solver = new TaskA(); solver.solve(1, in, out); out.close(); } } class TaskA { public void solve(int testNumber, InputReader in, OutputWriter out) { String s = in.readString(); int[] cMax = new int[s.length()]; for (int i = s.length() - 1; i >= 0; --i) { if (i == s.length() - 1) { cMax[i] = s.charAt(i); } else { cMax[i] = Math.max(cMax[i + 1], s.charAt(i)); } } for (int i = 0; i < s.length(); ++i) { if (s.charAt(i) == cMax[i]) { out.print(s.charAt(i)); } } } } class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (numChars == -1) throw new InputMismatchException(); if (curChar >= numChars) { curChar = 0; try { numChars = stream.read(buf); } catch (IOException e) { throw new InputMismatchException(); } if (numChars <= 0) return -1; } return buf[curChar++]; } public int readInt() { int c = read(); while (isSpaceChar(c)) c = read(); int sgn = 1; if (c == '-') { sgn = -1; c = read(); } int res = 0; do { if (c < '0' || c > '9') throw new InputMismatchException(); res *= 10; res += c - '0'; c = read(); } while (!isSpaceChar(c)); return res * sgn; } public String readString() { int c = read(); while (isSpaceChar(c)) c = read(); StringBuffer res = new StringBuffer(); do { res.appendCodePoint(c); c = read(); } while (!isSpaceChar(c)); return res.toString(); } public static boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } } class OutputWriter { private final PrintWriter writer; public OutputWriter(OutputStream outputStream) { writer = new PrintWriter(outputStream); } public OutputWriter(Writer writer) { this.writer = new PrintWriter(writer); } public void print(Object...objects) { for (int i = 0; i < objects.length; i++) { if (i != 0) writer.print(' '); writer.print(objects[i]); } } public void close() { writer.close(); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
75e144cdeb08b2ead190d3c88011b5c0
train_001.jsonl
1339506000
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence.We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≀ p1 &lt; p2 &lt; ... &lt; pk ≀ |s|) a subsequence of string s = s1s2... s|s|.String x = x1x2... x|x| is lexicographically larger than string y = y1y2... y|y|, if either |x| &gt; |y| and x1 = y1, x2 = y2, ... , x|y| = y|y|, or exists such number r (r &lt; |x|, r &lt; |y|), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &gt; yr + 1. Characters in lines are compared like their ASCII codes.
256 megabytes
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.PrintWriter; import java.util.Scanner; public class ProblemA { public static void main(String[] args) { new ProblemA().solve(); } private void solve() { Scanner in = new Scanner(new BufferedInputStream(System.in)); PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out)); char[] str = in.next().toCharArray(); int last = 0; for (int k = 25; k >= 0; k--) { char c = ((char)('a' + k)); for (int i = last; i < str.length; i++) { if (str[i] == c) { out.print(c); last = i; } } } out.println(); out.flush(); out.close(); } }
Java
["ababba", "abbcbccacbbcbaaba"]
2 seconds
["bbba", "cccccbba"]
NoteLet's look at samples and see what the sought subsequences look like (they are marked with uppercase bold letters).The first sample: aBaBBAThe second sample: abbCbCCaCbbCBaaBA
Java 6
standard input
[ "greedy", "strings" ]
77e2a6ba510987ed514fed3bd547b5ab
The single line contains a non-empty string s, consisting only of lowercase English letters. The string's length doesn't exceed 105.
1,100
Print the lexicographically maximum subsequence of string s.
standard output
PASSED
452d892f4f88e03827310fc91c3b3cc7
train_001.jsonl
1409061600
Appleman has a very big sheet of paper. This sheet has a form of rectangle with dimensions 1 × n. Your task is help Appleman with folding of such a sheet. Actually, you need to perform q queries. Each query will have one of the following types: Fold the sheet of paper at position pi. After this query the leftmost part of the paper with dimensions 1 × pi must be above the rightmost part of the paper with dimensions 1 × ([currentΒ widthΒ ofΒ sheet] - pi). Count what is the total width of the paper pieces, if we will make two described later cuts and consider only the pieces between the cuts. We will make one cut at distance li from the left border of the current sheet of paper and the other at distance ri from the left border of the current sheet of paper. Please look at the explanation of the first test example for better understanding of the problem.
256 megabytes
import java.io.*; import java.util.StringTokenizer; public class Main { public static void main(String[] args) { MyInput in = new MyInput(System.in); PrintWriter out = new PrintWriter(System.out); Solver solver = new Solver(); int testCase = 1; try { while (true) { solver.solve(testCase++, out, in); } } catch (UnknownError e) { out.flush(); out.close(); } } } class Solver { public void solve(int test, PrintWriter out, MyInput in) { int n = in.readInt(); int q = in.readInt(); FenwickTree fenwickTree = new FenwickTree(n); for (int i = 0; i < n; i++) { fenwickTree.update(i, 1); } int left = 0; int right = n; boolean reverse = false; for (int i = 0; i < q; i++) { int type = in.readInt(); if (type == 1) { int p = in.readInt(); if (left + p + p > right) { p = right - left - p; reverse = !reverse; } // out.println("right = " + right + " reverse = " + reverse); // out.flush(); if (reverse) { right -= p; for (int j = 0; j < p; j++) { fenwickTree.update(right - 1 - j, fenwickTree.rangeSum(right + j, right + j)); } } else { left += p; for (int j = 0; j < p; j++) { fenwickTree.update(left + j, fenwickTree.rangeSum(left - j - 1, left - j - 1)); } } } else { int l = in.readInt(); int r = in.readInt(); if (reverse) { out.println(fenwickTree.rangeSum(right - r, right - l - 1)); } else { out.println(fenwickTree.rangeSum(left + l, left + r - 1)); } // out.flush(); } } } } /** * Created by shamir14 on 3/14/14. */ class FenwickTree { private int[] tree; private int maxVal; public FenwickTree(int n) { maxVal = n; tree = new int[maxVal + 1]; } /** * update element val by adding the val to it * O(LOG(N)) */ public void update(int idx, int val) { idx++; while (idx <= maxVal) { tree[idx] += val; idx += (idx & (-idx)); } } /** * return the sum of values of tree[] from idx to 0 * O(LOG(N)) */ public int read(int idx) { idx++; int sum = 0; while (idx > 0) { sum += tree[idx]; idx -= (idx & -idx); } return sum; } public int getMaxVal() { return maxVal; } public int rangeSum(int left, int right) { if(left > right) return 0; int sumLeft = read(left - 1); int sumRight = read(right); return sumRight - sumLeft; } } class MyInput { BufferedReader br; StringTokenizer st; public MyInput (InputStream inputStream) { br = new BufferedReader(new InputStreamReader(inputStream)); st = null; } public String next() { if (st == null || !st.hasMoreElements()) { try { String str = br.readLine(); if (str == null || str.equals("")) { throw new UnknownError(); } st = new StringTokenizer(str); } catch (IOException e) { throw new UnknownError(); } } return st.nextToken(); } public void readEmptyLine() { try { br.readLine(); } catch (IOException e) { throw new UnknownError(); } } public int readInt() { return Integer.parseInt(next()); } }
Java
["7 4\n1 3\n1 2\n2 0 1\n2 1 2", "10 9\n2 2 9\n1 1\n2 0 1\n1 8\n2 0 8\n1 2\n2 1 3\n1 4\n2 2 4"]
2 seconds
["4\n3", "7\n2\n10\n4\n5"]
NoteThe pictures below show the shapes of the paper during the queries of the first example: After the first fold operation the sheet has width equal to 4, after the second one the width of the sheet equals to 2.
Java 7
standard input
[ "data structures", "implementation" ]
19d9a438bf6353638b08252b030c407b
The first line contains two integers: n and q (1  ≀ n ≀ 105;Β 1 ≀ q ≀ 105) β€” the width of the paper and the number of queries. Each of the following q lines contains one of the described queries in the following format: "1 pi" (1 ≀ pi &lt; [currentΒ widthΒ ofΒ sheet]) β€” the first type query. "2 li ri" (0 ≀ li &lt; ri ≀ [currentΒ widthΒ ofΒ sheet]) β€” the second type query.
2,200
For each query of the second type, output the answer.
standard output
PASSED
199d0e323fe264d73067ecd7af889383
train_001.jsonl
1409061600
Appleman has a very big sheet of paper. This sheet has a form of rectangle with dimensions 1 × n. Your task is help Appleman with folding of such a sheet. Actually, you need to perform q queries. Each query will have one of the following types: Fold the sheet of paper at position pi. After this query the leftmost part of the paper with dimensions 1 × pi must be above the rightmost part of the paper with dimensions 1 × ([currentΒ widthΒ ofΒ sheet] - pi). Count what is the total width of the paper pieces, if we will make two described later cuts and consider only the pieces between the cuts. We will make one cut at distance li from the left border of the current sheet of paper and the other at distance ri from the left border of the current sheet of paper. Please look at the explanation of the first test example for better understanding of the problem.
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 */ public class Main { public static void main(String[] args) { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader in = new InputReader(inputStream); PrintWriter out = new PrintWriter(outputStream); TaskC solver = new TaskC(); solver.solve(1, in, out); out.close(); } } class TaskC { public void solve(int testNumber, InputReader in, PrintWriter out) { int n = in.nextInt(); int numQueries = in.nextInt(); BinaryIndexedTree tree = new BinaryIndexedTree(n); for (int i = 0; i < n; ++i) { tree.update(i, 1); } int[] thick = new int[n]; Arrays.fill(thick, 1); int leftBorder = 0; int rightBorder = n; boolean reverse = false; for (int query = 0; query < numQueries; ++query) { int type = in.nextInt(); if (type == 1) { int leftSide = in.nextInt(); int rightSide = rightBorder - leftBorder - leftSide; boolean willReverse = !(leftSide < rightSide); if (reverse) { int tmp = leftSide; leftSide = rightSide; rightSide = tmp; } if (leftSide < rightSide) { for (int i = 0; i < leftSide; ++i) { tree.update(leftBorder + 2 * leftSide - i - 1, thick[leftBorder + i]); thick[leftBorder + 2 * leftSide - i - 1] += thick[leftBorder + i]; } leftBorder += leftSide; } else { for (int i = 0; i < rightSide; ++i) { tree.update(rightBorder - 2 * rightSide + i, thick[rightBorder - i - 1]); thick[rightBorder - 2 * rightSide + i] += thick[rightBorder - i - 1]; } rightBorder -= rightSide; } reverse ^= willReverse; } else { int left = in.nextInt(); int right = in.nextInt(); if (reverse) { left = rightBorder - leftBorder - left; right = rightBorder - leftBorder - right; int tmp = left; left = right; right = tmp; } long answer = tree.get(leftBorder + right - 1) - tree.get(leftBorder + left - 1); out.println(answer); } } } } class BinaryIndexedTree { long[] data; public BinaryIndexedTree(int n) { data = new long[n]; } void update(int at, int by) { while (at < data.length) { data[at] += by; at |= at + 1; } } long get(int at) { long answer = 0; while (at >= 0) { answer += data[at]; at -= ~at & (at + 1); } return answer; } } class InputReader { private BufferedReader reader; private StringTokenizer tokenizer; public InputReader(InputStream stream) { reader = new BufferedReader(new InputStreamReader(stream), 32768); tokenizer = null; } public String next() { while (tokenizer == null || !tokenizer.hasMoreTokens()) try { tokenizer = new StringTokenizer(reader.readLine()); } catch (IOException e) { throw new RuntimeException(e); } return tokenizer.nextToken(); } public int nextInt() { return Integer.parseInt(next()); } }
Java
["7 4\n1 3\n1 2\n2 0 1\n2 1 2", "10 9\n2 2 9\n1 1\n2 0 1\n1 8\n2 0 8\n1 2\n2 1 3\n1 4\n2 2 4"]
2 seconds
["4\n3", "7\n2\n10\n4\n5"]
NoteThe pictures below show the shapes of the paper during the queries of the first example: After the first fold operation the sheet has width equal to 4, after the second one the width of the sheet equals to 2.
Java 7
standard input
[ "data structures", "implementation" ]
19d9a438bf6353638b08252b030c407b
The first line contains two integers: n and q (1  ≀ n ≀ 105;Β 1 ≀ q ≀ 105) β€” the width of the paper and the number of queries. Each of the following q lines contains one of the described queries in the following format: "1 pi" (1 ≀ pi &lt; [currentΒ widthΒ ofΒ sheet]) β€” the first type query. "2 li ri" (0 ≀ li &lt; ri ≀ [currentΒ widthΒ ofΒ sheet]) β€” the second type query.
2,200
For each query of the second type, output the answer.
standard output
PASSED
9b5e036d7d011eaba5fdb406d0eb6de0
train_001.jsonl
1409061600
Appleman has a very big sheet of paper. This sheet has a form of rectangle with dimensions 1 × n. Your task is help Appleman with folding of such a sheet. Actually, you need to perform q queries. Each query will have one of the following types: Fold the sheet of paper at position pi. After this query the leftmost part of the paper with dimensions 1 × pi must be above the rightmost part of the paper with dimensions 1 × ([currentΒ widthΒ ofΒ sheet] - pi). Count what is the total width of the paper pieces, if we will make two described later cuts and consider only the pieces between the cuts. We will make one cut at distance li from the left border of the current sheet of paper and the other at distance ri from the left border of the current sheet of paper. Please look at the explanation of the first test example for better understanding of the problem.
256 megabytes
import java.io.*; import java.math.*; import java.util.*; public class Main { void add(int[] count, int k, int v) { int n = count.length; for (; k < n; k += -k & k) { count[k] += v; } } int ask(int[] count, int k) { int result = 0; for (; k > 0; k -= -k & k) { result += count[k]; } return result; } public void run() { int n = reader.nextInt(); int q = reader.nextInt(); int[] count = new int[n + 1]; for (int i = 1; i <= n; ++ i) { add(count, i, 1); } int offset = 0; int direction = +1; int width = n; while (q > 0) { q --; int type = reader.nextInt(); if (type == 1) { int p = reader.nextInt(); if (p + p <= width) { for (int i = 0; i < p; ++ i) { int j = offset + i * direction; if (direction == +1) { j ++; } int value = ask(count, j) - ask(count, j - 1); int k = offset + (2 * p - i) * direction; if (direction == -1) { k ++; } add(count, k, value); } offset += p * direction; } else { for (int i = p; i < width; ++ i) { int j = offset + i * direction; if (direction == +1) { j ++; } int value = ask(count, j) - ask(count, j - 1); int k = offset + (2 * p - i) * direction; if (direction == -1) { k ++; } add(count, k, value); } offset += p * direction; direction *= -1; } width = Math.max(p, width - p); } else { int l = reader.nextInt(); int r = reader.nextInt(); if (direction == +1) { writer.println(ask(count, offset + r) - ask(count, offset + l)); } else { writer.println(ask(count, offset - l) - ask(count, offset - r)); } } } writer.close(); } Main() { reader = new InputReader(System.in); writer = new PrintWriter(System.out); } public static void main(String[] args) { new Main().run(); } private static void debug(Object...os) { System.err.println(Arrays.deepToString(os)); } private InputReader reader; private PrintWriter writer; } class InputReader { public InputReader(InputStream stream) { this.stream = stream; } public int nextChar() { if (charCount == -1) throw new InputMismatchException(); if (head >= charCount) { head = 0; try { charCount = stream.read(buffer); } catch (IOException e) { throw new InputMismatchException(); } if (charCount <= 0) return -1; } return buffer[head ++]; } public int nextInt() { int c = nextChar(); while (isSpaceChar(c)) { c = nextChar(); } int sign = 1; if (c == '-') { sign = -1; c = nextChar(); } int result = 0; do { if (c < '0' || c > '9') { throw new InputMismatchException(); } result *= 10; result += c - '0'; c = nextChar(); } while (!isSpaceChar(c)); return sign * result; } public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; } private InputStream stream; private int head, charCount; private byte[] buffer = new byte[1024]; }
Java
["7 4\n1 3\n1 2\n2 0 1\n2 1 2", "10 9\n2 2 9\n1 1\n2 0 1\n1 8\n2 0 8\n1 2\n2 1 3\n1 4\n2 2 4"]
2 seconds
["4\n3", "7\n2\n10\n4\n5"]
NoteThe pictures below show the shapes of the paper during the queries of the first example: After the first fold operation the sheet has width equal to 4, after the second one the width of the sheet equals to 2.
Java 7
standard input
[ "data structures", "implementation" ]
19d9a438bf6353638b08252b030c407b
The first line contains two integers: n and q (1  ≀ n ≀ 105;Β 1 ≀ q ≀ 105) β€” the width of the paper and the number of queries. Each of the following q lines contains one of the described queries in the following format: "1 pi" (1 ≀ pi &lt; [currentΒ widthΒ ofΒ sheet]) β€” the first type query. "2 li ri" (0 ≀ li &lt; ri ≀ [currentΒ widthΒ ofΒ sheet]) β€” the second type query.
2,200
For each query of the second type, output the answer.
standard output
PASSED
7493805b3d541f5dedf53b5fce617cff
train_001.jsonl
1469205300
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
256 megabytes
import java.io.*; import java.util.HashSet; import java.util.StringTokenizer; public class Task1 { static class FastScanner { BufferedReader br; StringTokenizer st; FastScanner(File f) { try { br = new BufferedReader(new FileReader(f)); } catch (FileNotFoundException e) { e.printStackTrace(); } } FastScanner(InputStream f) { br = new BufferedReader(new InputStreamReader(f)); } String nextLine() { try { return br.readLine(); } catch (IOException e) { return null; } } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } } public static void main(String[] args) { FastScanner in = new FastScanner(System.in); TaskB solver = new TaskB(); solver.solve(in); } static class TaskB { public void solve(FastScanner in) { long n = in.nextInt(); int m = in.nextInt(); HashSet<Integer> coordX = new HashSet<>(); HashSet<Integer> coordY = new HashSet<>(); long total = n * n; for (int i = 0; i < m; i++) { int x = in.nextInt(); int y = in.nextInt(); coordX.add(x); coordY.add(y); long answer = total - n * (coordX.size() + coordY.size()) + (long) coordX.size() * coordY.size(); System.out.printf("%d ", answer); } System.out.println(); } } }
Java
["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"]
2 seconds
["4 2 0", "16 9", "9999800001"]
NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
Java 11
standard input
[ "data structures", "math" ]
faf1abdeb6f0cf34972d5cb981116186
The first line of the input contains two integers n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ min(100 000, n2))Β β€” the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
1,200
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
standard output
PASSED
d4a795fde7c291a7f5d25b443c548a33
train_001.jsonl
1469205300
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
256 megabytes
import java.io.*; import java.util.*; /* * To execute Java, please define "static void main" on a class * named Solution. * * If you need more classes, simply define them inline. */ public class CellsNotUnderAttack { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); boolean[] row = new boolean[N]; boolean[] col = new boolean[N]; //long safeBlockCount = N*N; int rowCount = N; int colCount = N; int rooksCount = sc.nextInt(); for(int k=0;k<rooksCount;k++){ int i = sc.nextInt()-1; int j = sc.nextInt()-1; if(!row[i]) { row[i] = true; rowCount--; } if(!col[j]){ col[j] = true; colCount--; } System.out.print(((long)rowCount*(long)colCount) + " "); } } } /* 0 O O O 0 x x x 0 X X X 0 X X X 0,0 , r=3,c = 3, 9 0 0 0 0 0 0 X X X X 0 X X X X 0 X X X X 0,0 20-(5+4-1), r=3, c = 4 1,0, r = 2, c = 4 , 8 3 3 1 1 3 1 2 2 0 0 0 0 x x 0 0 0 1,1 r = 2, c = 2, res : 4 3,1, r = 1, c = 2 res = 2 2,2 r=0,c =1, 0 */
Java
["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"]
2 seconds
["4 2 0", "16 9", "9999800001"]
NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
Java 11
standard input
[ "data structures", "math" ]
faf1abdeb6f0cf34972d5cb981116186
The first line of the input contains two integers n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ min(100 000, n2))Β β€” the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
1,200
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
standard output
PASSED
8b6a9bd1dc0cd52b6a332d8c212a8e7b
train_001.jsonl
1469205300
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
256 megabytes
import java.util.*; import java.io.*; public class main { public class nm { int m; int n; nm(int n, int m) { this.m = m; this.n = n; } } public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); main obj = new main(); nm arr[] = new nm[m]; for (int i = 0; i < m; i++) { arr[i] = obj.new nm(sc.nextInt(), sc.nextInt()); } int raw[] = new int[n]; int col[] = new int[n]; for (int i = 0; i < n; i++) { raw[i] = 0; col[i] = 0; } long r = 0, c = 0; for (int i = 0; i < m; i++) { if (raw[arr[i].n - 1] != 1) { raw[arr[i].n - 1] = 1; r++; } if (col[arr[i].m - 1] != 1) { col[arr[i].m - 1] = 1; c++; }long j=n; long p = ((j * j )- (j * c) - ((j - c) * r)); System.out.printf("%d ", p); } } }
Java
["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"]
2 seconds
["4 2 0", "16 9", "9999800001"]
NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
Java 11
standard input
[ "data structures", "math" ]
faf1abdeb6f0cf34972d5cb981116186
The first line of the input contains two integers n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ min(100 000, n2))Β β€” the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
1,200
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
standard output
PASSED
99c68a6f32b2507d636292ec55837075
train_001.jsonl
1469205300
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
256 megabytes
// Java Bootcamp Day 1, Problem F import java.io.*; import java.nio.charset.Charset; import java.util.HashSet; public class Main { public static void main(String[] args) { Charset charset = Charset.forName("ascii"); FastIO rd = new FastIO(System.in, System.out, charset); int n = rd.readInt(); // board size int m = rd.readInt(); // rooks HashSet<Integer> row = new HashSet<Integer>(n); HashSet<Integer> col = new HashSet<Integer>(n); long safe = (long) n* (long) n; while(m-- > 0) { int r = rd.readInt(); int c = rd.readInt(); int colsize = col.size(); int rowsize = row.size(); int count = 0; boolean rowflag = true; boolean colflag = true; if(row.add(r)) { rowflag = true; count += (n - colsize); } else { rowflag = false; //count++; } if(col.add(c)) { colflag = true; count += (n - rowsize); } else { colflag = false; //count++; } if(rowflag && colflag) { count--; } else { //count = 0; } safe -= count; System.out.print(safe); if(m > 0) { System.out.print(" "); } } } } class FastIO { public final StringBuilder cache = new StringBuilder(1 << 20); private final InputStream is; private final OutputStream os; private final Charset charset; private StringBuilder defaultStringBuf = new StringBuilder(1 << 8); private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastIO(InputStream is, OutputStream os, Charset charset) { this.is = is; this.os = os; this.charset = charset; } public FastIO(InputStream is, OutputStream os) { this(is, os, Charset.forName("ascii")); } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { throw new RuntimeException(e); } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } public long readLong() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } long val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } public double readDouble() { boolean sign = true; skipBlank(); if (next == '+' || next == '-') { sign = next == '+'; next = read(); } long val = 0; while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } if (next != '.') { return sign ? val : -val; } next = read(); long radix = 1; long point = 0; while (next >= '0' && next <= '9') { point = point * 10 + next - '0'; radix = radix * 10; next = read(); } double result = val + (double) point / radix; return sign ? result : -result; } public String readString(StringBuilder builder) { skipBlank(); while (next > 32) { builder.append((char) next); next = read(); } return builder.toString(); } public String readString() { defaultStringBuf.setLength(0); return readString(defaultStringBuf); } public int readLine(char[] data, int offset) { int originalOffset = offset; while (next != -1 && next != '\n') { data[offset++] = (char) next; next = read(); } return offset - originalOffset; } public int readString(char[] data, int offset) { skipBlank(); int originalOffset = offset; while (next > 32) { data[offset++] = (char) next; next = read(); } return offset - originalOffset; } public int readString(byte[] data, int offset) { skipBlank(); int originalOffset = offset; while (next > 32) { data[offset++] = (byte) next; next = read(); } return offset - originalOffset; } public char readChar() { skipBlank(); char c = (char) next; next = read(); return c; } public void flush() { try { os.write(cache.toString().getBytes(charset)); os.flush(); cache.setLength(0); } catch (IOException e) { throw new RuntimeException(e); } } public boolean hasMore() { skipBlank(); return next != -1; } }
Java
["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"]
2 seconds
["4 2 0", "16 9", "9999800001"]
NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
Java 11
standard input
[ "data structures", "math" ]
faf1abdeb6f0cf34972d5cb981116186
The first line of the input contains two integers n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ min(100 000, n2))Β β€” the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
1,200
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
standard output
PASSED
251d7b3a53eef96ac512bf39acdc52d0
train_001.jsonl
1469205300
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
256 megabytes
import java.util.*; public class CellsNotUnderAttack1 { public static void main (String[] args) { Scanner input = new Scanner(System.in); String[] nm = input.nextLine().split(" "); int n = Integer.parseInt(nm[0]); int m = Integer.parseInt(nm[1]); int arr[] = new int[n]; int arr1[] = new int[n]; Arrays.fill(arr, 0); Arrays.fill(arr1, 0); long total = (long)n*n; long count = 0; long p = 0, q = 0; for(int i=1;i<=m;i++) { String[] xy = input.nextLine().split(" "); int x = Integer.parseInt(xy[0]); int y = Integer.parseInt(xy[1]); if(arr[x-1] == 0){ count = count + n - q; arr[x-1]=1; p = p + 1; } if(arr1[y-1] == 0) { count = count + n - p ; arr1[y-1] = 1; q = q + 1; } System.out.println(total-count); } } }
Java
["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"]
2 seconds
["4 2 0", "16 9", "9999800001"]
NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
Java 11
standard input
[ "data structures", "math" ]
faf1abdeb6f0cf34972d5cb981116186
The first line of the input contains two integers n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ min(100 000, n2))Β β€” the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
1,200
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
standard output
PASSED
135037fb66fc598da7bf32fe1dfbf8b2
train_001.jsonl
1469205300
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
256 megabytes
import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.IOException; import java.lang.reflect.Array; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class Codeforces { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] nm = br.readLine().trim().split(" "); long n = Long.parseLong(nm[0]); long m = Long.parseLong(nm[1]); long res = n * n; Set<Integer> row = new HashSet<>(); Set<Integer> col = new HashSet<>(); int count = 0; while(m-- >0){ String[] xy = br.readLine().trim().split(" "); int x = Integer.parseInt(xy[0]); int y = Integer.parseInt(xy[1]); if( row.contains(x) && !col.contains(y)){ res = res - (n - row.size()); } else if(!row.contains(x) && col.contains(y)){ res = res - (n - col.size()); } else if(!row.contains(x) && !col.contains(y)){ // System.out.println(row.size() + col.size() + "s"); res = res - ((n + (n - 1)) - (row.size() + col.size())); } row.add(x); col.add(y); System.out.println(res); } } }
Java
["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"]
2 seconds
["4 2 0", "16 9", "9999800001"]
NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
Java 11
standard input
[ "data structures", "math" ]
faf1abdeb6f0cf34972d5cb981116186
The first line of the input contains two integers n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ min(100 000, n2))Β β€” the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
1,200
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
standard output
PASSED
b9c2384f3c10334cb1728de389c4586c
train_001.jsonl
1469205300
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
256 megabytes
import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.IOException; import java.lang.reflect.Array; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class Codeforces { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String[] nm = br.readLine().trim().split(" "); long n = Long.parseLong(nm[0]); long m = Long.parseLong(nm[1]); long res = n * n; Set<Integer> row = new HashSet<>(); Set<Integer> col = new HashSet<>(); int count = 0; while(m-- >0){ String[] xy = br.readLine().trim().split(" "); int x = Integer.parseInt(xy[0]); int y = Integer.parseInt(xy[1]); if(!row.isEmpty() && !col.isEmpty() && row.contains(x) && !col.contains(y)){ res = res - (n - row.size()); } else if(!row.isEmpty() && !col.isEmpty() && !row.contains(x) && col.contains(y)){ res = res - (n - col.size()); } else if(!row.contains(x) && !col.contains(y)){ // System.out.println(row.size() + col.size() + "s"); res = res - ((n + (n - 1)) - (row.size() + col.size())); } row.add(x); col.add(y); System.out.println(res); } } }
Java
["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"]
2 seconds
["4 2 0", "16 9", "9999800001"]
NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
Java 11
standard input
[ "data structures", "math" ]
faf1abdeb6f0cf34972d5cb981116186
The first line of the input contains two integers n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ min(100 000, n2))Β β€” the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
1,200
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
standard output
PASSED
01897282ce7e4aaeea9691d17deb1c70
train_001.jsonl
1469205300
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
256 megabytes
import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ public class Solution { // Complete the maximumSum function below. public 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 long gcd(long a,long b){ if(b==0) return a; long r=a%b; return gcd(b,r); } static long lcm(long a, long b) { return (a*b)/gcd(a, b); } public class ListNode { int val; ListNode next; ListNode() {} ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } } public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() {} TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } } class Node { public int val; public List<Node> children; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, List<Node> _children) { val = _val; children = _children; } } public static void main(String[] args) throws IOException { InputStream inputStream = System.in; OutputStream outputStream = System.out; InputReader scanner = new InputReader(inputStream); PrintWriter w = new PrintWriter(outputStream); int r=scanner.nextInt(),c=scanner.nextInt(); int total=r*r; long r0=r,c0=r; Set<Integer> a=new HashSet<>(); Set<Integer> b=new HashSet<>(); for(int i=0;i<c;i++){ int r1=scanner.nextInt(),c1=scanner.nextInt(); if(a.add(r1)) r0--; if(b.add(c1)) c0--; w.print((r0*c0)+" "); } w.close(); } }
Java
["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"]
2 seconds
["4 2 0", "16 9", "9999800001"]
NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
Java 11
standard input
[ "data structures", "math" ]
faf1abdeb6f0cf34972d5cb981116186
The first line of the input contains two integers n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ min(100 000, n2))Β β€” the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
1,200
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
standard output
PASSED
cce4f80d87092b673ff68197b26123db
train_001.jsonl
1469205300
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
256 megabytes
// Java Bootcamp Day 1, Problem F import java.io.*; import java.nio.charset.Charset; import java.util.HashSet; public class Main { public static void main(String[] args) { Charset charset = Charset.forName("ascii"); FastIO rd = new FastIO(System.in, System.out, charset); int n = rd.readInt(); // board size int m = rd.readInt(); // rooks HashSet<Integer> row = new HashSet<Integer>(n); HashSet<Integer> col = new HashSet<Integer>(n); long safe = (long) n* (long) n; while(m-- > 0) { int r = rd.readInt(); int c = rd.readInt(); int colsize = col.size(); int rowsize = row.size(); int count = 0; boolean rowflag = true; boolean colflag = true; if(row.add(r)) { rowflag = true; count += (n - colsize); } else { rowflag = false; } if(col.add(c)) { colflag = true; count += (n - rowsize); } else { colflag = false; } if(rowflag && colflag) { count--; } else { } safe -= count; System.out.print(safe); if(m > 0) { System.out.print(" "); } } } } class FastIO { public final StringBuilder cache = new StringBuilder(1 << 20); private final InputStream is; private final OutputStream os; private final Charset charset; private StringBuilder defaultStringBuf = new StringBuilder(1 << 8); private byte[] buf = new byte[1 << 13]; private int bufLen; private int bufOffset; private int next; public FastIO(InputStream is, OutputStream os, Charset charset) { this.is = is; this.os = os; this.charset = charset; } public FastIO(InputStream is, OutputStream os) { this(is, os, Charset.forName("ascii")); } private int read() { while (bufLen == bufOffset) { bufOffset = 0; try { bufLen = is.read(buf); } catch (IOException e) { throw new RuntimeException(e); } if (bufLen == -1) { return -1; } } return buf[bufOffset++]; } public void skipBlank() { while (next >= 0 && next <= 32) { next = read(); } } public int readInt() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } int val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } public long readLong() { int sign = 1; skipBlank(); if (next == '+' || next == '-') { sign = next == '+' ? 1 : -1; next = read(); } long val = 0; if (sign == 1) { while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } } else { while (next >= '0' && next <= '9') { val = val * 10 - next + '0'; next = read(); } } return val; } public double readDouble() { boolean sign = true; skipBlank(); if (next == '+' || next == '-') { sign = next == '+'; next = read(); } long val = 0; while (next >= '0' && next <= '9') { val = val * 10 + next - '0'; next = read(); } if (next != '.') { return sign ? val : -val; } next = read(); long radix = 1; long point = 0; while (next >= '0' && next <= '9') { point = point * 10 + next - '0'; radix = radix * 10; next = read(); } double result = val + (double) point / radix; return sign ? result : -result; } public String readString(StringBuilder builder) { skipBlank(); while (next > 32) { builder.append((char) next); next = read(); } return builder.toString(); } public String readString() { defaultStringBuf.setLength(0); return readString(defaultStringBuf); } public int readLine(char[] data, int offset) { int originalOffset = offset; while (next != -1 && next != '\n') { data[offset++] = (char) next; next = read(); } return offset - originalOffset; } public int readString(char[] data, int offset) { skipBlank(); int originalOffset = offset; while (next > 32) { data[offset++] = (char) next; next = read(); } return offset - originalOffset; } public int readString(byte[] data, int offset) { skipBlank(); int originalOffset = offset; while (next > 32) { data[offset++] = (byte) next; next = read(); } return offset - originalOffset; } public char readChar() { skipBlank(); char c = (char) next; next = read(); return c; } public void flush() { try { os.write(cache.toString().getBytes(charset)); os.flush(); cache.setLength(0); } catch (IOException e) { throw new RuntimeException(e); } } public boolean hasMore() { skipBlank(); return next != -1; } }
Java
["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"]
2 seconds
["4 2 0", "16 9", "9999800001"]
NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
Java 11
standard input
[ "data structures", "math" ]
faf1abdeb6f0cf34972d5cb981116186
The first line of the input contains two integers n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ min(100 000, n2))Β β€” the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
1,200
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
standard output
PASSED
2f50ad2d4691818fd16a34c9a4e8458d
train_001.jsonl
1469205300
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
256 megabytes
import java.util.*; public class Main { public static void main(String[] args) { long n,m,rowks=0,colrks=0,total,r,c; Scanner s= new Scanner(System.in); n=s.nextLong(); m=s.nextLong(); total=n*n; int r_arr[]=new int[(int)n]; int c_arr[]=new int[(int)n]; for(long i=0;i<m;i++) { r=s.nextLong(); c=s.nextLong(); r-=1; c-=1; if (r_arr[(int)r]==0) { r_arr[(int)r]=1; total-=n; total+=colrks; rowks+=1; } if (c_arr[(int)c]==0) { c_arr[(int)c]=1; total-=n; total+=rowks; colrks+=1; } System.out.print(total+" "); } } }
Java
["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"]
2 seconds
["4 2 0", "16 9", "9999800001"]
NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
Java 11
standard input
[ "data structures", "math" ]
faf1abdeb6f0cf34972d5cb981116186
The first line of the input contains two integers n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ min(100 000, n2))Β β€” the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
1,200
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
standard output
PASSED
2b6545a6c8f4f9ea4858c4c9140db63d
train_001.jsonl
1469205300
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
256 megabytes
import java.io.*; import java.math.BigInteger; import java.util.*; public class B { static int[] a = new int[100000]; static int[] b = new int[100000]; public static void main(String[] args) throws IOException{ FastScanner sc = new FastScanner(); // int yo = sc.nextInt(); // while(yo-->0) { // } long n = sc.nextLong(); long m = sc.nextLong(); List<Pair> al = new ArrayList<>(); for(int i = 0; i < m; i++) { int r = sc.nextInt(); int c = sc.nextInt(); al.add(new Pair(r,c)); } for(int i = 0; i < 100000; i++) { a[i] = 0; b[i] = 0; } long x, y; x = y = n; for(int i = 0; i < m; i++) { int r = al.get(i).start-1; int c = al.get(i).end-1; if(a[r] == 0) { x--; a[r] = 1; } if(b[c] == 0) { y--; b[c] = 1; } System.out.print(x*y + " "); } } static class Pair{ int start; int end; public Pair(int start, int end) { this.start = start; this.end = end; } } static int mod = 1000000007; static long pow(int a, int b) { if(b == 0) { return 1; } if(b == 1) { return a; } if(b%2 == 0) { long ans = pow(a,b/2); return ans*ans; } else { long ans = pow(a,(b-1)/2); return a * ans * ans; } } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } static int gcd(int a, int b) { return a%b == 0 ? b : gcd(b,a%b); } static boolean[] sieve(int n) { boolean isPrime[] = new boolean[n+1]; for(int i = 2; i <= n; i++) { if(isPrime[i]) continue; for(int j = 2*i; j <= n; j+=i) { isPrime[j] = true; } } return isPrime; } // For Input.txt and Output.txt // FileInputStream in = new FileInputStream("input.txt"); // FileOutputStream out = new FileOutputStream("output.txt"); // PrintWriter pw = new PrintWriter(out); // Scanner sc = new Scanner(in); // sc.nextLine() }
Java
["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"]
2 seconds
["4 2 0", "16 9", "9999800001"]
NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
Java 11
standard input
[ "data structures", "math" ]
faf1abdeb6f0cf34972d5cb981116186
The first line of the input contains two integers n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ min(100 000, n2))Β β€” the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
1,200
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
standard output
PASSED
869ac5cb7923a18d066f6a38ccebca89
train_001.jsonl
1469205300
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
256 megabytes
import java.io.*; import java.util.*; public class Main{ //sca 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; } } //dr public static void main(String[] args) throws IOException { FastReader sc=new FastReader(); int n = sc.nextInt(); int row=n; int col=n; HashSet<Integer> xv= new HashSet<Integer>(); HashSet<Integer> yv= new HashSet<Integer>(); int m =sc.nextInt(); for (int i=0;i<m;i++){ int x =sc.nextInt(); int y=sc.nextInt(); if (!xv.contains(x)){ xv.add(x); row--; } if (!yv.contains(y)){ yv.add(y); col--; } long colf=col; long rowf=row; long res=colf*rowf; System.out.println(res); } } }
Java
["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"]
2 seconds
["4 2 0", "16 9", "9999800001"]
NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
Java 11
standard input
[ "data structures", "math" ]
faf1abdeb6f0cf34972d5cb981116186
The first line of the input contains two integers n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ min(100 000, n2))Β β€” the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
1,200
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
standard output
PASSED
f08adf27a1625925ae981f9a0b4ed9d0
train_001.jsonl
1469205300
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
256 megabytes
import com.sun.jdi.ArrayReference; import jdk.swing.interop.SwingInterOpUtils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Array; import java.math.BigInteger; import java.text.DecimalFormat; import java.util.*; public class Main { public static void main(String[] args) { FastScanner fs = new FastScanner(); long n = fs.nextLong(), m = fs.nextLong(); int[] attackedRows = new int[(int)n+1]; int[] attackedColumns = new int[(int)n+1]; long notAttacked = n*n; int diffRowsAttacked = 0; int diffColumnsAttacked = 0; for (int i = 0; i<m; i++) { int row = fs.nextInt(), col = fs.nextInt(); attackedRows[row] +=1; attackedColumns[col] +=1; if (attackedRows[row] == 1 && attackedColumns[col] == 1) { notAttacked -= 2*n-diffColumnsAttacked-diffRowsAttacked-1; diffColumnsAttacked++; diffRowsAttacked++; System.out.print(notAttacked + " "); } else if (attackedColumns[col] > 1 && attackedRows[row] > 1) { System.out.print(notAttacked + " "); } else if (attackedRows[row] == 1) { notAttacked = notAttacked-n+diffColumnsAttacked; diffRowsAttacked++; System.out.print(notAttacked + " "); } else if (attackedColumns[col] == 1) { notAttacked = notAttacked - n + diffRowsAttacked; diffColumnsAttacked++; System.out.print(notAttacked + " "); } } } static class FastScanner { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st=new StringTokenizer(""); String next() { while (!st.hasMoreTokens()) try { st=new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } int[] readArray(int n) { int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=nextInt(); return a; } long nextLong() { return Long.parseLong(next()); } } }
Java
["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"]
2 seconds
["4 2 0", "16 9", "9999800001"]
NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
Java 11
standard input
[ "data structures", "math" ]
faf1abdeb6f0cf34972d5cb981116186
The first line of the input contains two integers n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ min(100 000, n2))Β β€” the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
1,200
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
standard output
PASSED
2c45c0f0f798a7aa900bd608f80a2c21
train_001.jsonl
1469205300
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
256 megabytes
//Written by Shagoto import java.util.*; import java.io.*; public class Main { public static void main(String[]args) throws IOException { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader read = new BufferedReader(isr); String initial = read.readLine(); String [] temp1 = initial.split(" "); long n = Long.parseLong(temp1[0]); int m = Integer.parseInt(temp1[1]);; HashSet<Long> row = new HashSet<Long>(); HashSet<Long> col = new HashSet<Long>(); long lastIndexR = n; long lastIndexC = n; for(int i = 0; i<m; i++) { String input = read.readLine(); String [] temp2 = input.split(" "); long r = Long.parseLong(temp2[0]); long c = Long.parseLong(temp2[1]); if(i == 0) { row.add(r); col.add(c); lastIndexR--; lastIndexC--; } else if(row.contains(r) && col.contains(c)) { } else if(row.contains(r)) { lastIndexR--; col.add(c); } else if(col.contains(c)) { lastIndexC--; row.add(r); } else { row.add(r); col.add(c); lastIndexR--; lastIndexC--; } System.out.print(lastIndexR * lastIndexC); if(i < m-1) { System.out.print(" "); } } } }
Java
["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"]
2 seconds
["4 2 0", "16 9", "9999800001"]
NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
Java 11
standard input
[ "data structures", "math" ]
faf1abdeb6f0cf34972d5cb981116186
The first line of the input contains two integers n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ min(100 000, n2))Β β€” the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
1,200
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
standard output
PASSED
9368dbb119a240bb9f1cdbe6071ed347
train_001.jsonl
1469205300
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
256 megabytes
//Written by Shagoto import java.util.*; public class Main { public static void main(String[]args) { Scanner read = new Scanner(System.in); long n = read.nextLong(); long total = n*n; long m = read.nextLong(); HashSet<Long> row = new HashSet<Long>(); HashSet<Long> col = new HashSet<Long>(); long lastIndexR = 1; long lastIndexC = 1; long remove = 0; for(long i = 0; i<m; i++) { long r = read.nextLong(); long c = read.nextLong(); if(i == 0) { row.add(r); col.add(c); remove = (n - lastIndexR) + (n - lastIndexC) + 1; } else if(row.contains(r) && col.contains(c)) { remove = 0; } else if(row.contains(r)) { remove = (n - lastIndexC); lastIndexR++; col.add(c); } else if(col.contains(c)) { remove = (n - lastIndexR); lastIndexC++; row.add(r); } else { row.add(r); col.add(c); lastIndexR++; lastIndexC++; remove = (n - lastIndexR) + (n - lastIndexC) + 1; } total = total - remove; System.out.print(total); if(i < m-1) { System.out.print(" "); } } } }
Java
["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"]
2 seconds
["4 2 0", "16 9", "9999800001"]
NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
Java 11
standard input
[ "data structures", "math" ]
faf1abdeb6f0cf34972d5cb981116186
The first line of the input contains two integers n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ min(100 000, n2))Β β€” the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
1,200
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
standard output
PASSED
e9518c0fea52a95694f844fc696a4d55
train_001.jsonl
1469205300
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
256 megabytes
import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Codeforces{ public static void main(String[] args) { Scanner sc=new Scanner(System.in); long x=sc.nextInt(); long y=x; int m=sc.nextInt(); Map<Long,Integer> ax=new HashMap<>(); Map<Long,Integer> ay=new HashMap<>(); for(int i=0;i<m;i++) { long x1=sc.nextInt(); long y1=sc.nextInt(); if(!ax.containsKey(x1)) { x--; ax.put(x1,0); } if(!ay.containsKey(y1)) { y--; ay.put(y1,0); } System.out.print(x*y); System.out.print(" "); } } }
Java
["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"]
2 seconds
["4 2 0", "16 9", "9999800001"]
NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
Java 11
standard input
[ "data structures", "math" ]
faf1abdeb6f0cf34972d5cb981116186
The first line of the input contains two integers n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ min(100 000, n2))Β β€” the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
1,200
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
standard output
PASSED
a85d722027b22da9f3fd7d1b7bd352f1
train_001.jsonl
1469205300
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
256 megabytes
import java.util.*; import java.io.*; public class solution { public static void merge(long arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged int n1 = m - l + 1; int n2 = r - m; /* Create temp arrays */ long L[] = new long[n1]; long R[] = new long[n2]; /*Copy data to temp arrays*/ 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]; /* Merge the temp arrays */ // Initial indexes of first and second subarrays int i = 0, j = 0; // Initial index of merged subarry array 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++; } /* Copy remaining elements of L[] if any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy remaining elements of R[] if any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } // Main function that sorts arr[l..r] using // merge() public static void sort(long arr[], int l, int r) { if (l < r) { // Find the middle point int m = (l + r) / 2; // Sort first and second halves sort(arr, l, m); sort(arr, m + 1, r); // Merge the sorted halves merge(arr, l, m, r); } } public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); long n = Long.parseLong(st.nextToken()); long m = Long.parseLong(st.nextToken()); HashSet<Long>X = new HashSet<>(); HashSet<Long>Y = new HashSet<>(); long squ = n*n; for(long i=0;i<m;i++){ st = new StringTokenizer(br.readLine()); long x = Long.parseLong(st.nextToken()); long y = Long.parseLong(st.nextToken()); if(X.contains(x) && Y.contains(y)){ System.out.print(squ + " "); } else if(X.contains(x) && !Y.contains(y)){ long opt = n-1; long minus = X.size()-1; long ans = opt-minus; System.out.print(squ-ans + " "); squ-=ans; } else if(!X.contains(x) && Y.contains(y)){ long opt = n-1; long minus = Y.size()-1; long ans = opt-minus; System.out.print(squ-ans + " "); squ-=ans; } else { long opt =(2*n)-1; long minus = Y.size()+X.size(); long ans = opt-minus; System.out.print(squ-ans + " "); squ-=ans; } X.add(x); Y.add(y); } System.out.println(); } static class sort implements Comparator<ArrayList<Integer>> { @Override public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) { int c = o1.get(0).compareTo(o2.get(0)); return c; } } }
Java
["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"]
2 seconds
["4 2 0", "16 9", "9999800001"]
NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
Java 11
standard input
[ "data structures", "math" ]
faf1abdeb6f0cf34972d5cb981116186
The first line of the input contains two integers n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ min(100 000, n2))Β β€” the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
1,200
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
standard output
PASSED
ca5bcfbf9d392fad62109b0f6a389bf8
train_001.jsonl
1469205300
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
256 megabytes
import java.util.*; import java.math.*; import java.io.*; import java.text.*; public class A{ static FastReader scan=new FastReader(); public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out)); static int d,n,m; static int arr[]; public static void main(String[] args) throws Exception { Set<Long>s1=new HashSet<Long>(); Set<Long>s2=new HashSet<Long>(); long n=scan.nextLong(); int m=scan.nextInt(); long cnt=0; for(int i=0;i<m;i++){ long a=scan.nextLong(),b=scan.nextLong(); s1.add(a); s2.add(b); //cnt=Math.abs(((s1.size()*s2.size())-(n*s1.size()+n*s2.size()))); // out.println(" cnt "+s1.size()); out.print((n-s1.size())*(n-s2.size())+" "); } out.close(); } public static long pow(long b, long e) { long r = 1; while (e > 0) { if (e % 2 == 1) r = r * b ; b = b * b; e >>= 1; } return r; } private static void sort(long[] arr) { List<Long> list = new ArrayList<>(); for (long object : arr) list.add(object); Collections.sort(list); for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i); } 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 int[] nextIntArray(int arraySize) { int array[] = new int[arraySize]; for (int i = 0; i < arraySize; i++) { array[i] = nextInt(); } return array; } } static class pair{ int i; int j; pair(int i,int j){ this.i=i; this.j=j; } }}
Java
["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"]
2 seconds
["4 2 0", "16 9", "9999800001"]
NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
Java 11
standard input
[ "data structures", "math" ]
faf1abdeb6f0cf34972d5cb981116186
The first line of the input contains two integers n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ min(100 000, n2))Β β€” the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
1,200
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
standard output
PASSED
855856079c596139c88f65893de79326
train_001.jsonl
1469205300
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
256 megabytes
import java.util.Arrays; import java.util.Comparator; import java.util.HashSet; import java.util.Scanner; import static java.lang.String.valueOf; public class Solve { public static void main(String[] args) { var x = new HashSet<Integer>(); var y = new HashSet<Integer>(); var sc = new Scanner(System.in); var maxLength = sc.nextInt(); var lines = sc.nextInt(); var result = new String[lines]; for (int i = 0; i < lines; i++) { x.add(sc.nextInt()); y.add(sc.nextInt()); result[i] = valueOf((maxLength - x.size()) * (long)(maxLength - y.size())); } System.out.println(String.join(" ", result)); } }
Java
["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"]
2 seconds
["4 2 0", "16 9", "9999800001"]
NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
Java 11
standard input
[ "data structures", "math" ]
faf1abdeb6f0cf34972d5cb981116186
The first line of the input contains two integers n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ min(100 000, n2))Β β€” the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
1,200
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
standard output
PASSED
97f2c175649e54bd6425926360aa6bf1
train_001.jsonl
1469205300
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
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.*; /** * * @author Bryan AW */ public class Codeforces { /** * @param args the command line arguments */ public static void main(String[] args){ //Cells Not Under Attack Scanner sc=new Scanner(System.in); long n=Long.parseLong(sc.next()); int m=Integer.parseInt(sc.next()); long xi, yi; long[] safe=new long[m]; HashMap <Long, Boolean> mapX =new HashMap <Long, Boolean> (); HashMap <Long, Boolean> mapY =new HashMap <Long, Boolean> (); long X=0, Y=0; for (int i=0;i<m;i++){ xi=Long.parseLong(sc.next()); yi=Long.parseLong(sc.next()); if (i==0){ safe[i]=(n-1)*(n-1); X++; Y++; mapX.put(xi, Boolean.TRUE); mapY.put(yi, Boolean.TRUE); } else { if (Objects.equals(mapX.get(xi), Boolean.TRUE) && Objects.equals(mapY.get(yi), Boolean.TRUE)){ safe[i]=safe[i-1]; } else if (Objects.equals(mapX.get(xi), Boolean.TRUE)){ safe[i]=safe[i-1]-(n-X); Y++; mapY.put(yi, Boolean.TRUE); } else if (Objects.equals(mapY.get(yi), Boolean.TRUE)){ safe[i]=safe[i-1]-(n-Y); X++; mapX.put(xi, Boolean.TRUE); } else { safe[i]=safe[i-1]-(n-X); Y++; mapY.put(yi, Boolean.TRUE); safe[i]-=(n-Y); X++; mapX.put(xi, Boolean.TRUE); } } } for (int i=0;i<m;i++){ System.out.print(safe[i]+" "); } System.out.println(); } }
Java
["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"]
2 seconds
["4 2 0", "16 9", "9999800001"]
NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
Java 11
standard input
[ "data structures", "math" ]
faf1abdeb6f0cf34972d5cb981116186
The first line of the input contains two integers n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ min(100 000, n2))Β β€” the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
1,200
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
standard output
PASSED
579d5ddd7e6aa2b7a696b7e81d6e6a4b
train_001.jsonl
1469205300
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
256 megabytes
import java.util.HashSet; import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner input = new Scanner(System.in); long n = input.nextLong(); long m = input.nextLong(); HashSet <Long> positionX = new HashSet<>(); HashSet <Long> positionY = new HashSet<>(); for(int i=0; i<m ;i++){ long x = input.nextLong(); long y = input.nextLong(); positionX.add(x); positionY.add(y); System.out.println((n-positionY.size())*(n-positionX.size())); } input.close(); } }
Java
["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"]
2 seconds
["4 2 0", "16 9", "9999800001"]
NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
Java 11
standard input
[ "data structures", "math" ]
faf1abdeb6f0cf34972d5cb981116186
The first line of the input contains two integers n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ min(100 000, n2))Β β€” the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
1,200
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
standard output
PASSED
668b247fd45ad517f9fd43a23872096b
train_001.jsonl
1469205300
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
256 megabytes
import java.util.*; public class underattack { public static void main(String [] args){ Scanner s = new Scanner(System.in); int size = s.nextInt(); HashSet<Integer> row = new HashSet(); HashSet<Integer> column = new HashSet(); int numP = s.nextInt(); int temp; for(int x = 0; x < numP;x++){ temp = s.nextInt(); if(!row.contains(temp)){ row.add(temp); } temp = s.nextInt(); if(!column.contains(temp)){ column.add(temp); } System.out.print((((long)size * size) - (((long)row.size()*size) + ((long)column.size() * (size - row.size())))) + " "); } } }
Java
["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"]
2 seconds
["4 2 0", "16 9", "9999800001"]
NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
Java 11
standard input
[ "data structures", "math" ]
faf1abdeb6f0cf34972d5cb981116186
The first line of the input contains two integers n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ min(100 000, n2))Β β€” the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
1,200
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
standard output
PASSED
f285f6000e38c785d1814a02b81c9165
train_001.jsonl
1469205300
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
256 megabytes
import java.io.*; import java.util.*; public class Main { final static long mod = 1000000007; static void debug(Object... args) { System.out.println(Arrays.deepToString(args)); } public static void main(String[] args) throws Exception { InputReader sc = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); Random gen = new Random(); int test = 1;//sc.nextInt(); while (test-- > 0) { StringBuilder sb = new StringBuilder(); int n = sc.nextInt(); int m = sc.nextInt(); boolean [] row = new boolean[n]; boolean [] col = new boolean[n]; long rs = n; long cs = n; while(m-->0) { int r = sc.nextInt()-1; int c = sc.nextInt()-1; if(!row[r]) rs--; row[r] = true; if(!col[c]) cs--; col[c] = true; pw.print((rs*cs)+" "); } pw.println(); } pw.flush(); pw.close(); } static class Data implements Comparable<Data> { int x; int y; public Data(int m, int n) { x = m; y = n; } @Override public int compareTo(Data o) { return o.y-y; } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } 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 nextInt() { 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 nextLong() { 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] = nextInt(); } return a; } public long[] nextLongArray(int n) { long [] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } public static int[] shuffle(int[] a, Random gen) { for(int i = 0, n = a.length;i < n;i++) { int ind = gen.nextInt(n-i)+i; int d = a[i]; a[i] = a[ind]; a[ind] = d; } return a; } public static long[] shuffle(long[] a, Random gen) { for(int i = 0, n = a.length;i < n;i++) { int ind = gen.nextInt(n-i)+i; long d = a[i]; a[i] = a[ind]; a[ind] = d; } 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
["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"]
2 seconds
["4 2 0", "16 9", "9999800001"]
NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
Java 11
standard input
[ "data structures", "math" ]
faf1abdeb6f0cf34972d5cb981116186
The first line of the input contains two integers n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ min(100 000, n2))Β β€” the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
1,200
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
standard output
PASSED
f412200c05e1727226a37d77a7acd2a7
train_001.jsonl
1469205300
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
256 megabytes
import java.io.*; import java.util.*; public class Main { final static long mod = 1000000007; static void debug(Object... args) { System.out.println(Arrays.deepToString(args)); } public static void main(String[] args) throws Exception { InputReader sc = new InputReader(System.in); PrintWriter pw = new PrintWriter(System.out); Random gen = new Random(); int test = 1;//sc.nextInt(); while (test-- > 0) { StringBuilder sb = new StringBuilder(); long n = sc.nextLong(); long m = sc.nextLong(); HashSet<Long> r = new HashSet<>(); HashSet<Long> c = new HashSet<>(); while(m-->0) { r.add(sc.nextLong()); c.add(sc.nextLong()); long s1 = r.size(); long s2 = c.size(); long ans = n*n - n*s1 - n*s2 + s1*s2; pw.print(ans+" "); } } pw.flush(); pw.close(); } static class Data implements Comparable<Data> { int x; int y; public Data(int m, int n) { x = m; y = n; } @Override public int compareTo(Data o) { return o.y-y; } } static class InputReader { private final InputStream stream; private final byte[] buf = new byte[8192]; private int curChar, snumChars; public InputReader(InputStream st) { this.stream = st; } 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 nextInt() { 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 nextLong() { 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] = nextInt(); } return a; } public long[] nextLongArray(int n) { long [] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } public static int[] shuffle(int[] a, Random gen) { for(int i = 0, n = a.length;i < n;i++) { int ind = gen.nextInt(n-i)+i; int d = a[i]; a[i] = a[ind]; a[ind] = d; } return a; } public static long[] shuffle(long[] a, Random gen) { for(int i = 0, n = a.length;i < n;i++) { int ind = gen.nextInt(n-i)+i; long d = a[i]; a[i] = a[ind]; a[ind] = d; } 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
["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"]
2 seconds
["4 2 0", "16 9", "9999800001"]
NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
Java 11
standard input
[ "data structures", "math" ]
faf1abdeb6f0cf34972d5cb981116186
The first line of the input contains two integers n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ min(100 000, n2))Β β€” the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
1,200
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
standard output
PASSED
9e747a497a95c6de6833d8e115ae9068
train_001.jsonl
1469205300
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
256 megabytes
import java.math.BigInteger; import java.util.Scanner; import java.util.*; public class java_main{ public static Scanner in=new Scanner(System.in); public static void main(String[] args){ String n=in.next(); long m=in.nextLong(); BigInteger N=new BigInteger(n); Set<Long> x = new HashSet<Long>(); Set<Long> y = new HashSet<Long>(); while(m-->0){ long a=in.nextLong(); long b=in.nextLong(); x.add(a); y.add(b); BigInteger temp= N.multiply(N); BigInteger term1= BigInteger.valueOf(x.size()); BigInteger term2= BigInteger.valueOf(y.size()); BigInteger term3= term1.multiply(term2); term1=term1.multiply(N); term2=term2.multiply(N); BigInteger term4= term1.add(term2); BigInteger term5=term4.subtract(term3); BigInteger res=temp.subtract(term5); System.out.print(res + " "); } } }
Java
["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"]
2 seconds
["4 2 0", "16 9", "9999800001"]
NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
Java 11
standard input
[ "data structures", "math" ]
faf1abdeb6f0cf34972d5cb981116186
The first line of the input contains two integers n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ min(100 000, n2))Β β€” the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
1,200
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
standard output
PASSED
78d06e5a9c8dc557b5698f0a7207f5f5
train_001.jsonl
1469205300
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
256 megabytes
/* Solution for:https://codeforces.com/problemset/problem/427/B*/ import java.util.*; import java.io.*; import java.util.Arrays; import java.util.ArrayList; import java.util.Collections; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.InputStream; import java.util.StringTokenizer; import java.math.BigInteger; public class Main { public static void main(String[] args) { try (PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out))) { FastScanner in = new FastScanner(System.in); int n = in.nextInt(); int m = in.nextInt(); HashSet<Integer> hsRow = new HashSet<>(); HashSet<Integer> hsColumn = new HashSet<>(); for(int i = 0; i<m; i++) { int row = in.nextInt(); int column = in.nextInt(); hsRow.add(row); hsColumn.add(column); long count = ((long)(n-hsRow.size()))*((long)(n-hsColumn.size())); out.print(count + " "); } out.println(); } finally { //out.close(); } } } class FastScanner { private final BufferedReader br; private StringTokenizer st; FastScanner(InputStream InputStream) { br = new BufferedReader(new InputStreamReader(InputStream)); } String next() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { throw new RuntimeException(e); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } char nextChar() { return (next()).charAt(0); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } ArrayList<Integer> nextIntList(int count) { ArrayList<Integer> array = new ArrayList<>(); for (int n = 0; n < count; n++) { int number = nextInt(); array.add(number); } return array; } int[] nextIntArray(int count) { int[] array = new int[count]; for (int n = 0; n < count; n++) { array[n] = nextInt(); } return array; } }
Java
["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"]
2 seconds
["4 2 0", "16 9", "9999800001"]
NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
Java 11
standard input
[ "data structures", "math" ]
faf1abdeb6f0cf34972d5cb981116186
The first line of the input contains two integers n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ min(100 000, n2))Β β€” the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
1,200
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
standard output
PASSED
8eea3ebc98b44bf1f77e47f0dffeea01
train_001.jsonl
1469205300
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a rook located in the cell, this cell is also under attack.You are given the positions of the board where Vasya will put rooks. For each rook you have to determine the number of cells which are not under attack after Vasya puts it on the board.
256 megabytes
// package cp; import java.io.*; import java.math.*; import java.util.*; public class Cf_one { public static void main(String[] args) throws IOException { PrintWriter out = new PrintWriter(System.out); Readers.init(System.in); int n=Readers.nextInt(); int m=Readers.nextInt(); int[] rows=new int[n]; int[] col=new int[n]; int zero_r=n; int zero_c=n; for (int i = 0; i < m; i++) { int x=Readers.nextInt(); int y=Readers.nextInt(); if(rows[x-1]==0) { rows[x-1]=1; zero_r-=1; } if(col[y-1]==0) { col[y-1]=1; zero_c-=1; } System.out.print((long)zero_r*(long)zero_c+" "); } out.flush(); } } class Readers { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } static double nextDouble() throws IOException { return Double.parseDouble( next() ); } static long nextLong() throws IOException{ return Long.parseLong(next()); } }
Java
["3 3\n1 1\n3 1\n2 2", "5 2\n1 5\n5 1", "100000 1\n300 400"]
2 seconds
["4 2 0", "16 9", "9999800001"]
NoteOn the picture below show the state of the board after put each of the three rooks. The cells which painted with grey color is not under the attack.
Java 11
standard input
[ "data structures", "math" ]
faf1abdeb6f0cf34972d5cb981116186
The first line of the input contains two integers n and m (1 ≀ n ≀ 100 000, 1 ≀ m ≀ min(100 000, n2))Β β€” the size of the board and the number of rooks. Each of the next m lines contains integers xi and yi (1 ≀ xi, yi ≀ n)Β β€” the number of the row and the number of the column where Vasya will put the i-th rook. Vasya puts rooks on the board in the order they appear in the input. It is guaranteed that any cell will contain no more than one rook.
1,200
Print m integer, the i-th of them should be equal to the number of cells that are not under attack after first i rooks are put.
standard output
PASSED
37c1cd745acf7824b3d31417c7c0323b
train_001.jsonl
1495877700
In his spare time Vladik estimates beauty of the flags.Every flag could be represented as the matrix n × m which consists of positive integers.Let's define the beauty of the flag as number of components in its matrix. We call component a set of cells with same numbers and between any pair of cells from that set there exists a path through adjacent cells from same component. Here is the example of the partitioning some flag matrix into components: But this time he decided to change something in the process. Now he wants to estimate not the entire flag, but some segment. Segment of flag can be described as a submatrix of the flag matrix with opposite corners at (1, l) and (n, r), where conditions 1 ≀ l ≀ r ≀ m are satisfied.Help Vladik to calculate the beauty for some segments of the given flag.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.Arrays; import java.util.StringTokenizer; /** * @author Don Li */ public class VladikEntertainingFlags { int N = (int) 1e6 + 10; int n, m, q; int[][] a; int id = 0; Node[] seg = new Node[N]; int[] parent = new int[N]; int timer = 0; int[] last = new int[N]; void solve() { n = in.nextInt(); m = in.nextInt(); q = in.nextInt(); a = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = in.nextInt(); } } Arrays.fill(parent, -1); build(0, 0, m); while (q-- > 0) { int l = in.nextInt() - 1, r = in.nextInt(); int ans = query(l, r, 0, 0, m).cnt; out.println(ans); } } void build(int k, int l, int r) { if (r - l == 1) { seg[k] = new Node(); for (int i = 0; i < n; i++) { seg[k].L[i] = seg[k].R[i] = ++id; } seg[k].cnt = n; for (int i = 1; i < n; i++) { if (a[i][l] == a[i - 1][l]) { seg[k].cnt--; seg[k].L[i] = seg[k].R[i] = seg[k].L[i - 1]; } } return; } build(2 * k + 1, l, (l + r) / 2); build(2 * k + 2, (l + r) / 2, r); seg[k] = merge(seg[2 * k + 1], seg[2 * k + 2], (l + r) / 2); } Node merge(Node x, Node y, int m) { ++timer; Node z = new Node(); z.cnt = x.cnt + y.cnt; for (int i = 0; i < n; i++) { parent[x.R[i]] = -1; parent[y.L[i]] = -1; last[x.R[i]] = timer; last[y.L[i]] = timer; } for (int i = 0; i < n; i++) { if (a[i][m - 1] == a[i][m]) { int u = find(x.R[i]), v = find(y.L[i]); if (u == v) continue; z.cnt--; union(u, v); } } for (int i = 0; i < n; i++) { if (last[x.L[i]] == timer) z.L[i] = find(x.L[i]); else z.L[i] = x.L[i]; if (last[y.R[i]] == timer) z.R[i] = find(y.R[i]); else z.R[i] = y.R[i]; } return z; } Node query(int a, int b, int k, int l, int r) { if (a <= l && b >= r) return seg[k]; int m = (l + r) >> 1; if (m <= a) return query(a, b, 2 * k + 2, m, r); if (m >= b) return query(a, b, 2 * k + 1, l, m); return merge(query(a, b, 2 * k + 1, l, m), query(a, b, 2 * k + 2, m, r), m); } int find(int i) { if (parent[i] < 0) return i; return parent[i] = find(parent[i]); } void union(int i, int j) { int u = find(i), v = find(j); if (u == v) return; parent[v] = u; } static class Node { int cnt; int[] L = new int[10], R = new int[10]; } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new VladikEntertainingFlags().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["4 5 4\n1 1 1 1 1\n1 2 2 3 3\n1 1 1 2 5\n4 4 5 5 5\n1 5\n2 5\n1 2\n4 5"]
2 seconds
["6\n7\n3\n4"]
NotePartitioning on components for every segment from first test case:
Java 8
standard input
[ "data structures", "dsu", "graphs" ]
167594e0be56b9d93e62258eb052fdc3
First line contains three space-separated integers n, m, q (1 ≀ n ≀ 10, 1 ≀ m, q ≀ 105)Β β€” dimensions of flag matrix and number of segments respectively. Each of next n lines contains m space-separated integersΒ β€” description of flag matrix. All elements of flag matrix is positive integers not exceeding 106. Each of next q lines contains two space-separated integers l, r (1 ≀ l ≀ r ≀ m)Β β€” borders of segment which beauty Vladik wants to know.
2,600
For each segment print the result on the corresponding line.
standard output
PASSED
4696bd0e21037473f07bf2a8f0b517b6
train_001.jsonl
1495877700
In his spare time Vladik estimates beauty of the flags.Every flag could be represented as the matrix n × m which consists of positive integers.Let's define the beauty of the flag as number of components in its matrix. We call component a set of cells with same numbers and between any pair of cells from that set there exists a path through adjacent cells from same component. Here is the example of the partitioning some flag matrix into components: But this time he decided to change something in the process. Now he wants to estimate not the entire flag, but some segment. Segment of flag can be described as a submatrix of the flag matrix with opposite corners at (1, l) and (n, r), where conditions 1 ≀ l ≀ r ≀ m are satisfied.Help Vladik to calculate the beauty for some segments of the given flag.
256 megabytes
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; /** * @author Don Li */ public class VladikEntertainingFlags2 { int N = (int) 1e6 + 10; int n, m, q; int[][] a; int id = 0; Node[] seg = new Node[N]; void solve() { n = in.nextInt(); m = in.nextInt(); q = in.nextInt(); a = new int[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { a[i][j] = in.nextInt(); } } build(0, 0, m); while (q-- > 0) { int l = in.nextInt() - 1, r = in.nextInt(); int ans = query(l, r, 0, 0, m).cnt; out.println(ans); } } Node query(int a, int b, int k, int l, int r) { if (a <= l && b >= r) return seg[k]; int m = (l + r) >> 1; if (m >= b) return query(a, b, 2 * k + 1, l, m); if (m <= a) return query(a, b, 2 * k + 2, m, r); return merge(query(a, b, 2 * k + 1, l, m), query(a, b, 2 * k + 2, m, r), m); } void build(int k, int l, int r) { if (r - l == 1) { seg[k] = new Node(); for (int i = 0; i < n; i++) seg[k].L[i] = seg[k].R[i] = ++id; seg[k].cnt = n; for (int i = 1; i < n; i++) { if (a[i][l] == a[i - 1][l]) { seg[k].cnt--; seg[k].L[i] = seg[k].R[i] = seg[k].L[i - 1]; } } return; } int m = (l + r) >> 1; build(2 * k + 1, l, m); build(2 * k + 2, m, r); seg[k] = merge(seg[2 * k + 1], seg[2 * k + 2], m); } Node merge(Node x, Node y, int m) { x = x.copy(); y = y.copy(); Node z = new Node(); for (int i = 0; i < n; i++) { z.L[i] = x.L[i]; z.R[i] = y.R[i]; } z.cnt = x.cnt + y.cnt; for (int i = 0; i < n; i++) { if (a[i][m - 1] != a[i][m]) continue; if (x.R[i] == y.L[i]) continue; z.cnt--; z.update(y.L[i], x.R[i]); x.update(y.L[i], x.R[i]); y.update(y.L[i], x.R[i]); } return z; } static class Node { int cnt; int[] L = new int[10], R = new int[10]; void update(int x, int nx) { for (int i = 0; i < 10; i++) { if (L[i] == x) L[i] = nx; if (R[i] == x) R[i] = nx; } } Node copy() { Node t = new Node(); t.cnt = cnt; for (int i = 0; i < 10; i++) { t.L[i] = L[i]; t.R[i] = R[i]; } return t; } } public static void main(String[] args) { in = new FastScanner(new BufferedReader(new InputStreamReader(System.in))); out = new PrintWriter(System.out); new VladikEntertainingFlags2().solve(); out.close(); } static FastScanner in; static PrintWriter out; static class FastScanner { BufferedReader in; StringTokenizer st; public FastScanner(BufferedReader in) { this.in = in; } public String nextToken() { while (st == null || !st.hasMoreTokens()) { try { st = new StringTokenizer(in.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } public int nextInt() { return Integer.parseInt(nextToken()); } public long nextLong() { return Long.parseLong(nextToken()); } public double nextDouble() { return Double.parseDouble(nextToken()); } } }
Java
["4 5 4\n1 1 1 1 1\n1 2 2 3 3\n1 1 1 2 5\n4 4 5 5 5\n1 5\n2 5\n1 2\n4 5"]
2 seconds
["6\n7\n3\n4"]
NotePartitioning on components for every segment from first test case:
Java 8
standard input
[ "data structures", "dsu", "graphs" ]
167594e0be56b9d93e62258eb052fdc3
First line contains three space-separated integers n, m, q (1 ≀ n ≀ 10, 1 ≀ m, q ≀ 105)Β β€” dimensions of flag matrix and number of segments respectively. Each of next n lines contains m space-separated integersΒ β€” description of flag matrix. All elements of flag matrix is positive integers not exceeding 106. Each of next q lines contains two space-separated integers l, r (1 ≀ l ≀ r ≀ m)Β β€” borders of segment which beauty Vladik wants to know.
2,600
For each segment print the result on the corresponding line.
standard output
PASSED
1bd78ead4964d260bcd460b1d29a237c
train_001.jsonl
1495877700
In his spare time Vladik estimates beauty of the flags.Every flag could be represented as the matrix n × m which consists of positive integers.Let's define the beauty of the flag as number of components in its matrix. We call component a set of cells with same numbers and between any pair of cells from that set there exists a path through adjacent cells from same component. Here is the example of the partitioning some flag matrix into components: But this time he decided to change something in the process. Now he wants to estimate not the entire flag, but some segment. Segment of flag can be described as a submatrix of the flag matrix with opposite corners at (1, l) and (n, r), where conditions 1 ≀ l ≀ r ≀ m are satisfied.Help Vladik to calculate the beauty for some segments of the given flag.
256 megabytes
import java.io.*; import java.util.*; public class E416 { static int n; static int m; static int flag[][]; static ArrayList<Node> tree; public static void main(String[] args) { InputReader sc = new InputReader(System.in); OutputWriter out = new OutputWriter(System.out); n = sc.nextInt(); m = sc.nextInt(); int q = sc.nextInt(); flag = new int[n][m]; for(int i = 0; i < n; ++i) { for(int j = 0; j < m; ++j) { flag[i][j] = sc.nextInt(); } } tree = new ArrayList<>(m * 4); for(int i = 0; i < m * 4; ++i) { tree.add(new Node()); } buildTree(0, 0, m - 1); // for(int i = 0; i < m * 4; ++i) { // System.out.println(tree.get(i)); // } int l, r; for(int i = 0; i < q; ++i) { l = sc.nextInt() - 1; r = sc.nextInt() - 1; out.println(query(0, 0, m - 1, l, r).seg); } out.close(); } static void buildTree(int cur, int l, int r) { if(l == r) { Node node = tree.get(cur); for(int i = 0; i < n; ++i) { node.left[i] = node.right[i] = l * n + i; // firstly different colour for // all nodes } node.seg = n; for(int i = 1; i < n; ++i) { if(flag[i][l] == flag[i-1][l]) { node.unit(node.left[i],node.left[i-1]); node.seg--; } } } else { int mid = (l + r) / 2; buildTree(cur * 2 + 1, l, mid); buildTree(cur * 2 + 2, mid + 1, r); tree.set(cur, merge(new Node( tree.get(cur * 2 + 1)), tree.get(cur * 2 + 2), mid, mid + 1)); } } static Node merge(Node a, Node b, int l, int r) { Node c = new Node(); for(int i = 0; i < n; ++i) { c.left[i] = a.left[i]; c.right[i] = b.right[i]; } c.seg = a.seg + b.seg; for(int i = 0; i < n; ++i) { if(flag[i][l] == flag[i][r]) { int col1 = a.right[i]; int col2 = b.left[i]; if(col1 != col2) { c.unit(col1, col2); c.seg--; a.unit(col1, col2); } } } return c; } static Node query(int cur, int l, int r, int x, int y) { if(x == l && y == r) { return tree.get(cur); } int mid = (l + r) / 2; if(x >= mid + 1) { return query(cur * 2 + 2, mid + 1, r, x, y); } else if(y <= mid) { return query(cur * 2 + 1, l, mid, x, y); } else { return merge(new Node(query(cur * 2 + 1, l, mid, x, mid)), query(cur * 2 + 2, mid + 1, r, mid + 1, y), mid, mid + 1); } } static class Node { int left[]; int right[]; int seg; Node() { left = new int[n]; right = new int[n]; } Node(Node node) { left = Arrays.copyOf(node.left, n); right = Arrays.copyOf(node.right, n); seg = node.seg; } void unit(int col1, int col2) { for(int i = 0; i < n; ++i) { if(left[i] == col1) { left[i] = col2; } if(right[i] == col1) { right[i] = col2; } } } @Override public String toString() { return "[" + Arrays.toString(left) + " " + Arrays.toString(right) + " " + seg + "]"; } } 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 printf(String format, Object... objects) { writer.printf(format, objects); } public void close() { writer.close(); } public void flush() { writer.flush(); } } static class InputReader { private InputStream stream; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public InputReader(InputStream stream) { this.stream = stream; } public int read() { if (this.numChars == -1) { throw new InputMismatchException(); } else { if (this.curChar >= this.numChars) { this.curChar = 0; try { this.numChars = this.stream.read(this.buf); } catch (IOException var2) { throw new InputMismatchException(); } if (this.numChars <= 0) { return -1; } } return this.buf[this.curChar++]; } } public int nextInt() { int c; for (c = this.read(); isSpaceChar(c); c = this.read()) { ; } byte sgn = 1; if (c == 45) { sgn = -1; c = this.read(); } int res = 0; while (c >= 48 && c <= 57) { res *= 10; res += c - 48; c = this.read(); if (isSpaceChar(c)) { return res * sgn; } } throw new InputMismatchException(); } public static boolean isSpaceChar(int c) { return c == 32 || c == 10 || c == 13 || c == 9 || c == -1; } } }
Java
["4 5 4\n1 1 1 1 1\n1 2 2 3 3\n1 1 1 2 5\n4 4 5 5 5\n1 5\n2 5\n1 2\n4 5"]
2 seconds
["6\n7\n3\n4"]
NotePartitioning on components for every segment from first test case:
Java 8
standard input
[ "data structures", "dsu", "graphs" ]
167594e0be56b9d93e62258eb052fdc3
First line contains three space-separated integers n, m, q (1 ≀ n ≀ 10, 1 ≀ m, q ≀ 105)Β β€” dimensions of flag matrix and number of segments respectively. Each of next n lines contains m space-separated integersΒ β€” description of flag matrix. All elements of flag matrix is positive integers not exceeding 106. Each of next q lines contains two space-separated integers l, r (1 ≀ l ≀ r ≀ m)Β β€” borders of segment which beauty Vladik wants to know.
2,600
For each segment print the result on the corresponding line.
standard output
PASSED
215208bdc3ea2f23fa76573dda29aabd
train_001.jsonl
1495877700
In his spare time Vladik estimates beauty of the flags.Every flag could be represented as the matrix n × m which consists of positive integers.Let's define the beauty of the flag as number of components in its matrix. We call component a set of cells with same numbers and between any pair of cells from that set there exists a path through adjacent cells from same component. Here is the example of the partitioning some flag matrix into components: But this time he decided to change something in the process. Now he wants to estimate not the entire flag, but some segment. Segment of flag can be described as a submatrix of the flag matrix with opposite corners at (1, l) and (n, r), where conditions 1 ≀ l ≀ r ≀ m are satisfied.Help Vladik to calculate the beauty for some segments of the given flag.
256 megabytes
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class e { static int n, m, id, data[][]; public static void main(String args[]) { FastScanner in = new FastScanner(); n = in.nextInt(); m = in.nextInt(); int q = in.nextInt(); data = new int[m][n]; id = 0; for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) data[j][i] = in.nextInt(); SegTree s = new SegTree(m, data); for(int i = 0; i < q; i++) { int l = in.nextInt()-1; int r = in.nextInt()-1; Node c = s.query(l, r); System.out.println(c.cnt); } } static class Node { int cnt, left[], right[]; public Node() { cnt = n; left = new int[n]; right = new int[n]; } public Node(int d[]) { this(); for(int i = 0; i < n; i++) { if(i > 0 && d[i] == d[i-1]) { left[i] = right[i] = left[i-1]; cnt--; } else left[i] = right[i] = id++; } } public Node(Node l, Node r, int m, int d[][]) { this(); cnt = l.cnt + r.cnt; int cLR[] = Arrays.copyOf(l.right, l.right.length); int cRL[] = Arrays.copyOf(r.left, r.left.length); for(int i = 0; i < n; i++) { left[i] = l.left[i]; right[i] = r.right[i]; } // boolean used[] = new boolean[n]; for(int i = 0; i < n; i++) { if(d[m][i] != d[m+1][i]) continue; if(cLR[i] == cRL[i]) continue; cnt--; int oc = cLR[i]; int nc = cRL[i]; // System.out.println(i + " " + "oc: " + oc + " nc: " + nc); for(int j = 0; j < n; j++) { if(left[j] == oc) left[j] = nc; if(right[j] == oc) right[j] = nc; if(cLR[j] == oc) cLR[j] = nc; if(cRL[j] == oc) cRL[j] = nc; } } } public void print() { System.out.println(cnt); System.out.println(Arrays.toString(left)); System.out.println(Arrays.toString(right)); System.out.println(); } } public static class SegTree { Node a[]; int s, pos; public SegTree(int size, int d[][]) { s = size; a = new Node[4*s+1]; pos = 0; build(0, s-1, 1, d); } private void build(int li, int ri, int c, int[][] d) { if(li == ri) { a[c] = new Node(d[li]); // a[c].print(); return; } int m = li + (ri-li)/2; build(li, m, 2*c, d); build(m+1, ri, 2*c+1, d); // System.out.println(li + " " + ri); a[c] = new Node(a[2*c], a[2*c+1], m, d); // a[c].print(); } public Node query(int l, int r) { return query(l, r, 0, s-1, 1); } private Node query(int lq, int rq, int li, int ri, int c) { if(rq < li || ri < lq) return null; if(lq <= li && ri <= rq) return a[c]; int m = li + (ri - li) / 2; Node l = query(lq, rq, li, m, 2*c); Node r = query(lq, rq, m+1, ri, 2*c+1); if(l == null) return r; if(r == null) return l; return new Node(l, r, m, data); } } public static class FastScanner { BufferedReader br; StringTokenizer st; public FastScanner(String s) { try { br = new BufferedReader(new FileReader(s)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public FastScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } String nextToken() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(nextToken()); } long nextLong() { return Long.parseLong(nextToken()); } double nextDouble() { return Double.parseDouble(nextToken()); } String next() { return nextToken(); } } }
Java
["4 5 4\n1 1 1 1 1\n1 2 2 3 3\n1 1 1 2 5\n4 4 5 5 5\n1 5\n2 5\n1 2\n4 5"]
2 seconds
["6\n7\n3\n4"]
NotePartitioning on components for every segment from first test case:
Java 8
standard input
[ "data structures", "dsu", "graphs" ]
167594e0be56b9d93e62258eb052fdc3
First line contains three space-separated integers n, m, q (1 ≀ n ≀ 10, 1 ≀ m, q ≀ 105)Β β€” dimensions of flag matrix and number of segments respectively. Each of next n lines contains m space-separated integersΒ β€” description of flag matrix. All elements of flag matrix is positive integers not exceeding 106. Each of next q lines contains two space-separated integers l, r (1 ≀ l ≀ r ≀ m)Β β€” borders of segment which beauty Vladik wants to know.
2,600
For each segment print the result on the corresponding line.
standard output