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 | a3dfb1ce88741e3d9dd08f181455a512 | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes |
import java.io.*;
import java.util.*;
/**
* Created by imahmoud on 5/13/17.
*/
public class C {
static class Writer {
private DataOutputStream dataOut;
public Writer(){
PrintStream out = new PrintStream( System.out );
dataOut = new DataOutputStream(out);
}
public void println() throws IOException {
dataOut.writeChar('\n');
}
public void println(String str) throws IOException {
dataOut.write(str.getBytes());
dataOut.writeChar('\n');
}
public void println(char v) throws IOException {
dataOut.writeChar(v);
dataOut.writeChar('\n');
}
public void println(short v) throws IOException {
dataOut.writeShort(v);
dataOut.writeChar('\n');
}
public void println(int v) throws IOException {
dataOut.writeInt(v);
dataOut.writeChar('\n');
}
public void println(long v) throws IOException {
dataOut.writeLong(v);
dataOut.writeChar('\n');
}
public void println(double v) throws IOException {
dataOut.writeDouble(v);
dataOut.writeChar('\n');
}
public void println(float v) throws IOException {
dataOut.writeDouble(v);
dataOut.writeChar('\n');
}
public void print(String str) throws IOException {
dataOut.write(str.getBytes());
}
public void print(char v) throws IOException {
dataOut.writeChar(v);
}
public void print(short v) throws IOException {
dataOut.writeShort(v);
}
public void print(int v) throws IOException {
dataOut.writeInt(v);
}
public void print(long v) throws IOException {
dataOut.writeLong(v);
}
public void print(double v) throws IOException {
dataOut.writeDouble(v);
}
public void print(float v) throws IOException {
dataOut.writeDouble(v);
}
public void flush() throws IOException {
dataOut.flush();
dataOut.flush();
dataOut.close();
}
}
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
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 int findIndex(Long[] a, long key) {
int lo = 0;
int hi = a.length - 1;
while (lo <= hi) {
// Key is in a[lo..hi] or not present.
int mid = lo + (hi - lo) / 2;
if (key < a[mid]) hi = mid - 1;
else if (key > a[mid]) lo = mid + 1;
else return mid;
}
return -1;
}
public void solve() throws IOException {
Reader in = new Reader();
// Writer out = new Writer();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
int N = in.nextInt();
Long[] arr = new Long[N];
for (int i = 0; i < N; i++) {
arr[i] = in.nextLong();
}
Long[] arr_s = arr.clone();
Arrays.sort(arr_s);
boolean[] visited = new boolean[N];
List<List<Integer>> res = new ArrayList<>();
for (int i = 0; i < N; i++) {
if(visited[i])
continue;
long l = arr[i];
int t_index = findIndex(arr_s, l);
int c_index = i;
List<Integer> list = new ArrayList<>();
visited[c_index] = true;
list.add(c_index);
while (t_index != c_index) {
long tmp = arr[c_index];
arr[c_index] = arr[t_index];
arr[t_index] = tmp;
visited[t_index] = true;
list.add(t_index);
t_index = findIndex(arr_s, arr[c_index]);
}
res.add(list);
}
out.write(""+res.size());
out.write('\n');
for (int i = 0; i < res.size(); i++) {
List<Integer> list = res.get(i);
out.write(""+list.size());
for (int j = 0; j < list.size(); j++) {
out.write(' ');
out.write(""+(list.get(j) + 1));
}
out.write('\n');
}
out.flush();
}
public static void main(String[] args) throws Exception{
try {
new C().solve();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | e24ab15fa42efd4e4a7c6ef84eb7412a | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes |
import java.io.*;
import java.util.*;
public class Main {
public static void main (String[] args) throws java.lang.Exception {
Output out = new Output();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int[] seq = new int[n];
int[] nums = new int[n];
st = new StringTokenizer(br.readLine());
HashMap<Integer, Integer> originalIndex = new HashMap<>();
for (int i=0 ; i<n ; i++) {
seq[i] = Integer.parseInt(st.nextToken());
originalIndex.put(seq[i], i);
nums[i] = seq[i];
}
for (int i=n-1 ; i>0 ; i--) {
int rand = (int)(Math.random() * i);
int temp = nums[n-1];
nums[n-1] = nums[rand];
nums[rand] = temp;
}
Arrays.sort(nums);
HashMap<Integer, Integer> sortedIndex = new HashMap<>();
for (int i=0 ; i<n ; i++) {
sortedIndex.put(nums[i], i);
}
LinkedList<HashSet<Integer>> subsequences = new LinkedList<>();
boolean[] visited = new boolean[n+1];
for (int i=0 ; i<n ; i++) {
if (visited[i+1]) continue;
HashSet<Integer> currentSub = new HashSet<>();
int current = i;
while (!currentSub.contains(current+1)) {
visited[current+1] = true;
currentSub.add(current+1);
current = sortedIndex.get(seq[current]);
}
subsequences.add(currentSub);
}
out.println(subsequences.size());
for (int i=0, s=subsequences.size() ; i<s ; i++) {
HashSet<Integer> currentSub = subsequences.remove();
out.print(currentSub.size() + " ");
for (int a : currentSub) out.print(a + " ");
out.println("");
}
out.flush();
}
}
class Output {
private BufferedWriter out;
Output() {
this.out = new BufferedWriter(new OutputStreamWriter(System.out));
}
void print(String s) throws IOException {this.out.write(s);}
void println(String s) throws IOException {this.out.write(s + "\n");}
void println(long n) throws IOException {this.out.write(n + "\n");}
void println(int n) throws IOException {this.out.write(n + "\n");}
void flush () throws IOException {this.out.flush();}
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | bb33e0956591b8b6eee8fa72de66a36b | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Sandip_Jana
*/
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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
int a[] = in.nextIntArray(n);
int b[] = new int[n];
HashMap<Integer, Integer> hm = new HashMap<>();
for (int i = 0; i < n; i++) {
b[i] = a[i];
hm.put(a[i], i);
}
Arrays.sort(b);
long ans = 0;
boolean present[] = new boolean[n];
StringBuffer sb = new StringBuffer("");
for (int i = 0; i < n; i++) {
if (!present[i]) {
ArrayList<Integer> list = new ArrayList<>();
int element = b[i];
present[i] = true;
if (a[i] == b[i]) {
++ans;
sb.append("1 " + (i + 1) + "\n");
} else {
++ans;
while (hm.get(element) != i && !present[hm.get(element)]) {
present[hm.get(element)] = true;
list.add(hm.get(element));
element = b[hm.get(element)];
}
list.add(i);
//Collections.sort(list);
sb.append(list.size() + " ");
for (int x : list)
sb.append((x + 1) + " ");
sb.append("\n");
}
}
}
out.println(ans);
out.println(sb);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public 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 int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void println(long i) {
writer.println(i);
}
}
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | 21447af328a3d788c4fef33504f041ad | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Map;
import java.io.BufferedReader;
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();
}
static class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[n + 1];
int[] b = new int[n];
Map<Integer, Integer> rel = new HashMap<>();
Map<Integer, Integer> mp = new HashMap<>();
for (int i = 1; i <= n; ++i) {
b[i - 1] = a[i] = in.nextInt();
}
Arrays.sort(b);
for (int i = 0; i < n; ++i) {
rel.put(b[i], i + 1);
}
for (int i = 1; i <= n; ++i) {
a[i] = rel.get(a[i]);
mp.put(a[i], i);
}
boolean[] visited = new boolean[n + 1];
List<List<Integer>> ans = new ArrayList<>();
for (int i = 1; i <= n; ++i) {
if (visited[a[i]]) continue;
List<Integer> seq = new ArrayList<>();
int k = i;
while (!visited[a[k]]) {
visited[a[k]] = true;
seq.add(k);
k = a[k];
}
ans.add(seq);
}
out.println(ans.size());
for (List<Integer> c : ans) {
out.print(c.size() + " " + c.get(0));
for (int i = 1; i < c.size(); ++i) {
out.print(" " + c.get(i));
}
out.println();
}
}
}
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 | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | 720d9d0d60afdc1b6ca6aa58054d83bc | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Set;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Toni Rajkovski
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
int[] a;
int[] b;
boolean[] used;
public void solve(int testNumber, FastReader in, PrintWriter out) {
int n = in.nextInt();
a = new int[n];
b = new int[n];
used = new boolean[n];
for (int i = 0; i < n; i++)
a[i] = b[i] = in.nextInt();
Arrays.sort(b);
List<Set<Integer>> res = new ArrayList<>();
for (int i = 0; i < n; i++)
if (!used[i]) {
res.add(check(i));
}
out.println(res.size());
for (Set<Integer> s : res) {
out.print(s.size() + " ");
for (Integer num : s) out.print((num + 1) + " ");
out.println();
}
}
private Set<Integer> check(int pos) {
Set<Integer> s;
if (a[pos] == b[pos]) {
s = new HashSet<>();
s.add(pos);
used[pos] = true;
} else {
int ind = Arrays.binarySearch(b, a[pos]);
int temp = a[pos];
a[pos] = a[ind];
a[ind] = temp;
s = check(pos);
s.add(ind);
used[ind] = true;
}
return s;
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
public FastReader(InputStream is) {
br = new BufferedReader(new
InputStreamReader(is));
}
public String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | 44a958fd04b6bcf9cca6c0ea2c6e786c | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import javax.smartcardio.CommandAPDU;
import java.io.* ;
import java.lang.reflect.Array;
import java.util.* ;
import java.math.* ;
public class Main
{
static BufferedReader reader;
static StringTokenizer tokenizer;
static void init(InputStream input)
{
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
static String next() throws IOException
{
while (!tokenizer.hasMoreTokens())
{
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
static long nextInt() throws IOException
{
return Long.parseLong(next());
}
public static int ri() throws IOException
{
return (int) nextInt();
}
public static long rl() throws IOException
{
return nextInt();
}
public static double rd() throws NumberFormatException, IOException
{
return Double.parseDouble(next());
}
static void print_a(int[] arr)
{
for (int i = 0; i < arr.length; i++)
{
print(arr[i] + " ");
}
println();
}
public static int[] ria(int n) throws IOException
{
int[] a = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = ri();
}
return a;
}
public static long[] rla(int n) throws IOException
{
long[] a = new long[n];
for (int i = 0; i < n; i++)
{
a[i] = rl();
}
return a;
}
public static int p(int i)
{
return (int) Math.pow(2, i);
}
static PrintWriter writer;
static void outit(OutputStream outputStream)
{
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
static void print(Object... objects)
{
for (int i = 0; i < objects.length; i++)
{
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
static void println(Object... objects)
{
print(objects);
writer.println();
flush();
}
static void close()
{
writer.close();
}
static void flush()
{
writer.flush();
}
public static void main(String[] args) throws IOException
{
init(System.in);
outit(System.out);
// int t = (int) nextInt();
// for (int i = 0; i < t; i++)
output();
flush();
close();
}
static int n ;
static long mod = 1000000007 ;
static long [] pre ;
public static void output() throws IOException
{
int n = ri() ;
int [] a = new int[n] ;
int [] at = new int[n] ;
for (int i = 0; i <n ; i++)
{
a[i] = ri() ;
at[i] = a[i] ;
}
Arrays.sort(at);
HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>() ;
for (int i = 0; i <n ; i++)
{
hm.put(at[i],i) ;
}
for (int i = 0; i <n ; i++)
{
a[i] = hm.get(a[i]) ;
}
boolean [] visited = new boolean[n] ;
Arrays.fill(visited,false);
ArrayList<ArrayList<Integer>> tot = new ArrayList<ArrayList<Integer>>() ;
for (int i = 0; i <n ; i++)
{
int curr = i ;
ArrayList<Integer> ar = new ArrayList<Integer>() ;
while(!visited[curr])
{
visited[curr] = true ;
ar.add(curr);
curr = a[curr] ;
}
if(ar.size()>0)
{
tot.add(ar) ;
}
}
println(tot.size());
for(int i = 0; i<tot.size() ; i++)
{
ArrayList<Integer> ar = tot.get(i) ;
print(ar.size()+" ");
for (int j = 0; j < ar.size(); j++)
{
print((ar.get(j)+1) + " ");
}
println();
}
}
} | Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | 7fde511ba8c60cd5fcf8c7a626b3c21c | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
static int []a=null;
static int []b=null;
static boolean []isPlaced=null;
static HashMap<Integer,Integer> map= new HashMap<Integer,Integer>();
static ArrayList<ArrayList<Integer>> list= new ArrayList<ArrayList<Integer>>();
static void dfs(int i, ArrayList<Integer> l) {
int v= a[i];
int index= map.get(v);
if(isPlaced[index])
return;
isPlaced[index]=true;
l.add(index+1);
dfs(index,l);
}
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) {
int n= in.nextInt();
a= new int[n];
b= new int[n];
isPlaced= new boolean[n+5];
Arrays.fill(isPlaced, false);
for(int i=0;i<n;i++) {
a[i]=b[i]=in.nextInt();
}
Arrays.sort(b);
for(int i=0;i<n;i++)
map.put(b[i], i);
int k=0;
for(int i=0;i<n;i++) {
if(!isPlaced[i]) {
k++;
ArrayList<Integer> l=new ArrayList<Integer>();
dfs(i,l);
list.add(l);
}
}
out.println(k);
for(int i=0;i<list.size();i++) {
ArrayList<Integer> l= list.get(i);
out.print(l.size()+" ");
for(int j=0;j<l.size();j++)
out.print(l.get(j)+" ");
out.println();
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | f02639a391265d0c51da2de94e35c258 | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.HashMap;
import java.io.IOException;
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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] ar = new int[n];
int[] sorted = new int[n];
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
sorted[i] = ar[i] = in.nextInt();
}
Arrays.sort(sorted);
for (int i = 0; i < n; i++) {
map.put(sorted[i], i);
sorted[i] = i;
}
for (int i = 0; i < n; i++) {
ar[i] = map.get(ar[i]);
}
boolean[] ok = new boolean[n];
ArrayList<ArrayList<Integer>> ansList = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (ok[i])
continue;
int j = i;
ArrayList<Integer> l = new ArrayList<>();
while (!ok[j]) {
ok[j] = true;
j = ar[j];
l.add(j);
}
ansList.add(l);
}
out.println(ansList.size());
for (ArrayList<Integer> list : ansList) {
out.print(list.size());
for (int i = 0; i < list.size(); i++) {
out.print(" " + (list.get(i) + 1));
}
out.println();
}
}
}
static class InputReader {
StringTokenizer st;
BufferedReader br;
public InputReader(InputStream is) {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
this.br = br;
}
public String next() {
if (st == null || !st.hasMoreTokens()) {
String nextLine = null;
try {
nextLine = br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (nextLine == null)
return null;
st = new StringTokenizer(nextLine);
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | 1f1b2bfd74d9578d153338fe946a6ecb | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.TreeMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Abhilash Mandaliya
*/
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();
}
static class TaskC {
public void solve (int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
Map<Integer, TaskC.Node> elePosi = new TreeMap<>();
for ( int i = 1; i <= n; i++ ) {
int next = in.nextInt();
elePosi.put( next, new TaskC.Node( i ) );
}
Iterator<Integer> keys = elePosi.keySet().iterator();
int index = 1;
while ( keys.hasNext() ) {
int key = keys.next();
elePosi.get( key ).should = index;
index++;
}
TaskC.Node[] nodes = new TaskC.Node[n + 1];
index = 0;
keys = elePosi.keySet().iterator();
while ( keys.hasNext() ) {
nodes[++ index] = elePosi.get( keys.next() );
}
boolean[] visited = new boolean[n + 1];
ArrayList<ArrayList<Integer>> output = new ArrayList<>();
for ( int i = 1; i <= n; i++ ) {
if ( ! visited[nodes[i].original] ) {
ArrayList indices = new ArrayList();
print( nodes, visited, nodes[i].original, indices );
output.add( indices );
}
}
out.println( output.size() );
for ( ArrayList<Integer> list : output ) {
out.print( list.size() );
for ( int ele : list ) {
out.print( " " + ele );
}
out.println();
}
}
public void print (TaskC.Node[] nodes, boolean[] visited, int original, ArrayList<Integer> indices) {
if ( ! visited[original] ) {
visited[original] = true;
TaskC.Node node = nodes[original];
indices.add( node.should );
if ( node.original != node.should ) {
print( nodes, visited, node.original, indices );
}
}
}
static class Node {
int original;
int should;
Node (int original) {
this.original = original;
}
}
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar;
private int 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 boolean isSpaceChar (int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == - 1;
}
}
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | 59b684e627371b70cd7373c3b8f45c11 | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import java.util.*;
import java.io.*;
public class B {
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner(System.in);
PrintWriter pw=new PrintWriter (System.out);
int n=sc.nextInt();
Integer[]a=new Integer[n];
TreeSet<Integer> set=new TreeSet();
for(int i=0;i<n;i++)
set.add(a[i]=sc.nextInt());
TreeMap<Integer,Integer>map=new TreeMap();
Iterator it=set.iterator();
while(it.hasNext())
map.put((Integer) it.next(), map.size());
UF dsu=new UF(n);
for(int i=0;i<n;i++)
dsu.union(i, map.get(a[i]));
ArrayList<Integer> []members=new ArrayList[n];
for(int i=0;i<n;i++)
members[i] = new ArrayList();
for(int i=0;i<n;i++)
members[dsu.findSet(i)].add(i+1);
pw.println(dsu.numSets);
for(ArrayList<Integer> list:members)
{
if(list.isEmpty())
continue;
pw.print(list.size()+" ");
for(int x:list)
pw.print(x+" ");
pw.println();
}
pw.close();
}
static class UF
{
int []p,r;
int numSets=0;
public UF(int n)
{
p=new int [n];
r=new int [n];
for(int i=0;i<n;i++)
p[i]=i;
numSets=n;
}
public int numSets()
{
return numSets;
}
public void union(int i,int j)
{
if(isSameSet(i,j))
return;
int x=findSet(i);
int y=findSet(j);
if(r[x]>r[y])
p[y]=x;
else
{
p[x]=y;
if(r[x]==r[y])
r[y]++;
}
numSets--;
}
public int findSet(int x)
{
if(p[x]==x)
return x;
else
return p[x]=findSet(p[x]);
}
public boolean isSameSet(int i,int j)
{
return findSet(i)==findSet(j);
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader s) {
br = new BufferedReader(s);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException { return br.readLine();}
public boolean ready() throws IOException {return br.ready();}
public double nextDouble() throws IOException {return Double.parseDouble(next());}
}
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | e9a19cc1bc303555f5bf373f0c79c4dc | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
import java.util.regex.*;
public class Aim4c {
static Scanner input = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
static Reader fastInput = new Reader();
public static void main(String[] args) throws IOException {
int n = fastInput.nextInt();
NumPos[] seq = new NumPos[n];
for (int i = 0; i < n; i++) {
seq[i] = new NumPos(fastInput.nextInt(), i);
}
Arrays.sort(seq, (NumPos f, NumPos s) -> f.n - s.n);
ArrayList<String> ans = new ArrayList<String>();
for (int i = 0; i < n; i++) {
if (!seq[i].visited) {
seq[i].visited = true;
int start = seq[i].p;
int cur = seq[i].p;
ArrayList<String> curAns = new ArrayList<>();
do {
curAns.add(String.valueOf(seq[cur].p + 1));
cur = seq[cur].p;
seq[cur].visited = true;
} while (start != cur);
ans.add(curAns.size() + " " + String.join(" ", curAns));
}
}
System.out.println(ans.size());
System.out.println(String.join("\n", ans));
}
static class NumPos {
int n, p;
boolean visited = false;
NumPos(int num, int pos) {
n = num;
p = pos;
}
}
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
break;
}
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg) {
return -ret;
}
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ') {
c = read();
}
boolean neg = (c == '-');
if (neg) {
c = read();
}
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg) {
return -ret;
}
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1) {
buffer[0] = -1;
}
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) {
fillBuffer();
}
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null) {
return;
}
din.close();
}
}
} | Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | edec3714323e3f2c75ba182433c38d3b | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import java.io.*;
import java.util.*;
public class Major {
static boolean visited[];
static int pos[];
static int cnt;
static StringBuilder var;
static void dfs(int idx){
visited[idx] = true;
++cnt;
var.append(idx + " ");
if(visited[pos[idx]])return;
else dfs(pos[idx]);
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int array[] = new int[n + 1];
StringTokenizer st = new StringTokenizer(br.readLine());
for(int i = 1;i <= n;i++)
array[i] = Integer.parseInt(st.nextToken());
array[0] = Integer.MIN_VALUE;
int temp[] = array.clone();
Arrays.sort(array);
HashMap<Integer, Integer>map = new HashMap<>();
for(int i = 1;i <= n;i++){
map.put(array[i], i);
}
pos = new int[n + 1];
visited = new boolean[n + 1];
for(int i = 1;i <= n;i++){
pos[i] = map.get(temp[i]);
}
int ans = 0;
StringBuilder sb = new StringBuilder();
for(int i = 1;i <= n;i++){
if(visited[i])continue;
++ans;
cnt = 0;
var = new StringBuilder();
dfs(i);
sb.append(cnt + " ");
sb.append(var);
sb.append('\n');
}
System.out.println(ans);
System.out.print(sb);
}
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | 72f0eae9f9c85e7d0360b2bd7b651d4e | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import java.io.*;
import java.util.*;
public class Major {
static boolean visited[];
static int pos[];
static int cnt;
static StringBuilder var;
static void dfs(int idx){
visited[idx] = true;
++cnt;
var.append(idx + " ");
if(visited[pos[idx]])return;
else dfs(pos[idx]);
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int array[] = new int[n + 1];
StringTokenizer st = new StringTokenizer(br.readLine());
for(int i = 1;i <= n;i++)
array[i] = Integer.parseInt(st.nextToken());
array[0] = Integer.MIN_VALUE;
int temp[] = array.clone();
Arrays.sort(array);
HashMap<Integer, Integer>map = new HashMap<>();
for(int i = 1;i <= n;i++){
map.put(array[i], i);
}
pos = new int[n + 1];
visited = new boolean[n + 1];
for(int i = 1;i <= n;i++){
pos[map.get(temp[i])] = map.get(array[i]);
}
int ans = 0;
StringBuilder sb = new StringBuilder();
for(int i = 1;i <= n;i++){
if(visited[i])continue;
++ans;
cnt = 0;
var = new StringBuilder();
dfs(i);
sb.append(cnt + " ");
sb.append(var);
sb.append('\n');
}
System.out.println(ans);
System.out.print(sb);
}
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | 4fe1bc4229c943ddec971383becb086d | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() throws FileNotFoundException {
boolean test=false;
InputStream inputStream = test?new FileInputStream("/Users/aj/code/HackerRank/input.txt"):System.in;
br = new BufferedReader(new
InputStreamReader(inputStream));//System.in
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) throws FileNotFoundException {
FastReader in = new FastReader();
StringBuilder sb = new StringBuilder();
int N=in.nextInt();
int[] arr=new int[N];
pair[] pairs=new pair[N];
for(int i=0;i<N;i++){
int val=in.nextInt();
pair pr=new pair(val,i);
pairs[i]=pr;
}
Arrays.sort(pairs);
for(int i=0;i<pairs.length;i++)
arr[i]=pairs[i].y;
int cnt=0;
for(int i=0;i<pairs.length;i++){
int start=i;
int val=arr[i];
if(val==-1)
continue;
cnt++;
ArrayList<Integer> sub=new ArrayList<>();
sub.add(start+1);
while(i!=arr[start]){
int olds=start;
start=arr[start];
arr[olds]=-1;
sub.add(start+1);
}
arr[start]=-1;
sb.append(sub.size()).append(" ");
for(int v:sub)
sb.append(v).append(" ");
sb.append("\n");
}
System.out.println(cnt);
System.out.println(sb.toString());
}
}
class pair implements Comparable<pair>{
pair(int _x,int _y){
x=_x;
y=_y;
}
@Override
public int compareTo(pair other){
if(x<other.x){
return -1;
}
else if(x>other.x){
return 1;
}
else {
return 0;
}
}
public int x;
public int y;
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | 8b4be1611efdf96517fcaa4258d24b0a | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | /*
* DA-IICT
* Author: Jugal Kalal
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class Hackerearth{
static long mod=(long)Math.pow(10,9)+7l;
public static void main(String args[]) {
new Thread(null, new Runnable() {
public void run() {
try{
solve();
w.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}, "1", 1 << 26).start();
}
static InputReader in=new InputReader(System.in);
static PrintWriter w=new PrintWriter(System.out);
char ch[][];
//int ans = 0, cnt = 0, Q;
int n1, n2, k1, k2, M;
static ArrayList<Integer>[] g;
static long ok[];
static int phi[]=new int[500005];//static int b[]=new int[100005];
static void solve(){
int n=in.nextInt();
int a[]=in.nextIntArray(n);
int b[]=Arrays.copyOf(a,n);
Arrays.sort(b);
g=new ArrayList[n+1];
HashMap<Integer,Integer> hm=new HashMap();
for(int i=0;i<n;i++)
{
hm.put(a[i],i+1);
}
for(int i=1;i<=n;i++)
g[i]=new ArrayList<Integer>();
for(int i=0;i<n;i++)
{
int x=hm.get(b[i]);
g[i+1].add(x);
g[x].add(i+1);
}
ans=new ArrayList[n+1];
for(int i=0;i<=n;i++)
ans[i]=new ArrayList<Integer>();
for(int i=1;i<=n;i++)
{
if(!visited[i])
{
dfs(i);
count++;
}
}
w.println(count);
for(int i=0;i<count;i++)
{
w.print(ans[i].size()+" ");
for(int x:ans[i])
{
w.print(x+" ");
}
w.println();
}
}
static ArrayList<Integer> ans[];
static int count=0;
private static void dfs(int curr) {
visited[curr]=true;
ans[count].add(curr);
for(int x:g[curr])
{
if(!visited[x])
{
dfs(x);
}
}
}
static boolean visited[]=new boolean[100005];
public static void minSwaps(int[] arr){
int n = arr.length,ans=0;
for(int i=0;i<n;i++) {
if(arr[i]==i+1) {
w.println("1 "+arr[i]);
ans++;
}
}
// Create two arrays and use as pairs where first
// array is element and second array
// is position of first element
ArrayList <Pair> arrpos =new ArrayList <Pair> ();
for (int i = 0; i < n; i++)
arrpos.add(new Pair(arr[i], i));
// Sort the array by array element values to
// get right position of every element as the
// elements of second array.
arrpos.sort(new Comparator<Pair>(){
@Override
public int compare(Pair o1,Pair o2){
if (o1.first < o2.first)
return -1;
// We can change this to make it then look at the
// words alphabetical order
else if (o1.second==(o2.second))
return 0;
else
return 1;
}
});
// To keep track of visited elements. Initialize
// all elements as not visited or false.
Boolean[] vis = new Boolean[n];
Arrays.fill(vis, false);
// Initialize result
// Traverse array elements
for (int i = 0; i < n; i++){
// already swapped and corrected or
// already present at correct pos
if (vis[i] || arrpos.get(i).second == i)
continue;
// find out the number of node in
// this cycle and add in ans
int j = i;
HashSet<Integer> set=new HashSet<>();
while (!vis[j]){
vis[j] = true;
// move to next node
j = arrpos.get(j).second;
set.add(j+1);
}
if(set.size()>0) {
ans++;
w.print(set.size()+" ");
for(int jack:set) {
w.print(jack+" ");
}
w.println();
}
// Update answer by adding current cycle.
}
// Return result
System.out.println(ans);
}
static class Pair{
int first;
int second;
public Pair(int first,int second) {
this.first=first;
this.second=second;
}
}
static int Arr[];
static void initialize(int n) {
Arr=new int[n];
for(int i=0;i<n;i++)
Arr[i]=i;
}
static int root(int i){
while(Arr[ i ] != i){
i = Arr[ i ];
}
return i;
}
/*modified union function where we connect the elements by changing the root of one of the element */
static void union(int A ,int B) {
int root_A = root(A);
int root_B = root(B);
Arr[ root_A ] = root_B ; //setting parent of root(A) as root(B).
}
static boolean find(int A,int B){
if( root(A)==root(B) ) //if A and B have same root,means they are connected.
return true;
else
return false;
}
static void delete_edge(int A,int B) {
int parent_A=Arr[A];
int parent_B=Arr[B];
if(parent_A==B) {
Arr[A]=A;
}else {
Arr[B]=B;
}
}
// static int Arr[];
// static long size[];
// //modified initialize function:
// static void initialize(int N){
// Arr=new int[N];
// size=new long[N];
// for(int i = 0;i<N;i++){
// Arr[ i ] = i ;
// size[ i ] = 1;
// }
// }
// static boolean find(int A,int B){
// if( root(A)==root(B) )//if A and B have same root,means they are connected.
// return true;
// else
// return false;
// }
// static void delete_edge() {
//
// }
// // modified root function.
// static void weighted_union(int A,int B,int n){
// int root_A = root(A);
// int root_B = root(B);
// if(size[root_A] < size[root_B ]){
// Arr[ root_A ] = Arr[root_B];
// size[root_B] += size[root_A];
// }
// else{
// Arr[ root_B ] = Arr[root_A];
// size[root_A] += size[root_B];
// }
// }
// static int root (int i){
// while(Arr[ i ] != i){
// Arr[ i ] = Arr[ Arr[ i ] ] ;
// i = Arr[ i ];
// }
// return i;
// }
// static long[] isHamiltonian_path(int n){
// boolean dp[][]=new boolean[n][1<<n];
// long ans[]=new long[n];
// long sum[]=new long[n];
// for(int i=0;i<n;i++){
// dp[i][1<<i]=true;
// ans[i]=0;
// sum[i]=i+1;
// }
// for(int mask=0;mask<(1<<n);mask++){
// int s=0;
// int count=0,temp=mask;
// while(temp>0){
// s+=1+Math.log(temp&(-temp))/Math.log(2);
// temp=temp&(temp-1);
// count++;
// }
// for(int j=0;j<n;j++){
// if((mask&(1<<j))>0){
// for(int k=0;k<n;k++){
// if(j!=k&&(mask&(1<<k))>0&&adj[j][k]&&dp[k][mask^(1<<j)]){
// dp[j][mask]=true;
// ans[j]=Math.max(ans[j],count-1);
// if(ans[j]==count-1){
// sum[j]=Math.max(sum[j], s);
// }
// }
// }
// }
// }
// }
// return sum;
// }
// static void bfs(int s,int n){
// boolean visited[]=new boolean[n];
// LinkedList<Integer> queue=new LinkedList<Integer>();
// queue.add(s);
// visited[s]=true;
// while(!queue.isEmpty()){
// int num=queue.pop();
//// System.out.println(ans.toString());
// for(int i=0;i<adj[num].size();i++){
// if(!visited[adj[num].get(i)]){
// visited[adj[num].get(i)]=true;
// queue.add(adj[num].get(i));
// }
// }
// }
// }
static int gcd(int a,int b){
if(a==0){
return b;
}
return gcd(b%a,a);
}
static long power(long base, long exponent, long modulus){
long result = 1L;
while (exponent > 0) {
if (exponent % 2L == 1L)
result = (result * base) % modulus;
exponent = exponent >> 1;
base = (base * base) % modulus;
}
return result;
}
static HashMap<Long,Long> primeFactors(long n){
HashMap<Long,Long> ans=new HashMap<Long,Long>();
// Print the number of 2s that divide n
while (n%2L==0L)
{
if(ans.containsKey(2L)){
ans.put(2L,ans.get(2L)+1L);
}else{
ans.put(2L,1L);
}
n /= 2L;
}
// n must be odd at this point. So we can
// skip one element (Note i = i +2)
for (long i = 3; i <= Math.sqrt(n); i+= 2L)
{
// While i divides n, print i and divide n
while (n%i == 0)
{
if(ans.containsKey(i)){
ans.put(i,ans.get(i)+1L);
}else{
ans.put(i,1L);
}
n /= i;
}
}
// This condition is to handle the case whien
// n is a prime number greater than 2
if (n > 2)
ans.put(n,1L);
return ans;
}
////for marking all prime numbers greater than 1 and less than equal to N
static void sieve(int N) {
boolean isPrime[]=new boolean[N+1];
isPrime[0] = true;
isPrime[1] = true;
for(int i = 2; i * i <= N; ++i) {
if(isPrime[i] == false) {//Mark all the multiples of i as composite numbers
for(int j = i * i; j <= N ;j += i)
isPrime[j] = true;
}
}
}
// //if str2 (pattern) is subsequence of str1 (Text) or not
// static boolean function(String str1,String str2){
// str2 = str2.replace("", ".*"); //returns .*a.*n.*n.*a.
// return (str1.matches(str2)); // returns true
// }
static boolean isPrime(long n) {
if(n < 2L) return false;
if(n == 2L || n == 3L) return true;
if(n%2L == 0 || n%3L == 0) return false;
long sqrtN = (long)Math.sqrt(n)+1L;
for(long i = 6L; i <= sqrtN; i += 6L) {
if(n%(i-1) == 0 || n%(i+1) == 0) return false;
}
return true;
}
// static HashMap<Integer,Integer> level;;
// static HashMap<Integer,Integer> parent;
static int maxlevel=0;
// static boolean T[][][];
// static void subsetSum(int input[], int total, int count) {
// T = new boolean[input.length + 1][total + 1][count+1];
// for (int i = 0; i <= input.length; i++) {
// T[i][0][0] = true;
// for(int j = 1; j<=count; j++){
// T[i][0][j] = false;
// }
// }
// int sum[]=new int[input.length+1];
// for(int i=1;i<=input.length;i++){
// sum[i]=sum[i-1]+input[i-1];
// }
// for (int i = 1; i <= input.length; i++) {
// for (int j = 1; j <= (int)Math.min(total,sum[i]); j++) {
// for (int k = 1; k <= (int)Math.min(i,count); k++){
// if (j >= input[i - 1]) {//Exclude and Include
// T[i][j][k] = T[i - 1][j][k] || T[i - 1][j - input[i - 1]][k-1];
// } else {
// T[i][j][k] = T[i-1][j][k];
// }
// }
// }
// }
// }
// static <K,V extends Comparable<? super V>>
// SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
// SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
// new Comparator<Map.Entry<K,V>>() {
// @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
// int res = e2.getValue().compareTo(e1.getValue());
// return res != 0 ? res : 1;
// }
// }
// );
// sortedEntries.addAll(map.entrySet());
// return sortedEntries;
// }
//minimum prime factor of all the numbers less than n
static int minPrime[];
static void minimumPrime(int n){
minPrime=new int[n+1];
minPrime[1]=1;
for (int i = 2; i * i <= n; ++i) {
if (minPrime[i] == 0) { //If i is prime
for (int j = i * i; j <= n; j += i) {
if (minPrime[j] == 0) {
minPrime[j] = i;
}
}
}
}
for (int i = 2; i <= n; ++i) {
if (minPrime[i] == 0) {
minPrime[i] = i;
}
}
}
static long modInverse(long A, long M)
{
long x=extendedEuclid(A,M)[0];
return (x%M+M)%M; //x may be negative
}
static long[] extendedEuclid(long A, long B) {
if(B == 0) {
long d = A;
long x = 1;
long y = 0;
return new long[]{x,y,d};
}
else {
long arr[]=extendedEuclid(B, A%B);
long temp = arr[0];
arr[0] = arr[1];
arr[1] = temp - (A/B)*arr[1];
return arr;
}
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, 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() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String 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 long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
} | Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | 072a276fbcbff5a25f9d61447d88a9b9 | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
/**
* http://codeforces.com/problemset/problem/844/C
*/
public class SortSub {
InputStream is;
PrintWriter out;
String INPUT = "";
long mod = 1000000007;
int[] rank, parent;
int n;
// Returns representative of x's set
int find(int x) {
// Finds the representative of the set
// that x is an element of
if (parent[x] != x) {
// if x is not the parent of itself
// Then x is not the representative of
// his set,
parent[x] = find(parent[x]);
// so we recursively call Find on its parent
// and move i's node directly under the
// representative of this set
}
return parent[x];
}
// Unites the set that includes x and the set
// that includes x
void union(int x, int y) {
// Find representatives of two sets
int xRoot = find(x), yRoot = find(y);
// Elements are in the same set, no need
// to unite anything.
if (xRoot == yRoot)
return;
// If x's rank is less than y's rank
if (rank[xRoot] < rank[yRoot])
// Then move x under y so that depth
// of tree remains less
parent[xRoot] = yRoot;
// Else if y's rank is less than x's rank
else if (rank[yRoot] < rank[xRoot])
// Then move y under x so that depth of
// tree remains less
parent[yRoot] = xRoot;
else // if ranks are the same
{
// Then move y under x (doesn't matter
// which one goes where)
parent[yRoot] = xRoot;
// And increment the the result tree's
// rank by 1
rank[xRoot] = rank[xRoot] + 1;
}
}
void solve() {
n = ni();
int[] ar = na(n);
List<Integer> li = new ArrayList();
for (int k : ar) {
li.add(k);
}
Collections.sort(li);
Map<Integer, Integer> pos = new HashMap();
for (int i = 0; i < n; i++) {
pos.put(li.get(i), i);
}
for (int i = 0; i < n; i++) {
ar[i] = pos.get(ar[i]);
}
parent = new int[n];
rank = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
}
for (int i = 0; i < n; i++) {
if (ar[i] != i) {
union(ar[i], i);
}
}
Map<Integer, List<Integer>> map = new HashMap();
for (int i = 0; i < n; i++) {
int parent = find(i);
map.putIfAbsent(parent, new ArrayList());
map.get(parent).add(i+1);
}
out.println(map.size());
map.values().forEach(list -> {
out.print(list.size());
list.forEach(item -> out.print(" " + item));
out.println();
});
}
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception {
new SortSub().run();
}
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1) throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0) return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++) map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o) {
System.out.println(Arrays.deepToString(o));
}
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | f6fc8b9b5e1ce90f4728c7e958b8bf25 | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
import java.util.StringTokenizer;
public class Main {
static long array[];
static long array2[];
static Stack<LinkedList<Integer>> ls = new Stack<LinkedList<Integer>>();
static boolean visited[];
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());
visited = new boolean[n];
array = new long[n];
array2 = new long[n];
st = new StringTokenizer(br.readLine());
for(int i = 0; i< n; i++){
array[i] = Long.parseLong(st.nextToken());
array2[i] = array[i];
}
Arrays.sort(array2);
int k = 0;
for(int i = 0; i < n; i++){
if(!visited[i]){
k++;
ls.add(new LinkedList<Integer>());
explore(i);
}
}
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
out.println(k);
for(LinkedList<Integer> ll : ls){
out.print(ll.size());
StringBuilder bb = new StringBuilder();
for(Integer w : ll){
bb.append(" " + w);
}
out.println(bb.toString());
}
out.close();
}
private static void explore(int i) {
if(!visited[i]){
visited[i] = true;
int ii = Arrays.binarySearch(array2, (array[i]));
ls.peek().add(i+1);
explore(ii);
}
}
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | ea1fc4b3cf8caf5360b5e5f93ee8300c | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Random;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Map;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Wolfgang Beyer
*/
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();
}
static class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = in.readIntArray(n);
int[] aSorted = new int[n];
System.arraycopy(a, 0, aSorted, 0, a.length);
Sorting.shuffle(aSorted, new Random());
Arrays.sort(aSorted);
Map<Integer, Integer> initialPos = new HashMap<>();
for (int i = 0; i < n; i++) {
initialPos.put(a[i], i);
}
boolean[] visited = new boolean[n];
int pos = 0;
List<List<Integer>> result = new ArrayList<>();
while (pos < n) {
if (!visited[pos]) {
List<Integer> subSeq = new ArrayList<>();
int current = pos;
while (!visited[current]) {
visited[current] = true;
subSeq.add(current);
current = initialPos.get(aSorted[current]);
}
result.add(subSeq);
}
pos++;
}
out.println(result.size());
for (int i = 0; i < result.size(); i++) {
List<Integer> subSeq = result.get(i);
out.print(subSeq.size() + " ");
for (int j = 0; j < subSeq.size(); j++) {
out.print((subSeq.get(j) + 1) + " ");
}
out.println();
}
}
}
static class Sorting {
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;
}
}
static class InputReader {
private static BufferedReader in;
private static StringTokenizer tok;
public InputReader(InputStream in) {
this.in = new BufferedReader(new InputStreamReader(in));
}
public int nextInt() {
return Integer.parseInt(next());
}
public int[] readIntArray(int n) {
int[] ar = new int[n];
for (int i = 0; i < n; i++) {
ar[i] = nextInt();
}
return ar;
}
public String next() {
try {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
//tok = new StringTokenizer(in.readLine(), ", \t\n\r\f"); //adds commas as delimeter
}
} catch (IOException ex) {
System.err.println("An IOException was caught :" + ex.getMessage());
}
return tok.nextToken();
}
}
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | c162e83809a5e924390c42a782b0b87c | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import java.util.*;
import java.awt.List;
import java.io.*;
import java.lang.*;
public class code1
{
public static void main(String[] args)
{
InputReader in = new InputReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
//Code starts..
int n = in.nextInt();
int[] a = new int[n];
int[] srt = new int[n];
for(int i=0; i<n; i++)
{
a[i] = in.nextInt();
srt[i] = a[i];
}
Arrays.sort(srt);
HashMap<Integer, Integer> map = new HashMap<>();
for(int i=0; i<n; i++)
{
map.put(srt[i], i);
}
int[] cng = new int[n];
for(int i=0; i<n; i++)
cng[i] = map.get(a[i]);
int[] set = new int[n];
int count = 1;
for(int i=0; i<n; i++)
{
if(set[i]==0)
{
set[i] = count;
int j = cng[i];
while(j!=i)
{
set[j] = count;
j = cng[j];
}
count++;
}
}
ArrayList<Integer>[] list = new ArrayList[count];
for(int i=0; i<count; i++)
list[i] = new ArrayList<>();
for(int i=0; i<n; i++)
list[set[i]].add(i+1);
pw.println(count-1);
for(int i=1; i<count; i++)
{
pw.print(list[i].size()+" ");
for(int j=0; j<list[i].size(); j++)
pw.print(list[i].get(j)+" ");
pw.println();
}
//Code ends....
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;
}
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 c = 0;
public static long mod = 1000000007;
public static int d;
public static int p;
public static int q;
public static boolean flag;
public static long INF= Long.MAX_VALUE;
public static long fun(int[] a, int[] b, int m,int n) {
long result =0;
for(int i=0; i<m; i++)
for(int j=0; j<m; j++)
{
long[] fib = new long[Math.max(2, n+2)];
fib[1] = a[i];
fib[2] = b[j];
for(int k=3; k<=n; k++)
fib[k] = (fib[k-1]%mod + fib[k-2]%mod)%mod;
result = (result%mod + fib[n]%mod)%mod;
}
return result;
}
public static double slope(pair p1, pair p2)
{
double m = INF;
if((p1.x - p2.x)!=0)
m = p1.y - p2.y/(p1.x - p2.x);
return Math.abs(m);
}
public static int count(String[] s, int f)
{
int count = 0;
int n = s[0].length();
if(f==1)
{
for(int i = 0; i<n; i++)
{
for(int j=0; j<n; j++)
{
if(i%2==0)
{
if(j%2==0 && s[i].charAt(j)=='0')
count++;
if(j%2==1 && s[i].charAt(j)=='1')
count++;
}
if(i%2==1)
{
if(j%2==1 && s[i].charAt(j)=='0')
count++;
if(j%2==0 && s[i].charAt(j)=='1')
count++;
}
}
}
}
else
{
count = 0;
for(int i = 0; i<n; i++)
{
for(int j=0; j<n; j++)
{
if(i%2==1)
{
if(j%2==0 && s[i].charAt(j)=='0')
count++;
if(j%2==1 && s[i].charAt(j)=='1')
count++;
}
if(i%2==0)
{
if(j%2==1 && s[i].charAt(j)=='0')
count++;
if(j%2==0 && s[i].charAt(j)=='1')
count++;
}
}
}
}
return count;
}
public static int gcd(int p2, int p22)
{
if (p2 == 0)
return (int) p22;
return gcd(p22%p2, p2);
}
public static int findGCD(int arr[], int n)
{
int result = arr[0];
for (int i=1; i<n; i++)
result = gcd(arr[i], result);
return result;
}
public static void nextGreater(long[] a, int[] ans)
{
Stack<Integer> stk = new Stack<>();
stk.push(0);
for(int i=1; i<a.length; i++)
{
if(!stk.isEmpty())
{
int s = stk.pop();
while(a[s]<a[i])
{
ans[s] = i;
if(!stk.isEmpty())
s = stk.pop();
else
break;
}
if(a[s]>=a[i])
stk.push(s);
}
stk.push(i);
}
return;
}
public static void nextGreaterRev(long[] a, int[] ans)
{
int n = a.length;
int[] pans = new int[n];
Arrays.fill(pans, -1);
long[] arev = new long[n];
for(int i=0; i<n; i++)
arev[i] = a[n-1-i];
Stack<Integer> stk = new Stack<>();
stk.push(0);
for(int i=1; i<n; i++)
{
if(!stk.isEmpty())
{
int s = stk.pop();
while(arev[s]<arev[i])
{
pans[s] = n - i-1;
if(!stk.isEmpty())
s = stk.pop();
else
break;
}
if(arev[s]>=arev[i])
stk.push(s);
}
stk.push(i);
}
//for(int i=0; i<n; i++)
//System.out.print(pans[i]+" ");
for(int i=0; i<n; i++)
ans[i] = pans[n-i-1];
return;
}
public static void nextSmaller(long[] a, int[] ans)
{
Stack<Integer> stk = new Stack<>();
stk.push(0);
for(int i=1; i<a.length; i++)
{
if(!stk.isEmpty())
{
int s = stk.pop();
while(a[s]>a[i])
{
ans[s] = i;
if(!stk.isEmpty())
s = stk.pop();
else
break;
}
if(a[s]<=a[i])
stk.push(s);
}
stk.push(i);
}
return;
}
public static long lcm(int[] numbers) {
long lcm = 1;
int divisor = 2;
while (true) {
int cnt = 0;
boolean divisible = false;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == 0) {
return 0;
} else if (numbers[i] < 0) {
numbers[i] = numbers[i] * (-1);
}
if (numbers[i] == 1) {
cnt++;
}
if (numbers[i] % divisor == 0) {
divisible = true;
numbers[i] = numbers[i] / divisor;
}
}
if (divisible) {
lcm = lcm * divisor;
} else {
divisor++;
}
if (cnt == numbers.length) {
return lcm;
}
}
}
public static long fact(long n) {
long factorial = 1;
for(int i = 1; i <= n; i++)
{
factorial *= i;
}
return factorial;
}
public static void factSieve(int[] a, int n) {
for(int i=2; i<=n; i+=2)
a[i] = 2;
for(int i=3; i<=n; i+=2)
{
if(a[i]==0)
{
a[i] = i;
for(int j=i; j*i<=n; j++)
{
a[i*j] = i;
}
}
}
int k = 1000;
while(k!=1)
{
System.out.print(a[k]+" ");
k /= a[k];
}
}
public static int lowerLimit(int[] a, int n) {
int ans = 0;
int ll = 0;
int rl = a.length-1;
// System.out.println(a[rl]+" "+n);
if(a[0]>n)
return 0;
if(a[0]==n)
return 1;
else if(a[rl]<=n)
return rl+1;
while(ll<=rl)
{
int mid = (ll+rl)/2;
if(a[mid]==n)
{
ans = mid + 1;
break;
}
else if(a[mid]>n)
{
rl = mid-1;
}
else
{
ans = mid+1;
ll = mid+1;
}
}
return ans;
}
public static long choose(long total, long choose){
if(total < choose)
return 0;
if(choose == 0 || choose == total)
return 1;
return (choose(total-1,choose-1)+choose(total-1,choose))%mod;
}
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 int floorSearch(int arr[], int low, int high, int x)
{
if (low > high)
return -1;
if (x > arr[high])
return high;
int mid = (low+high)/2;
if (mid > 0 && arr[mid-1] < x && x < arr[mid])
return mid-1;
if (x < arr[mid])
return floorSearch(arr, low, mid-1, x);
return floorSearch(arr, mid+1, high, x);
}
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 lowerbound(ArrayList<Long> net, long c2) {
int i=Collections.binarySearch(net, c2);
if(i<0)
i = -(i+2);
return i;
}
public static int uperbound(ArrayList<Long> net, long c2) {
int i=Collections.binarySearch(net, c2);
if(i<0)
i = -(i+1);
return i;
}
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 int[] countDer(int n)
{
int der[] = new int[n + 1];
der[0] = 1;
der[1] = 0;
der[2] = 1;
for (int i = 3; i <= n; ++i)
der[i] = (i - 1) * (der[i - 1] + der[i - 2]);
// Return result for n
return der;
}
static long binomialCoeff(int n, int k)
{
long C[][] = new long[n+1][k+1];
int i, j;
// Calculate value of Binomial Coefficient in bottom up manner
for (i = 0; i <= n; i++)
{
for (j = 0; j <= Math.min(i, k); j++)
{
// Base Cases
if (j == 0 || j == i)
C[i][j] = 1;
// Calculate value using previosly stored values
else
C[i][j] = C[i-1][j-1] + C[i-1][j];
}
}
return C[n][k];
}
public static long binaryExponentiation(long x,long n)
{
long result=1;
while(n>0)
{
if(n % 2 ==1)
result=result * x;
x=(x%mod * x%mod)%mod;
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 checkYear(int year)
{
if (year % 400 == 0)
return true;
if (year % 100 == 0)
return false;
if (year % 4 == 0)
return true;
return false;
}
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 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();
}
}
static class triplet implements Comparable<triplet>
{
Integer x,y,z;
triplet(int x,int y,int z)
{
this.x = x;
this.y = y;
this.z = z;
}
public int compareTo(triplet o)
{
int result = x.compareTo(o.x);
if(result==0)
result = y.compareTo(o.y);
if(result==0)
result = z.compareTo(o.z);
return result;
}
public boolean equlas(Object o)
{
if(o instanceof triplet)
{
triplet p = (triplet)o;
return x==p.x && y==p.y && z==p.z;
}
return false;
}
public String toString()
{
return x+" "+y+" "+z;
}
public int hashCode()
{
return new Long(x).hashCode()*31 + new Long(y).hashCode() + new Long(z).hashCode();
}
}
static class node implements Comparable<node>
{
Integer x, y, z;
node(int x,int y, int z)
{
this.x=x;
this.y=y;
this.z=z;
}
public int compareTo(pair o) {
int result = x.compareTo(o.x);
if(result==0)
result = y.compareTo(o.y);
if(result==0)
result = z.compareTo(z);
return result;
}
@Override
public int compareTo(node o) {
// TODO Auto-generated method stub
return 0;
}
}
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | 7d35e8d6fb34d61feb7dedd2c7ae08e2 | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import java.lang.reflect.Array;
import java.util.Scanner;
import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class main implements Runnable {
static ArrayList<Integer> adj[];
static void Check2(int n) {
adj = new ArrayList[n + 1];
for (int i = 0; i <= n; i++) {
adj[i] = new ArrayList<>();
}
}
static void add(int i, int j) {
adj[i].add(j);
adj[j].add(i);
}
public static void main(String[] args) {
new Thread(null, new main(), "Check2", 1 << 26).start();// to increse stack size in java
}
static long mod = (long) (1e9 + 7);
public void run() {
InputReader in = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n=in.nextInt();
long a[]=new long[n+1];
Long b[]=new Long[n+1];
b[0]=(Long)Long.MIN_VALUE;
HashMap <Long,Integer> map=new HashMap<>();
for(int i=1;i<=n;i++){
a[i]=in.nextLong();
b[i]=a[i];
map.put(a[i],i);
}
Arrays.sort(b);
Check2(n);
for(int i=1;i<=n;i++){
if(a[i]!=b[i]){
adj[i].add(map.get(b[i]));
adj[map.get(b[i])].add(i);
}
}
int v[]=new int[n+1];
list=new ArrayList<>();
ArrayList <Integer> ans[]=new ArrayList[n+1];
int co=0;
for(int i=0;i<=n;i++)ans[i]=new ArrayList<>();
for(int i=1;i<=n;i++){
if(v[i]==0){
list.clear();
dfs(i,v,w);
ans[co].addAll(list);
co++;
}
}
w.println(co);
for(int i=0;i<co;i++){
list=ans[i];
w.print(list.size()+" ");
for(int j=0;j<list.size();j++){
w.print(list.get(j)+" ");
}
w.println();
}
w.close();
}
static ArrayList <Integer> list;
static void dfs(int i,int v[],PrintWriter w){
if(v[i]==1)return;
v[i]=1;
list.add(i);
for(Integer ne:adj[i]){
dfs(ne,v,w);
}
}
static class cmp implements Comparator<pair>{
public int compare(pair o1,pair o2){
return o1.dist-o2.dist;
}
}
static class pair {
int val,dist;
pair(int a,int b){
val=a;
dist=b;
}
}
static long modinv(long a,long b)
{
long p=power(b,mod-2);
p=a%mod*p%mod;
p%=mod;
return p;
}
static long power(long x,long y){
if(y==0)return 1%mod;
if(y==1)return x%mod;
long res=1;
x=x%mod;
while(y>0){
if((y%2)!=0){
res=(res*x)%mod;
}
y=y/2;
x=(x*x)%mod;
}
return res;
}
static int gcd(int a,int b){
if(b==0)return a;
return gcd(b,a%b);
}
static void sev(int a[],int n){
for(int i=2;i<=n;i++)a[i]=i;
for(int i=2;i<=n;i++){
if(a[i]!=0){
for(int j=2*i;j<=n;){
a[j]=0;
j=j+i;
}
}
}
}
static class node{
int y;
int val;
node(int a,int b){
y=a;
val=b;
}
}
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);
}
}
} | Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | 461e2512582c0a5a682b2dea4fceca13 | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Comparator;
import java.io.InputStream;
import java.util.ArrayList;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Pradyumn Agrawal coderbond007 PLEASE!! PLEASE!! HACK MY SOLUTION!!
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, FastReader in, PrintWriter out) {
int n = in.nextInt();
int[][] ai = new int[n][];
for (int i = 0; i < n; i++) {
ai[i] = new int[]{in.nextInt(), i};
}
Arrays.sort(ai, new Comparator<int[]>() {
public int compare(int[] L, int[] R) {
return L[0] - R[0];
}
});
TaskC.DJSet djSet = new TaskC.DJSet(n);
for (int i = 0; i < n; i++) {
djSet.union(i, ai[i][1]);
}
out.println(djSet.count());
for (int i = 0; i < n; i++) {
if (djSet.upper[i] < 0) {
out.print(-djSet.upper[i]);
out.print(" ");
for (int x : djSet.lists.get(i)) {
out.print((x + 1) + " ");
}
out.println();
}
}
}
static class DJSet {
public int[] upper;
public List<List<Integer>> lists;
public DJSet(int n) {
this.upper = new int[n];
ArrayUtils.fill(upper, -1);
lists = new ArrayList<>();
for (int i = 0; i < n; i++) {
List<Integer> list = new ArrayList<>();
list.add(i);
lists.add(list);
}
}
public int root(int x) {
return upper[x] < 0 ? x : (upper[x] = root(upper[x]));
}
public boolean union(int x, int y) {
x = root(x);
y = root(y);
if (x != y) {
if (upper[y] < upper[x]) {
int d = x;
x = y;
y = d;
}
lists.get(x).addAll(lists.get(y));
upper[x] += upper[y];
upper[y] = x;
}
return x == y;
}
public int count() {
int ct = 0;
for (int u : upper) {
if (u < 0) {
ct += 1;
}
}
return ct;
}
}
}
static class ArrayUtils {
public static void fill(int[] array, int value) {
Arrays.fill(array, value);
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int pnumChars;
private FastReader.SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
private int pread() {
if (pnumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= pnumChars) {
curChar = 0;
try {
pnumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (pnumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = pread();
while (isSpaceChar(c))
c = pread();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = pread();
}
int res = 0;
do {
if (c == ',') {
c = pread();
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = pread();
} while (!isSpaceChar(c));
return res * sgn;
}
private boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
private static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | 1001d4e7d48521715c92ff7aab2dd632 | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
HashMap<Integer, Integer> original = new HashMap<Integer, Integer>();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
original.put(i, a[i]);
}
Arrays.sort(a);
HashMap<Integer, Integer> sorted = new HashMap<Integer, Integer>();
for (int i = 0; i < n; i++) {
sorted.put(a[i], i);
}
StringBuilder sb = new StringBuilder();
int cnt = 0;
for (int i = 0; i < n; i++) {
if (original.containsKey(i)) {
StringBuilder temp = new StringBuilder();
temp.append((i + 1));
int key = original.remove(i);
int p = sorted.remove(key);
int t = 1;
while (p != i) {
temp.append(" ");
temp.append((p + 1));
key = original.remove(p);
p = sorted.remove(key);
t++;
}
sb.append(t);
sb.append(" ");
sb.append(temp);
sb.append("\n");
cnt++;
}
}
System.out.println(cnt);
System.out.println(sb);
}
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | 076d921e42bb37ec4d56e517697c6362 | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes |
/**
* Date: 14 Mar, 2018
* Link :
*
* @author Prasad-Chaudhari
* @email prasadc8897@gmail.com
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Comparator;
public class New_File_3 {
public static void main (String[] args) throws java.lang.Exception {
FastIO2 in = new FastIO2();
int n = in.ni();
int a[] = new int[n];
Data d[] = new Data[n];
for(int i=0;i<n;i++){
a[i] = in.ni();
d[i] = new Data(a[i],i);
}
Arrays.sort(d,new Com());
boolean b[] = new boolean[n];
int count = 0;
StringBuilder sb = new StringBuilder();
for(int i=0;i<n;i++){
if(a[i]==d[i].a){
b[i] = true;
sb.append("1 "+(i+1)+"\n");
count++;
}
}
for(int i=0;i<n;i++){
if(!b[i]){
StringBuilder sb2 = new StringBuilder();
int index = i;
int count2 = 0;
while(!b[index]){
b[index] = true;
sb2.append((index+1)+" ");
index = d[index].b;
count2++;
}
sb.append(count2+" "+sb2.toString()+"\n");
count++;
}
}
System.out.println(count+"\n"+sb.toString());
}
static class FastIO2 {
private final BufferedReader br;
private String s[];
private int index;
public FastIO2() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
index = 0;
}
public int ni() throws IOException {
return Integer.parseInt(nextToken());
}
public double nd() throws IOException {
return Double.parseDouble(nextToken());
}
public long nl() throws IOException {
return Long.parseLong(nextToken());
}
public String next() throws IOException {
return nextToken();
}
public String nli() throws IOException {
return br.readLine();
}
public int[] gia(int n) throws IOException {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}
public int[] gia(int n, int start, int end) throws IOException {
validate(n, start, end);
int a[] = new int[n];
for (int i = start; i < end; i++) {
a[i] = ni();
}
return a;
}
public double[] gda(int n) throws IOException {
double a[] = new double[n];
for (int i = 0; i < n; i++) {
a[i] = nd();
}
return a;
}
public double[] gda(int n, int start, int end) throws IOException {
validate(n, start, end);
double a[] = new double[n];
for (int i = start; i < end; i++) {
a[i] = nd();
}
return a;
}
public long[] gla(int n) throws IOException {
long a[] = new long[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}
public long[] gla(int n, int start, int end) throws IOException {
validate(n, start, end);
long a[] = new long[n];
for (int i = start; i < end; i++) {
a[i] = ni();
}
return a;
}
private String nextToken() throws IndexOutOfBoundsException, IOException {
if(s == null){
s = br.readLine().split(" ");
}
if (index == s.length) {
s = br.readLine().split(" ");
index = 0;
}
return s[index++];
}
private void validate(int n, int start, int end) {
if (start < 0 || end >= n) {
throw new IllegalArgumentException();
}
}
}
}
class Data {
int a, b;
public Data(int a, int b) {
this.a = a;
this.b = b;
}
}
class Com implements Comparator<Data> {
@Override
public int compare(Data a, Data b) {
if (a.a == b.a) {
if (a.b == b.b) {
return 0;
} else {
return a.b - b.b;
}
} else {
return a.a - b.a;
}
}
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | 3115be85344138969932111b8efea0e6 | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Debabrata
*/
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);
SortingBySubsequence solver = new SortingBySubsequence();
solver.solve(1, in, out);
out.close();
}
static class SortingBySubsequence {
public void solve(int testNumber, InputReader scan, OutputWriter out) {
int n = scan.nextInt();
SortingBySubsequence.pair[] array = new SortingBySubsequence.pair[n];
for (int i = 0; i < n; i++) {
array[i] = new SortingBySubsequence.pair(scan.nextInt(), i);
}
Arrays.sort(array);
int p[] = new int[n];
for (int i = 0; i < n; i++) {
p[i] = array[i].second;
}
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
boolean vis[] = new boolean[n];
for (int i = 0; i < n; i++) {
if (vis[i]) continue;
ArrayList<Integer> l = new ArrayList<>();
int P = i;
while (!vis[P]) {
l.add(P);
vis[P] = true;
P = p[P];
}
list.add(l);
}
out.println(list.size());
for (ArrayList<Integer> l : list) {
out.print(l.size());
out.print(" ");
for (int i : l) {
out.print((i + 1) + " ");
}
out.println();
}
}
static class pair implements Comparable<SortingBySubsequence.pair> {
int first;
int second;
public pair(int first, int second) {
this.first = first;
this.second = second;
}
public int compareTo(SortingBySubsequence.pair p) {
return this.first - p.first;
}
}
}
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() {
writer.println();
}
public void close() {
writer.close();
}
public void print(int i) {
writer.print(i);
}
public void println(int i) {
writer.println(i);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int 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 boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | 9beea1a56b95ab9f75b933e3420cf9ab | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import java.io.*;
import java.util.*;
public class problem {
static Node node[];
static boolean visited[];
static List<List<Integer>> allList = new LinkedList<>();
static List<Integer> list = new LinkedList<>();
static class Node {
List<Integer> next = new LinkedList<>();
}
static void dfs(int u) {
list.add(u);
visited[u] = true;
for (int v : node[u].next) {
if (!visited[v]) {
dfs(v);
}
}
}
private static FastScanner in = new FastScanner();
private static void solve() {
StringBuilder ans = new StringBuilder();
int n = in.nextInt();
int a[][] = new int[n][2];
for (int i = 0; i < n; i++) {
a[i][0] = in.nextInt();
a[i][1] = i;
}
Arrays.sort(a, (x, y) -> Integer.compare(x[0], y[0]));
node = new Node[n];
for (int i = 0; i < n; i++) {
node[i] = new Node();
}
visited = new boolean[n];
Arrays.fill(visited, false);
for (int i = 0; i < n; i++) {
node[i].next.add(a[i][1]);
node[a[i][1]].next.add(i);
}
for (int i = 0; i < n; i++) {
if (!visited[i]) {
dfs(i);
allList.add(list);
list = new LinkedList<>();
}
}
ans.append(allList.size()).append("\n");
for (List<Integer> li : allList) {
ans.append(li.size()).append(" ");
for (int x : li) {
ans.append(x + 1).append(" ");
}
ans.append("\n");
}
System.out.println(ans);
}
public static void main(String[] args) throws IOException {
new problem().solve();
}
}
class FastScanner {
public static String debug = null;
private final InputStream in = System.in;
private int ptr = 0;
private int buflen = 0;
private byte[] buffer = new byte[1024];
private boolean eos = false;
private boolean hasNextByte() {
if (ptr < buflen) {
return true;
} else {
ptr = 0;
try {
if (debug != null) {
buflen = debug.length();
buffer = debug.getBytes();
debug = "";
eos = true;
} else {
buflen = in.read(buffer);
}
} catch (IOException e) {
e.printStackTrace();
}
if (buflen < 0) {
eos = true;
return false;
} else if (buflen == 0) {
return false;
}
}
return true;
}
private int readByte() {
if (hasNextByte())
return buffer[ptr++];
else
return -1;
}
private static boolean isPrintableChar(int c) {
return 33 <= c && c <= 126;
}
private void skipUnprintable() {
while (hasNextByte() && !isPrintableChar(buffer[ptr]))
ptr++;
}
public boolean isEOS() {
return this.eos;
}
public boolean hasNext() {
skipUnprintable();
return hasNextByte();
}
public String next() {
if (!hasNext())
throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while (isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public long nextLong() {
if (!hasNext())
throw new NoSuchElementException();
long n = 0;
boolean minus = false;
int b = readByte();
if (b == '-') {
minus = true;
b = readByte();
}
if (b < '0' || '9' < b) {
throw new NumberFormatException();
}
while (true) {
if ('0' <= b && b <= '9') {
n *= 10;
n += b - '0';
} else if (b == -1 || !isPrintableChar(b)) {
return minus ? -n : n;
} else {
throw new NumberFormatException();
}
b = readByte();
}
}
public int nextInt() {
return (int) nextLong();
}
public long[] nextLongList(int n) {
return nextLongTable(1, n)[0];
}
public int[] nextIntList(int n) {
return nextIntTable(1, n)[0];
}
public long[][] nextLongTable(int n, int m) {
long[][] ret = new long[n][m];
for (int i = 0; i < n; i ++) {
for (int j = 0; j < m; j ++) {
ret[i][j] = nextLong();
}
}
return ret;
}
public int[][] nextIntTable(int n, int m) {
int[][] ret = new int[n][m];
for (int i = 0; i < n; i ++) {
for (int j = 0; j < m; j ++) {
ret[i][j] = nextInt();
}
}
return ret;
}
} | Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | d33df59781f13bd8b25cc5c419c0f0fc | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import java.util.*;
import java.io.*;
public class C
{
Reader in;
PrintWriter out;
int i = 0, j = 0;
void solve()
{
//START//
int n = in.nextInt();
int[] arr = new int[n];
int[] arrOrder = new int[n];
int[] order = new int[n];
boolean[] done = new boolean[n];
for (i = 0; i < n; i++)
{
arr[i] = in.nextInt();
arrOrder[i] = arr[i];
}
Arrays.sort(arrOrder);
HashMap<Integer, Integer> ind = new HashMap<Integer, Integer>();
for (i = 0; i < n; i++)
{
ind.put(arrOrder[i], i);
}
int[] listOrder = new int[n];
for (i = 0; i < n; i++)
{
listOrder[i] = ind.get(arr[i]);
}
StringBuilder sb = new StringBuilder();
int numGroups = 0;
for (i = 0; i < n; i++)
{
if (!done[i])
{
ArrayList<Integer> curGroup = new ArrayList<Integer>();
int current = i;
numGroups++;
while (!done[current])
{
curGroup.add(current);
done[current] = true;
current = listOrder[current];
}
sb.append(curGroup.size());
for (Integer t : curGroup)
sb.append(" " + (t+1));
sb.append("\n");
}
}
out.println(numGroups);
out.print(sb.toString());
//END
}
void runIO()
{
in = new Reader();
out = new PrintWriter(System.out, false);
solve();
out.close();
}
public static void main(String[] args)
{
new C().runIO();
}
// input/output
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public final String next()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
StringBuilder res = new StringBuilder();
do
{
res.append((char) c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int nextInt()
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong()
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble()
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.')
while ((c = read()) >= '0' && c <= '9')
ret += (c - '0') / (div *= 10);
if (neg)
return -ret;
return ret;
}
public int[] readIntArray(int size)
{
int[] arr = new int[size];
for (int i = 0; i < size; i++)
arr[i] = nextInt();
return arr;
}
public long[] readLongArray(int size)
{
long[] arr = new long[size];
for (int i = 0; i < size; i++)
arr[i] = nextInt();
return arr;
}
private void fillBuffer()
{
try
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
}
catch (IOException e)
{
}
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read()
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
}
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | 6236bc00440691d7c184ab371b0bedb8 | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes |
import java.math.BigInteger;
import java.util.StringTokenizer;
import java.util.*;
import java.io.*;
public class Wtf {
public static void main(String[] args) throws IOException {
Ifmo ifmo = new Ifmo();
}
}
class Ifmo {
ArrayList<Integer> Graph[];
int n, l, m, timer;
char[][] field;
ArrayList<FUCKINGVERTEX> Ribs;
int[][] roofs, ans, up;
Vertex[][] highes;
ArrayList<Integer> fin;
static int cur;
int[] p, size, tin, tout;
boolean[] used;
int logn;
int[][] longest;
int[][][] dp = new int[31][31][51];
ArrayList<Pair>[] tree;
Ifmo() throws IOException {
FScanner fs = new FScanner(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
int n = fs.nextInt();
int[] mas = new int[n];
for (int i = 0;i < n; i++)
mas[i] = fs.nextInt();
HashSet<Integer> lo = new HashSet<>();
int[] copy = mas.clone();
Arrays.sort(copy);
int[] poses = new int[n];
for (int i = 0; i<n; i++)
poses[i] = Arrays.binarySearch(copy, mas[i]);
ArrayList<Integer>[] ans = new ArrayList[n];
int SIZE = 0;
boolean[] used = new boolean[n];
for (int i = 0; i<n; i++)
if (copy[i] == mas[i]) {
lo.add(mas[i]);
ans[SIZE++] = new ArrayList<>();
ans[SIZE-1].add(i+1);
used[i] = true;
}
for (int i = 0; i<n; i++) {
if (used[i])
continue;
ans[SIZE++] = new ArrayList<>();
ans[SIZE-1].add(i+1);
used[i] = true;
int s =i;
while (!used[poses[s]]) {
s = poses[s];
ans[SIZE-1].add(s+1);
used[s] = true;
}
}
System.out.println(SIZE);
for (int i = 0; i<SIZE; i++) {
pw.print(ans[i].size() + " ");
for (int x : ans[i])
pw.print(x + " ");
pw.println();
}
pw.close();
}
void dfs_combo(int cur, int it, int[] p, int[] q) {
used[cur] = true;
if (q[cur] == -1 || q[cur] == p[cur]);
}
void dfs_timer_lca(int v, int p, int c) {
tin[v] = ++timer;
up[v][0] = p;
used[v] = true;
for (int i = 1; i<logn; i++) {
up[v][i] = up[up[v][i-1]][i-1];
}
for (int i = 0; i<tree[v].size(); i++)
if (!used[tree[v].get(i).x]) {
dfs_timer_lca(tree[v].get(i).x, v, tree[v].get(i).y);
}
tout[v] = timer++;
}
boolean upper(int a, int b) {
return tin[a]<=tin[b] && tout[a]>=tout[b];
}
int lca(int a, int b) {
if (upper(a, b)) return a;
if (upper(b, a)) return b;
for (int i = logn-1; i>=0; i--) {
if (!upper(up[a][i], b))
a = up[a][i];
}
return up[a][0];
}
int log_2(int g) {
int s = 1;
int ans = 0;
while (g>=s)
{
ans++;
s*=2;
}
return ans;
}
int dsu_get(int v) {
return p[v] == v? v : (p[v] = dsu_get(p[v]));
}
void dsu_unit(int a, int b) { // a or dsu_get(a)? what's your choice?
if (a!=b) {
if (size[b]>size[a])
{
int q = a;
a = b;
b = q;
}
p[b] = a;
size[a]+=size[b];
}
}
}
class Pair implements Comparable<Pair> {
int x, y;
Pair(int x1, int y1) {
x = x1;
y = y1;
}
@Override
public int compareTo(Pair o) {
return Integer.compare(x, o.x);
}
}
class Lines implements Comparable<Lines> {
int pos;
boolean start;
Lines(int x, boolean f) {
pos = x;
start = f;
}
@Override
public int compareTo(Lines o) {
return Integer.compare(pos, o.pos);
}
}
class Vertex implements Comparable<Vertex> {
int a, b, c;
Vertex(int a1, int b1, int c1) {
a = a1;
b = b1;
c = c1;
}
@Override
public int compareTo(Vertex o) {
return Integer.compare(a, o.a);
}
}
class FUCKINGVERTEX implements Comparable<FUCKINGVERTEX> {
int a, b, c, d;
FUCKINGVERTEX(int a1, int b1, int c1, int d1) {
a = a1;
b = b1;
c = c1;
d = d1;
}
@Override
public int compareTo(FUCKINGVERTEX o) {
return Integer.compare(a, o.a);
}
}
class FScanner {
StringTokenizer st;
BufferedReader reader;
FScanner(InputStreamReader isr) {
reader = new BufferedReader(isr);
}
String nextLine() throws IOException {
return reader.readLine();
}
String nextToken() throws IOException{
while (st == null || !st.hasMoreTokens()) {
String s = reader.readLine();
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
char nextChar() throws IOException {
return (char) reader.read();
}
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | ab7201e5b5439b76184519c923b4e81b | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 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 Code210
{
public static int max = 1000005;
public static TreeSet<Integer> visited = new TreeSet<>();
public static HashMap<Integer,Integer> index= new HashMap<Integer,Integer>();
public static HashMap<Integer,Integer> sorted = new HashMap<>();
public static void dfs(PrintWriter pw)
{
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
for(int p : index.keySet())
{
if(!visited.contains(p))
{
ArrayList<Integer> arr = new ArrayList<>();
dfsutil(p,arr);
ans.add(arr);
}
}
pw.println(ans.size());
for(int i=0;i<ans.size();i++)
{
pw.print(ans.get(i).size() + " ");
for(int j = 0;j<ans.get(i).size();j++)
pw.print(ans.get(i).get(j)+ " ");
pw.println();
}
}
public static void dfsutil(int p, ArrayList<Integer> arr)
{
if(visited.contains(p))
return;
visited.add(p);
arr.add(index.get(p));
dfsutil(sorted.get(p), arr);
}
public static void main(String[] args)
{
InputReader in = new InputReader(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = in.nextInt();
int[] a = new int[n];
int[] b = new int[n];
for(int i=0;i<n;i++)
{
b[i] = in.nextInt();
a[i] = b[i];
index.put(b[i], i+1);
}
Arrays.sort(b);
for(int i=0;i<n;i++)
sorted.put(a[i], b[i]);
dfs(pw);
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;
}
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 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 | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | 03f8f714a6206be2a1b505e37e1e3da1 | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
public class Solution {
InputReader in;
PrintWriter out;
public Solution() {
in = new InputReader(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
// Start of Solution
public void solve() {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
Pair[] p = new Pair[n];
for (int i = 0; i < n; i++)
p[i] = new Pair(a[i], i);
// sorting using first index
Arrays.sort(p);
DisjointSet dj = new DisjointSet(n);
for (int i = 0; i < n; i++) {
dj.join(i, p[i].second);
}
int cnt = 0;
ArrayList<Integer>[] ans = new ArrayList[n];
for(int i=0;i<n;i++)
ans[i]=new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
int currentParent = dj.findParent(i);
if (ans[currentParent].size() == 0)
cnt++;
ans[currentParent].add(i);
}
out.println(cnt);
for (int i = 0; i < n; i++) {
if (ans[i].size() != 0) {
out.print(ans[i].size() + " ");
for (int value : ans[i])
out.print(value + 1 + " ");
out.println();
}
}
}
// End of Solution
static class SortUsingSecondIndex implements Comparator<Pair> {
@Override
public int compare(Pair o1, Pair o2) {
if (o1.second >= o2.second) return 1;
return -1;
}
}
static class Pair implements Comparable<Pair> {
int first, second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
@Override
public int compareTo(Pair o) {
if (Long.compare(this.first, o.first) != 0)
return Long.compare(this.first, o.first);
else
return -Long.compare(this.second, o.second);
}
}
static class DisjointSet {
int[] parent, size;
int elements;
public DisjointSet(int elements) {
this.elements = elements;
parent = new int[elements];
size = new int[elements];
for (int i = 0; i < elements; i++) {
size[i] = 1;
parent[i] = i;
}
}
// to find the parent of a given node
public int findParent(int node) {
while (node != parent[node]) {
parent[node] = parent[parent[node]];
node = parent[node];
}
return node;
}
// to join the two nodes x and y
public int join(int x, int y) {
int parentOfX = findParent(x);
int parentOfY = findParent(y);
if (parentOfX == parentOfY)
return 0;
if (size[parentOfX] < size[parentOfY])
parentOfY = swap(parentOfX, parentOfX = parentOfY);
size[parentOfX] += size[parentOfY];
parent[parentOfY] = parentOfX;
return 1;
}
int swap(int x, int y) { // usage: y = swap(x, x=y);
return x;
}
}
public static void main(String[] argv) {
new Solution();
}
// Fast Input
static final class InputReader {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1) {
return -1;
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r') {
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0) {
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines) {
return readLine();
} else {
return readLine0();
}
}
public BigInteger readBigInteger() {
try {
return new BigInteger(nextString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char nextCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E') {
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1) {
read();
}
return value == -1;
}
public String next() {
return nextString();
}
public SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
public int[] nextSortedIntArray(int n) {
int array[] = nextIntArray(n);
Arrays.sort(array);
return array;
}
public int[] nextSumIntArray(int n) {
int[] array = new int[n];
array[0] = nextInt();
for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt();
return array;
}
public long[] nextLongArray(int n) {
long[] array = new long[n];
for (int i = 0; i < n; ++i) array[i] = nextLong();
return array;
}
public long[] nextSumLongArray(int n) {
long[] array = new long[n];
array[0] = nextInt();
for (int i = 1; i < n; ++i) array[i] = array[i - 1] + nextInt();
return array;
}
public long[] nextSortedLongArray(int n) {
long array[] = nextLongArray(n);
Arrays.sort(array);
return array;
}
}
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | 720f7d759a18fac7350f5acf5c1ce948 | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import javafx.util.Pair;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import static java.util.Collections.sort;
public class Solution {
private FastScanner in;
private PrintWriter out;
private void solve() throws IOException {
int n = in.nextInt();
ArrayList<Pair<Integer, Integer>> p = new ArrayList<>(n);
for (int i = 0; i < n; i++) p.add(new Pair<>(in.nextInt(), i));
sort(p, Comparator.comparingInt(Pair::getKey));
boolean used[] = new boolean[n];
ArrayList<ArrayList<Integer>> s = new ArrayList<>();
for (int i = 0; i < n; i++)
if (!used[i]) {
ArrayList<Integer> ts = new ArrayList<>();
used[i] = true;
ts.add(i);
int ci = p.get(i).getValue();
while (ci != i) {
ts.add(ci);
used[ci] = true;
ci = p.get(ci).getValue();
}
s.add(ts);
}
out.println(s.size());
for (ArrayList<Integer> ts : s) {
out.print(ts.size() + " ");
for (int i : ts) out.print((i + 1) + " ");
out.println();
}
}
class FastScanner {
StringTokenizer st;
BufferedReader br;
FastScanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.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());
}
String nextLine() throws IOException {
return br.readLine();
}
boolean ready() throws IOException {
return br.ready();
}
}
private void run() throws IOException {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.flush();
out.close();
}
public static void main(String[] args) throws IOException {
new Solution().run();
}
} | Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | 893bed662db00e4cfdf40d05828fc51d | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.io.BufferedReader;
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();
}
static class TaskC {
final int R = (int) 2e5;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
Pair[] v = new Pair[n];
for (int i = 0; i < n; ++i) v[i] = new Pair(in.nextInt(), i);
Arrays.sort(v);
int k = 0;
boolean[] bylemTu = new boolean[R];
List<Integer>[] ans = new List[R];
for (int i = 0; i < n; ++i) ans[i] = new ArrayList();
for (int i = 0; i < n; ++i) {
if (bylemTu[i]) continue;
int cur = i;
while (!bylemTu[cur]) {
bylemTu[cur] = true;
ans[k].add(cur + 1);
cur = v[cur].index;
}
++k;
}
out.println(k);
for (int i = 0; i < k; ++i) {
out.print(ans[i].size() + " ");
for (int x : ans[i]) out.print(x + " ");
out.println();
}
}
class Pair implements Comparable<Pair> {
int wartosc;
int index;
public Pair(int a, int b) {
this.wartosc = a;
this.index = b;
}
public int compareTo(Pair o) {
if (this.wartosc > o.wartosc) return 1;
else if (this.wartosc < o.wartosc) return -1;
return 0;
}
}
}
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 | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | c60cef35f3286667ff62dbc6959fdf25 | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
public class AIMR4C {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int n = Integer.parseInt(br.readLine());
int[] perm = new int[n];
Integer[] arr = new Integer[n];
String[] in = br.readLine().split(" ");
for(int i = 0; i < n; i++){
perm[i] = Integer.parseInt(in[i]);
arr[i] = perm[i];
}
Arrays.sort(arr);
//stores index for each integer
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < n; i++){
map.put(arr[i], i);
}
boolean[] skip = new boolean[n];
ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
int m = 0;
for(int i = 0; i < n; i++){
if(skip[i]) continue;
skip[i] = true;
int x = map.get(perm[i]);
if(x != i){
int idx = x;
ans.add(new ArrayList<Integer>());
ans.get(m).add(i+1);
while(idx != i){
skip[idx] = true;
ans.get(m).add(idx+1);
idx = map.get(perm[idx]);
}
}
else{
ans.add(new ArrayList<Integer>());
ans.get(m).add(i+1);
}
m++;
}
out.println(ans.size());
for(int i = 0; i < ans.size(); i++){
out.print(ans.get(i).size()+" ");
for(int j = 0; j < ans.get(i).size(); j++){
out.print(ans.get(i).get(j)+" ");
}
out.println();
}
out.flush();
}
static class Optimize{
int num;
int idx;
public Optimize(int num, int idx){
this.num = num;
this.idx = idx;
}
}
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | af0eeed31c400126f0f66ad7919c1d73 | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Map;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] arr = new int[n], sorted_arr = new int[n];
Map<Integer, Integer> memo = new HashMap<>();
for (int i = 0; i < n; i++) {
sorted_arr[i] = arr[i] = in.nextInt();
memo.put(arr[i], i);
}
Arrays.sort(sorted_arr);
StringBuilder sb = new StringBuilder();
int ans = 0;
boolean[] visited = new boolean[n];
for (int i = 0; i < n; i++) {
if (!visited[i]) {
visited[i] = true;
ans++;
StringBuilder temp = new StringBuilder();
temp.append(i + 1);
int count = 0;
int j = i;
while (sorted_arr[j] != arr[i]) {
j = memo.get(sorted_arr[j]);
visited[j] = true;
temp.append(" ").append(j + 1);
count++;
}
sb.append(count + 1).append(" ").append(temp.toString()).append("\n");
}
}
out.println(ans);
out.print(sb);
}
}
static class InputReader {
private int lenbuf = 0;
private int ptrbuf = 0;
private InputStream in;
private byte[] inbuf = new byte[1024];
public InputReader(InputStream in) {
this.in = in;
}
private int readByte() {
if (lenbuf == -1) throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = in.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0) return -1;
}
return inbuf[ptrbuf++];
}
public 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();
}
}
}
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | 4c8f2c24a4873ef3d027db68fe46479b | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.StringTokenizer;
public class C_AIM_Round_4_Div2 {
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner();
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int[] data = new int[n];
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
data[i] = in.nextInt();
map.put(data[i], i);
}
Arrays.sort(data);
boolean[] check = new boolean[n];
ArrayList<ArrayList<Integer>> re = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (!check[i]) {
ArrayList<Integer> list = new ArrayList<>();
int start = i;
while (!check[start]) {
check[start] = true;
list.add(start + 1);
start = map.get(data[start]);
}
re.add(list);
}
}
out.println(re.size());
for (ArrayList<Integer> list : re) {
out.print(list.size());
for (int i : list) {
out.println(" " + i);
}
out.println();
}
out.close();
}
static class Seg {
int st, ed;
String v;
public Seg(int st, int ed, String v) {
super();
this.st = st;
this.ed = ed;
this.v = v;
}
}
public static int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static int digit(long n) {
int result = 0;
while (n > 0) {
n /= 10;
result++;
}
return result;
}
public static double dist(long a, long b, long x, long y) {
double val = (b - a) * (b - a) + (x - y) * (x - y);
val = Math.sqrt(val);
double other = x * x + a * a;
other = Math.sqrt(other);
return val + other;
}
public static class Point implements Comparable<Point> {
int x, y;
public Point(int start, int end) {
this.x = start;
this.y = end;
}
@Override
public int hashCode() {
int hash = 5;
hash = 47 * hash + this.x;
hash = 47 * hash + this.y;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Point other = (Point) obj;
if (this.x != other.x) {
return false;
}
if (this.y != other.y) {
return false;
}
return true;
}
@Override
public int compareTo(Point o) {
return Integer.compare(x, o.x);
}
}
public static class FT {
long[] data;
FT(int n) {
data = new long[n];
}
public void update(int index, long value) {
while (index < data.length) {
data[index] += value;
index += (index & (-index));
}
}
public long get(int index) {
long result = 0;
while (index > 0) {
result += data[index];
index -= (index & (-index));
}
return result;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static long pow(long a, long b, long MOD) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2, MOD);
if (b % 2 == 0) {
return val * val % MOD;
} else {
return val * (val * a % MOD) % MOD;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new
// BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new
// FileInputStream(new File("input.txt"))));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | c7d0d2d0a928d027df042fb70113906c | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes |
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
public class C implements Closeable {
private InputReader in = new InputReader(System.in);
private PrintWriter out = new PrintWriter(System.out);
public void solve() {
int n = in.ni();
List<Pair> sorted = new ArrayList<>();
Map<Integer, Integer> index = new HashMap<>();
for (int i = 0; i < n; i++) {
int value = in.ni();
sorted.add(new Pair(i, value));
index.put(value, i);
}
sorted.sort(Comparator.naturalOrder());
List<List<Integer>> result = new ArrayList<>();
List<Integer> next = new ArrayList<>();
boolean[] used = new boolean[n];
for (int idx = 0; idx < n; idx++) {
if (!used[idx]) {
int start = idx;
while (true) {
if (used[start]) {
result.add(next);
next = new ArrayList<>();
break;
} else {
used[start] = true;
next.add(start + 1);
start = sorted.get(start).idx;
}
}
}
}
out.println(result.size());
for (List<Integer> integers : result) {
out.print(integers.size());
out.print(' ');
for (Integer value : integers) {
out.print(value);
out.print(' ');
}
out.println();
}
}
private class Pair implements Comparable<Pair> {
private int idx, value;
private Pair(int idx, int value) {
this.idx = idx;
this.value = value;
}
@Override
public int compareTo(Pair o) {
return Integer.compare(this.value, o.value);
}
}
@Override
public void close() throws IOException {
in.close();
out.close();
}
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 ni() {
return Integer.parseInt(next());
}
public long nl() {
return Long.parseLong(next());
}
public void close() throws IOException {
reader.close();
}
}
public static void main(String[] args) throws IOException {
try (C instance = new C()) {
instance.solve();
}
}
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | ae425b3a27328e82deda12685f4cfd70 | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes |
//package leto;
import java.io.*;
import java.util.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class force_education_2 {
FastScanner in;
PrintWriter out;
static ArrayList<Integer>[] gr, ans;
static int[] a, cnt;
static ArrayList<Integer> del;
static int maxN = 1000010;
static int mod = 1000000007;
static int cons = 200001;
public static void main(String[] arg) {
new force_education_2().run();
}
public void solve() throws IOException {
// Scanner scan = new Scanner(System.in);
int n = in.nextInt();
HashMap<Integer, Integer> h = new HashMap <Integer, Integer>();
int []a = new int [n];
for(int i = 0;i<n;i++){
a[i] = in.nextInt();
h.put(a[i], i);
}
ans = new ArrayList [n];
Arrays.sort(a);
boolean []visit = new boolean [n];
int sum = 0;
for(int i = 0;i<n;i++){
if(!visit[i]){
visit[i] = true;
ans[sum] = new ArrayList();
ans[sum].add(i);
int t = h.get(a[i]);
while(!visit[t]){
visit[t] = true;
ans[sum].add(t);
t = h.get(a[t]);
}
sum++;
}
}
out.println(sum);
for(int i = 0;i<sum;i++){
out.print(ans[i].size()+" ");
for(int j: ans[i]){
out.print((j+1)+" ");
}
out.println();
}
}
private static int gcd(int a, int b) {
while ((a != 0) && (b != 0)) {
if (a < b) {
int tmp = a;
a = b;
b = tmp;
}
a %= b;
}
return (a + b);
}
public void run() {
try {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(BufferedReader bufferedReader) {
br = new BufferedReader(new InputStreamReader(System.in));
}
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());
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | c8aeaaf7cc21780cb425878c886c4b06 | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
HashMap<Integer, Integer> original = new HashMap<Integer, Integer>();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
original.put(i, a[i]);
}
Arrays.sort(a);
HashMap<Integer, Integer> sorted = new HashMap<Integer, Integer>();
for (int i = 0; i < n; i++) {
sorted.put(a[i], i);
}
StringBuilder sb = new StringBuilder();
int cnt = 0;
for (int i = 0; i < n; i++) {
if (original.containsKey(i)) {
StringBuilder tmp = new StringBuilder();
tmp.append((i + 1));
int key = original.remove(i);
int p = sorted.remove(key);
int t = 1;
while (p != i) {
tmp.append(" ");
tmp.append((p + 1));
key = original.remove(p);
p = sorted.remove(key);
t++;
}
sb.append(t);
sb.append(" ");
sb.append(tmp);
sb.append("\n");
cnt++;
}
}
System.out.println(cnt);
System.out.println(sb);
}
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | 789c73402391b650a70bad452b30950d | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
/*
public class _844C {
}
*/
public class _844C
{
class num
{
int i;
int n;
public num(int i, int n) {
super();
this.i = i;
this.n = n;
}
}
public void solve() throws FileNotFoundException
{
InputStream inputStream = System.in;
InputHelper inputHelper = new InputHelper(inputStream);
PrintStream out = System.out;
// actual solution
int n = inputHelper.readInteger();
int[] a = new int[n];
num[] an = new num[n];
for (int i = 0; i < n; i++)
{
a[i] = inputHelper.readInteger();
an[i] = new num(i, a[i]);
}
Arrays.sort(an, (n1, n2) -> n1.n - n2.n);
boolean[] isIn = new boolean[n];
List<List<Integer>> ans = new ArrayList<List<Integer>>();
for (int i = 0; i < n; i++)
{
if (!isIn[i])
{
int si = an[i].i;
List<Integer> al = new ArrayList<Integer>();
int ci = si;
do
{
isIn[ci] = true;
al.add(ci + 1);
ci = an[ci].i;
} while (ci != si);
ans.add(al);
}
}
StringBuilder sb = new StringBuilder();
sb.append(ans.size() + "\n");
for (int i = 0; i < ans.size(); i++)
{
List<Integer> al = ans.get(i);
sb.append(al.size() + " ");
for (int j = 0; j < al.size(); j++)
{
sb.append(al.get(j) + " ");
}
sb.append("\n");
}
System.out.println(sb.toString());
// end here
}
public static void main(String[] args) throws FileNotFoundException
{
(new _844C()).solve();
}
class InputHelper
{
StringTokenizer tokenizer = null;
private BufferedReader bufferedReader;
public InputHelper(InputStream inputStream)
{
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
bufferedReader = new BufferedReader(inputStreamReader, 16384);
}
public String read()
{
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try
{
String line = bufferedReader.readLine();
if (line == null)
{
return null;
}
tokenizer = new StringTokenizer(line);
} catch (IOException e)
{
e.printStackTrace();
}
}
return tokenizer.nextToken();
}
public Integer readInteger()
{
return Integer.parseInt(read());
}
public Long readLong()
{
return Long.parseLong(read());
}
}
}
| Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | da16a72e4c78457f8165d866ebba95e7 | train_003.jsonl | 1503592500 | You are given a sequence a1, a2, ..., an consisting of different integers. It is required to split this sequence into the maximum number of subsequences such that after sorting integers in each of them in increasing order, the total sequence also will be sorted in increasing order.Sorting integers in a subsequence is a process such that the numbers included in a subsequence are ordered in increasing order, and the numbers which are not included in a subsequence don't change their places.Every element of the sequence must appear in exactly one subsequence. | 256 megabytes | import java.util.*;
import java.io.*;
import java.text.*;
public class Main{
//SOLUTION BEGIN
//Into the Hardware Mode
void pre() throws Exception{}
void solve(int TC) throws Exception{
int n = ni();
long[] a = new long[n];
TreeSet<Long> s = new TreeSet<>();
for(int i = 0; i< n; i++){
a[i] = nl();
s.add(a[i]);
}
int[] b = new int[n];
HashMap<Long, Integer> mp = new HashMap<>();int c = 0;
for(long x:s)mp.put(x, c++);
for(int i = 0; i< n; i++)b[i] = mp.get(a[i]);
ArrayList<Integer>[] ans = new ArrayList[n];
int cnt = 0;
boolean[] vis = new boolean[n];
for(int i = 0; i< n; i++){
if(vis[i])continue;
ans[cnt] = new ArrayList<>();
ans[cnt].add(i);
vis[i] = true;
int cur = b[i];
while(!vis[cur]){
vis[cur] = true;
ans[cnt].add(cur);
cur = b[cur];
}
cnt++;
}
pn(cnt);
for(ArrayList<Integer> d:ans){
if(d==null)continue;
p(d.size()+" ");
for(int e:d)p(e+1+" ");pn("");
}
}
//SOLUTION END
void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
long IINF = (long)1e18, mod = (long)1e9+7;
final int INF = (int)1e9, MX = (int)2e5+5;
DecimalFormat df = new DecimalFormat("0.00");
double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-6;
static boolean multipleTC = false, memory = false, fileIO = false;
FastReader in;PrintWriter out;
void run() throws Exception{
if(fileIO){
in = new FastReader("input.txt");
out = new PrintWriter("output.txt");
}else {
in = new FastReader();
out = new PrintWriter(System.out);
}
//Solution Credits: Taranpreet Singh
int T = (multipleTC)?ni():1;
pre();for(int t = 1; t<= T; t++)solve(t);
out.flush();
out.close();
}
public static void main(String[] args) throws Exception{
if(memory)new Thread(null, new Runnable() {public void run(){try{new Main().run();}catch(Exception e){e.printStackTrace();}}}, "1", 1 << 28).start();
else new Main().run();
}
long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
int bit(long n){return (n==0)?0:(1+bit(n&(n-1)));}
void p(Object o){out.print(o);}
void pn(Object o){out.println(o);}
void pni(Object o){out.println(o);out.flush();}
String n()throws Exception{return in.next();}
String nln()throws Exception{return in.nextLine();}
int ni()throws Exception{return Integer.parseInt(in.next());}
long nl()throws Exception{return Long.parseLong(in.next());}
double nd()throws Exception{return Double.parseDouble(in.next());}
class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws Exception{
br = new BufferedReader(new FileReader(s));
}
String next() throws Exception{
while (st == null || !st.hasMoreElements()){
try{
st = new StringTokenizer(br.readLine());
}catch (IOException e){
throw new Exception(e.toString());
}
}
return st.nextToken();
}
String nextLine() throws Exception{
String str = "";
try{
str = br.readLine();
}catch (IOException e){
throw new Exception(e.toString());
}
return str;
}
}
} | Java | ["6\n3 2 1 6 5 4", "6\n83 -75 -49 11 37 62"] | 1 second | ["4\n2 1 3\n1 2\n2 4 6\n1 5", "1\n6 1 2 3 4 5 6"] | NoteIn the first sample output:After sorting the first subsequence we will get sequence 1 2 3 6 5 4.Sorting the second subsequence changes nothing.After sorting the third subsequence we will get sequence 1 2 3 4 5 6.Sorting the last subsequence changes nothing. | Java 8 | standard input | [
"dfs and similar",
"math"
] | 159365b2f037647fbaa656905e6f5252 | The first line of input data contains integer n (1 ≤ n ≤ 105) — the length of the sequence. The second line of input data contains n different integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109) — the elements of the sequence. It is guaranteed that all elements of the sequence are distinct. | 1,400 | In the first line print the maximum number of subsequences k, which the original sequence can be split into while fulfilling the requirements. In the next k lines print the description of subsequences in the following format: the number of elements in subsequence ci (0 < ci ≤ n), then ci integers l1, l2, ..., lci (1 ≤ lj ≤ n) — indices of these elements in the original sequence. Indices could be printed in any order. Every index from 1 to n must appear in output exactly once. If there are several possible answers, print any of them. | standard output | |
PASSED | e20bcfe2490a51eb41cea0f2ac981c62 | train_003.jsonl | 1387380600 | Inna, Dima and Sereja are in one room together. It's cold outside, so Sereja suggested to play a board game called "Babies". The babies playing board is an infinite plane containing n blue babies and m red ones. Each baby is a segment that grows in time. At time moment t the blue baby (x, y) is a blue segment with ends at points (x - t, y + t), (x + t, y - t). Similarly, at time t the red baby (x, y) is a red segment with ends at points (x + t, y + t), (x - t, y - t) of the plane. Initially, at time t = 0 all babies are points on the plane.The goal of the game is to find the first integer moment of time when the plane contains a rectangle of a non-zero area which sides are fully covered by some babies. A side may be covered by multiple babies. More formally, each point of each side of the rectangle should be covered by at least one baby of any color. At that, you must assume that the babies are closed segments, that is, they contain their endpoints.You are given the positions of all babies — help Inna and Dima to find the required moment of time. | 256 megabytes |
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.InputMismatchException;
public class E {
static int[] Bx, By, Rx, Ry;
static int n, m;
public static boolean can(int t) {
segment[] vert = new segment[n];
segment[] horz = new segment[m];
segment[] vertU = new segment[n];
segment[] horzU = new segment[m];
for (int i = 0; i < n; i++)
vert[i] = new segment(Bx[i], Bx[i], By[i] - 2 * t, By[i] + 2 * t);
Arrays.sort(vert, new Comparator<segment>() {
@Override
public int compare(segment o1, segment o2) {
if (o1.minX != o2.minX)
return o1.minX - o2.minX;
return o1.minY - o2.minY;
}
});
int v = 0;
for (int i = 0; i < n;) {
int maxY = vert[i].maxY;
int j = i;
while (j < n && vert[j].minX == vert[i].minX
&& vert[j].minY <= maxY) {
maxY = Math.max(maxY, vert[j].maxY);
j++;
}
vert[i].maxY = maxY;
vertU[v++] = vert[i];
i = j;
}
for (int i = 0; i < m; i++)
horz[i] = new segment(Rx[i] - 2 * t, Rx[i] + 2 * t, Ry[i], Ry[i]);
Arrays.sort(horz, new Comparator<segment>() {
public int compare(segment o1, segment o2) {
if (o1.minY != o2.minY)
return o1.minY - o2.minY;
return o1.minX - o2.minX;
}
});
int h = 0;
for (int i = 0; i < m;) {
int maxX = horz[i].maxX;
int j = i;
while (j < m && horz[j].minY == horz[i].minY
&& horz[j].minX <= maxX) {
maxX = Math.max(maxX, horz[j].maxX);
j++;
}
horz[i].maxX = maxX;
horzU[h++] = horz[i];
i = j;
}
boolean[][] visited = new boolean[v][v];
int[] involved = new int[v];
for (int i = 0; i < h; i++) {
int ind = 0;
for (int j = 0; j < v; j++)
if (horzU[i].minX <= vertU[j].minX
&& vertU[j].minX <= horzU[i].maxX)
if (vertU[j].minY <= horzU[i].minY
&& horzU[i].minY <= vertU[j].maxY)
involved[ind++] = j;
for (int j = 0; j < ind; j++)
for (int k = j + 1; k < ind; k++)
if (visited[involved[j]][involved[k]])
return true;
else
visited[involved[j]][involved[k]] = true;
}
return false;
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
n = in.readInt();
m = in.readInt();
Bx = new int[n];
By = new int[n];
Rx = new int[m];
Ry = new int[m];
for (int i = 0; i < n; i++) {
int x = in.readInt();
int y = in.readInt();
Bx[i] = x + y;
By[i] = x - y;
}
for (int i = 0; i < m; i++) {
int x = in.readInt();
int y = in.readInt();
Rx[i] = x + y;
Ry[i] = x - y;
}
int lo = 1;
int hi = (int) 1e9;
int ans = -1;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (can(mid)) {
ans = mid;
hi = mid - 1;
} else
lo = mid + 1;
}
if (ans == -1)
System.out.println("Poor Sereja!");
else
System.out.println(ans);
}
}
class segment {
int minX, maxX, minY, maxY;
public segment(int i, int j, int k, int l) {
minX = i;
maxX = j;
minY = k;
maxY = l;
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1000];
private int curChar, numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
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 long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new 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();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuffer buf = new StringBuffer();
int c = read();
while (c != '\n' && c != -1) {
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines)
return readLine();
else
return readLine0();
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new 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, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
} | Java | ["2 2\n2 2\n5 5\n3 7\n5 1", "3 2\n2 2\n3 2\n6 2\n4 2\n5 2"] | 6 seconds | ["3", "1"] | null | Java 6 | standard input | [
"geometry",
"dsu",
"implementation",
"data structures",
"binary search"
] | 6ee9ea1c487b349017d9f11a411ccfff | The first line of the input contains two integers n and m (1 ≤ n, m ≤ 2000). Next n lines contain the coordinates of the blue babies. The i-th line contains integers xi, yi — a baby's coordinates. Next m lines contain the coordinates of m red babies in the similar form. All coordinates of the input don't exceed 106 in their absolute value. Note that all babies stand in distinct points. | 2,600 | In the single line print a single integer — the answer to the problem. If the rectangle never appears on the plane, print "Poor Sereja!" without the quotes. | standard output | |
PASSED | 63c87385425a61211f7002c858bd0e7d | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.util.Scanner;
public class TicketGame {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String s = sc.next();
int a = 0;
int b = 0;
int c1 = 0;
int c2 = 0;
for(int i=0;i<s.length();i++) {
if(s.charAt(i) == '?') {
if((i+1) <= n/2 ) {
a++;
} else {
b++;
}
} else {
if((i+1) <= n/2 ) {
c1 += s.charAt(i)-'0';
} else {
c2 += s.charAt(i)-'0';
}
}
}
int dif = a-b;
int c = c2-c1;
dif = dif/2;
if(dif*9 == c) {
System.out.println("Bicarp");
} else {
System.out.println("Monocarp");
}
}
}
| Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | a7d84a0f2cfaf07be7e90c7d2bc69f06 | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.util.Scanner;
public class r585d {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
int slota=0, slotb=0;
int suma=0, sumb=0;
char[] a=scan.next().toCharArray();
for(int i=0;i<n/2;i++) {
if(a[i]=='?') slota++;
else suma+=(int)(a[i]-'0');
}
for(int i=n/2;i<n;i++) {
if(a[i]=='?') slotb++;
else sumb+=(int)(a[i]-'0');
}
if(slota>slotb) {
slota-=slotb;
slotb=0;
}
else {
slotb-=slota;
slota=0;
}
if(suma>sumb&&slota>0) {
System.out.println("Monocarp");
}
else if(sumb>suma&&slotb>0) {
System.out.println("Monocarp");
}
else if(sumb+slotb/2*9>suma+slota/2*9) {
System.out.println("Monocarp");
}
else if(suma+slota/2*9>sumb+slotb/2*9) {
System.out.println("Monocarp");
}
else {
System.out.println("Bicarp");
}
}
} | Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | 2206fa86735b582d1590dbe86ad5b0db | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes |
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.*;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
static int k;
public static void main(String[] args) {
OutputStream outputStream = System.out;
InputReader in = new InputReader();
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n=in.nextInt();
String s=in.nextLine();
int c1=0;
int c2=0;
long a=0;
long b=0;
for(int i=0;i<n;i++) {
char x=s.charAt(i);
if(x=='?')
if(i<n/2)
c1++;
else
c2++;
else if(i<n/2) {
a+=Character.getNumericValue(x);
}
else {
b+=Character.getNumericValue(x);
}
}
if(c1>c2) {
if(b-a==9*((c1-c2)/2)) {
out.println("Bicarp");
}
else {
out.println("Monocarp");
}
}
else if(c2>c1){
if(a-b==9*((c2-c1)/2)) {
out.println("Bicarp");
}
else {
out.println("Monocarp");
}
}
else {
if(a==b) {
out.println("Bicarp");
}
else {
out.println("Monocarp");
}
}
}
}
static class InputReader
{
BufferedReader br;
StringTokenizer st;
public InputReader()
{
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 | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | 29d693d0ff571c45af0ccef4a1043636 | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Say My Name
*/
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);
DTicketGame solver = new DTicketGame();
solver.solve(1, in, out);
out.close();
}
static class DTicketGame {
public void solve(int testNumber, InputReader c, OutputWriter w) {
int n = c.readInt();
char[] s = c.readString().toCharArray();
int cnt1 = 0, cnt2 = 0;
ArrayList<Integer> arr1 = new ArrayList<>(), arr2 = new ArrayList<>();
for (int i = 0; i < n / 2; i++) {
if (s[i] == '?') {
arr1.add(i);
} else {
cnt1 += s[i] - '0';
}
}
for (int i = n / 2; i < n; i++) {
if (s[i] == '?') {
arr2.add(i);
} else {
cnt2 += s[i] - '0';
}
}
int ncnt1 = cnt1, ncnt2 = cnt2;
//w.printLine(cnt1+" "+ cnt2);
//w.printLine(arr1.size()+" "+ arr2.size());
int chance = 0;
for (int i : arr1) {
if (chance == 0) {
cnt1 += 9;
}
chance ^= 1;
}
for (int i : arr2) {
if (chance == 1) {
cnt2 += 9;
}
chance ^= 1;
}
chance = 0;
for (int i : arr2) {
if (chance == 0) {
ncnt2 += 9;
}
chance ^= 1;
}
for (int i : arr1) {
if (chance == 1) {
ncnt1 += 9;
}
chance ^= 1;
}
//w.printLine(cnt1+" "+cnt2);
if (cnt1 <= cnt2 && ncnt1 >= ncnt2) {
w.printLine("Bicarp");
} else {
w.printLine("Monocarp");
}
}
}
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();
}
}
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 interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | d7451b4a74cb4fead194ea094a2f304d | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Jenish
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
DTicketGame solver = new DTicketGame();
solver.solve(1, in, out);
out.close();
}
static class DTicketGame {
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int n = in.scanInt();
char arr[] = in.scanString().toCharArray();
long leftsum = 0;
long rightsum = 0;
long left = 0;
long right = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == '?') {
if (i < n / 2) {
left++;
} else {
right++;
}
} else {
if (i < n / 2) {
leftsum += (arr[i] - '0');
} else {
rightsum += (arr[i] - '0');
}
}
}
leftsum += (left / 2) * 9;
rightsum += (right / 2) * 9;
if (leftsum == rightsum) {
out.println("Bicarp");
} else {
out.println("Monocarp");
}
}
}
static class ScanReader {
private byte[] buf = new byte[4 * 1024];
private int INDEX;
private BufferedInputStream in;
private int TOTAL;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() {
if (INDEX >= TOTAL) {
INDEX = 0;
try {
TOTAL = in.read(buf);
} catch (Exception e) {
e.printStackTrace();
}
if (TOTAL <= 0) return -1;
}
return buf[INDEX++];
}
public int scanInt() {
int I = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
I *= 10;
I += n - '0';
n = scan();
}
}
return neg * I;
}
public String scanString() {
int c = scan();
while (isWhiteSpace(c)) c = scan();
StringBuilder RESULT = new StringBuilder();
do {
RESULT.appendCodePoint(c);
c = scan();
} while (!isWhiteSpace(c));
return RESULT.toString();
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
}
}
| Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | bbe883dd790e4c911e56e55d763e74cb | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import javafx.util.Pair;
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException{
Locale.setDefault(Locale.US);
//----------------CODE HERE-------------------
int n;
n = sc.nextInt();
char[] s;
s = sc.next().toCharArray();
double s1 = 0,s2 = 0;
for (int i = 0; i < n/2; i++) {
if(s[i] == '?') {
s1+=4.5;
}
else {
s1+=s[i]-'0';
}
}
for (int i = n/2; i < n; i++) {
if(s[i] == '?') {
s2+=4.5;
}
else {
s2+=s[i]-'0';
}
}
if (Math.abs(s1-s2) < 0.00000001) {
out.println("Bicarp");
}
else {
out.println("Monocarp");
}
//----------------CODE HERE--------------------
out.flush();
}
//-----------PrintWriter for faster output---------------------------------
public static MyScanner sc = new MyScanner();
public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.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 | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | 5995fb83b01e0d3ff16d145010c47efb | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
import static java.util.Comparator.*;
public class Main {
FastScanner in;
PrintWriter out;
ArrayList<Integer>[] graph;
ArrayList<GraphPair>[] weightedGraph;
long mod = (long) 1e9 + 7; // 998_244_353L || (long) 1e9 + 9
boolean multitests = false;
private void solve() throws IOException {
// solveA();
// solveB();
int C;
solveD();
// solveE();
// solveF();
// solveG();
// solveH();
long I;
int J;
// solveK();
// solveL();
// solve0A();
// solve0B();
// solve0C();
// solve0D();
}
private void solveA() throws IOException {
int a1 = in.nextInt(), a2 = in.nextInt(), k1 = in.nextInt(), k2 = in.nextInt();
int n = in.nextInt();
if (k1 > k2) {
int a = a1;
a1 = a2;
a2 = a;
int k = k1;
k1 = k2;
k2 = k;
}
int max_k1 = min(n / k1, a1), max_k2 = min((n - max_k1 * k1) / k2, a2);
out.print(max(0, n - a1 * (k1 - 1) - a2 * (k2 - 1)) + " " + (max_k1 + max_k2));
}
boolean[] colored, interes;
int[] haveCol;
private void solveB() throws IOException {
int n = in.nextInt(), k = in.nextInt();
colored = new boolean[n];
for (int i = 0; i < k; i++)
colored[in.nextInt() - 1] = true;
interes = new boolean[n];
haveCol = new int[n];
graph = in.nextGraph(n, n - 1, false);
dfs(0, -1);
dfs2(0, -1, false);
int cnt = 0;
for (int i = 0; i < n; i++)
if (interes[i])
cnt++;
out.println(cnt);
for (int i = 0; i < n; i++)
if (interes[i])
out.print(i + 1 + " ");
}
private void dfs(int v, int p) {
haveCol[v] = colored[v] ? 1 : 0;
for (int u : graph[v]) {
if (u != p) {
dfs(u, v);
haveCol[v] += haveCol[u] > 0 ? 1 : 0;
}
}
}
private void dfs2(int v, int p, boolean up) {
interes[v] = !colored[v] && graph[v].size() - (p == -1 ? 0 : 1) == haveCol[v] && (p == -1 || up);
for (int u : graph[v]) {
if (u != p) {
dfs2(u, v, up || colored[v] || haveCol[v] > 1 || (haveCol[v] == 1 && haveCol[u] == 0));
}
}
}
private void solveC() throws IOException {
}
private void solveD() throws IOException {
int n = in.nextInt();
char[] s = in.next().toCharArray();
int[] sum = new int[2], cnt = new int[2];
for (int i = 0; i < n; i++)
if (s[i] != '?')
sum[i / (n / 2)] += s[i] - '0';
else
cnt[i / (n / 2)]++;
if (sum[0] + (cnt[0] + 1) / 2 * 9 > sum[1] + (cnt[1] + cnt[0] % 2) / 2 * 9)
out.println("Monocarp");
else if (sum[1] + (cnt[1] + 1) / 2 * 9 > sum[0] + (cnt[0] + cnt[1] % 2) / 2 * 9)
out.println("Monocarp");
else
out.println("Bicarp");
}
class Type {
int color, cnt;
Type(int color, int cnt) {
this.color = color;
this.cnt = cnt;
}
}
private void solveE() throws IOException {
int n = in.nextInt(), m = in.nextInt(), k = in.nextInt();
PriorityQueue<Type> pq = new PriorityQueue<>(comparingInt(o -> -o.cnt));
for (int i = 0; i < m; i++)
pq.add(new Type(i, in.nextInt()));
int[] color = new int[n], cnt = new int[n];
for (int i = 0; i < n; i++) {
if (i == 0 || cnt[i - 1] < k || pq.peek().color != color[i - 1]) {
Type cur = pq.poll();
color[i] = cur.color;
cnt[i] = i == 0 || color[i] != color[i - 1] ? 1 : cnt[i - 1] + 1;
cur.cnt--;
if (cur.cnt > 0)
pq.add(cur);
} else if (pq.size() == 1) {
out.println(-1);
return;
} else {
Type f = pq.poll();
Type cur = pq.poll();
color[i] = cur.color;
cnt[i] = color[i] != color[i - 1] ? 1 : cnt[i - 1] + 1;
cur.cnt--;
pq.add(f);
if (cur.cnt > 0)
pq.add(cur);
}
}
for (int i = 0; i < n; i++)
out.print(color[i] + 1 + " ");
}
private void solveF() throws IOException {
int pos = 0, neg = 0, zero = 0;
long posSum = 0, negSum = 0, zeroSum = 0;
int n = in.nextInt();
for (int i = 0; i < n; i++) {
int ai = in.nextInt();
if (ai > 0) {
pos++;
} else if (ai == 0) {
zero = i + 1;
pos = neg = 0;
} else { // ai < 0
int swap = pos;
pos = neg;
neg = swap + 1;
}
zeroSum += zero;
posSum += pos;
negSum += neg;
}
out.println(negSum + " " + zeroSum + " " + posSum);
}
private void solveG() throws IOException {
int n = in.nextInt();
char[] s = in.next().toCharArray(), t = in.next().toCharArray();
int[] sa = new int[n], ta = new int[n];
int sas = 0, tas = 0;
for (int i = 0; i < n; i++) {
if (s[i] == t[i])
continue;
if (s[i] == 'a')
sa[sas++] = i;
else
ta[tas++] = i;
}
if (sas % 2 + tas % 2 == 1) {
out.println(-1);
return;
}
out.println((sas + 1) / 2 + (tas + 1) / 2);
while (sas > 1) {
out.println(sa[sas - 1] + 1 + " " + (sa[sas - 2] + 1));
sas -= 2;
}
while (tas > 1) {
out.println(ta[tas - 1] + 1 + " " + (ta[tas - 2] + 1));
tas -= 2;
}
if (sas + tas == 2) {
out.println(sa[sas - 1] + 1 + " " + (sa[sas - 1] + 1));
out.println(sa[sas - 1] + 1 + " " + (ta[tas - 1] + 1));
}
}
private void solveH() throws IOException {
int n = in.nextInt();
long[] x = in.nextLongArray(n);
int[][] map = new int[n][];
for (int i = 0; i < n; i++) {
map[i] = new int[i];
}
int ans = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
int v = 1;
int l = -1, r = j;
while (l + 1 < r) {
int m = (l + r) / 2;
if (x[i] - x[j] <= x[j] - x[m])
l = m;
else
r = m;
}
if (l >= 0 && x[i] - x[j] == x[j] - x[l])
v += map[j][l];
else
v++;
map[i][j] = v;
if (v > ans)
ans = v;
}
}
out.println(ans);
}
private void solveI() throws IOException {
}
private void solveJ() throws IOException {
}
private void solveK() throws IOException {
int n = in.nextInt();
out.println(n * n * 3 / 4);
for (int i = 1; i <= n; i += 2) {
for (int j = 1; j <= n; j += 2) {
out.println("1 " + (i + 1) + " " + j + " 2");
out.println("1 " + i + " " + (j + 1) + " 2");
out.println("2 " + i + " " + j + " 1");
}
}
}
private void solveL() throws IOException {
int n = in.nextInt(), k = in.nextInt();
char[] s = new StringBuilder(in.next()).reverse().append(in.next()).toString().toCharArray();
int first = -1, last = -1;
for (int i = 0; i < 2 * n; i++) {
if (s[i] == '1') {
if (first == -1)
first = i < n ? i : i + k + 1;
last = i < n ? i : i + k + 1;
}
}
int ans = last, pos = 0;
for (int i = 1; i < 2 * n; i++) {
int curPos = i < n ? i : i + k + 1;
if (max(abs(first - curPos), abs(last - curPos)) < ans) {
ans = max(abs(first - curPos), abs(last - curPos));
pos = curPos;
}
}
out.println(ans);
if (pos < n)
out.println("2 " + (n - pos));
else
out.println("1 " + (pos - n - k));
}
void shuffleInt(int[] a) {
Random random = new Random();
for (int i = a.length - 1; i > 0; i--) {
int j = random.nextInt(i + 1);
int swap = a[j];
a[j] = a[i];
a[i] = swap;
}
}
void shuffleLong(long[] a) {
Random random = new Random();
for (int i = a.length - 1; i > 0; i--) {
int j = random.nextInt(i + 1);
long swap = a[j];
a[j] = a[i];
a[i] = swap;
}
}
void reverseInt(int[] a) {
for (int i = 0, j = a.length - 1; i < j; i++, j--) {
int swap = a[i];
a[i] = a[j];
a[j] = swap;
}
}
void reverseLong(long[] a) {
for (int i = 0, j = a.length - 1; i < j; i++, j--) {
long swap = a[i];
a[i] = a[j];
a[j] = swap;
}
}
int maxInt(int[] a) {
int max = a[0];
for (int i = 1; i < a.length; i++)
if (max < a[i])
max = a[i];
return max;
}
long maxLong(long[] a) {
long max = a[0];
for (int i = 1; i < a.length; i++)
if (max < a[i])
max = a[i];
return max;
}
int minInt(int[] a) {
int min = a[0];
for (int i = 1; i < a.length; i++)
if (min > a[i])
min = a[i];
return min;
}
long minLong(long[] a) {
long min = a[0];
for (int i = 1; i < a.length; i++)
if (min > a[i])
min = a[i];
return min;
}
long sumInt(int[] a) {
long s = 0;
for (int i = 0; i < a.length; i++)
s += a[i];
return s;
}
long sumLong(long[] a) {
long s = 0;
for (int i = 0; i < a.length; i++)
s += a[i];
return s;
}
long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
long binpowmod(long a, long n) {
long res = 1;
a %= mod;
n %= mod - 1;
while (n > 0) {
if (n % 2 == 1)
res = (res * a) % mod;
a = (a * a) % mod;
n /= 2;
}
return res;
}
class GraphPair implements Comparable<GraphPair> {
int v;
long w;
GraphPair(int v, long w) {
this.v = v;
this.w = w;
}
public int compareTo(GraphPair o) {
return w != o.w ? Long.compare(w, o.w) : Integer.compare(v, o.v);
}
}
ArrayList<Integer>[] createGraph(int n) throws IOException {
ArrayList<Integer>[] graph = new ArrayList[n];
for (int i = 0; i < n; i++)
graph[i] = new ArrayList<>();
return graph;
}
ArrayList<GraphPair>[] createWeightedGraph(int n) throws IOException {
ArrayList<GraphPair>[] graph = new ArrayList[n];
for (int i = 0; i < n; i++)
graph[i] = new ArrayList<>();
return graph;
}
class FastScanner {
StringTokenizer st;
BufferedReader br;
FastScanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s), 32768);
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
boolean hasNext() throws IOException {
return br.ready() || (st != null && st.hasMoreTokens());
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = in.nextInt();
return a;
}
int[][] nextIntTable(int n, int m) throws IOException {
int[][] a = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
a[i][j] = in.nextInt();
return a;
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
long[] nextLongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = in.nextLong();
return a;
}
long[][] nextLongTable(int n, int m) throws IOException {
long[][] a = new long[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
a[i][j] = in.nextLong();
return a;
}
ArrayList<Integer>[] nextGraph(int n, int m, boolean directed) throws IOException {
ArrayList<Integer>[] graph = createGraph(n);
for (int i = 0; i < m; i++) {
int v = in.nextInt() - 1, u = in.nextInt() - 1;
graph[v].add(u);
if (!directed)
graph[u].add(v);
}
return graph;
}
ArrayList<GraphPair>[] nextWeightedGraph(int n, int m, boolean directed) throws IOException {
ArrayList<GraphPair>[] graph = createWeightedGraph(n);
for (int i = 0; i < m; i++) {
int v = in.nextInt() - 1, u = in.nextInt() - 1;
long w = in.nextLong();
graph[v].add(new GraphPair(u, w));
if (!directed)
graph[u].add(new GraphPair(v, w));
}
return graph;
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
String nextLine() throws IOException {
return br.readLine();
}
boolean hasNextLine() throws IOException {
return br.ready();
}
}
private void run() throws IOException {
in = new FastScanner(System.in); // new FastScanner(new FileInputStream(".in"));
out = new PrintWriter(System.out); // new PrintWriter(new FileOutputStream(".out"));
for (int t = multitests ? in.nextInt() : 1; t-- > 0; )
solve();
out.flush();
out.close();
}
public static void main(String[] args) throws IOException {
new Main().run();
}
private void solve0A() throws IOException {
out.print(in.nextInt() * in.nextInt());
}
private void solve0B() throws IOException {
int n = in.nextInt();
String[] s = new String[n];
for (int i = 0; i < n; i++) {
s[i] = in.next();
}
for (int i = s.length - 1; i >= 0; i--) {
out.println(s[i]);
}
}
class Box {
int cnt, size;
Box(int cnt, int size) {
this.cnt = cnt;
this.size = size;
}
}
private void solve0C() throws IOException {
int n = in.nextInt(), m = in.nextInt();
Box[] b = new Box[m];
for (int i = 0; i < m; i++) {
b[i] = new Box(in.nextInt(), in.nextInt());
}
sort(b, comparingInt(o -> -o.size));
int ans = 0;
for (int i = 0; i < m && n > 0; i++) {
ans += min(n, b[i].cnt) * b[i].size;
n -= min(n, b[i].cnt);
}
out.println(ans);
}
private void solve0D() throws IOException {
long a = in.nextLong(), b = in.nextLong(), x = in.nextLong(), y = in.nextLong();
long g = gcd(x, y);
x /= g;
y /= g;
long k = min(a / x, b / y);
out.println(x * k + " " + (y * k));
}
} | Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | 33f974b7ff6277827cf64d627c90af8b | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author anand.oza
*/
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);
DTicketGame solver = new DTicketGame();
solver.solve(1, in, out);
out.close();
}
static class DTicketGame {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
char[] s = in.next().toCharArray();
int diff = 0;
int first = 0, second = 0;
for (int i = 0; i < n / 2; i++) {
if (s[i] == '?') {
first++;
} else {
diff += s[i] - '0';
}
}
for (int i = n / 2; i < n; i++) {
if (s[i] == '?') {
second++;
} else {
diff -= s[i] - '0';
}
}
boolean answer = canBeMadeEqual(first, second, diff);
out.println(answer ? "Bicarp" : "Monocarp");
}
private boolean canBeMadeEqual(int first, int second, int diff) {
return diff + 9 * (first - second) / 2 == 0;
}
}
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 | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | ec98a44adbf139a6b67019d1e2e975a5 | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.*;
import java.io.*;
public class codeforces
{
static class Student{
int x,y;
Student(int x,int y){
this.x=x;
this.y=y;
//this.z=z;
}
}
static int prime[];
static void sieveOfEratosthenes(int n)
{
// Create a boolean array "prime[0..n]" and initialize
// all entries it as true. A value in prime[i] will
// finally be false if i is Not a prime, else true.
int pos=0;
prime= new int[n+1];
for(int p = 2; p*p <=n; p++)
{
// If prime[p] is not changed, then it is a prime
if(prime[p] == 0)
{
// Update all multiples of p
prime[p]=p;
for(int i = p*p; i <= n; i += p)
if(prime[i]==0)
prime[i] = p;
}
}
}
static class Sortbyroll implements Comparator<Student>
{
// Used for sorting in ascending order of
// roll number
public int compare(Student c, Student b)
{
return c.y-b.y;
}
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static class Edge{
int a,b;
Edge(int a,int b){
this.a=a;
this.b=b;
}
}
static class Trie{
HashMap<Character,Trie>map;
int c;
Trie(){
map=new HashMap<>();
//z=null;
//o=null;
c=0;
}
}
//static long ans;
static int parent[];
static int rank[];
// static int b[][];
static int bo[];
static int ho[];
static int seg[];
//static int pos;
static long mod=1000000007;
//static int dp[][];
static HashMap<Integer,Integer>map;
static PriorityQueue<Student>q=new PriorityQueue<>();
//static Stack<Integer>st;
// static ArrayList<Character>ans;
static ArrayList<ArrayList<Integer>>adj;
//static long ans;
static int pos;
static Trie root;
static long fac[];
static int gw,gb;
//static long mod=(long)(998244353);
//static int ans;
static void solve()throws IOException{
FastReader sc=new FastReader();
int n,i,c1=0,c2=0,s1=0,s2=0,ts1=0,ts2=0;
String s;
n=sc.nextInt();
s=sc.nextLine();
for(i=0;i<n/2;i++){
if(s.charAt(i)=='?')
++c1;
else
s1+=(int)(s.charAt(i)-'0');
}
for(i=n/2;i<n;i++){
if(s.charAt(i)=='?')
++c2;
else
s2+=(int)(s.charAt(i)-'0');
}
if(s1>=s2){
ts1=s1;
ts2=s2;
}
else{
ts1=s2;
ts2=s1;
s1=c1;
c1=c2;
c2=s1;
}
if((ts1-ts2)%9==0&&(ts1-ts2)/9==(c2-c1)/2)
System.out.println("Bicarp");
else
System.out.println("Monocarp");
}
static long tr(int i,int a[],long dp[][],int bo[][],int x){
if(i>=dp.length||i<=0)
return 0;
if(bo[i][x]==1)
return -1;
if(dp[i][x]!=Integer.MIN_VALUE)
return dp[i][x];
long ans;
bo[i][x]=1;
if(x==0)
ans=tr(i+a[i-2],a,dp,bo,1-x);
else
ans=tr(i-a[i-2],a,dp,bo,1-x);
if(ans==-1)
dp[i][x]=-1;
else
dp[i][x]=ans+a[i-2];
bo[i][x]=0;
return dp[i][x];
}
static long fac(long x,long y){
if(y==0||x==0)
return 1;
return x * fac(x-1,y-1);
}
static long nCr(long n, long r,
long p)
{
return (fac[(int)n]* modInverse(fac[(int)r], p)
% p * modInverse(fac[(int)(n-r)], p)
% p) % p;
}
//static int prime[];
//static int dp[];
public static void main(String[] args){
//long sum=0;
try {
codeforces.solve();
} catch (Exception e) {
e.printStackTrace();
}
}
static long modInverse(long n, long p)
{
return power(n, p-(long)2,p);
}
static long power(long x, long y, long p)
{
long res = 1; // Initialize result
x = x % p; // Update x if it is more than or
// equal to p
while (y > 0)
{
// If y is odd, multiply x with result
if (y %(long)2!=0)
res = (res*x) % p;
// y must be even now
y = y>>1; // y = y/2
x = (x*x) % p;
}
return res%p;
}
/*public static long power(long x,long a) {
if(a==0) return 1;
if(a%2==1)return (x*1L*power(x,a-1))%mod;
return (power((int)((x*1L*x)%mod),a/2))%mod;
}*/
static int find(int x)
{
// Finds the representative of the set
// that x is an element of
while(parent[x]!=x)
{
// if x is not the parent of itself
// Then x is not the representative of
// his set,
x=parent[x];
// so we recursively call Find on its parent
// and move i's node directly under the
// representative of this set
}
return x;
}
static void union(int x, int y)
{
// Find representatives of two sets
int xRoot = find(x), yRoot = find(y);
// Elements are in the same set, no need
// to unite anything.
if (xRoot == yRoot)
return;
// If x's rank is less than y's rank
if (rank[xRoot] < rank[yRoot])
// Then move x under y so that depth
// of tree remains less
parent[xRoot] = yRoot;
// Else if y's rank is less than x's rank
else if (rank[yRoot] < rank[xRoot])
// Then move y under x so that depth of
// tree remains less
parent[yRoot] = xRoot;
else // if ranks are the same
{
// Then move y under x (doesn't matter
// which one goes where)
parent[yRoot] = xRoot;
// And increment the the result tree's
// rank by 1
rank[xRoot] = rank[xRoot] + 1;
}
}
static long gcd(long a, long b)
{
if (a == 0){
//ans+=b;
return b;
}
return gcd(b % a, a);
}
} | Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | 5aade4fc5a620536deb92646ef5d359c | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.util.Scanner;
public class que4 {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
String s = scn.next();
int suml = 0;
int cl = 0;
int sumr = 0;
int cr = 0;
for (int i = 0; i < s.length() / 2; i++) {
char v = s.charAt(i);
if (v == '?') {
cl++;
} else {
suml += (v - '0');
}
}
for (int i = s.length() / 2; i < s.length(); i++) {
char v = s.charAt(i);
if (v == '?') {
cr++;
} else {
sumr += (v - '0');
}
}
int difs = Math.abs(suml - sumr);
int difd = Math.abs(cr - cl);
int rs = difs / 9;
int rd = difd / 2;
if (difd % 2 != 0 || difs % 9 != 0) {
System.out.println("Monocarp");
} else if (rs != rd) {
System.out.println("Monocarp");
} else if ((suml <= sumr && cl >= cr)||(suml>=sumr&&cr>=cl)) {
System.out.println("Bicarp");
} else {
System.out.println("Monocarp");
}
}
}
| Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | b91512156e2bdf1780e444f8fd06ca0d | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.io.*;
import java.util.*;
import static jdk.nashorn.internal.objects.Global.print;
/**
* A simple template for competitive programming problems.
*/
public class Banana {
final InputReader in = new InputReader(System.in);
final PrintWriter out = new PrintWriter(System.out);
void solve() {
int n = in.nextInt();
int h = n/2;
String s = in.nextString();
int leftSum = 0; int rightSum = 0;
int lq = 0; int rq = 0;
for(int i=0; i<h; i++) {
if(s.charAt(i)=='?') {
lq++; continue;
}
leftSum += s.charAt(i)-'0';
}
for(int i=h; i<n; i++) {
if(s.charAt(i)=='?') {
rq++; continue;
}
rightSum += s.charAt(i)-'0';
}
if(lq>=rq) {
int dq = (lq-rq)/2;
if(rightSum-leftSum==dq*9) {
out.println("Bicarp");
} else {
out.println("Monocarp");
}
} else if(rq>lq) {
int dq = (rq-lq)/2;
if(leftSum-rightSum==dq*9) {
out.println("Bicarp");
} else {
out.println("Monocarp");
}
}
}
public static void main(String[] args) throws FileNotFoundException { Banana s = new Banana(); s.solve(); s.out.close(); }
public Banana() throws FileNotFoundException { }
private static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[1024];
private int curChar;
private int numChars;
InputReader(InputStream stream) {
this.stream = stream;
}
InputReader(String fileName) {
InputStream stream = null;
try {
stream = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
this.stream = stream;
}
int[] nextArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
int[] nextRandomArray(int n, int lim) {
int[] arr = new int[n];
Random r = new Random();
for(int i=0; i<n; i++) {
arr[i] = r.nextInt(lim);
}
return arr;
}
int[] nextRandomArray(int n) {
int[] arr = new int[n];
Random r = new Random();
for(int i=0; i<n; i++) {
arr[i] = r.nextInt();
}
return arr;
}
int[] nextRandomArray(int n, int low, int lim) {
int[] arr = new int[n];
Random r = new Random();
for(int i=0; i<n; i++) {
arr[i] = low+r.nextInt(lim-low+1);
}
return arr;
}
int[][] nextMatrix(int n, int m) {
int[][] matrix = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
matrix[i][j] = nextInt();
return matrix;
}
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();
}
String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
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;
}
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;
}
double nextDouble() {
return Double.parseDouble(nextString());
}
private int read() {
if (numChars == -1) throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try { numChars = stream.read(buf); }
catch (IOException e) { throw new InputMismatchException(); }
if (numChars <= 0) return -1;
}
return buf[curChar++];
}
private 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 | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | 67096c0fbd80fa849308a980e7142139 | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes |
import java.io.*;
import java.util.*;
public class Main{
static StreamTokenizer in=new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out));
static BufferedReader buff=new BufferedReader(new InputStreamReader(System.in));
static Scanner sc=new Scanner(System.in);
public static void main(String args[])throws Exception{
buff.readLine();
String s=buff.readLine();
int a=0,b=0;
int len=s.length();
for(int i=0;i<len/2;i++)a+=f(s.charAt(i));
for(int i=len/2;i<len;i++)b+=f(s.charAt(i));
System.out.println(a==b?"Bicarp":"Monocarp");
}
static int f(char x){
if(x=='?')return 9;
return (x-'0')*2;
}
static int getInt()throws Exception{
in.nextToken();
return (int)in.nval;
}
} | Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | 370e4d33c298e9bf6efaf924c67f7973 | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.util.*;
import org.omg.CORBA.IdentifierHelper;
import java.io.*;
public class codeforces {
public static void main(String[] args) throws Exception {
int n=sc.nextInt();
String s=sc.next();
long sum1=0;
long sum2=0;
int c1=0;
int c2=0;
for(int i=0;i<n;i++) {
if(i<(n+1)/2) {
if(s.charAt(i)=='?') {
c1++;
}
else {
sum1+=s.charAt(i)-'0';
}
}else {
if(s.charAt(i)=='?') {
c2++;
}
else {
sum2+=s.charAt(i)-'0';
}
}
}
if(c1<c2) {
if(sum1-sum2==((c2-c1)/2)*9) {
pw.println("Bicarp");
}else {
pw.println("Monocarp");
}
}else {
if(sum2-sum1==((c1-c2)/2)*9) {
pw.println("Bicarp");
}else {
pw.println("Monocarp");
}
}
pw.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
static class pair implements Comparable<pair> {
int x;
int y;
public pair(int x, int y) {
this.x = x;
this.y = y;
}
public String toString() {
return x + " " + y;
}
public int compareTo(pair other) {
if (this.x == other.x) {
return this.y - other.y;
} else {
return this.x - other.x;
}
}
}
static class tuble implements Comparable<tuble> {
int x;
int y;
int z;
public tuble(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public String toString() {
return x + " " + y + " " + z;
}
public int compareTo(tuble other) {
if (this.x == other.x) {
return this.y - other.y;
} else {
return this.x - other.x;
}
}
}
public static long GCD(long a, long b) {
if (b == 0)
return a;
if (a == 0)
return b;
return (a > b) ? GCD(a % b, b) : GCD(a, b % a);
}
public static long LCM(long a, long b) {
return a * b / GCD(a, b);
}
public static long nCk(int n, int k) { // O(K)
if (k > n) {
return 0;
}
long res = 1;
for (int i = 1; i <= k; i++) {
res = ((n - k + i) * res / i) % 1000000007;
}
return res;
}
public static long C(int a, int b, long[][] s) {
int m = (int) 1e9 + 7;
if (s[a][b] >= 0) {
return s[a][b];
} else if (a < b | a < 0 | b < 0) {
s[a][b] = 0;
return 0;
} else if (a == b | b == 0) {
s[a][b] = 1;
return 1;
} else {
return s[a][b] = (C(a - 1, b, s) % m + C(a - 1, b - 1, s) % m) % m;
}
}
static Scanner sc = new Scanner(System.in);
static PrintWriter pw = new PrintWriter(System.out);
}
| Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | cca11eeac56cde0c96163e8c86e1ea6e | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes |
import java.io.*;
import java.util.StringTokenizer;
public class mainD {
public static PrintWriter out = new PrintWriter(System.out);
public static FastScanner enter = new FastScanner(System.in);
public static void main(String[] args) throws IOException {
solve();
out.close();
}
private static void solve() throws IOException {
int n=enter.nextInt();
String s=enter.next();
int ans=0;
for (int i = n/2; i <n ; i++) {
ans+=(s.charAt(i)=='?')? 9:(s.charAt(i)-'0')*2;
}
for (int i = 0; i <n/2 ; i++) {
ans-=(s.charAt(i)=='?')? 9:(s.charAt(i)-'0')*2;
}
out.println((ans==0)?"Bicarp":"Monocarp");
/*int l=0, r=0;
int sl=0, sr=0;
for (int i = 0; i <n/2 ; i++) {
if(s.charAt(i)=='?') l++;
else sl+=(s.charAt(i)-'0');
}
for (int i = n/2; i <n ; i++) {
if(s.charAt(i)=='?') r++;
else sr+=(s.charAt(i)-'0');
}
for (int i = 0; i <=l ; i++) {
if(checkMONO(i, l, r, sl, sr)){
out.println("Monocarp");
return;
}
}
out.println("Bicarp");*/
}
private static boolean checkMONO(int i, int l, int r, int sl, int sr) {
int leftq=i;
int rightq=(r+l)/2-i;
if(rightq<0) return false;
int a1=sl;
int a2=sl+leftq*9;
int b1=sr;
int b2=sr+rightq*9;
int c1=0;
int c2=(l-leftq)*9;
int d1=0;
int d2=(r-rightq)*9;
if((a1+c1<=b1 && a2+c2>=b2) || (b1+d1<=a1 && b2+d2>=a2)) return false;
return true;
}
static class FastScanner {
BufferedReader br;
StringTokenizer stok;
FastScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
String next() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
String s = br.readLine();
if (s == null) {
return null;
}
stok = new StringTokenizer(s);
}
return stok.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
char nextChar() throws IOException {
return (char) (br.read());
}
String nextLine() throws IOException {
return br.readLine();
}
}
}
| Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | 595b4f2d4d7c6cfcb843b40f913c05a3 | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.io.*;
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class Solution {
static PrintWriter out;
static class MyScanner {
BufferedReader br;
StringTokenizer st;
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();
}
String nextLine(){
String result = "";
try {
result = br.readLine();
} catch (IOException e){
e.printStackTrace();
}
return result;
}
int nextInt(){
return Integer.parseInt(next());
}
}
public static void main(String args[]) {
MyScanner scan = new MyScanner();
out = new PrintWriter(new BufferedOutputStream(System.out));
int n = scan.nextInt();
String ticket = scan.next();
findWinner(n, ticket);
out.close();
}
private static void findWinner(int n, String ticket) {
int leftTotal = 0;
int rightTotal = 0;
int leftQ = 0;
int rightQ = 0;
for(int i = 0; i < n/2; i++){
char c = ticket.charAt(i);
if(c != '?') {
leftTotal += Integer.parseInt(c + "");
continue;
}
leftQ++;
}
for(int i = n/2; i < n; i++){
char c = ticket.charAt(i);
if(c != '?') {
rightTotal += Integer.parseInt(c + "");
continue;
}
rightQ++;
}
int remainderQ = leftQ - rightQ;
if(remainderQ == 0) {
if(leftTotal == rightTotal) {
out.println("Bicarp");
} else {
out.println("Monocarp");
}
return;
}
boolean isLeft = leftQ > rightQ;
if(isLeft) {
remainderQ = leftQ - rightQ;
int rQ = remainderQ/2;
int rem = rightTotal - leftTotal;
if(rem == 0 && remainderQ % 2 != 0) {
out.println("Monocarp");
return;
}
if(rem <= 0 || (rem-(9*rQ) > 0) || (rem-(9*rQ) < 0)) {
out.println("Monocarp");
return;
}
out.println("Bicarp");
return;
// int rQ = remainderQ/2;
//
// if(rQ * 9 >= rem) {
// out.println("Bicarp");
// return;
// }
// out.println("Monocarp");
// return;
} else {
remainderQ = rightQ - leftQ;
int rQ = remainderQ/2;
int wQ = remainderQ - rQ;
int rem = leftTotal - rightTotal;
if(rem == 0 && remainderQ % 2 != 0) {
out.println("Monocarp");
return;
}
if(rem <= 0 || (rem-(9*rQ) > 0) || (rem-(9*rQ) < 0)) {
out.println("Monocarp");
return;
}
out.println("Bicarp");
//
// if(rQ * 9 >= rem) {
// out.println("Bicarp");
// return;
// }
//
// out.println("Monocarp");
return;
}
}
} | Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | 4f0abee5072dcea3bd9ce440c6ae1eac | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.util.Scanner;
public class CodeForces1215D {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt() / 2;
String s = in.next();
int k = 0;
int l = 0;
int sum = 0;
for (int i = 0; i < s.length(); i++) {
if (i < n) {
if (s.charAt(i) == '?') k++;
else sum += s.charAt(i) - 48;
} else {
if (s.charAt(i) == '?') l++;
else sum -= s.charAt(i) - 48;
}
}
if (k < l) {
k = l - k;
} else {
k -= l;
sum *= -1;
}
if (sum != k / 2 * 9) System.out.println("Monocarp");
else {
System.out.println("Bicarp");
}
}
} | Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | c528dc1edde27740e720d5eba3134590 | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author prakhar897
*/
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);
DTicketGame solver = new DTicketGame();
solver.solve(1, in, out);
out.close();
}
static class DTicketGame {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
char arr[] = in.nextString().toCharArray();
int i, l = 0, r = 0, suml = 0, sumr = 0;
for (i = 0; i < n / 2; i++) {
if (arr[i] == '?')
l++;
else
suml += arr[i] - '0';
}
for (i = n / 2; i < n; i++) {
if (arr[i] == '?')
r++;
else
sumr += arr[i] - '0';
}
int moves = l + r;
for (i = 0; i < moves; i++) {
if (i % 2 == 0) // monocarp moves
{
if (suml == sumr) {
if (l != 0 && r != 0) {
if (l > r)
r--;
else
l--;
} else if (l != 0) {
l--;
suml += 9;
} else {
r--;
sumr += 9;
}
} else if (suml > sumr) {
if (l != 0) {
l--;
suml += 9;
} else {
r--;
if (sumr + 9 > suml)
sumr += 9;
}
} else {
if (r != 0) {
r--;
sumr += 9;
} else {
l--;
if (suml + 9 > sumr)
suml += 9;
}
}
} else //bicarp moves
{
if (suml == sumr) {
if (l != 0 && r != 0) {
if (l > r)
l--;
else
r--;
} else if (l != 0) {
l--;
} else {
r--;
}
} else if (suml > sumr) {
if (r != 0) {
r--;
sumr += Math.min(9, suml - sumr);
} else {
l--;
}
} else {
if (l != 0) {
l--;
suml += Math.min(9, sumr - suml);
} else {
r--;
}
}
}
}
if (suml == sumr)
out.println("Bicarp");
else
out.println("Monocarp");
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | ea4f598209470383b27a03e306f0ff22 | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Round585Div2D {
public static void main(String[] args) {
// TODO Auto-generated method stub
out=new PrintWriter (new BufferedOutputStream(System.out));
FastReader s=new FastReader();
int n=s.nextInt();
String str=s.next();
int[] arr=new int[n];
for(int i=0;i<n;i++) {
if(str.charAt(i)=='?') {
arr[i]=-1;
}else {
arr[i]=str.charAt(i)-'0';
}
}
boolean first =fill(arr,0,0);
boolean second=fill(arr,0,9);
boolean third=fill(arr,9,0);
boolean fourth=fill(arr,9,9);
if(first && second && third && fourth) {
out.println("Bicarp");
}else {
out.println("Monocarp");
}
out.close();
}
public static boolean fill(int[] arrr,int first,int second) {
boolean value=true;
int n=arrr.length;
int[] arr=new int[n];
for(int i=0;i<n;i++)arr[i]=arrr[i];
for(int i=0;i<n/2;i++) {
if(arr[i]==-1 && value) {
value =false;
arr[i]=first;
}else if(arr[i]==-1) {
value=true;
}
}
for(int i=n/2;i<n;i++) {
if(arr[i]==-1 && value) {
value =false;
arr[i]=second;
}else if(arr[i]==-1) {
value=true;
}
}
boolean check=check(arr);
return check;
}
public static boolean check(int[] arr) {
int n=arr.length;
int cb_1=0,cb_2=0,sum1=0,sum2=0;
for(int i=0;i<n/2;i++) {
if(arr[i]==-1) {
cb_1++;
}else {
sum1+=arr[i];
}
}
for(int i=n/2;i<n;i++) {
if(arr[i]==-1) {
cb_2++;
}else {
sum2+=arr[i];
}
}
if(sum2>sum1) {
int diff=sum2-sum1;
int blanks=diff%9==0?diff/9:diff/9+1;
if(blanks>cb_1) {
return false;
}
}else if(sum2<sum1) {
int diff=sum1-sum2;
int blanks=diff%9==0?diff/9:diff/9+1;
if(blanks>cb_2) {
return false;
}
}
return true;
}
public static PrintWriter out;
public static class FastReader {
BufferedReader br;
StringTokenizer st;
//it reads the data about the specified point and divide the data about it ,it is quite fast
//than using direct
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
//InputStream reads the data and decodes in character stream
//It acts as bridge between byte stream and character stream
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());//converts string to integer
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | c2bde063239d207bb2756f007221ac5a | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.io.*;
import java.util.*;
public class D {
static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
static MyScanner sc;
static {
try {
sc = new MyScanner();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
doTask();
out.flush();
}
public static void doTask(){
int n = sc.nextInt();
String a = sc.nextLine();
int half = n/2,left=0,right=0,leftU=0, rightU=0;
for (int i=0; i<n; i++) {
char c = a.charAt(i);
if (c == '?') {
if (i < half) leftU++; else rightU++;
} else {
if (i < half) left+=(c-48); else right+=(c-48);
}
}
int min = Math.min(leftU, rightU);
leftU -= min;
rightU -= min;
if (leftU == 0) {
doIt(right, left, rightU);
} else {
doIt(left, right, leftU);
}
}
static void doIt(int l,int r,int diff) {
if (l<r && diff%2==1) {
out.println("Monocarp");
} else {
out.println((r-l) == diff/2*9 ? "Bicarp" :"Monocarp");
}
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() throws FileNotFoundException {
// br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("C:\\Users\\Dell\\Downloads\\t1007.in"))));
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());
}
Long[] nextLongArr(int n) {
Long[] r = new Long[n];
for (int i=0; i<n; i++) {
r[i] = sc.nextLong();
}
return r;
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static class Pair {
Pair(int cx, int cy) {
x = cx; y = cy;
}
long x,y;
}
}
| Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | 89c91f197fcc57c26c2f7ecb567d4cb2 | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
public class Main {
static final long MOD = 998244353;
//static final long MOD = 1000000007;
static boolean[] visited;
public static void main(String[] args) throws IOException {
FastScanner sc = new FastScanner();
int N = sc.nextInt();
String s = sc.next();
int blank1 = 0;
int blank2 = 0;
int sum1 = 0;
int sum2 = 0;
for (int i = 0; i < N/2; i++) {
char c = s.charAt(i);
if (c=='?') {
blank1++;
} else {
sum1 += ((int)c-48);
}
}
for (int i = N/2; i < N; i++) {
char c = s.charAt(i);
if (c=='?') {
blank2++;
} else {
sum2 += ((int)c-48);
}
}
if (blank1+blank2 % 2 == 1) {
System.out.println("Monocarp");
} else {
int min = Math.min(blank1,blank2);
blank1 -= min;
blank2 -= min;
sum1 += (blank1/2)*9;
sum2 += (blank2/2)*9;
if (sum1 == sum2) {
System.out.println("Bicarp");
} else {
System.out.println("Monocarp");
}
}
}
public static int[] baseN(int N, int num) {
int[] ans = new int[N];
for (int i = N-1; i >= 0; i--) {
int pow = (int)Math.pow(N,i);
ans[i] = num/pow;
num -= ans[i]*pow;
}
return ans;
}
public static int[][] sort(int[][] array) {
//Sort an array (immune to quicksort TLE)
Random rgen = new Random();
for (int i = 0; i< array.length; i++) {
int randomPosition = rgen.nextInt(array.length);
int[] temp = array[i];
array[i] = array[randomPosition];
array[randomPosition] = temp;
}
Arrays.sort(array, new Comparator<int[]>() {
@Override
public int compare(int[] arr1, int[] arr2) {
//Descending order
return arr2[0]-arr1[0];
}
});
return array;
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
class Node {
public HashSet<Node> children;
public int n;
public Node(int n) {
this.n = n;
children = new HashSet<Node>();
}
public void addChild(Node node) {
children.add(node);
}
public void removeChild(Node node) {
children.remove(node);
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return n;
}
@Override
public boolean equals(Object obj) {
if (! (obj instanceof Node)) {
return false;
} else {
Node node = (Node) obj;
return (n == node.n);
}
}
public String toString() {
return (this.n+1)+"";
}
} | Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | da920ea5e28a5f53a80c6223800c25d0 | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB
{
void solve(int TestCase, InputReader in, PrintWriter out)
{
int n = in.nextInt();
String s = in.next();
int c1 = 0;
int c2 = 0;
int s1 = 0;
int s2 = 0;
for(int i = 0; i < n / 2; i++)
{
if(s.charAt(i) == '?')
c1++;
else
s1 += s.charAt(i) - '0';
}
for(int i = n / 2; i < n; i++)
{
if(s.charAt(i) == '?')
c2++;
else
s2 += s.charAt(i) - '0';
}
s1 += c1 / 2 * 9;
c1 %= 2;
s2 += c2 / 2 * 9;
c2 %= 2;
if(s1 == s2)
out.println("Bicarp");
else
out.println("Monocarp");
}
}
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 | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | f8f1d2b04181b772af05bd5be2e82981 | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | /*
If you want to aim high, aim high
Don't let that studying and grades consume you
Just live life young
******************************
If I'm the sun, you're the moon
Because when I go up, you go down
*******************************
I'm working for the day I will surpass you
https://www.a2oj.com/Ladder16.html
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class x1215D
{
public static void main(String omkar[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
String input = infile.readLine();
int[] arr = new int[N];
for(int i=0; i < N; i++)
{
if(input.charAt(i) == '?')
arr[i] = -1;
else
arr[i] = Integer.parseInt(input.substring(i,i+1));
}
//minimize
boolean res = min(N, arr, 0);
if(!res)
System.out.println("Monocarp");
else
System.out.println("Bicarp");
}
public static boolean min(int N, int[] arr, int b)
{
int cnt = 0;
int sum1 = 0;
for(int i=b; i < b+N/2; i++)
{
if(arr[i] == -1)
cnt++;
else
sum1+=arr[i];
}
int cnt2 = 0;
int sum2 = 0;
for(int ai=b+N/2; ai < N; ai++)
{
int i = ai%N;
if(arr[i] == -1)
cnt2++;
else
sum2 += arr[i];
}
if(sum2-sum1 == (cnt-cnt2)/2*9)
return true;
return false;
}
} | Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | 00f13713a80661ab26dd6ca61e93577b | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
Read.init(System.in);
int T = 1;
// T = Read.nextInt();
while (T != 0) {
int n=Read.nextInt();
char []str=Read.next().toCharArray();
int k=n/2;
int d1=0;
int d2=0;
int cur=0;
for(int i=0;i<k;i++){
if(str[i]=='?'){
d1++;
}else{
cur-= (str[i]-'0');
}
}
//
for(int i=k;i<n;i++){
if(str[i]=='?'){
d2++;
}else{
cur+=(str[i]-'0');
}
}
//
int d=d1-d2;
d/=2;
if(d*9==cur) {
System.out.println("Bicarp");
}else{
System.out.println("Monocarp");
}
T--;
}
//
}
//
}
//
class BIT {
int length;
int[] a;
private static int lowbit(int x) {
return x & -x;
}
public BIT(int n) {
length = n;
a = new int[n + 2];
}
//
void add(int pos, int val) {
while (pos <= length) {
a[pos] += val;
pos += lowbit(pos);
}
}
long query(int pos) {
long ret = 0;
while (pos != 0) {
ret += (long)a[pos];
pos -= lowbit(pos);
}
return ret;
}
}
//
class Read {
static BufferedReader reader;
static StringTokenizer tokenizer;
static void init(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static Double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
| Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | 314a0cc55cdf10d3eb7760e08867fa79 | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.io.InputStream;
/**
* @author khokharnikunj8
*/
public class Main {
public static void main(String[] args) {
new Thread(null, new Runnable() {
public void run() {
new Main().solve();
}
}, "1", 1 << 26).start();
}
void solve() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
DTicketGame solver = new DTicketGame();
solver.solve(1, in, out);
out.close();
}
static class DTicketGame {
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int n = in.scanInt();
int left_rem = 0;
int left_sum = 0;
int right_rem = 0;
int right_sum = 0;
for (int i = 0; i < n / 2; i++) {
char c = in.scanChar();
if (c == '?') left_rem++;
else left_sum += (c - '0');
}
for (int i = 0; i < n / 2; i++) {
char c = in.scanChar();
if (c == '?') right_rem++;
else right_sum += (c - '0');
}
if (left_rem > right_rem) {
if (right_sum == left_sum + (left_rem - right_rem) / 2 * 9) out.println("Bicarp");
else out.println("Monocarp");
} else {
if (left_sum == right_sum + (right_rem - left_rem) / 2 * 9) out.println("Bicarp");
else out.println("Monocarp");
}
}
}
static class ScanReader {
private byte[] buf = new byte[4 * 1024];
private int index;
private BufferedInputStream in;
private int total;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() {
if (index >= total) {
index = 0;
try {
total = in.read(buf);
} catch (Exception e) {
e.printStackTrace();
}
if (total <= 0) return -1;
}
return buf[index++];
}
public char scanChar() {
int c = scan();
while (isWhiteSpace(c)) c = scan();
return (char) c;
}
public int scanInt() {
int integer = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
integer *= 10;
integer += n - '0';
n = scan();
}
}
return neg * integer;
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
}
}
| Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | ed6b49f61d5bdebfd14dd57f44435bed | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.io.*;
import java.util.Random;
import java.util.StringTokenizer;
public class D {
//Solution by Sathvik Kuthuru
public static void main(String[] args) {
FastReader scan = new FastReader();
PrintWriter out = new PrintWriter(System.out);
Task solver = new Task();
int t = 1;
for(int tt = 1; tt <= t; tt++) solver.solve(tt, scan, out);
out.close();
}
static class Task {
public void solve(int testNumber, FastReader scan, PrintWriter out) {
int n = scan.nextInt();
char[] a = scan.next().toCharArray();
long ret = 0;
for(int i = 0; i < n; i++) {
long val = a[i] == '?' ? 9 : 2 * (a[i] - '0');
ret += i < n / 2 ? val : -val;
}
out.println(ret == 0 ? "Bicarp" : "Monocarp");
}
}
static void shuffle(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
static void shuffle(long[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
long temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File(s)));
}
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 | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | d4823106987b0d5b4871222ddb651029 | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
int n=s.nextInt();
String str=s.next();
int left=0;
int right=0;
int suml=0;
int sumr=0;
for(int i=0;i<n/2;i++)
{
if(str.charAt(i)=='?')
{
left++;
}
else
{
suml=suml+Integer.valueOf(str.charAt(i)+"");
}
}
for(int i=n/2;i<n;i++)
{
if(str.charAt(i)=='?')
{
right++;
}
else
{
sumr=sumr+Integer.valueOf(str.charAt(i)+"");
}
}
int p=0;
int total=left+right;
int ll=suml+9*(Math.min(left,total/2));
int rr=sumr+9*(Math.min(total/2,right));
if(sumr>ll||rr<ll)
{
p=1;
}
else if(suml>rr||rr>ll)
{
p=1;
}
if(p==1)
{
System.out.println("Monocarp");
}
else
{
System.out.println("Bicarp");
}
}
} | Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | c43b1ae8664ccdd5d505e06468dcec0b | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author KharYusuf
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
DTicketGame solver = new DTicketGame();
solver.solve(1, in, out);
out.close();
}
static class DTicketGame {
public void solve(int testNumber, FastReader s, PrintWriter w) {
int n = s.nextInt(), m = n >> 1;
char[] c = s.next().toCharArray();
int lsum = 0, rsum = 0, lq = 0, rq = 0;
for (int i = 0; i < m; i++) {
if (c[i] == '?') lq++;
else lsum += c[i] - '0';
}
for (int i = m; i < n; i++) {
if (c[i] == '?') rq++;
else rsum += c[i] - '0';
}
int[] ll = new int[4], rr = new int[4], lrem = new int[4], rrem = new int[4];
ll[0] = lsum + (int) Math.ceil(lq / 2.0) * 9;
lrem[0] = lq / 2;
ll[1] = lsum;
lrem[1] = lq / 2;
rr[0] = rsum;
rrem[0] = (int) Math.ceil(rq / 2.0);
rr[1] = rsum + (rq / 2) * 9;
rrem[1] = rrem[0];
ll[2] = lsum;
lrem[2] = (int) Math.ceil(lq / 2.0);
rr[2] = rsum + (int) Math.ceil(rq / 2.0) * 9;
rrem[2] = rq / 2;
ll[3] = lsum + (lq / 2) * 9;
lrem[3] = lrem[2];
rr[3] = rsum;
rrem[3] = rq / 2;
int f = 0;
for (int i = 0; i < 4; i++) {
//w.println(ll[i]+" "+rr[i]+" "+lrem[i]+" "+rrem[i]);
if (ll[i] < rr[i]) {
if (ll[i] + lrem[i] * 9 < rr[i]) {
f = 1;
}
} else {
if (rr[i] + rrem[i] * 9 < ll[i]) {
f = 1;
}
}
}
w.println(f == 1 ? "Monocarp" : "Bicarp");
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private FastReader.SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | 6174aa957aad895688dc7b7b39ae0667 | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.io.*;
import java.util.*;
public class asdf {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
String s = br.readLine();
int leftcount = 0;
int rightcount = 0;
int leftqs = 0;
int rightqs= 0 ;
for (int i=0; i<N/2; i++) {
if (s.charAt(i)=='?') {
leftqs++;
}
else {
leftcount+=Integer.parseInt(s.charAt(i)+"");
}
}
for (int i=N/2; i<N; i++) {
if (s.charAt(i)=='?') {
rightqs++;
}
else {
rightcount+=Integer.parseInt(s.charAt(i)+"");
}
}
int bb = rightqs-leftqs;
int qq = rightcount-leftcount;
if (-9*bb/2==qq) {
System.out.println("Bicarp");
}
else System.out.println("Monocarp");
}
}
| Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | 86c20522b6b580e6f380e8b40082db11 | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.util.*;
import java.io.*;
public class CFA {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
private static final long MOD = 1000L * 1000L * 1000L + 7;
private static final int[] dx = {0, -1, 0, 1};
private static final int[] dy = {1, 0, -1, 0};
private static final String yes = "Yes";
private static final String no = "No";
void solve() throws IOException {
int T = 1;
for (int i = 0; i < T; i++) {
helper();
}
}
void helper() throws IOException {
int n = nextInt();
char[] arr = nextString().toCharArray();
int sum = 0;
int hf = 0;
int cnt = 0;
int hcnt = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == '?') {
cnt++;
if (i < n / 2) {
hcnt++;
}
} else {
sum += arr[i] - '0';
if (i < n / 2) {
hf += arr[i] - '0';
}
}
}
if (cnt == 0 || 2 * hcnt == cnt) {
outln(2 * hf == sum ? "Bicarp" : "Monocarp");
return;
}
int dCnt = 2 * hcnt - cnt;
if (dCnt > 0) {
int diff = sum - 2 * hf;
if (dCnt % 2 == 0 && dCnt / 2 * 9 == diff) {
outln("Bicarp");
return;
}
} else {
int diff = 2 * hf - sum;
dCnt = -dCnt;
if (dCnt % 2 == 0 && dCnt / 2 * 9 == diff) {
outln("Bicarp");
return;
}
}
outln("Monocarp");
}
void shuffle(long[] a) {
int n = a.length;
for(int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
long tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
}
long gcd(long a, long b) {
while(a != 0 && b != 0) {
long c = b;
b = a % b;
a = c;
}
return a + b;
}
private void outln(Object o) {
out.println(o);
}
private void out(Object o) {
out.print(o);
}
private void formatPrint(double val) {
outln(String.format("%.9f%n", val));
}
public CFA() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new CFA();
}
public long[] nextLongArr(int n) throws IOException{
long[] res = new long[n];
for(int i = 0; i < n; i++)
res[i] = nextLong();
return res;
}
public int[] nextIntArr(int n) throws IOException {
int[] res = new int[n];
for(int i = 0; i < n; i++)
res[i] = nextInt();
return res;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return null;
}
}
return st.nextToken();
}
public String nextString() {
try {
return br.readLine();
} catch (IOException e) {
eof = true;
return null;
}
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
} | Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | cce628d2b3f77b180b0c412741412118 | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
import java.util.Vector;
public class Test {
public static void main(String[] args) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(System.out);
int n = Integer.parseInt(br.readLine());
String s = br.readLine();
int suml = 0;
int sumr = 0;
int pl = 0;
int pr = 0;
for(int i = 0; i < n/2; i++)
{
if(s.charAt(i) == '?') pl++;
else suml += s.charAt(i)-'0';
}
for(int i = n/2; i < n; i++)
{
if(s.charAt(i) == '?') pr++;
else sumr += s.charAt(i)-'0';
}
if((suml-sumr)*2 == (pr-pl)*9) writer.println("Bicarp");
else writer.println("Monocarp");
br.close();
writer.close();
}
}
| Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | cf0472d9964dbd3f0b239117171bc472 | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
char[] b = in.nextString().toCharArray();
int qLeft = 0;
int qRight = 0;
int sumLeft = 0;
int sumRight = 0;
for (int i = 0; i < n; i++) {
if (i < n / 2) {
if (b[i] == '?') {
qLeft += 1;
} else {
sumLeft += b[i] - '0';
}
} else {
if (b[i] == '?') {
qRight += 1;
} else {
sumRight += b[i] - '0';
}
}
}
if (qLeft == qRight) {
out.println(sumLeft == sumRight ? "Bicarp" : "Monocarp");
return;
}
int t;
int num;
if (qLeft < qRight) {
num = sumLeft - sumRight;
t = (qRight - qLeft) / 2;
} else {
num = sumRight - sumLeft;
t = (qLeft - qRight) / 2;
}
out.println(num == 9 * t ? "Bicarp" : "Monocarp");
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
}
| Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | 49a9706b682bf90432eacc6a6747d48e | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Jaynil
*/
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
String x = in.next();
int sleft = 0;
int qleft = 0;
for (int i = 0; i < n / 2; i++) {
if (x.charAt(i) != '?')
sleft += Character.getNumericValue(x.charAt(i));
else qleft++;
}
int sright = 0;
int qright = 0;
for (int i = n / 2; i < n; i++) {
if (x.charAt(i) != '?')
sright += Character.getNumericValue(x.charAt(i));
else qright++;
}
if (sleft - sright == ((qright - qleft) / 2) * 9) {
out.println("Bicarp");
} else {
out.println("Monocarp");
}
}
}
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 | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | fa7d7396a1be4829c241d57557f548e4 | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | // No sorceries shall previal. //
import java.util.Scanner;
import java.io.PrintWriter;
import java.util.*;
import java.util.Arrays;
public class InVoker {
public static void main(String args[]) {
Scanner inp = new Scanner(System.in);
PrintWriter out= new PrintWriter(System.out);
int n=inp.nextInt();
char s[]=inp.next().toCharArray();
int q1=0,q2=0,i=0,sum1=0,sum2=0;
for(i=0;i<n/2;i++)
if(s[i]!='?')
sum1+=(int)(s[i]-'0');
else q1++;
for(;i<n;i++)
if(s[i]!='?')
sum2+=(int)(s[i]-'0');
else q2++;
out.println((sum1-sum2)*2==(q2-q1)*9?"Bicarp":"Monocarp");
out.close();
inp.close();
}
} | Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | d73aa79d610c8e885430fa66f14e0499 | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes |
import java.util.*;
import java.io.*;
import java.math.*;
import java.awt.geom.*;
import static java.lang.Math.*;
public class Main implements Runnable
{
boolean multiiple = false;
void solve() throws Exception
{
int n = sc.nextInt();
int L = 0, R = 0, ml = 0, mr = 0;
String s = sc.nextToken();
for (int i = 0; i < n; i++)
{
if (s.charAt(i) == '?')
if (i < n / 2)
ml++;
else
mr++;
else
if (i < n / 2)
L += s.charAt(i) - '0';
else
R += s.charAt(i) - '0';
}
if (ml == mr)
if (L == R)
System.out.println("Bicarp");
else
System.out.println("Monocarp");
if (ml > mr)
{
if (L < R && ((ml - mr) / 2) * 9 == R - L)
System.out.println("Bicarp");
else
System.out.println("Monocarp");
}
if (ml < mr)
{
if (L > R && ((mr - ml) / 2) * 9 == L - R)
System.out.println("Bicarp");
else
System.out.println("Monocarp");
}
}
@Override
public void run()
{
try
{
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
sc = new FastScanner(in);
if (multiiple)
{
int q = sc.nextInt();
for (int i = 0; i < q; i++)
solve();
}
else
solve();
}
catch (Throwable uncaught)
{
Main.uncaught = uncaught;
}
finally
{
out.close();
}
}
public static void main(String[] args) throws Throwable {
Thread thread = new Thread(null, new Main(), "", (1 << 26));
thread.start();
thread.join();
if (Main.uncaught != null) {
throw Main.uncaught;
}
}
static Throwable uncaught;
BufferedReader in;
FastScanner sc;
PrintWriter out;
}
class FastScanner
{
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in)
{
this.in = in;
}
public String nextToken() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
public int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
public long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
public double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
} | Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | 4ed412cb448c1768ceb8262e2bd26e36 | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | //package com.company;
import java.util.*;
public class Main {
//static int n;
public static void main(String[] args) {
// write your code here
Scanner s = new Scanner(System.in);
int n=s.nextInt();
char []a =s.next().toCharArray();long s1=0;int b1=0;long s2=0;int b2=0;int ans=-1;
for(int i=0;i<n/2;i++){
if(a[i]!='?') s1+=(a[i]-48);
else b1++;
}for(int i=n/2;i<n;i++){
if(a[i]!='?') s2+=(a[i]-48);
else b2++;
}
// System.out.println(s1+" "+s2);
if(s1<s2){int x=0;int y=0;if(b1%2!=0) x=1; if(b2%2!=0) y=1;
// System.out.println();
if((s1+(b1/2)*9>=s2+(b2/2)*9)&&(s1+(b1/2+x)*9<=s2+(b2/2+y)*9))
ans=1;
else
ans=0;
}
else if(s1>s2){int x=0;int y=0;if(b1%2!=0) x=1; if(b2%2!=0) y=1;
// System.out.println(s1+(b1/2+x)*9+" "+(s2+(b2/2+y)*9));
if((s1+(b1/2)*9<=s2+(b2/2)*9)&&(s1+(b1/2+x)*9>=s2+(b2/2+y)*9))
ans=1;
else
ans=0;
}else if(s1==s2){int x=0;int y=0;if(b1%2!=0) x=1; if(b2%2!=0) y=1;
// System.out.println("hi"+x+y);
if((s1+(b1/2)*9==s2+(b2/2)*9)&&(s1+(b1/2+x)*9==s2+(b2/2+y)*9))
ans=1;
else
ans=0;
}
// System.out.println(s1+" " +s2);
if(ans==0)
System.out.println("Monocarp");
else
System.out.println("Bicarp");
}
} | Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | 629c0ab101626d9e2ea2e31e78fba265 | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String s = in.next();
int a = 0;
int b = 0;
int _a = 0;
int _b = 0;
for (int i = 0; i < n / 2; i++) {
if (s.charAt(i) == '?') {
_a++;
} else {
a += (s.charAt(i) - '0');
}
}
for (int i = n / 2; i < n; i++) {
if (s.charAt(i) == '?') {
_b++;
} else {
b += (s.charAt(i) - '0');
}
}
int min = Math.min(_a, _b);
_a -= min;
_b -= min;
if (_a == 0 && _b == 0) {
System.out.println(a == b ? "Bicarp" : "Monocarp");
} else {
int sum;
if (_a == 0) {
sum = a - b;
} else {
sum = b - a;
}
int req = Math.max(_a, _b);
if (sum == (req / 2) * 9) {
System.out.println("Bicarp");
} else {
System.out.println("Monocarp");
}
}
}
} | Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | 2522692a1584b68d0dcd4765c996edc4 | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
InputStream is;
PrintWriter out;
String INPUT = "";
//class Declaration
static class pair implements Comparable < pair > {
long x;
long y;
pair(long i, long j) {
x = i;
y = j;
}
public int compareTo(pair p) {
if (this.x != p.x) {
return Long.compare(this.x,p.x);
} else {
return Long.compare(this.y,p.y);
}
}
public int hashCode() {
return (x + " " + y).hashCode();
}
public String toString() {
return x + " " + y;
}
public boolean equals(Object o) {
pair x = (pair) o;
return (x.x == this.x && x.y == this.y);
}
}
// int[] dx = {0,0,1,-1};
// int[] dy = {1,-1,0,0};
// int[] ddx = {0,0,1,-1,1,-1,1,-1};
// int[] ddy = {1,-1,0,0,1,-1,-1,1};
int inf = (int) 1e9 + 9;
long biginf = (long)1e17 + 7 ;
long mod = (long)1e9 + 7;
void solve() throws Exception {
int n=ni();
char[] s= ns().toCharArray();
int leftSum = 0,rightSum =0;
ArrayList<Integer> mono = new ArrayList<>();
ArrayList<Integer> bi = new ArrayList<>();
int cnt =0;
for(int i=0;i<n;++i){
if(s[i]!='?'){
if(i<n/2) leftSum+=(s[i]-'0');
else rightSum+=(s[i]-'0');
}
else{
if(cnt%2==0) mono.add(i);
else bi.add(i);
cnt++;
}
}
boolean pos = false;
//leftheavy
int ls = leftSum,rs = rightSum;
for(int x: mono)
if(x<n/2) ls+=9;
for(int x: bi){
if(x<n/2){
ls+= rs-ls>0?Math.min(rs-ls,9):0;
}
else{
rs+= ls-rs>0?Math.min(ls-rs,9):0;
}
}
if(ls!=rs) pos = true;
//right heavy
ls = leftSum ; rs = rightSum;
for(int x: mono)
if(x>=n/2) rs+=9;
for(int x: bi){
if(x<n/2){
ls+= rs-ls>0?Math.min(rs-ls,9):0;
}
else{
rs+= ls-rs>0?Math.min(ls-rs,9):0;
}
}
if(ls!=rs) pos = true;
pn(pos?"Monocarp":"Bicarp");
}
long pow(long a, long b) {
long result = 1;
while (b > 0) {
if (b % 2 == 1) result = (result * a) % mod;
b /= 2;
a = (a * a) % mod;
}
return result;
}
void print(Object o) {
System.out.println(o);
System.out.flush();
}
long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
if (!INPUT.isEmpty()) tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception {
new Main().run();
}
//output methods
private void pn(Object o) {
out.println(o);
}
private void p(Object o) {
out.print(o);
}
private ArrayList < ArrayList < Integer >> ng(int n, int e) {
ArrayList < ArrayList < Integer >> g = new ArrayList < > ();
for (int i = 0; i <= n; ++i) g.add(new ArrayList < > ());
for (int i = 0; i < e; ++i) {
int u = ni(), v = ni();
g.get(u).add(v);
g.get(v).add(u);
}
return g;
}
private ArrayList < ArrayList < pair >> nwg(int n, int e) {
ArrayList < ArrayList < pair >> g = new ArrayList < > ();
for (int i = 0; i <= n; ++i) g.add(new ArrayList < > ());
for (int i = 0; i < e; ++i) {
int u = ni(), v = ni(), w = ni();
g.get(u).add(new pair(w, v));
g.get(v).add(new pair(w, u));
}
return g;
}
//input methods
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1) throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0) return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b));
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++) map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private void tr(Object...o) {
if (INPUT.length() > 0) System.out.println(Arrays.deepToString(o));
}
void watch(Object...a) throws Exception {
int i = 1;
print("watch starts :");
for (Object o: a) {
//print(o);
boolean notfound = true;
if (o.getClass().isArray()) {
String type = o.getClass().getName().toString();
//print("type is "+type);
switch (type) {
case "[I":
{
int[] test = (int[]) o;
print(i + " " + Arrays.toString(test));
break;
}
case "[[I":
{
int[][] obj = (int[][]) o;
print(i + " " + Arrays.deepToString(obj));
break;
}
case "[J":
{
long[] obj = (long[]) o;
print(i + " " + Arrays.toString(obj));
break;
}
case "[[J":
{
long[][] obj = (long[][]) o;
print(i + " " + Arrays.deepToString(obj));
break;
}
case "[D":
{
double[] obj = (double[]) o;
print(i + " " + Arrays.toString(obj));
break;
}
case "[[D":
{
double[][] obj = (double[][]) o;
print(i + " " + Arrays.deepToString(obj));
break;
}
case "[Ljava.lang.String":
{
String[] obj = (String[]) o;
print(i + " " + Arrays.toString(obj));
break;
}
case "[[Ljava.lang.String":
{
String[][] obj = (String[][]) o;
print(i + " " + Arrays.deepToString(obj));
break;
}
case "[C":
{
char[] obj = (char[]) o;
print(i + " " + Arrays.toString(obj));
break;
}
case "[[C":
{
char[][] obj = (char[][]) o;
print(i + " " + Arrays.deepToString(obj));
break;
}
default:
{
print(i + " type not identified");
break;
}
}
notfound = false;
}
if (o.getClass() == ArrayList.class) {
print(i + " al: " + o);
notfound = false;
}
if (o.getClass() == HashSet.class) {
print(i + " hs: " + o);
notfound = false;
}
if (o.getClass() == TreeSet.class) {
print(i + " ts: " + o);
notfound = false;
}
if (o.getClass() == TreeMap.class) {
print(i + " tm: " + o);
notfound = false;
}
if (o.getClass() == HashMap.class) {
print(i + " hm: " + o);
notfound = false;
}
if (o.getClass() == LinkedList.class) {
print(i + " ll: " + o);
notfound = false;
}
if (o.getClass() == PriorityQueue.class) {
print(i + " pq : " + o);
notfound = false;
}
if (o.getClass() == pair.class) {
print(i + " pq : " + o);
notfound = false;
}
if (notfound) {
print(i + " unknown: " + o);
}
i++;
}
print("watch ends ");
}
} | Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | 2939e03d198bb1f677be758c4bbeb8c6 | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class SepLong {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static FastReader scn = new FastReader();
public static void main(String[] args) {
int t = 1;
while(t-- > 0) {
run2();
}
}
private static void run2(){
int n = scn.nextInt();
String a = scn.next();
int left = 0, right = 0;
int ll = 0, rr = 0;
for(int i = 0; i<n/2; i++){
if(a.charAt(i) == '?'){
ll++;
continue;
}
left += a.charAt(i)-'0';
}
for(int i = n/2; i<n; i++){
if(a.charAt(i) == '?'){
rr++;
continue;
}
right += a.charAt(i)-'0';
}
if(right > left){
int t = right;
right = left;
left = t;
t = rr;
rr = ll;
ll = t;
}
while(ll>0 || rr>0){
if(ll != 0){
left += 9;
ll--;
}
else{
if((rr/2)*9 == left-right){
System.out.println("Bicarp");
return;
}
else{
System.out.println("Monocarp");
return;
}
}
if(rr == 0){
System.out.println("Monocarp");
return;
}
else{
rr--;
int d = Math.min(9, left-right);
right += d;
}
}
if(left == right){
System.out.println("Bicarp");
}
else{
System.out.println("Monocarp");
}
}
}
| Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | 0469c3d2e0867a99a0468274cc9729d1 | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.InputMismatchException;
import java.util.List;
public class Main {
private static final int MAXN = 10;
private static final String NO = "No";
private static final String YES = "Yes";
InputStream is;
PrintWriter out;
String INPUT = "";
private static final long MOD = 1000000007L;
int N;
void solve() {
int N = ni();
char[] a = ns().toCharArray();
int sum[] = new int[2];
for (int i = 0; i < N / 2; i++)
if (a[i] != '?')
sum[0] += a[i] - '0';
else
sum[1]--;
for (int i = N / 2; i < N; i++)
if (a[i] != '?')
sum[0] -= a[i] - '0';
else
sum[1]++;
if (sum[0] <= 0) {
sum[0] *= -1;
sum[1] *= -1;
}
if (2 * sum[0] == sum[1] * 9)
out.println("Bicarp");
else
out.println("Monocarp");
}
private long gcd(long a, long b) {
while (a != 0) {
long tmp = b % a;
b = a;
a = tmp;
}
return b;
}
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
if (!INPUT.isEmpty())
tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception {
new Main().run();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private boolean vis[];
private int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != '
// ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n) {
if (!(isSpaceChar(b)))
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private List<Integer> na2(int n) {
List<Integer> a = new ArrayList<Integer>();
for (int i = 0; i < n; i++)
a.add(ni());
return a;
}
private int[][] na(int n, int m) {
int[][] a = new int[n][];
for (int i = 0; i < n; i++)
a[i] = na(m);
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long[] nl(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nl();
return a;
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o) {
System.out.println(Arrays.deepToString(o));
}
} | Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | df12bea4d617abb39e453c8f4cf39ada | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String args[]) {new Main().run();}
FastReader in = new FastReader();
PrintWriter out = new PrintWriter(System.out);
void run(){
work();
out.flush();
}
long mod=1000000007;
long gcd(long a,long b) {
return b==0?a:gcd(b,a%b);
}
void work() {
int n=in.nextInt();
String s=in.next();
int c1=0,c2=0;
int cnt1=0,cnt2=0;
for(int i=0;i<n/2;i++) {
if(s.charAt(i)=='?') c1++;
else {
cnt1+=s.charAt(i)-'0';
}
}
for(int i=n/2;i<n;i++) {
if(s.charAt(i)=='?') c2++;
else {
cnt2+=s.charAt(i)-'0';
}
}
cnt1+=(c1-c2)/2*9;
if(cnt1==cnt2) {
out.println("Bicarp");
}else {
out.println("Monocarp");
}
}
}
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br=new BufferedReader(new InputStreamReader(System.in));
}
public String next()
{
if(st==null || !st.hasMoreElements())
{
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
} | Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | 8539281de93289bc7eb5a362a515b487 | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.io.*;
import java.nio.CharBuffer;
import java.util.NoSuchElementException;
public class P1215D {
public static void main(String[] args) {
SimpleScanner scanner = new SimpleScanner(System.in);
PrintWriter writer = new PrintWriter(System.out);
int n = scanner.nextInt();
char[] s = scanner.next().toCharArray();
int[] sum = new int[2];
int[] cnt = new int[2];
for (int i = 0; i < n; ++i) {
int k = i >= n / 2 ? 1 : 0;
if (s[i] == '?')
++cnt[k];
else
sum[k] += s[i] - '0';
}
int diffCnt, diffSum;
if (cnt[0] < cnt[1]) {
diffCnt = cnt[1] - cnt[0];
diffSum = sum[1] - sum[0];
} else {
diffCnt = cnt[0] - cnt[1];
diffSum = sum[0] - sum[1];
}
writer.println(diffSum == -9 * (diffCnt / 2) ? "Bicarp" : "Monocarp");
writer.close();
}
private static class SimpleScanner {
private static final int BUFFER_SIZE = 10240;
private Readable in;
private CharBuffer buffer;
private boolean eof;
private SimpleScanner(InputStream in) {
this.in = new BufferedReader(new InputStreamReader(in));
buffer = CharBuffer.allocate(BUFFER_SIZE);
buffer.limit(0);
eof = false;
}
private char read() {
if (!buffer.hasRemaining()) {
buffer.clear();
int n;
try {
n = in.read(buffer);
} catch (IOException e) {
n = -1;
}
if (n <= 0) {
eof = true;
return '\0';
}
buffer.flip();
}
return buffer.get();
}
private void checkEof() {
if (eof)
throw new NoSuchElementException();
}
private char nextChar() {
checkEof();
char b = read();
checkEof();
return b;
}
private String next() {
char b;
do {
b = read();
checkEof();
} while (Character.isWhitespace(b));
StringBuilder sb = new StringBuilder();
do {
sb.append(b);
b = read();
} while (!eof && !Character.isWhitespace(b));
return sb.toString();
}
private int nextInt() {
return Integer.parseInt(next());
}
private long nextLong() {
return Long.parseLong(next());
}
private double nextDouble() {
return Double.parseDouble(next());
}
}
}
| Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | bccb4a6d43a66beaf7467394d3d8841f | train_003.jsonl | 1568543700 | Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally. | 256 megabytes | import java.lang.*;
import java.util.*;
import java.io.*;
public class Main {
void solve() {
int n=ni();
char s[]=ns().toCharArray();
int S1=0,S2=0,c1=0,c2=0;
for(int i=1;i<=n;i++){
if(i<=n/2){
if(s[i-1]=='?') c1++;
else
S1+=s[i-1]-'0';
}else {
if(s[i-1]=='?') c2++;
else S2+=s[i-1]-'0';
}
}
int t=0,x=c1,y=c2;
int diff=S1-S2;
while(x>0 || y>0){
if(t==0){
if(x>0){
diff+=9;
x--;
}else y--;
}else {
if(y>0) {
diff-=9;
y--;
}
else x--;
}
t^=1;
}
if(diff>0){
pw.println("Monocarp");
return;
}
t=0;x=c1; y=c2;
diff=S1-S2;
while(x>0 || y>0){
if(t==0){
if(y>0){
diff-=9;
y--;
}else x--;
}else {
if(x>0){
diff+=9;
x--;
}else y--;
}
t^=1;
}
if(diff<0){
pw.println("Monocarp");
return;
}
pw.println("Bicarp");
}
long M = (long)1e9+7;
// END
PrintWriter pw;
StringTokenizer st;
BufferedReader br;
void run() throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
pw.flush();
}
public static void main(String[] args) throws Exception {
new Main().run();
}
String ns() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine() throws Exception {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
throw new Exception(e.toString());
}
return str;
}
int ni() {
return Integer.parseInt(ns());
}
long nl() {
return Long.parseLong(ns());
}
double nd() {
return Double.parseDouble(ns());
}
} | Java | ["4\n0523", "2\n??", "8\n?054??0?", "6\n???00?"] | 1 second | ["Bicarp", "Bicarp", "Bicarp", "Monocarp"] | NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy. | Java 8 | standard input | [
"greedy",
"games",
"math"
] | 028882706ed58b61b4672fc3e76852c4 | The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even. | 1,700 | If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes). | standard output | |
PASSED | 75950dade748d15789e54f35383820dd | train_003.jsonl | 1563636900 | Recall that string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero or all) characters. For example, for the string $$$a$$$="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", "ooo".The wow factor of a string is the number of its subsequences equal to the word "wow". Bob wants to write a string that has a large wow factor. However, the "w" key on his keyboard is broken, so he types two "v"s instead. Little did he realise that he may have introduced more "w"s than he thought. Consider for instance the string "ww". Bob would type it as "vvvv", but this string actually contains three occurrences of "w": "vvvv" "vvvv" "vvvv" For example, the wow factor of the word "vvvovvv" equals to four because there are four wows: "vvvovvv" "vvvovvv" "vvvovvv" "vvvovvv" Note that the subsequence "vvvovvv" does not count towards the wow factor, as the "v"s have to be consecutive.For a given string $$$s$$$, compute and output its wow factor. Note that it is not guaranteed that it is possible to get $$$s$$$ from another string replacing "w" with "vv". For example, $$$s$$$ can be equal to "vov". | 256 megabytes | import java.io.*;
import java.util.*;
public class wowFactor {
public static long totalW(String str) {
long count = 0;
for (int i = 0; i < str.length()-1; i++) {
if (str.substring(i,i+2).equals("vv")) {
count++;
}
}
return count;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
String str = sc.next();
long numberW = 0;
long ans = 0;
long totalW = totalW(str);
for (int i = 0; i < str.length()-2; i++) {
if (str.substring(i,i+2).equals("vv")) {
numberW++;
}
else if (str.substring(i,i+1).equals("o")) {
ans += numberW * (totalW-numberW);
}
}
pw.println(ans);
sc.close();
pw.close();
}
} | Java | ["vvvovvv", "vvovooovovvovoovoovvvvovovvvov"] | 1 second | ["4", "100"] | NoteThe first example is explained in the legend. | Java 8 | standard input | [
"dp",
"strings"
] | 6cc6db6f426bb1bce59f23bfcb762b08 | The input contains a single non-empty string $$$s$$$, consisting only of characters "v" and "o". The length of $$$s$$$ is at most $$$10^6$$$. | 1,300 | Output a single integer, the wow factor of $$$s$$$. | standard output | |
PASSED | ffe5a670cbd5dbfc1bde417409f378a6 | train_003.jsonl | 1563636900 | Recall that string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero or all) characters. For example, for the string $$$a$$$="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", "ooo".The wow factor of a string is the number of its subsequences equal to the word "wow". Bob wants to write a string that has a large wow factor. However, the "w" key on his keyboard is broken, so he types two "v"s instead. Little did he realise that he may have introduced more "w"s than he thought. Consider for instance the string "ww". Bob would type it as "vvvv", but this string actually contains three occurrences of "w": "vvvv" "vvvv" "vvvv" For example, the wow factor of the word "vvvovvv" equals to four because there are four wows: "vvvovvv" "vvvovvv" "vvvovvv" "vvvovvv" Note that the subsequence "vvvovvv" does not count towards the wow factor, as the "v"s have to be consecutive.For a given string $$$s$$$, compute and output its wow factor. Note that it is not guaranteed that it is possible to get $$$s$$$ from another string replacing "w" with "vv". For example, $$$s$$$ can be equal to "vov". | 256 megabytes | import java.io.*;
import java.util.*;
import java.nio.file.*;
import static java.lang.Math.*;
public class B {
public static void main(String[] args) throws Exception {
String s = s();
int n = s.length();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = s.charAt(i) == 'v' ? 1 : 0;
}
int[] w = new int[n - 1];
for (int i = 0; i < n - 1; i++) {
if (s.charAt(i) == 'v' && s.charAt(i + 1) == 'v') {
w[i] = 1;
}
}
if (n < 3) {
out.println(0);
out.close();
System.exit(0);
}
int[] pre = new int[n - 1];
pre[0] = w[0];
for (int i = 1; i < n - 1; i++) {
pre[i] = w[i] + pre[i - 1];
}
long ans = 0;
for (int i = 0; i < n - 1; i++) {
if (a[i] == 1) continue;
long beg = pre[i], end = pre[n - 2] - pre[i];
ans += beg * end;
}
out.println(ans);
out.close();
}
static BufferedReader in;
static StringTokenizer st = new StringTokenizer("");
static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
static {
try {
in = Files.newBufferedReader(Paths.get("test.in"));
} catch (Exception e) {
in = new BufferedReader(new InputStreamReader(System.in));
}
}
static void check() throws Exception {
while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine());
}
static String s() throws Exception { check(); return st.nextToken(); }
static int i() throws Exception { return Integer.parseInt(s()); }
static long l() throws Exception { return Long.parseLong(s()); }
static double d() throws Exception { return Double.parseDouble(s()); }
}
| Java | ["vvvovvv", "vvovooovovvovoovoovvvvovovvvov"] | 1 second | ["4", "100"] | NoteThe first example is explained in the legend. | Java 8 | standard input | [
"dp",
"strings"
] | 6cc6db6f426bb1bce59f23bfcb762b08 | The input contains a single non-empty string $$$s$$$, consisting only of characters "v" and "o". The length of $$$s$$$ is at most $$$10^6$$$. | 1,300 | Output a single integer, the wow factor of $$$s$$$. | standard output | |
PASSED | e395e56d55129e0cf7feaff907a316bc | train_003.jsonl | 1563636900 | Recall that string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero or all) characters. For example, for the string $$$a$$$="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", "ooo".The wow factor of a string is the number of its subsequences equal to the word "wow". Bob wants to write a string that has a large wow factor. However, the "w" key on his keyboard is broken, so he types two "v"s instead. Little did he realise that he may have introduced more "w"s than he thought. Consider for instance the string "ww". Bob would type it as "vvvv", but this string actually contains three occurrences of "w": "vvvv" "vvvv" "vvvv" For example, the wow factor of the word "vvvovvv" equals to four because there are four wows: "vvvovvv" "vvvovvv" "vvvovvv" "vvvovvv" Note that the subsequence "vvvovvv" does not count towards the wow factor, as the "v"s have to be consecutive.For a given string $$$s$$$, compute and output its wow factor. Note that it is not guaranteed that it is possible to get $$$s$$$ from another string replacing "w" with "vv". For example, $$$s$$$ can be equal to "vov". | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.security.KeyStore.Entry;
import java.text.DecimalFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.SSLContext;
public class Main
{
static long mod=(long)(1e+9 + 7);
static int[] sieve;
static ArrayList<Integer> primes;
static int[] visited;
public static void main(String[] args) throws java.lang.Exception
{
fast s = new fast();
PrintWriter out=new PrintWriter(System.out);
Scanner sc=new Scanner(System.in);
StringBuilder fans = new StringBuilder();
String str=s.nextLine();
int k=0;
while(k<str.length() && str.charAt(k)=='o') k++;
long ans=0;
long suf_zero[]=new long[str.length()];
long suf_vv[]=new long[str.length()];
long suf_prod[]=new long[str.length()];
suf_vv[str.length()-1]=0;
suf_zero[str.length()-1]=0;
Arrays.fill(suf_prod, 0);
for(int i=str.length()-2;i>=0;i--)
{
if(str.charAt(i)=='v' && str.charAt(i)==str.charAt(i+1))
suf_vv[i]=(long)suf_vv[i+1]+1;
else
suf_vv[i]=(long)suf_vv[i+1];
if(str.charAt(i)=='o')
{
suf_zero[i]=(long)suf_zero[i+1]+1;
suf_prod[i]=(long)suf_prod[i+1]+suf_vv[i+1];
}
else
{suf_zero[i]=(long)suf_zero[i+1];suf_prod[i]=(long)suf_prod[i+1];}
}
int i=k+1;
while(i<str.length())
{
int left=0;
while(i<str.length() && str.charAt(i)=='v' && str.charAt(i)==str.charAt(i-1))
{left++;i++;}
if(i<str.length())
ans=ans+(long)(left)*suf_prod[i];
while(i<str.length() && str.charAt(i)=='o')
i++;
i++;
}
System.out.println(ans);
}
static class fast {
private InputStream i;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
//Return floor log2n
public static long log2(long bits) // returns 0 for bits=0
{
int log = 0;
if( ( bits & 0xffff0000 ) != 0 ) { bits >>>= 16; log = 16; }
if( bits >= 256 ) { bits >>>= 8; log += 8; }
if( bits >= 16 ) { bits >>>= 4; log += 4; }
if( bits >= 4 ) { bits >>>= 2; log += 2; }
return log + ( bits >>> 1 );
}
public static boolean next_permutation(int a[])
{
int i=0,j=0;int index=-1;
int n=a.length;
for(i=0;i<n-1;i++)
if(a[i]<a[i+1]) index=i;
if(index==-1) return false;
i=index;
for(j=i+1;j<n && a[i]<a[j];j++);
int temp=a[i];
a[i]=a[j-1];
a[j-1]=temp;
for(int p=i+1,q=n-1;p<q;p++,q--)
{
temp=a[p];
a[p]=a[q];
a[q]=temp;
}
return true;
}
public static void division(char ch[],int divisor)
{
int div=Character.getNumericValue(ch[0]); int mul=10;int remainder=0;
StringBuilder quotient=new StringBuilder("");
for(int i=1;i<ch.length;i++)
{
div=div*mul+Character.getNumericValue(ch[i]);
if(div<divisor) {quotient.append("0");continue;}
quotient.append(div/divisor);
div=div%divisor;mul=10;
}
remainder=div;
while(quotient.charAt(0)=='0')quotient.deleteCharAt(0);
System.out.println(quotient+" "+remainder);
}
public static void sieve(int size)
{
sieve=new int[size+1];
primes=new ArrayList<Integer>();
sieve[1]=1;
for(int i=2;i<=Math.sqrt(size);i++)
{
if(sieve[i]==0)
{
for(int j=i*i;j<size;j+=i) {sieve[j]=1;}
}
}
for(int i=2;i<=size;i++)
{
if(sieve[i]==0) primes.add(i);
}
}
public static long pow(long n, long b, long MOD)
{
long x=1;long y=n;
while(b > 0)
{
if(b%2 == 1)
{
x=x*y;
if(x>MOD) x=x%(MOD);
}
y = y*y;
if(y>MOD) y=y%(MOD);
b >>= 1;
}
return x;
}
public static long mod_inv(long n,long mod)
{
return pow(n,mod-2,mod);
}
//Returns index of highest number less than or equal to key
public static int upper(long[] a,int length,long key)
{
int low = 0;
int high = length-1;
int ans=-1;
while (low <= high) {
int mid = (low + high) / 2;
if (key >= a[mid]) {
ans=mid;
low = mid+1;
} else if(a[mid]>key){
high = mid - 1;
}
}
return ans;
}
//Returns index of least number greater than or equal to key
public static int lower(long[] a,int length,long key)
{
int low = 0;
int high = length-1;
int ans=-1;
while (low <= high) {
int mid = (low + high) / 2;
if (key<=a[mid]) {
ans=mid;
high = mid-1;
}
else{
low=mid+1;
}
}
return ans;
}
public long gcd(long r,long ans)
{
if(r==0) return ans;
return gcd(ans%r,r);
}
public fast() {
this(System.in);
}
public fast(InputStream is) {
i = is;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = i.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
} | Java | ["vvvovvv", "vvovooovovvovoovoovvvvovovvvov"] | 1 second | ["4", "100"] | NoteThe first example is explained in the legend. | Java 8 | standard input | [
"dp",
"strings"
] | 6cc6db6f426bb1bce59f23bfcb762b08 | The input contains a single non-empty string $$$s$$$, consisting only of characters "v" and "o". The length of $$$s$$$ is at most $$$10^6$$$. | 1,300 | Output a single integer, the wow factor of $$$s$$$. | standard output | |
PASSED | ef6c82b3964642e101443d9777aab878 | train_003.jsonl | 1563636900 | Recall that string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero or all) characters. For example, for the string $$$a$$$="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", "ooo".The wow factor of a string is the number of its subsequences equal to the word "wow". Bob wants to write a string that has a large wow factor. However, the "w" key on his keyboard is broken, so he types two "v"s instead. Little did he realise that he may have introduced more "w"s than he thought. Consider for instance the string "ww". Bob would type it as "vvvv", but this string actually contains three occurrences of "w": "vvvv" "vvvv" "vvvv" For example, the wow factor of the word "vvvovvv" equals to four because there are four wows: "vvvovvv" "vvvovvv" "vvvovvv" "vvvovvv" Note that the subsequence "vvvovvv" does not count towards the wow factor, as the "v"s have to be consecutive.For a given string $$$s$$$, compute and output its wow factor. Note that it is not guaranteed that it is possible to get $$$s$$$ from another string replacing "w" with "vv". For example, $$$s$$$ can be equal to "vov". | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class WOWFactor {
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 {
long mod = (long)(1000000007);
long max = Long.MIN_VALUE;
public void solve(int testNumber, InputReader in, PrintWriter out) {
while(testNumber-->0){
String s = in.next();
ArrayList<Integer> a = new ArrayList<>();
int l = s.length();
int i = s.indexOf('v');
if(i<0){
out.println(0);
break;
}
for(i=i;i<l;i++){
int count = 0;
while(i<l && s.charAt(i) == 'v'){
count++;
i++;
}
count--;
count = (count>=0)?count:0;
a.add(count);
}
long b[] = new long[a.size()+1];
for(i=0;i<a.size();i++){
b[i+1] = b[i] + a.get(i);
}
long ans = 0;
for(i=1;i<a.size()+1;i++){
ans += (b[i] *(b[a.size()] - b[i]));
}
out.println(ans);
}
}
class Combine{
int value;
int delete;
Combine(int val , int delete){
this.value = val;
this.delete = delete;
}
}
class Sort2 implements Comparator<Combine>{
public int compare(Combine a , Combine b){
if(a.value > b.value)
return 1;
else if(a.value == b.value && a.delete>b.delete)
return 1;
else if(a.value == b.value && a.delete == b.delete)
return 0;
return -1;
}
}
public int lowerBound(ArrayList<Integer> a , int x){
int l = 0;
int r = a.size()-1;
if(a.get(l)>=x)
return -1;
if(a.get(r)<x)
return r;
int mid = -1;
while(l<=r){
mid = (l+r)/2;
if(a.get(mid) == x && a.get(mid-1)<x)
return mid-1;
else if(a.get(mid)>=x)
r = mid-1;
else if(a.get(mid)<x && a.get(mid+1)>=x)
return mid;
else if(a.get(mid)<x && a.get(mid+1)<x)
l = mid+1;
}
return mid;
}
public int upperBound(ArrayList<Integer> a , int x){
int l = 0;
int r = a.size()-1;
if(a.get(l)>x)
return l;
if(a.get(r)<=x)
return r+1;
int mid = -1;
while(l<=r){
mid = (l+r)/2;
if(a.get(mid) == x && a.get(mid+1)>x)
return mid+1;
else if(a.get(mid)<=x)
l = mid+1;
else if(a.get(mid)>x && a.get(mid-1)<=x)
return mid;
else if(a.get(mid)>x && a.get(mid-1)>x)
r = mid-1;
}
return mid;
}
public long log(float number , int base){
return (long) Math.floor((Math.log(number) / Math.log(base)));
}
public long gcd(long a , long b){
if(a<b){
long c = b;
b = a;
a = c;
}
if(a%b==0)
return b;
return gcd(b , a%b);
}
public void print2d(int a[][] , PrintWriter out){
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++)
out.print(a[i][j] + " ");
out.println();
}
}
public void print1d(int a[] , PrintWriter out){
for(int i=0;i<a.length;i++)
out.print(a[i] + " ");
out.println();
out.println();
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["vvvovvv", "vvovooovovvovoovoovvvvovovvvov"] | 1 second | ["4", "100"] | NoteThe first example is explained in the legend. | Java 8 | standard input | [
"dp",
"strings"
] | 6cc6db6f426bb1bce59f23bfcb762b08 | The input contains a single non-empty string $$$s$$$, consisting only of characters "v" and "o". The length of $$$s$$$ is at most $$$10^6$$$. | 1,300 | Output a single integer, the wow factor of $$$s$$$. | standard output | |
PASSED | 3a7f4b72fafdb25b12033c78fe3dcf2e | train_003.jsonl | 1563636900 | Recall that string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero or all) characters. For example, for the string $$$a$$$="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", "ooo".The wow factor of a string is the number of its subsequences equal to the word "wow". Bob wants to write a string that has a large wow factor. However, the "w" key on his keyboard is broken, so he types two "v"s instead. Little did he realise that he may have introduced more "w"s than he thought. Consider for instance the string "ww". Bob would type it as "vvvv", but this string actually contains three occurrences of "w": "vvvv" "vvvv" "vvvv" For example, the wow factor of the word "vvvovvv" equals to four because there are four wows: "vvvovvv" "vvvovvv" "vvvovvv" "vvvovvv" Note that the subsequence "vvvovvv" does not count towards the wow factor, as the "v"s have to be consecutive.For a given string $$$s$$$, compute and output its wow factor. Note that it is not guaranteed that it is possible to get $$$s$$$ from another string replacing "w" with "vv". For example, $$$s$$$ can be equal to "vov". | 256 megabytes | import java.io.*;
import java.util.*;
public class TaskB {
void run() {
FastReader in = new FastReader(System.in);
// FastReader in = new FastReader(new FileInputStream("input.txt"));
PrintWriter out = new PrintWriter(System.out);
// PrintWriter out = new PrintWriter(new FileOutputStream("output.txt"));
char[] s = in.next().toCharArray();
int n = s.length;
int cnt = 0;
int[] pre = new int[n];
for (int i = 1; i < n; i++) {
if (s[i] == 'v' && s[i - 1] == 'v')
cnt++;
pre[i] = cnt;
}
long ans = 0;
for (int i = 2; i < n; i++) {
if (s[i] == 'o')
ans += (long) pre[i - 1] * (cnt - pre[i]);
}
out.println(ans);
out.close();
}
class FastReader {
BufferedReader br;
StringTokenizer st;
FastReader(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
Integer nextInt() {
return Integer.parseInt(next());
}
Long nextLong() {
return Long.parseLong(next());
}
Double nextDouble() {
return Double.parseDouble(next());
}
String next() {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(nextLine());
return st.nextToken();
}
String nextLine() {
String x = "";
try {
x = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return x;
}
}
public static void main(String[] args) {
new TaskB().run();
}
}
| Java | ["vvvovvv", "vvovooovovvovoovoovvvvovovvvov"] | 1 second | ["4", "100"] | NoteThe first example is explained in the legend. | Java 8 | standard input | [
"dp",
"strings"
] | 6cc6db6f426bb1bce59f23bfcb762b08 | The input contains a single non-empty string $$$s$$$, consisting only of characters "v" and "o". The length of $$$s$$$ is at most $$$10^6$$$. | 1,300 | Output a single integer, the wow factor of $$$s$$$. | standard output | |
PASSED | faa558ceaa2d61e25b72ec6b7ea5f449 | train_003.jsonl | 1563636900 | Recall that string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero or all) characters. For example, for the string $$$a$$$="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", "ooo".The wow factor of a string is the number of its subsequences equal to the word "wow". Bob wants to write a string that has a large wow factor. However, the "w" key on his keyboard is broken, so he types two "v"s instead. Little did he realise that he may have introduced more "w"s than he thought. Consider for instance the string "ww". Bob would type it as "vvvv", but this string actually contains three occurrences of "w": "vvvv" "vvvv" "vvvv" For example, the wow factor of the word "vvvovvv" equals to four because there are four wows: "vvvovvv" "vvvovvv" "vvvovvv" "vvvovvv" Note that the subsequence "vvvovvv" does not count towards the wow factor, as the "v"s have to be consecutive.For a given string $$$s$$$, compute and output its wow factor. Note that it is not guaranteed that it is possible to get $$$s$$$ from another string replacing "w" with "vv". For example, $$$s$$$ can be equal to "vov". | 256 megabytes |
import java.util.ArrayList;
import java.util.Scanner;
public class WOW {
public static void main(String[] args) {
Scanner nik = new Scanner(System.in);
String s = nik.next();
s += 'o';
long c1 = 0;
long oc = 0;
ArrayList<pair> a1 = new ArrayList<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == 'o') {
if (c1 > 1) {
a1.add(new pair(i - 1, c1 - 1));
oc += (c1 - 1);
}
c1 = 0;
} else {
c1++;
}
}
long res = 0;
c1 = 0;
int idx = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == 'o') {
if (idx < a1.size()) {
int g = a1.get(idx).idx;
if (g < i) {
c1 += a1.get(idx).c;
oc -= a1.get(idx).c;
idx++;
}
}
res += (c1 * oc);
}
}
System.out.println(res);
}
private static class pair {
int idx;
long c;
pair(int idx, long c) {
this.idx = idx;
this.c = c;
}
}
}
| Java | ["vvvovvv", "vvovooovovvovoovoovvvvovovvvov"] | 1 second | ["4", "100"] | NoteThe first example is explained in the legend. | Java 8 | standard input | [
"dp",
"strings"
] | 6cc6db6f426bb1bce59f23bfcb762b08 | The input contains a single non-empty string $$$s$$$, consisting only of characters "v" and "o". The length of $$$s$$$ is at most $$$10^6$$$. | 1,300 | Output a single integer, the wow factor of $$$s$$$. | standard output | |
PASSED | f856f0064c32a62576278ff70f76037b | train_003.jsonl | 1563636900 | Recall that string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero or all) characters. For example, for the string $$$a$$$="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", "ooo".The wow factor of a string is the number of its subsequences equal to the word "wow". Bob wants to write a string that has a large wow factor. However, the "w" key on his keyboard is broken, so he types two "v"s instead. Little did he realise that he may have introduced more "w"s than he thought. Consider for instance the string "ww". Bob would type it as "vvvv", but this string actually contains three occurrences of "w": "vvvv" "vvvv" "vvvv" For example, the wow factor of the word "vvvovvv" equals to four because there are four wows: "vvvovvv" "vvvovvv" "vvvovvv" "vvvovvv" Note that the subsequence "vvvovvv" does not count towards the wow factor, as the "v"s have to be consecutive.For a given string $$$s$$$, compute and output its wow factor. Note that it is not guaranteed that it is possible to get $$$s$$$ from another string replacing "w" with "vv". For example, $$$s$$$ can be equal to "vov". | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
String wow = new Scanner(System.in).nextLine();
long[] cumSum = new long[wow.length()];
cumSum[0] = 0;
for (int i = 1; i < wow.length(); i++) {
cumSum[i] = cumSum[i - 1];
if (wow.charAt(i) == 'v' && wow.charAt(i - 1) == 'v') {
cumSum[i] = cumSum[i] + 1;
}
}
long sum = 0;
for (int i = 2; i < wow.length(); i++) {
if (wow.charAt(i) == 'o') {
sum += (cumSum[i] - cumSum[0]) * (cumSum[wow.length() - 1] - cumSum[i]);
}
}
System.out.println(sum);
}
}
| Java | ["vvvovvv", "vvovooovovvovoovoovvvvovovvvov"] | 1 second | ["4", "100"] | NoteThe first example is explained in the legend. | Java 8 | standard input | [
"dp",
"strings"
] | 6cc6db6f426bb1bce59f23bfcb762b08 | The input contains a single non-empty string $$$s$$$, consisting only of characters "v" and "o". The length of $$$s$$$ is at most $$$10^6$$$. | 1,300 | Output a single integer, the wow factor of $$$s$$$. | standard output | |
PASSED | 6c3f8ce551a8864b08ae25a44056e633 | train_003.jsonl | 1563636900 | Recall that string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero or all) characters. For example, for the string $$$a$$$="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", "ooo".The wow factor of a string is the number of its subsequences equal to the word "wow". Bob wants to write a string that has a large wow factor. However, the "w" key on his keyboard is broken, so he types two "v"s instead. Little did he realise that he may have introduced more "w"s than he thought. Consider for instance the string "ww". Bob would type it as "vvvv", but this string actually contains three occurrences of "w": "vvvv" "vvvv" "vvvv" For example, the wow factor of the word "vvvovvv" equals to four because there are four wows: "vvvovvv" "vvvovvv" "vvvovvv" "vvvovvv" Note that the subsequence "vvvovvv" does not count towards the wow factor, as the "v"s have to be consecutive.For a given string $$$s$$$, compute and output its wow factor. Note that it is not guaranteed that it is possible to get $$$s$$$ from another string replacing "w" with "vv". For example, $$$s$$$ can be equal to "vov". | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.concurrent.ThreadLocalRandom;
public class Main2 {
static int mod = 998244353;
static FastScanner scanner;
public static void main(String[] args) {
scanner = new FastScanner();
String token = scanner.nextToken();
if (token.length() < 2) {
System.out.println("0");
return;
}
long[] w = new long[token.length()];
w[0] = 0;
w[1] = token.startsWith("vv") ? 1 : 0;
for (int i = 2; i < token.length(); i++) {
w[i] = w[i - 1] + (token.charAt(i) == 'v' && token.charAt(i - 1) == 'v' ? 1 : 0);
}
long[] wb = new long[token.length()];
wb[token.length() - 1] = 0;
wb[token.length() - 2] = token.endsWith("vv") ? 1 : 0;
for (int i = token.length() - 3; i >= 0; i--) {
wb[i] = wb[i + 1] + (token.charAt(i) == 'v' && token.charAt(i + 1) == 'v' ? 1 : 0);
}
BigInteger result = BigInteger.ZERO;
for (int i = 0; i < token.length(); i++) {
if (token.charAt(i) == 'o') {
result = result.add(BigInteger.valueOf(w[i] * wb[i]));
}
}
System.out.println(result);
}
static class WithIdx implements Comparable<WithIdx>{
int val, idx;
public WithIdx(int val, int idx) {
this.val = val;
this.idx = idx;
}
@Override
public int compareTo(WithIdx o) {
return Integer.compare(val, o.val);
}
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
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();
}
String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
int[] nextIntArray(int n) {
int[] res = new int[n];
for (int i = 0; i < n; i++) res[i] = nextInt();
return res;
}
long[] nextLongArray(int n) {
long[] res = new long[n];
for (int i = 0; i < n; i++) res[i] = nextLong();
return res;
}
String[] nextStringArray(int n) {
String[] res = new String[n];
for (int i = 0; i < n; i++) res[i] = nextToken();
return res;
}
}
static class PrefixSums {
long[] sums;
public PrefixSums(long[] sums) {
this.sums = sums;
}
public long sum(int fromInclusive, int toExclusive) {
if (fromInclusive > toExclusive) throw new IllegalArgumentException("Wrong value");
return sums[toExclusive] - sums[fromInclusive];
}
public static PrefixSums of(int[] ar) {
long[] sums = new long[ar.length + 1];
for (int i = 1; i <= ar.length; i++) {
sums[i] = sums[i - 1] + ar[i - 1];
}
return new PrefixSums(sums);
}
public static PrefixSums of(long[] ar) {
long[] sums = new long[ar.length + 1];
for (int i = 1; i <= ar.length; i++) {
sums[i] = sums[i - 1] + ar[i - 1];
}
return new PrefixSums(sums);
}
}
static class ADUtils {
static void sort(int[] ar) {
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
Arrays.sort(ar);
}
static void reverse(int[] arr) {
int last = arr.length / 2;
for (int i = 0; i < last; i++) {
int tmp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = tmp;
}
}
static void sort(long[] ar) {
Random rnd = ThreadLocalRandom.current();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
long a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
Arrays.sort(ar);
}
}
static class MathUtils {
static long[] FIRST_PRIMES = {
2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89 , 97 , 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
283, 293, 307, 311, 313, 317, 331, 337, 347, 349,
353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
467, 479, 487, 491, 499, 503, 509, 521, 523, 541,
547, 557, 563, 569, 571, 577, 587, 593, 599, 601,
607, 613, 617, 619, 631, 641, 643, 647, 653, 659,
661, 673, 677, 683, 691, 701, 709, 719, 727, 733,
739, 743, 751, 757, 761, 769, 773, 787, 797, 809,
811, 821, 823, 827, 829, 839, 853, 857, 859, 863,
877, 881, 883, 887, 907, 911, 919, 929, 937, 941,
947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013,
1019, 1021, 1031, 1033, 1039, 1049, 1051};
static long[] primes(int to) {
long[] all = new long[to + 1];
long[] primes = new long[to + 1];
all[1] = 1;
int primesLength = 0;
for (int i = 2; i <= to; i ++) {
if (all[i] == 0) {
primes[primesLength++] = i;
all[i] = i;
}
for (int j = 0; j < primesLength && i * primes[j] <= to && all[i] >= primes[j]; j++) {
all[(int) (i * primes[j])] = primes[j];
}
}
return Arrays.copyOf(primes, primesLength);
}
static long modpow(long b, long e, long m) {
long result = 1;
while (e > 0) {
if ((e & 1) == 1) {
/* multiply in this bit's contribution while using modulus to keep
* result small */
result = (result * b) % m;
}
b = (b * b) % m;
e >>= 1;
}
return result;
}
static long submod(long x, long y, long m) {
return (x - y + m) % m;
}
}
}
| Java | ["vvvovvv", "vvovooovovvovoovoovvvvovovvvov"] | 1 second | ["4", "100"] | NoteThe first example is explained in the legend. | Java 8 | standard input | [
"dp",
"strings"
] | 6cc6db6f426bb1bce59f23bfcb762b08 | The input contains a single non-empty string $$$s$$$, consisting only of characters "v" and "o". The length of $$$s$$$ is at most $$$10^6$$$. | 1,300 | Output a single integer, the wow factor of $$$s$$$. | standard output | |
PASSED | 0548fd8cee69c4c07bff0987aced4822 | train_003.jsonl | 1563636900 | Recall that string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero or all) characters. For example, for the string $$$a$$$="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", "ooo".The wow factor of a string is the number of its subsequences equal to the word "wow". Bob wants to write a string that has a large wow factor. However, the "w" key on his keyboard is broken, so he types two "v"s instead. Little did he realise that he may have introduced more "w"s than he thought. Consider for instance the string "ww". Bob would type it as "vvvv", but this string actually contains three occurrences of "w": "vvvv" "vvvv" "vvvv" For example, the wow factor of the word "vvvovvv" equals to four because there are four wows: "vvvovvv" "vvvovvv" "vvvovvv" "vvvovvv" Note that the subsequence "vvvovvv" does not count towards the wow factor, as the "v"s have to be consecutive.For a given string $$$s$$$, compute and output its wow factor. Note that it is not guaranteed that it is possible to get $$$s$$$ from another string replacing "w" with "vv". For example, $$$s$$$ can be equal to "vov". | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Formatter;
import java.util.Locale;
import java.util.Scanner;
/**
* @author edemairy
*/
public class Main {
private int nbTC;
private StringBuilder result = new StringBuilder();
private String cleanS;
private static class EndException extends RuntimeException {
}
public void run() throws IOException {
Scanner scanner = new Scanner(System.in);
// BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// nbTC = readInt(reader);
nbTC = 1;//scanner.nextInt();
// nbTC = Integer.MAX_VALUE;
// scanner.nextLine();
try {
for (int tc = 1; tc <= nbTC; ++tc) {
result.append(oneTestCase(scanner));
result.append('\n');
}
} catch (EndException e) {
}
System.out.print(result);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
Main main = new Main();
main.run();
}
StringBuilder clean = new StringBuilder();
long[] memnbw;
long[] memnbow;
long[] memnbwow;
private StringBuilder oneTestCase(Scanner scanner) throws IOException {
Formatter formatter = new Formatter(Locale.ENGLISH);
String line = scanner.nextLine();
StringBuilder output = new StringBuilder(line.length());
int cpt = 0;
boolean firstW = false;
while (cpt < line.length()) {
if (line.charAt(cpt) == 'o') {
if (firstW) {
clean.append('o');
}
cpt++;
} else {
cpt++;
int seqW = 0;
while (cpt < line.length() && line.charAt(cpt) == 'v') {
seqW++;
cpt++;
}
if (seqW > 0) {
firstW = true;
for (int i = 0; i < seqW; i++) {
clean.append('w');
}
}
}
}
cleanS = clean.toString();
memnbow = new long[cleanS.length() + 1];
Arrays.fill(memnbow, -1L);
memnbwow = new long[cleanS.length() + 1];
Arrays.fill(memnbwow, -1L);
memnbw = new long[cleanS.length() + 1];
Arrays.fill(memnbw, -1L);
memnbw[cleanS.length()] = 0;
for (int i=cleanS.length()-1; i>=0; i--) {
memnbw[i] = memnbw[i+1] + (cleanS.charAt(i)=='w' ? 1 : 0);
}
memnbow[cleanS.length()] = 0;
for (int i=cleanS.length()-1; i>=0; i--) {
memnbow[i] = memnbow[i+1] + (cleanS.charAt(i)=='o' ? memnbw[i+1] : 0);
}
memnbwow[cleanS.length()] = 0;
for (int i=cleanS.length()-1; i>=0; i--) {
memnbwow[i] = memnbwow[i+1] + (cleanS.charAt(i)=='w' ? memnbow[i+1] : 0);
}
output.append(memnbwow[0]);
return output;
}
private int readInt(BufferedReader reader) throws IOException {
int r = 0;
boolean positive = true;
char currentChar = (char) reader.read();
while ((currentChar == ' ') || (currentChar == '\n')) {
currentChar = (char) reader.read();
}
if (currentChar == (char) -1) {
throw new IOException("end of stream");
}
if (currentChar == '-') {
positive = false;
currentChar = (char) reader.read();
}
while ((currentChar >= '0') && (currentChar <= '9')) {
r = r * 10 + currentChar - '0';
currentChar = (char) reader.read();
}
if (positive) {
return r;
} else {
return -r;
}
}
private char readChar(BufferedReader reader) throws IOException {
return (char) reader.read();
}
private int mod(int a, int b) {
int result = a % b;
if (result < 0) {
result += b;
}
return result;
}
}
| Java | ["vvvovvv", "vvovooovovvovoovoovvvvovovvvov"] | 1 second | ["4", "100"] | NoteThe first example is explained in the legend. | Java 8 | standard input | [
"dp",
"strings"
] | 6cc6db6f426bb1bce59f23bfcb762b08 | The input contains a single non-empty string $$$s$$$, consisting only of characters "v" and "o". The length of $$$s$$$ is at most $$$10^6$$$. | 1,300 | Output a single integer, the wow factor of $$$s$$$. | standard output | |
PASSED | 830725111e5ae367ca2bf464786e2265 | train_003.jsonl | 1563636900 | Recall that string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero or all) characters. For example, for the string $$$a$$$="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", "ooo".The wow factor of a string is the number of its subsequences equal to the word "wow". Bob wants to write a string that has a large wow factor. However, the "w" key on his keyboard is broken, so he types two "v"s instead. Little did he realise that he may have introduced more "w"s than he thought. Consider for instance the string "ww". Bob would type it as "vvvv", but this string actually contains three occurrences of "w": "vvvv" "vvvv" "vvvv" For example, the wow factor of the word "vvvovvv" equals to four because there are four wows: "vvvovvv" "vvvovvv" "vvvovvv" "vvvovvv" Note that the subsequence "vvvovvv" does not count towards the wow factor, as the "v"s have to be consecutive.For a given string $$$s$$$, compute and output its wow factor. Note that it is not guaranteed that it is possible to get $$$s$$$ from another string replacing "w" with "vv". For example, $$$s$$$ can be equal to "vov". | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Formatter;
import java.util.Locale;
import java.util.Scanner;
/**
* @author edemairy
*/
public class Main {
private int nbTC;
private StringBuilder result = new StringBuilder();
private String cleanS;
private static class EndException extends RuntimeException {
}
public void run() throws IOException {
Scanner scanner = new Scanner(System.in);
// BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// nbTC = readInt(reader);
nbTC = 1;//scanner.nextInt();
// nbTC = Integer.MAX_VALUE;
// scanner.nextLine();
try {
for (int tc = 1; tc <= nbTC; ++tc) {
result.append(oneTestCase(scanner));
result.append('\n');
}
} catch (EndException e) {
}
System.out.print(result);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
Main main = new Main();
main.run();
}
StringBuilder clean = new StringBuilder();
long[] memnbw;
long[] memnbow;
long[] memnbwow;
private StringBuilder oneTestCase(Scanner scanner) throws IOException {
Formatter formatter = new Formatter(Locale.ENGLISH);
StringBuilder output = new StringBuilder();
String line = scanner.nextLine();
long total = 0;
int cpt = 0;
boolean firstW = false;
while (cpt < line.length()) {
if (line.charAt(cpt) == 'o') {
if (firstW) {
clean.append('o');
}
cpt++;
} else {
cpt++;
int seqW = 0;
while (cpt < line.length() && line.charAt(cpt) == 'v') {
seqW++;
cpt++;
}
if (seqW > 0) {
firstW = true;
for (int i = 0; i < seqW; i++) {
clean.append('w');
}
}
}
}
cleanS = clean.toString();
memnbow = new long[cleanS.length() + 1];
Arrays.fill(memnbow, -1L);
memnbwow = new long[cleanS.length() + 1];
Arrays.fill(memnbwow, -1L);
memnbw = new long[cleanS.length() + 1];
Arrays.fill(memnbw, -1L);
output.append(nbwow(0));
return output;
}
private long nbwow(int p) {
long result = memnbwow[p];
if (result == -1) {
if (p >= cleanS.length()) {
result = 0;
} else if (cleanS.charAt(p) == 'o') {
result = nbwow(p + 1);
} else {
result = nbow(p + 1) + nbwow(p + 1);
}
}
memnbwow[p] = result;
return result;
}
private long nbow(int p) {
long result = memnbow[p];
if (result == -1) {
if (p >= cleanS.length()) {
result = 0;
} else if (cleanS.charAt(p) == 'o') {
result = nbw(p + 1) + nbow(p + 1);
} else {
result = nbow(p + 1);
}
}
memnbow[p] = result;
return result;
}
private long nbw(int p) {
long result = memnbw[p];
if (result == -1) {
if (p >= cleanS.length()) {
result = 0;
} else if (cleanS.charAt(p) == 'w') {
result = 1 + nbw(p + 1);
} else {
result = nbw(p + 1);
}
}
memnbw[p] = result;
return result;
}
private int readInt(BufferedReader reader) throws IOException {
int r = 0;
boolean positive = true;
char currentChar = (char) reader.read();
while ((currentChar == ' ') || (currentChar == '\n')) {
currentChar = (char) reader.read();
}
if (currentChar == (char) -1) {
throw new IOException("end of stream");
}
if (currentChar == '-') {
positive = false;
currentChar = (char) reader.read();
}
while ((currentChar >= '0') && (currentChar <= '9')) {
r = r * 10 + currentChar - '0';
currentChar = (char) reader.read();
}
if (positive) {
return r;
} else {
return -r;
}
}
private char readChar(BufferedReader reader) throws IOException {
return (char) reader.read();
}
private int mod(int a, int b) {
int result = a % b;
if (result < 0) {
result += b;
}
return result;
}
} | Java | ["vvvovvv", "vvovooovovvovoovoovvvvovovvvov"] | 1 second | ["4", "100"] | NoteThe first example is explained in the legend. | Java 8 | standard input | [
"dp",
"strings"
] | 6cc6db6f426bb1bce59f23bfcb762b08 | The input contains a single non-empty string $$$s$$$, consisting only of characters "v" and "o". The length of $$$s$$$ is at most $$$10^6$$$. | 1,300 | Output a single integer, the wow factor of $$$s$$$. | standard output | |
PASSED | 9f219b6afe1d993a364bc2a7b71dd288 | train_003.jsonl | 1563636900 | Recall that string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero or all) characters. For example, for the string $$$a$$$="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", "ooo".The wow factor of a string is the number of its subsequences equal to the word "wow". Bob wants to write a string that has a large wow factor. However, the "w" key on his keyboard is broken, so he types two "v"s instead. Little did he realise that he may have introduced more "w"s than he thought. Consider for instance the string "ww". Bob would type it as "vvvv", but this string actually contains three occurrences of "w": "vvvv" "vvvv" "vvvv" For example, the wow factor of the word "vvvovvv" equals to four because there are four wows: "vvvovvv" "vvvovvv" "vvvovvv" "vvvovvv" Note that the subsequence "vvvovvv" does not count towards the wow factor, as the "v"s have to be consecutive.For a given string $$$s$$$, compute and output its wow factor. Note that it is not guaranteed that it is possible to get $$$s$$$ from another string replacing "w" with "vv". For example, $$$s$$$ can be equal to "vov". | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
/**
* created by vidyut on 2019-05-12
**/
public class B {
public static void main(String[] args) throws Exception {
InputReader in = new InputReader(System.in);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
char ws[] = in.readLine().toCharArray();
int n = ws.length;
int countvleft[] = new int[n];
int countvright[] = new int[n];
for (int i = 1; i < n; i++) {
countvleft[i] = ws[i] == 'v' && ws[i - 1] == 'v' ? 1 : 0;
if (i - 1 >= 0)
countvleft[i] += countvleft[i - 1];
}
for (int i = n - 2; i >= 0; i--) {
countvright[i] = ws[i] == 'v' && ws[i + 1] == 'v' ? 1 : 0;
if (i + 1 < n)
countvright[i] += countvright[i + 1];
}
long ans = 0L;
for (int i = 1; i < n - 1; i++) {
if (ws[i] == 'o') {
ans += (((long)countvleft[i - 1]) * (countvright[i + 1]));
}
}
out.write(Long.toString(ans));
out.close();
}
}
class InputReader {
private boolean finished = false;
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 peek() {
if (numChars == -1)
return -1;
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0)
return -1;
}
return buf[curChar];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int length = readInt();
if (length < 0)
return null;
byte[] bytes = new byte[length];
for (int i = 0; i < length; i++)
bytes[i] = (byte) read();
try {
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
return new String(bytes);
}
}
public static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuffer buf = new StringBuffer();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r')
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines)
return readLine();
else
return readLine0();
}
public BigInteger readBigInteger() {
try {
return new BigInteger(readString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new 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, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1)
read();
return value == -1;
}
public String next() {
return readString();
}
public boolean readBoolean() {
return readInt() == 1;
}
}
| Java | ["vvvovvv", "vvovooovovvovoovoovvvvovovvvov"] | 1 second | ["4", "100"] | NoteThe first example is explained in the legend. | Java 8 | standard input | [
"dp",
"strings"
] | 6cc6db6f426bb1bce59f23bfcb762b08 | The input contains a single non-empty string $$$s$$$, consisting only of characters "v" and "o". The length of $$$s$$$ is at most $$$10^6$$$. | 1,300 | Output a single integer, the wow factor of $$$s$$$. | standard output | |
PASSED | 9b01feff72521d3d7ed5c66dd4ba16b4 | train_003.jsonl | 1563636900 | Recall that string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero or all) characters. For example, for the string $$$a$$$="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", "ooo".The wow factor of a string is the number of its subsequences equal to the word "wow". Bob wants to write a string that has a large wow factor. However, the "w" key on his keyboard is broken, so he types two "v"s instead. Little did he realise that he may have introduced more "w"s than he thought. Consider for instance the string "ww". Bob would type it as "vvvv", but this string actually contains three occurrences of "w": "vvvv" "vvvv" "vvvv" For example, the wow factor of the word "vvvovvv" equals to four because there are four wows: "vvvovvv" "vvvovvv" "vvvovvv" "vvvovvv" Note that the subsequence "vvvovvv" does not count towards the wow factor, as the "v"s have to be consecutive.For a given string $$$s$$$, compute and output its wow factor. Note that it is not guaranteed that it is possible to get $$$s$$$ from another string replacing "w" with "vv". For example, $$$s$$$ can be equal to "vov". | 256 megabytes | /*
* @author derrick20
*/
import java.io.*;
import java.util.*;
public class wow {
public static void main(String args[]) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
String s = sc.next();
long[] prefix = new long[s.length() + 1];
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i - 1) == s.charAt(i) && s.charAt(i) == 'v') {
prefix[i + 1]++;
}
}
for (int i = 1; i < prefix.length; i++) {
prefix[i] += prefix[i - 1];
}
long ans = 0;
for (int i = 2; i < s.length() - 2; i++) {
if (s.charAt(i) == 'o') {
long after = (prefix[s.length()] - prefix[i + 1 + 1]);
long before = prefix[i];
ans += after * before;
}
}
out.println(ans);
out.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
Scanner(FileReader s) {
br = new BufferedReader(s);
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
}
}
| Java | ["vvvovvv", "vvovooovovvovoovoovvvvovovvvov"] | 1 second | ["4", "100"] | NoteThe first example is explained in the legend. | Java 8 | standard input | [
"dp",
"strings"
] | 6cc6db6f426bb1bce59f23bfcb762b08 | The input contains a single non-empty string $$$s$$$, consisting only of characters "v" and "o". The length of $$$s$$$ is at most $$$10^6$$$. | 1,300 | Output a single integer, the wow factor of $$$s$$$. | standard output | |
PASSED | 935e77f41dc9bff92fc507effdd38263 | train_003.jsonl | 1563636900 | Recall that string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero or all) characters. For example, for the string $$$a$$$="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", "ooo".The wow factor of a string is the number of its subsequences equal to the word "wow". Bob wants to write a string that has a large wow factor. However, the "w" key on his keyboard is broken, so he types two "v"s instead. Little did he realise that he may have introduced more "w"s than he thought. Consider for instance the string "ww". Bob would type it as "vvvv", but this string actually contains three occurrences of "w": "vvvv" "vvvv" "vvvv" For example, the wow factor of the word "vvvovvv" equals to four because there are four wows: "vvvovvv" "vvvovvv" "vvvovvv" "vvvovvv" Note that the subsequence "vvvovvv" does not count towards the wow factor, as the "v"s have to be consecutive.For a given string $$$s$$$, compute and output its wow factor. Note that it is not guaranteed that it is possible to get $$$s$$$ from another string replacing "w" with "vv". For example, $$$s$$$ can be equal to "vov". | 256 megabytes | import java.util.*;
import java.io.*;
public class B {
static final boolean stdin = true;
static final String filename = "";
static FastScanner br;
static PrintWriter pw;
public static void main(String[] args) throws IOException {
if (stdin) {
br = new FastScanner();
pw = new PrintWriter(new OutputStreamWriter(System.out));
} else {
br = new FastScanner(filename + ".in");
pw = new PrintWriter(new FileWriter(filename + ".out"));
}
Solver solver = new Solver();
solver.solve(br, pw);
}
static class Solver {
static long mod = 1000000000;
public void solve(FastScanner br, PrintWriter pw) throws IOException {
char[] arr = br.nextToken().toCharArray();
long a = 0, b = 0, c = 0;
for (int i = 0; i < arr.length; i++) {
if (i <= arr.length - 2 && arr[i] == 'v' && arr[i + 1] == 'v') {
a++;
c += b;
} else if (arr[i] == 'o') {
b+=a;
}
}
pw.println(c);
pw.close();
}
static long gcd(long a, long b) {
if (a > b)
return gcd(b, a);
if (a == 0)
return b;
return gcd(b % a, a);
}
static long pow(long a, long b) {
if (b == 0)
return 1L;
long val = pow(a, b / 2);
if (b % 2 == 0)
return val * val % mod;
else
return val * val % mod * a % mod;
}
}
static class Point1 implements Comparable<Point1> {
int a;
int b;
Point1(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(Point1 o) {
return this.a - o.a;
}
}
static class Point2 implements Comparable<Point2> {
int a;
int b;
Point2(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(Point2 o) {
return this.b - o.b;
}
}
static class UnionFind {
// The number of elements in this union find
private int size;
// Used to track the size of each of the component
private int[] sz;
// id[i] points to the parent of i, if id[i] = i then i is a root node
private int[] id;
// Tracks the number of components in the union find
private int numComponents;
public UnionFind(int size) {
if (size <= 0)
throw new IllegalArgumentException("Size <= 0 is not allowed");
this.size = numComponents = size;
sz = new int[size];
id = new int[size];
for (int i = 0; i < size; i++) {
id[i] = i; // Link to itself (self root)
sz[i] = 1; // Each component is originally of size one
}
}
// Find which component/set 'p' belongs to in amortized constant time.
public int find(int p) {
// Find the root of the component/set
int root = p;
while (root != id[root])
root = id[root];
// Compress the path leading back to the root.
// Doing this operation is called "path compression"
// and is what gives us amortized time complexity.
while (p != root) {
int next = id[p];
id[p] = root;
p = next;
}
return root;
}
// This is an alternative recursive formulation for the find method
// public int find(int p) {
// if (p == id[p]) return p;
// return id[p] = find(id[p]);
// }
// Return whether or not the elements 'p' and
// 'q' are in the same components/set.
public boolean connected(int p, int q) {
return find(p) == find(q);
}
// Return the size of the components/set 'p' belongs to
public int componentSize(int p) {
return sz[find(p)];
}
// Return the number of elements in this UnionFind/Disjoint set
public int size() {
return size;
}
// Returns the number of remaining components/sets
public int components() {
return numComponents;
}
// Unify the components/sets containing elements 'p' and 'q'
public void unify(int p, int q) {
int root1 = find(p);
int root2 = find(q);
// These elements are already in the same group!
if (root1 == root2)
return;
// Merge smaller component/set into the larger one.
if (sz[root1] < sz[root2]) {
sz[root2] += sz[root1];
id[root1] = root2;
} else {
sz[root1] += sz[root2];
id[root2] = root1;
}
// Since the roots found are different we know that the
// number of components/sets has decreased by one
numComponents--;
}
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
ArrayList<Integer>[] nextGraph(int nodes, int edges) {
ArrayList<Integer>[] adj = new ArrayList[nodes];
for (int i = 0; i < nodes; i++) {
adj[i] = new ArrayList<Integer>();
}
for (int i = 0; i < edges; i++) {
int a = nextInt() - 1;
int b = nextInt() - 1;
adj[a].add(b);
adj[b].add(a);
}
return adj;
}
}
} | Java | ["vvvovvv", "vvovooovovvovoovoovvvvovovvvov"] | 1 second | ["4", "100"] | NoteThe first example is explained in the legend. | Java 8 | standard input | [
"dp",
"strings"
] | 6cc6db6f426bb1bce59f23bfcb762b08 | The input contains a single non-empty string $$$s$$$, consisting only of characters "v" and "o". The length of $$$s$$$ is at most $$$10^6$$$. | 1,300 | Output a single integer, the wow factor of $$$s$$$. | standard output | |
PASSED | d7e32685e1c3f81cd39a81b3352b69bf | train_003.jsonl | 1563636900 | Recall that string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero or all) characters. For example, for the string $$$a$$$="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", "ooo".The wow factor of a string is the number of its subsequences equal to the word "wow". Bob wants to write a string that has a large wow factor. However, the "w" key on his keyboard is broken, so he types two "v"s instead. Little did he realise that he may have introduced more "w"s than he thought. Consider for instance the string "ww". Bob would type it as "vvvv", but this string actually contains three occurrences of "w": "vvvv" "vvvv" "vvvv" For example, the wow factor of the word "vvvovvv" equals to four because there are four wows: "vvvovvv" "vvvovvv" "vvvovvv" "vvvovvv" Note that the subsequence "vvvovvv" does not count towards the wow factor, as the "v"s have to be consecutive.For a given string $$$s$$$, compute and output its wow factor. Note that it is not guaranteed that it is possible to get $$$s$$$ from another string replacing "w" with "vv". For example, $$$s$$$ can be equal to "vov". | 256 megabytes | import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Arrays;
public class B {
static char s[];
static int N;
public static void main(String args[]){
new Thread(null, ()->asdf(args), "", 1<<28).start();
}
static long dp[][];
public static void asdf(String[] args) {
JS in = new JS();
s = in.next().toCharArray();
// s = new char[1000000];
// Arrays.fill(s,'v');
N = s.length;
dp = new long[4][N];
for(long a[] : dp)Arrays.fill(a, -1);
long res = go(0,0);
for(int id = N-1; id >= 0; id--) {
for(int st = 0; st <= 3; st++) {
go(st, id);
}
}
System.out.println(res);
}
// 0 -> not started
// 1 -> have a W
// 2 -> have an 0
// 3 -> finished
static long go(int st, int id) {
if(st == 3) return 1;
if(id >= N-1) return 0;
if(dp[st][id] != -1) return dp[st][id];
long res = go(st, id+1);
if(st == 0) {
if(s[id] == 'v' && s[id+1] == 'v') res += go(1, id+2);
}
else if(st == 1) {
if(s[id] == 'o') res += go(2, id+1);
}
else if(st == 2) {
if(s[id] == 'v' && s[id+1] == 'v') res += go(3, id+2);
}
return dp[st][id] = res;
}
static class JS{
public int BS = 1<<16;
public char NC = (char)0;
byte[] buf = new byte[BS];
int bId = 0, size = 0;
char c = NC;
double num = 1;
BufferedInputStream in;
public JS() {
in = new BufferedInputStream(System.in, BS);
}
public JS(String s) throws FileNotFoundException {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
public char nextChar(){
while(bId==size) {
try {
size = in.read(buf);
}catch(Exception e) {
return NC;
}
if(size==-1)return NC;
bId=0;
}
return (char)buf[bId++];
}
public int nextInt() {
return (int)nextLong();
}
public long nextLong() {
num=1;
boolean neg = false;
if(c==NC)c=nextChar();
for(;(c<'0' || c>'9'); c = nextChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=nextChar()) {
res = (res<<3)+(res<<1)+c-'0';
num*=10;
}
return neg?-res:res;
}
public double nextDouble() {
while(c!='.'&&c!='-'&&(c <'0' || c>'9')) c = nextChar();
boolean neg = c=='-';
if(neg)c=nextChar();
boolean fl = c=='.';
double cur = nextLong();
if(fl) return neg ? -cur/num : cur/num;
if(c == '.') {
double next = nextLong();
return neg ? -cur-next/num : cur+next/num;
}
else return neg ? -cur : cur;
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c>32) {
res.append(c);
c=nextChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c!='\n') {
res.append(c);
c=nextChar();
}
return res.toString();
}
public boolean hasNext() {
if(c>32)return true;
while(true) {
c=nextChar();
if(c==NC)return false;
else if(c>32)return true;
}
}
}
}
| Java | ["vvvovvv", "vvovooovovvovoovoovvvvovovvvov"] | 1 second | ["4", "100"] | NoteThe first example is explained in the legend. | Java 8 | standard input | [
"dp",
"strings"
] | 6cc6db6f426bb1bce59f23bfcb762b08 | The input contains a single non-empty string $$$s$$$, consisting only of characters "v" and "o". The length of $$$s$$$ is at most $$$10^6$$$. | 1,300 | Output a single integer, the wow factor of $$$s$$$. | standard output | |
PASSED | 71b9132d959cf9bff3ab05c63dae66ec | train_003.jsonl | 1563636900 | Recall that string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero or all) characters. For example, for the string $$$a$$$="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", "ooo".The wow factor of a string is the number of its subsequences equal to the word "wow". Bob wants to write a string that has a large wow factor. However, the "w" key on his keyboard is broken, so he types two "v"s instead. Little did he realise that he may have introduced more "w"s than he thought. Consider for instance the string "ww". Bob would type it as "vvvv", but this string actually contains three occurrences of "w": "vvvv" "vvvv" "vvvv" For example, the wow factor of the word "vvvovvv" equals to four because there are four wows: "vvvovvv" "vvvovvv" "vvvovvv" "vvvovvv" Note that the subsequence "vvvovvv" does not count towards the wow factor, as the "v"s have to be consecutive.For a given string $$$s$$$, compute and output its wow factor. Note that it is not guaranteed that it is possible to get $$$s$$$ from another string replacing "w" with "vv". For example, $$$s$$$ can be equal to "vov". | 256 megabytes |
import java.math.BigInteger;
import java.util.*;
public class Main {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
String s = input.next();
long o =0,w=0,wow=0;
for (int i = 1; i < s.length(); i++) {
if(s.charAt(i)=='v'&&s.charAt(i-1)=='v')
{
w++;
wow+=o;
}
else if(s.charAt(i)=='o')
{
o+=w;
}
}
System.out.println(wow);
}
}
| Java | ["vvvovvv", "vvovooovovvovoovoovvvvovovvvov"] | 1 second | ["4", "100"] | NoteThe first example is explained in the legend. | Java 8 | standard input | [
"dp",
"strings"
] | 6cc6db6f426bb1bce59f23bfcb762b08 | The input contains a single non-empty string $$$s$$$, consisting only of characters "v" and "o". The length of $$$s$$$ is at most $$$10^6$$$. | 1,300 | Output a single integer, the wow factor of $$$s$$$. | standard output | |
PASSED | db3662bf59c06132c88dc9c54c294779 | train_003.jsonl | 1563636900 | Recall that string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero or all) characters. For example, for the string $$$a$$$="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", "ooo".The wow factor of a string is the number of its subsequences equal to the word "wow". Bob wants to write a string that has a large wow factor. However, the "w" key on his keyboard is broken, so he types two "v"s instead. Little did he realise that he may have introduced more "w"s than he thought. Consider for instance the string "ww". Bob would type it as "vvvv", but this string actually contains three occurrences of "w": "vvvv" "vvvv" "vvvv" For example, the wow factor of the word "vvvovvv" equals to four because there are four wows: "vvvovvv" "vvvovvv" "vvvovvv" "vvvovvv" Note that the subsequence "vvvovvv" does not count towards the wow factor, as the "v"s have to be consecutive.For a given string $$$s$$$, compute and output its wow factor. Note that it is not guaranteed that it is possible to get $$$s$$$ from another string replacing "w" with "vv". For example, $$$s$$$ can be equal to "vov". | 256 megabytes | import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
char[] n = s.nextLine().toCharArray();
long l = 0,o = 0 , r = 0;
for (int i = 0 ; i < n.length - 1; i++)
{
if ((n[i]=='v')&&(n[i+1]=='v'))
{
l++;
r = r + o;
}
if (n[i]=='o')
o = o +l;
}
System.out.println(r);
}
} | Java | ["vvvovvv", "vvovooovovvovoovoovvvvovovvvov"] | 1 second | ["4", "100"] | NoteThe first example is explained in the legend. | Java 8 | standard input | [
"dp",
"strings"
] | 6cc6db6f426bb1bce59f23bfcb762b08 | The input contains a single non-empty string $$$s$$$, consisting only of characters "v" and "o". The length of $$$s$$$ is at most $$$10^6$$$. | 1,300 | Output a single integer, the wow factor of $$$s$$$. | standard output | |
PASSED | e2c74efa83b2d9522c78b189a8850283 | train_003.jsonl | 1563636900 | Recall that string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero or all) characters. For example, for the string $$$a$$$="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", "ooo".The wow factor of a string is the number of its subsequences equal to the word "wow". Bob wants to write a string that has a large wow factor. However, the "w" key on his keyboard is broken, so he types two "v"s instead. Little did he realise that he may have introduced more "w"s than he thought. Consider for instance the string "ww". Bob would type it as "vvvv", but this string actually contains three occurrences of "w": "vvvv" "vvvv" "vvvv" For example, the wow factor of the word "vvvovvv" equals to four because there are four wows: "vvvovvv" "vvvovvv" "vvvovvv" "vvvovvv" Note that the subsequence "vvvovvv" does not count towards the wow factor, as the "v"s have to be consecutive.For a given string $$$s$$$, compute and output its wow factor. Note that it is not guaranteed that it is possible to get $$$s$$$ from another string replacing "w" with "vv". For example, $$$s$$$ can be equal to "vov". | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution
{
public static void main(String ag[])
{
Scanner sc=new Scanner(System.in);
int i,j,k;
String str=sc.next();
int N=str.length();
long dp[]=new long[N+1];
for(i=1;i<N;i++)
{
if(str.charAt(i)=='v'&&str.charAt(i-1)=='v')
dp[i]=dp[i-1]+1;
else
dp[i]=dp[i-1];
}
long ans=0;
for(i=0;i<N;i++)
{
if(str.charAt(i)=='o')
ans+=(dp[i]*(dp[N-1]-dp[i]));
}
System.out.println(ans);
}
} | Java | ["vvvovvv", "vvovooovovvovoovoovvvvovovvvov"] | 1 second | ["4", "100"] | NoteThe first example is explained in the legend. | Java 8 | standard input | [
"dp",
"strings"
] | 6cc6db6f426bb1bce59f23bfcb762b08 | The input contains a single non-empty string $$$s$$$, consisting only of characters "v" and "o". The length of $$$s$$$ is at most $$$10^6$$$. | 1,300 | Output a single integer, the wow factor of $$$s$$$. | standard output | |
PASSED | 8d19ab26670c673ce1ca82309f69223c | train_003.jsonl | 1563636900 | Recall that string $$$a$$$ is a subsequence of a string $$$b$$$ if $$$a$$$ can be obtained from $$$b$$$ by deletion of several (possibly zero or all) characters. For example, for the string $$$a$$$="wowwo", the following strings are subsequences: "wowwo", "wowo", "oo", "wow", "", and others, but the following are not subsequences: "owoo", "owwwo", "ooo".The wow factor of a string is the number of its subsequences equal to the word "wow". Bob wants to write a string that has a large wow factor. However, the "w" key on his keyboard is broken, so he types two "v"s instead. Little did he realise that he may have introduced more "w"s than he thought. Consider for instance the string "ww". Bob would type it as "vvvv", but this string actually contains three occurrences of "w": "vvvv" "vvvv" "vvvv" For example, the wow factor of the word "vvvovvv" equals to four because there are four wows: "vvvovvv" "vvvovvv" "vvvovvv" "vvvovvv" Note that the subsequence "vvvovvv" does not count towards the wow factor, as the "v"s have to be consecutive.For a given string $$$s$$$, compute and output its wow factor. Note that it is not guaranteed that it is possible to get $$$s$$$ from another string replacing "w" with "vv". For example, $$$s$$$ can be equal to "vov". | 256 megabytes | import java.util.*;
public class code1{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
String s=sc.next();
char ch[]=s.toCharArray();
int a[]=new int[ch.length];
for(int i=1;i<s.length();i++)
{
a[i]=a[i-1];
if(ch[i]==ch[i-1]&&ch[i]=='v')
a[i]+=1;
}
long sum=0;
int n=s.length();
for(int i=2;i<n-2;i++)
{
if(ch[i]=='o')
sum=(long) (sum +(long) a[i-1]*(a[n-1]-a[i]));
}
System.out.println(sum);
sc.close();
}
} | Java | ["vvvovvv", "vvovooovovvovoovoovvvvovovvvov"] | 1 second | ["4", "100"] | NoteThe first example is explained in the legend. | Java 8 | standard input | [
"dp",
"strings"
] | 6cc6db6f426bb1bce59f23bfcb762b08 | The input contains a single non-empty string $$$s$$$, consisting only of characters "v" and "o". The length of $$$s$$$ is at most $$$10^6$$$. | 1,300 | Output a single integer, the wow factor of $$$s$$$. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.