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 | 5eea2d13848d487baeb47aa9c34bf60c | train_107.jsonl | 1612535700 | Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m > 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solver {
public static void main(String[] args) {
FastReader in = new FastReader();
int t = in.nextInt();
while (t-- > 0) {
solve(in);
}
}
public static void solve(FastReader in) {
int n = in.nextInt(), m = in.nextInt();
String[] adj = new String[n];
for (int i = 0; i < n; i++)
adj[i] = in.next();
if (n == 2) {
if (m % 2 == 0 && adj[0].charAt(1) != adj[1].charAt(0)) {
System.out.println("NO");
return;
}
}
System.out.println("YES");
StringBuilder res = new StringBuilder(m);
if (n==2 || m % 2 == 1) {
for (int j = 0; j <= m; j++) {
res.append((j % 2 == 0) ? 1 : 2);
res.append(" ");
}
System.out.println(res);
return;
}
// for (int i = 1; i < n; i++) {
// char e1 = adj[0].charAt(i);
// char e2 = adj[i].charAt(0);
// if (e1 == e2) {
// for (int j = 0; j <= m; j++) {
// res.append((j % 2 == 0) ? 1 : i + 1);
// res.append(" ");
// }
// System.out.println(res);
// return;
// }
// }
char e1 = adj[0].charAt(1);
char e2 = adj[1].charAt(2);
char e3 = adj[2].charAt(0);
int v1 = 0, v2 = 1, v3 = 2;
if (e2 == e3) {
v1 = 1;
v2 = 2;
v3 = 0;
} else if (e3 == e1) {
v1 = 2;
v2 = 0;
v3 = 1;
}
LinkedList<Integer> path = new LinkedList<>();
path.add(v1 + 1);
path.add(v2 + 1);
path.add(v3 + 1);
int turn = 0;
for (int i = 0; i < m - 2; i += 2) {
if (turn == 0) {
path.addFirst(v3 + 1);
path.addLast(v1 + 1);
turn++;
} else if (turn == 1) {
path.addFirst(v2 + 1);
path.addLast(v2 + 1);
turn++;
} else {
path.addFirst(v1 + 1);
path.addLast(v3 + 1);
turn = 0;
}
}
path.stream().forEach(x -> System.out.print(x + " "));
System.out.println();
}
public static class FastReader {
BufferedReader br;
StringTokenizer st;
private 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 class FastWriter {
private static final int BUF_SIZE = 1 << 13;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastWriter() {
out = null;
}
public FastWriter(OutputStream os) {
this.out = os;
}
public FastWriter(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastWriter write(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE)
innerflush();
return this;
}
public FastWriter write(char c) {
return write((byte) c);
}
public FastWriter write(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE)
innerflush();
}
return this;
}
public FastWriter write(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE)
innerflush();
});
return this;
}
private static int countDigits(int l) {
if (l >= 1000000000)
return 10;
if (l >= 100000000)
return 9;
if (l >= 10000000)
return 8;
if (l >= 1000000)
return 7;
if (l >= 100000)
return 6;
if (l >= 10000)
return 5;
if (l >= 1000)
return 4;
if (l >= 100)
return 3;
if (l >= 10)
return 2;
return 1;
}
public FastWriter write(int x) {
if (x == Integer.MIN_VALUE) {
return write((long) x);
}
if (ptr + 12 >= BUF_SIZE)
innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L)
return 19;
if (l >= 100000000000000000L)
return 18;
if (l >= 10000000000000000L)
return 17;
if (l >= 1000000000000000L)
return 16;
if (l >= 100000000000000L)
return 15;
if (l >= 10000000000000L)
return 14;
if (l >= 1000000000000L)
return 13;
if (l >= 100000000000L)
return 12;
if (l >= 10000000000L)
return 11;
if (l >= 1000000000L)
return 10;
if (l >= 100000000L)
return 9;
if (l >= 10000000L)
return 8;
if (l >= 1000000L)
return 7;
if (l >= 100000L)
return 6;
if (l >= 10000L)
return 5;
if (l >= 1000L)
return 4;
if (l >= 100L)
return 3;
if (l >= 10L)
return 2;
return 1;
}
public FastWriter write(long x) {
if (x == Long.MIN_VALUE) {
return write("" + x);
}
if (ptr + 21 >= BUF_SIZE)
innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
public FastWriter write(double x, int precision) {
if (x < 0) {
write('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
// if(x < 0){ x = 0; }
write((long) x).write(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
write((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastWriter writeln(char c) {
return write(c).writeln();
}
public FastWriter writeln(int x) {
return write(x).writeln();
}
public FastWriter writeln(long x) {
return write(x).writeln();
}
public FastWriter writeln(double x, int precision) {
return write(x, precision).writeln();
}
public FastWriter write(int... xs) {
boolean first = true;
for (int x : xs) {
if (!first)
write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter write(long... xs) {
boolean first = true;
for (long x : xs) {
if (!first)
write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter writeln() {
return write((byte) '\n');
}
public FastWriter writeln(int... xs) {
return write(xs).writeln();
}
public FastWriter writeln(long... xs) {
return write(xs).writeln();
}
public FastWriter writeln(char[] line) {
return write(line).writeln();
}
public FastWriter writeln(char[]... map) {
for (char[] line : map)
write(line).writeln();
return this;
}
public FastWriter writeln(String s) {
return write(s).writeln();
}
private void innerflush() {
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush() {
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
public FastWriter print(byte b) {
return write(b);
}
public FastWriter print(char c) {
return write(c);
}
public FastWriter print(char[] s) {
return write(s);
}
public FastWriter print(String s) {
return write(s);
}
public FastWriter print(int x) {
return write(x);
}
public FastWriter print(long x) {
return write(x);
}
public FastWriter print(double x, int precision) {
return write(x, precision);
}
public FastWriter println(char c) {
return writeln(c);
}
public FastWriter println(int x) {
return writeln(x);
}
public FastWriter println(long x) {
return writeln(x);
}
public FastWriter println(double x, int precision) {
return writeln(x, precision);
}
public FastWriter print(int... xs) {
return write(xs);
}
public FastWriter print(long... xs) {
return write(xs);
}
public FastWriter println(int... xs) {
return writeln(xs);
}
public FastWriter println(long... xs) {
return writeln(xs);
}
public FastWriter println(char[] line) {
return writeln(line);
}
public FastWriter println(char[]... map) {
return writeln(map);
}
public FastWriter println(String s) {
return writeln(s);
}
public FastWriter println() {
return writeln();
}
}
} | Java | ["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"] | 2 seconds | ["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"] | NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba. | Java 11 | standard input | [
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 79b629047e674883a9bc04b1bf0b7f09 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$. | 2,000 | For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO". | standard output | |
PASSED | 302b87accc1116cc6831a27cd484d55e | train_107.jsonl | 1612535700 | Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m > 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solver {
public static void main(String[] args) {
FastReader in = new FastReader();
int t = in.nextInt();
while (t-- > 0) {
solve(in);
}
}
public static void solve(FastReader in) {
int n = in.nextInt(), m = in.nextInt();
String[] adj = new String[n];
for (int i = 0; i < n; i++)
adj[i] = in.next();
if (n == 2) {
if (m % 2 == 0 && adj[0].charAt(1) != adj[1].charAt(0)) {
System.out.println("NO");
return;
}
}
System.out.println("YES");
StringBuilder res = new StringBuilder(m);
if (m % 2 == 1) {
for (int j = 0; j <= m; j++) {
res.append((j % 2 == 0) ? 1 : 2);
res.append(" ");
}
System.out.println(res);
return;
}
for (int i = 1; i < n; i++) {
char e1 = adj[0].charAt(i);
char e2 = adj[i].charAt(0);
if (e1 == e2) {
for (int j = 0; j <= m; j++) {
res.append((j % 2 == 0) ? 1 : i + 1);
res.append(" ");
}
System.out.println(res);
return;
}
}
char e1 = adj[0].charAt(1);
char e2 = adj[1].charAt(2);
char e3 = adj[2].charAt(0);
int v1 = 0, v2 = 1, v3 = 2;
if (e2 == e3) {
v1 = 1;
v2 = 2;
v3 = 0;
} else if (e3 == e1) {
v1 = 2;
v2 = 0;
v3 = 1;
}
LinkedList<Integer> path = new LinkedList<>();
path.add(v1 + 1);
path.add(v2 + 1);
path.add(v3 + 1);
int turn = 0;
for (int i = 0; i < m - 2; i += 2) {
if (turn == 0) {
path.addFirst(v3 + 1);
path.addLast(v1 + 1);
turn++;
} else if (turn == 1) {
path.addFirst(v2 + 1);
path.addLast(v2 + 1);
turn++;
} else {
path.addFirst(v1 + 1);
path.addLast(v3 + 1);
turn = 0;
}
}
path.stream().forEach(x -> System.out.println(x + " "));
System.out.println();
}
public static class FastReader {
BufferedReader br;
StringTokenizer st;
private 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 class FastWriter {
private static final int BUF_SIZE = 1 << 13;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastWriter() {
out = null;
}
public FastWriter(OutputStream os) {
this.out = os;
}
public FastWriter(String path) {
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastWriter write(byte b) {
buf[ptr++] = b;
if (ptr == BUF_SIZE)
innerflush();
return this;
}
public FastWriter write(char c) {
return write((byte) c);
}
public FastWriter write(char[] s) {
for (char c : s) {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE)
innerflush();
}
return this;
}
public FastWriter write(String s) {
s.chars().forEach(c -> {
buf[ptr++] = (byte) c;
if (ptr == BUF_SIZE)
innerflush();
});
return this;
}
private static int countDigits(int l) {
if (l >= 1000000000)
return 10;
if (l >= 100000000)
return 9;
if (l >= 10000000)
return 8;
if (l >= 1000000)
return 7;
if (l >= 100000)
return 6;
if (l >= 10000)
return 5;
if (l >= 1000)
return 4;
if (l >= 100)
return 3;
if (l >= 10)
return 2;
return 1;
}
public FastWriter write(int x) {
if (x == Integer.MIN_VALUE) {
return write((long) x);
}
if (ptr + 12 >= BUF_SIZE)
innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L)
return 19;
if (l >= 100000000000000000L)
return 18;
if (l >= 10000000000000000L)
return 17;
if (l >= 1000000000000000L)
return 16;
if (l >= 100000000000000L)
return 15;
if (l >= 10000000000000L)
return 14;
if (l >= 1000000000000L)
return 13;
if (l >= 100000000000L)
return 12;
if (l >= 10000000000L)
return 11;
if (l >= 1000000000L)
return 10;
if (l >= 100000000L)
return 9;
if (l >= 10000000L)
return 8;
if (l >= 1000000L)
return 7;
if (l >= 100000L)
return 6;
if (l >= 10000L)
return 5;
if (l >= 1000L)
return 4;
if (l >= 100L)
return 3;
if (l >= 10L)
return 2;
return 1;
}
public FastWriter write(long x) {
if (x == Long.MIN_VALUE) {
return write("" + x);
}
if (ptr + 21 >= BUF_SIZE)
innerflush();
if (x < 0) {
write((byte) '-');
x = -x;
}
int d = countDigits(x);
for (int i = ptr + d - 1; i >= ptr; i--) {
buf[i] = (byte) ('0' + x % 10);
x /= 10;
}
ptr += d;
return this;
}
public FastWriter write(double x, int precision) {
if (x < 0) {
write('-');
x = -x;
}
x += Math.pow(10, -precision) / 2;
// if(x < 0){ x = 0; }
write((long) x).write(".");
x -= (long) x;
for (int i = 0; i < precision; i++) {
x *= 10;
write((char) ('0' + (int) x));
x -= (int) x;
}
return this;
}
public FastWriter writeln(char c) {
return write(c).writeln();
}
public FastWriter writeln(int x) {
return write(x).writeln();
}
public FastWriter writeln(long x) {
return write(x).writeln();
}
public FastWriter writeln(double x, int precision) {
return write(x, precision).writeln();
}
public FastWriter write(int... xs) {
boolean first = true;
for (int x : xs) {
if (!first)
write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter write(long... xs) {
boolean first = true;
for (long x : xs) {
if (!first)
write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter writeln() {
return write((byte) '\n');
}
public FastWriter writeln(int... xs) {
return write(xs).writeln();
}
public FastWriter writeln(long... xs) {
return write(xs).writeln();
}
public FastWriter writeln(char[] line) {
return write(line).writeln();
}
public FastWriter writeln(char[]... map) {
for (char[] line : map)
write(line).writeln();
return this;
}
public FastWriter writeln(String s) {
return write(s).writeln();
}
private void innerflush() {
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush() {
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
public FastWriter print(byte b) {
return write(b);
}
public FastWriter print(char c) {
return write(c);
}
public FastWriter print(char[] s) {
return write(s);
}
public FastWriter print(String s) {
return write(s);
}
public FastWriter print(int x) {
return write(x);
}
public FastWriter print(long x) {
return write(x);
}
public FastWriter print(double x, int precision) {
return write(x, precision);
}
public FastWriter println(char c) {
return writeln(c);
}
public FastWriter println(int x) {
return writeln(x);
}
public FastWriter println(long x) {
return writeln(x);
}
public FastWriter println(double x, int precision) {
return writeln(x, precision);
}
public FastWriter print(int... xs) {
return write(xs);
}
public FastWriter print(long... xs) {
return write(xs);
}
public FastWriter println(int... xs) {
return writeln(xs);
}
public FastWriter println(long... xs) {
return writeln(xs);
}
public FastWriter println(char[] line) {
return writeln(line);
}
public FastWriter println(char[]... map) {
return writeln(map);
}
public FastWriter println(String s) {
return writeln(s);
}
public FastWriter println() {
return writeln();
}
}
} | Java | ["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"] | 2 seconds | ["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"] | NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba. | Java 11 | standard input | [
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 79b629047e674883a9bc04b1bf0b7f09 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$. | 2,000 | For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO". | standard output | |
PASSED | 0ac983c4487a8143c316eff2501ccbc5 | train_107.jsonl | 1612535700 | Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m > 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(br.readLine());
while(t-->0)
{
String s1[]=br.readLine().split(" ");
int n=Integer.parseInt(s1[0]);
int m=Integer.parseInt(s1[1]);
char c[][]=new char[n][n];
for(int i=0;i<n;i++) {
String str=br.readLine();
for(int j=0;j<str.length();j++) {
c[i][j]=str.charAt(j);
}
}
if(m%2==1) {
System.out.println("YES");
for(int i=0;i<=m;i++) {
if(i%2==0)
System.out.print(1+" ");
else
System.out.print(2+" ");
}
System.out.println();
}
else {
int sameR=-1;
int sameC=-1;
for(int i=0;i<n;i++)
for(int j=0;j<n && sameR==-1;j++)
if(i!=j && c[i][j]==c[j][i])
{
sameR=i+1;
sameC=j+1;
break;
}
if( sameR!=-1) {
System.out.println("YES");
for(int i=0;i<=m;i++) {
if(i%2==0)
System.out.print(sameR+" ");
else
System.out.print(sameC+" ");
}
System.out.println();
}
else {
int ans[]=new int[3];
for(int i=0;i<n;i++)
{
ArrayList<Integer> a=new ArrayList<>();
ArrayList<Integer> b=new ArrayList<>();
for(int j=0;j<n;j++)
if(j!=i)
{
if(c[i][j]=='a')
a.add(j);
else
b.add(j);
}
if(a.size()>0 && b.size()>0)
{
ans[0]=i+1;
ans[1]=a.get(0)+1;
ans[2]=b.get(0)+1;
break;
}
}
if(ans[0]!=0) {
if(m%4==0) {
System.out.println("YES");
int count=0;
for(int i=0;i<=m;i++) {
if(i%2!=0 && count%2==0) {
System.out.print(ans[1]+" ");
count++;
}
else if(i%2!=0 && count%2!=0) {
System.out.print(ans[2]+" ");
count++;
}
else
System.out.print(ans[0]+" ");
}
System.out.println();
}
else {
System.out.println("YES");
int count=0;
for(int i=0;i<=m;i++) {
if(i%2==0 && count%2==0) {
System.out.print(ans[1]+" ");
count++;
}
else if(i%2==0 && count%2!=0) {
System.out.print(ans[2]+" ");
count++;
}
else
System.out.print(ans[0]+" ");
}
System.out.println();
}
}
else {
System.out.println("NO");
}
}
}
}
}
}
| Java | ["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"] | 2 seconds | ["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"] | NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba. | Java 11 | standard input | [
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 79b629047e674883a9bc04b1bf0b7f09 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$. | 2,000 | For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO". | standard output | |
PASSED | 49a43cd0b5c08a99939655144dafa936 | train_107.jsonl | 1612535700 | Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m > 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times. | 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.StringTokenizer;
public class problemD {
/*
if (u,v) == (v,y) then print it m times.
if m is odd (uv)(vu)(uv)(vu)(uv)
if m is even
abab-baba --> (uv)(vu)(uv)(vu)-(uw)(wu)(uw)(wu)
aba-aba --> (vu)(uv)(vu)-(uw)(wu)(uw)
*/
static class Solution {
class Node {
ArrayList<Integer>[] inDegree = new ArrayList[2];
ArrayList<Integer>[] outDegree = new ArrayList[2];
Node() {
for (int i = 0 ; i < 2 ; i ++ ) {
inDegree[i] = new ArrayList<>();
outDegree[i] = new ArrayList<>();
}
}
}
Node[] nodes;
void solve() {
int n = fs.nextInt();
int m = fs.nextInt();
char[][] G = new char[n][];
for (int i = 0 ; i < n ; i ++ ) G[i] = fs.next().toCharArray();
for (int i = 0 ; i < n ; i ++ ) {
for (int j = i+1; j < n ; j ++ ) {
if (G[i][j] == G[j][i]) {
out.println("YES");
print(i,j,m, false);
out.println();
return;
}
}
}
if (m % 2 == 1) {
out.println("YES");
print(0,1, m, false);
out.println();
return;
}
nodes = new Node[n];
for (int i = 0 ; i < n ; i ++ ) nodes[i] = new Node();
for (int i = 0 ; i < n ; i ++ ) {
for (int j = i+1; j < n ; j ++ ) {
nodes[i].outDegree[toInt(G[i][j])].add(j);
nodes[j].inDegree[toInt(G[i][j])].add(i);
nodes[j].outDegree[toInt(G[j][i])].add(i);
nodes[i].inDegree[toInt(G[j][i])].add(j);
}
}
int u=-1, v=-1, w=-1;
for (int i = 0 ; i < n ; i ++ ) {
for (int a = 0 ; a < 2 ; a ++ ) {
if (!nodes[i].inDegree[a].isEmpty() && !nodes[i].outDegree[a].isEmpty()) {
u = i;
v = nodes[u].inDegree[a].get(0);
w = nodes[u].outDegree[a].get(0);
break;
}
}
}
if (u == -1) {
out.println("NO");
return;
}
int k = m / 2;
out.println("YES");
if (k % 2 == 0) {
print(u, v, k, false);
print(u, w, k, true);
} else {
print(v, u, k, false);
print(u, w, k, true);
}
out.println();
}
int toInt(char c) {
return (int)(c-'a');
}
void print(int a, int b, int m, boolean skipFirst) {
a++;
b++;
if (!skipFirst) {
out.print(a);
out.print(' ');
}
boolean first = true;
for (int i = 0 ; i < m ; i ++ ) {
out.print(first ? b : a);
out.print(' ');
first = !first;
}
}
}
public static void main(String[] args) throws Exception {
int T = 1;
T = fs.nextInt();
Solution solution = new Solution();
for (int t = 0; t < T; t++) solution.solve();
out.close();
}
static void debug(Object... O) {
System.err.println("DEBUG: " + Arrays.deepToString(O));
}
private static FastScanner fs = new FastScanner();
private static PrintWriter out = new PrintWriter(System.out);
static class FastScanner { // Thanks SecondThread.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
ArrayList<Integer> readArrayList(int n) {
ArrayList<Integer> a = new ArrayList<>(n);
for (int i = 0 ; i < n; i ++ ) a.add(fs.nextInt());
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextString() {
return next();
}
}
}
| Java | ["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"] | 2 seconds | ["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"] | NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba. | Java 11 | standard input | [
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 79b629047e674883a9bc04b1bf0b7f09 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$. | 2,000 | For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO". | standard output | |
PASSED | 1dbac652e0dc6131bee241b254f3ecdd | train_107.jsonl | 1612535700 | Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m > 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class TheTreasureOfTheSegments {
public static void main(String[] args) throws IOException {
// InputStream inputStream = new FileInputStream("input.txt");
// OutputStream outputStream = new FileOutputStream("output.txt");
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(in.nextInt(), in, out);
out.close();
}
static class TaskA {
long mod = (long)(1e9) + 7;
long fact[];
int depth[];
int parentTable[][];
int degree[];
ArrayList<Integer> leaves;
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
int diam = 0;
int res = 0;
public void solve(int testNumber, InputReader in, PrintWriter out) throws IOException {
while(testNumber-->0){
int n = in.nextInt();
int m = in.nextInt();
char g[][] = new char[n][];
for (int i = 0; i < n; i++) {
g[i] = in.next().toCharArray();
}
if (n == 2) {
if (m % 2 == 0 && g[0][1] != g[1][0])
out.println("NO");
else {
out.println("YES");
for (int k = 0; k <= m; k++) {
out.print((2 - k % 2) + " ");
}
out.println();
}
continue;
}
boolean found = false;
X:
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (g[i][j] == g[j][i]) {
out.println("YES");
for (int k = 0; k <= m; k++) {
if (k % 2 == 0)
out.print((i + 1) + " ");
else
out.print((j + 1) + " ");
}
out.println();
// return;
found = true;
break X;
}
}
}
if(found)
continue;
int v1 = -1, v2 = -1, v3 = -1;
for (int i = 0; i < n; i++) {
v2 = -1;
v3 = -1;
for (int j = 0; j < n; j++) {
if (g[i][j] == 'a')
v2 = j;
else if (g[i][j] == 'b')
v3 = j;
}
if (v2 != -1 && v3 != -1) {
v1 = i;
break;
}
}
out.println("YES");
if (m % 4 == 0) {
for (int k = 0; k < m / 4; k++) {
out.print((v1 + 1) + " " + (v2 + 1) + " " + (v1 + 1) + " " + (v3 + 1) + " ");
}
out.println(v1 + 1);
} else if (m % 4 == 2) {
out.print((v2 + 1) + " ");
for (int k = 0; k < m / 4; k++) {
out.print((v1 + 1) + " " + (v2 + 1) + " " + (v1 + 1) + " " + (v3 + 1) + " ");
}
out.println((v1 + 1) + " " + (v3 + 1));
} else {
for (int k = 0; k <= m / 2; k++) {
out.print((v1 + 1) + " " + (v2 + 1) + " ");
}
out.println();
}
}
}
public int distance(ArrayList<ArrayList<Integer>> a , int u , int v){
return depth[u]+depth[v] - 2*depth[lca(a , u , v)];
}
public int lca(ArrayList<ArrayList<Integer>> a , int u , int v){
if(depth[v]<depth[u]){
int x = u;
u = v;
v = x;
}
int diff = depth[v] - depth[u];
for(int i=0;i<parentTable[v].length;i++){
// checking whether the ith bit is set in the diff variable
if(((diff>>i)&1) == 1)
v = parentTable[v][i];
}
if(v == u)
return v;
for(int i=parentTable[v].length-1;i>=0;i--){
if(parentTable[u][i] != parentTable[v][i]){
v = parentTable[v][i];
u = parentTable[u][i];
}
}
return parentTable[u][0];
}
public int[][] multiply(int a[][] , int b[][]){
int c[][] = new int[a.length][b[0].length];
for(int i=0;i<a.length;i++){
for(int j=0;j<b[0].length;j++){
for(int k=0;k<b.length;k++)
c[i][j] += a[i][k]*b[k][j];
}
}
return c;
}
public int[][] multiply(int a[][] , int b[][] , int mod){
int c[][] = new int[a.length][b[0].length];
for(int i=0;i<a.length;i++){
for(int j=0;j<b[0].length;j++){
for(int k=0;k<b.length;k++){
c[i][j] += a[i][k]*b[k][j];
c[i][j]%=mod;
}
}
}
return c;
}
public int[][] pow(int a[][] , long b){
int res[][] = new int[a.length][a[0].length];
for(int i=0;i<a.length;i++)
res[i][i] = 1;
while(b>0){
if((b&1) == 1)
res = multiply(res , a , 10);
a = multiply(a , a , 10);
b>>=1;
}
return res;
}
// for the min max problems
public void build(int lookup[][] , int arr[], int n) {
for (int i = 0; i < n; i++)
lookup[i][0] = arr[i];
for (int j = 1; (1 << j) <= n; j++) {
for (int i = 0; (i + (1 << j) - 1) < n; i++) {
if (lookup[i][j - 1] > lookup[i + (1 << (j - 1))][j - 1])
lookup[i][j] = lookup[i][j - 1];
else
lookup[i][j] = lookup[i + (1 << (j - 1))][j - 1];
}
}
}
public int query(int lookup[][] , int L, int R) {
int j = (int)(Math.log(R - L + 1)/Math.log(2));
if (lookup[L][j] >= lookup[R - (1 << j) + 1][j])
return lookup[L][j];
else
return lookup[R - (1 << j) + 1][j];
}
// for printing purposes
public void print1d(int a[] , PrintWriter out){
for(int i=0;i<a.length;i++)
out.print(a[i] + " ");
out.println();
}
public void print1d(boolean a[] , PrintWriter out){
for(int i=0;i<a.length;i++)
out.print(a[i] + " ");
out.println();
}
public void print1d(long a[] , PrintWriter out){
for(int i=0;i<a.length;i++)
out.print(a[i] + " ");
out.println();
}
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();
}
// out.println();
}
public void print2d(long 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();
}
// out.println();
}
public void sieve(int a[]){
a[0] = a[1] = 1;
int i;
for(i=2;i*i<=a.length;i++){
if(a[i] != 0)
continue;
a[i] = i;
for(int k = (i)*(i);k<a.length;k+=i){
if(a[k] != 0)
continue;
a[k] = i;
}
}
}
public long nCrPFermet(int n , int r , long p){
if(r==0)
return 1l;
// long fact[] = new long[n+1];
// fact[0] = 1;
// for(int i=1;i<=n;i++)
// fact[i] = (i*fact[i-1])%p;
long modInverseR = pow(fact[r] , p-2 , p);
long modInverseNR = pow(fact[n-r] , p-2 , p);
long w = (((fact[n]*modInverseR)%p)*modInverseNR)%p;
return w;
}
public long pow(long a, long b, long m) {
a %= m;
long res = 1;
while (b > 0) {
long x = b&1;
if (x == 1)
res = res * a % m;
a = a * a % m;
b >>= 1;
}
return res;
}
public long pow(long a, long b) {
long res = 1;
while (b > 0) {
long x = b&1;
if (x == 1)
res = res * a;
a = a * a;
b >>= 1;
}
return res;
}
public void sortedArrayToBST(TreeSet<Integer> a , int start, int end) {
if (start > end) {
return;
}
int mid = (start + end) / 2;
a.add(mid);
sortedArrayToBST(a, start, mid - 1);
sortedArrayToBST(a, mid + 1, end);
}
public int lowerLastBound(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 upperFirstBound(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 int lowerLastBound(long a[] , long x){
int l = 0;
int r = a.length-1;
if(a[l]>=x)
return -1;
if(a[r]<x)
return r;
int mid = -1;
while(l<=r){
mid = (l+r)/2;
if(a[mid] == x && a[mid-1]<x)
return mid-1;
else if(a[mid]>=x)
r = mid-1;
else if(a[mid]<x && a[mid+1]>=x)
return mid;
else if(a[mid]<x && a[mid+1]<x)
l = mid+1;
}
return mid;
}
public int upperFirstBound(long a[] , long x){
int l = 0;
int r = a.length-1;
if(a[l]>x)
return l;
if(a[r]<=x)
return r+1;
int mid = -1;
while(l<=r){
mid = (l+r)/2;
if(a[mid] == x && a[mid+1]>x)
return mid+1;
else if(a[mid]<=x)
l = mid+1;
else if(a[mid]>x && a[mid-1]<=x)
return mid;
else if(a[mid]>x && a[mid-1]>x)
r = mid-1;
}
return mid;
}
public long log(float number , int base){
return (long) Math.ceil((Math.log(number) / Math.log(base)) + 1e-9);
}
public long gcd(long a , long b){
if(a<b){
long c = b;
b = a;
a = c;
}
while(b!=0){
long c = a;
a = b;
b = c%a;
}
return a;
}
public long[] gcdEx(long p, long q) {
if (q == 0)
return new long[] { p, 1, 0 };
long[] vals = gcdEx(q, p % q);
long d = vals[0];
long a = vals[2];
long b = vals[1] - (p / q) * vals[2];
// 0->gcd 1->xValue 2->yValue
return new long[] { d, a, b };
}
public void sievePhi(int a[]){
a[0] = 0;
a[1] = 1;
for(int i=2;i<a.length;i++)
a[i] = i-1;
for(int i=2;i<a.length;i++)
for(int j = 2*i;j<a.length;j+=i)
a[j] -= a[i];
}
public void lcmSum(long a[]){
int sievePhi[] = new int[(int)1e6 + 1];
sievePhi(sievePhi);
a[0] = 0;
for(int i=1;i<a.length;i++)
for(int j = i;j<a.length;j+=i)
a[j] += (long)i*sievePhi[i];
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"] | 2 seconds | ["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"] | NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba. | Java 11 | standard input | [
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 79b629047e674883a9bc04b1bf0b7f09 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$. | 2,000 | For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO". | standard output | |
PASSED | 9b15bda86e362f0f48a0cc0b17d25410 | train_107.jsonl | 1612535700 | Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m > 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
int tc = sc.nextInt();
main:
while (tc-- > 0) {
int n = sc.nextInt(), m = sc.nextInt();
char[][] graph = new char[n][];
for (int i = 0; i < n; i++)
graph[i] = sc.next().toCharArray();
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++)
if (graph[i][j] == graph[j][i]) {
out.println("YES");
int[] ans = {i + 1, j + 1};
int c = 0;
while (m-- > 0) {
out.print(ans[c] + " ");
c = 1 - c;
}
out.println(ans[c]);
continue main;
}
}
if (m % 2 != 0) {
out.println("YES");
int[] ans = {1, 2};
int c = 0;
while (m-- > 0) {
out.print(ans[c] + " ");
c = 1 - c;
}
out.println(ans[c]);
continue main;
}
// if (m == 2) {
// out.println("NO");
// continue;
// }
for (int i = 0; i < n; i++) {
int one = -1, two = -1;
for (int j = 0; j < n; j++) {
if (i == j) continue;
if (graph[i][j] == 'a' && graph[j][i] == 'b') one = j;
else two = j;
}
if (one != -1 && two != -1) {
out.println("YES");
int mm = m / 2;
if (mm % 2 == 0) {
int[] ans = {i + 1, one + 1};
int cnt = mm, c = 0;
while (cnt-- > 0) {
out.print(ans[c] + " ");
c = 1 - c;
}
ans = new int[]{i + 1, two + 1};
cnt = mm;
c = 0;
while (cnt-- > 0) {
out.print(ans[c] + " ");
c = 1 - c;
}
out.println(i + 1);
} else {
int[] ans = {one + 1, i + 1};
int cnt = mm, c = 0;
while (cnt-- > 0) {
out.print(ans[c] + " ");
c = 1 - c;
}
out.print(i + 1 + " ");
ans = new int[]{two + 1, i + 1};
cnt = mm;
c = 0;
while (cnt-- > 0) {
out.print(ans[c] + " ");
c = 1 - c;
}
out.println();
}
continue main;
}
}
out.println("NO");
}
out.flush();
out.close();
}
static String get(int cnt, int[] a) {
StringBuilder ans = new StringBuilder();
int c = 0;
while (cnt-- > 0) {
ans.append(a[0] + " ");
c = 1 - c;
}
return ans.toString();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public Scanner(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(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 int[] nextIntArray(int n) throws IOException {
int[] ans = new int[n];
for (int i = 0; i < n; i++)
ans[i] = nextInt();
return ans;
}
public long[] nextLongArray(int n) throws IOException {
long[] ans = new long[n];
for (int i = 0; i < n; i++)
ans[i] = nextLong();
return ans;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] ans = new Integer[n];
for (int i = 0; i < n; i++)
ans[i] = nextInt();
return ans;
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public boolean ready() throws IOException {
return br.ready();
}
}
} | Java | ["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"] | 2 seconds | ["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"] | NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba. | Java 11 | standard input | [
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 79b629047e674883a9bc04b1bf0b7f09 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$. | 2,000 | For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO". | standard output | |
PASSED | 06261c4a4710dfd669bd3d5684d8ea86 | train_107.jsonl | 1612535700 | Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m > 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
int tc = sc.nextInt();
main:
while (tc-- > 0) {
int n = sc.nextInt(), m = sc.nextInt();
char[][] graph = new char[n][];
for (int i = 0; i < n; i++)
graph[i] = sc.next().toCharArray();
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++)
if (graph[i][j] == graph[j][i]) {
out.println("YES");
int[] ans = {i + 1, j + 1};
int c = 0;
while (m-- > 0) {
out.print(ans[c] + " ");
c = 1 - c;
}
out.println(ans[c]);
continue main;
}
}
if (m % 2 != 0) {
out.println("YES");
int[] ans = {1, 2};
int c = 0;
while (m-- > 0) {
out.print(ans[c] + " ");
c = 1 - c;
}
out.println(ans[c]);
continue main;
}
for (int i = 0; i < n; i++) {
int one = -1, two = -1;
for (int j = 0; j < n; j++) {
if (i == j) continue;
if (graph[i][j] == 'a' && graph[j][i] == 'b') one = j;
else two = j;
}
if (one != -1 && two != -1) {
out.println("YES");
if (m == 2) {
out.println(one + 1 + " " + (i + 1) + " " + (two + 1));
continue main;
}
int mm = m / 2;
if (mm % 2 == 0) {
int[] ans = {i + 1, one + 1};
int cnt = mm, c = 0;
while (cnt-- > 0) {
out.print(ans[c] + " ");
c = 1 - c;
}
ans = new int[]{i + 1, two + 1};
cnt = mm;
c = 0;
while (cnt-- > 0) {
out.print(ans[c] + " ");
c = 1 - c;
}
out.println(i + 1);
} else {
int[] ans = {one + 1, i + 1};
int cnt = mm, c = 0;
while (cnt-- > 0) {
out.print(ans[c] + " ");
c = 1 - c;
}
out.print(i + 1 + " ");
ans = new int[]{two + 1, i + 1};
cnt = mm;
c = 0;
while (cnt-- > 0) {
out.print(ans[c] + " ");
c = 1 - c;
}
out.println();
}
continue main;
}
}
out.println("NO");
}
out.flush();
out.close();
}
static String get(int cnt, int[] a) {
StringBuilder ans = new StringBuilder();
int c = 0;
while (cnt-- > 0) {
ans.append(a[0] + " ");
c = 1 - c;
}
return ans.toString();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public Scanner(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(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 int[] nextIntArray(int n) throws IOException {
int[] ans = new int[n];
for (int i = 0; i < n; i++)
ans[i] = nextInt();
return ans;
}
public long[] nextLongArray(int n) throws IOException {
long[] ans = new long[n];
for (int i = 0; i < n; i++)
ans[i] = nextLong();
return ans;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] ans = new Integer[n];
for (int i = 0; i < n; i++)
ans[i] = nextInt();
return ans;
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public boolean ready() throws IOException {
return br.ready();
}
}
} | Java | ["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"] | 2 seconds | ["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"] | NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba. | Java 11 | standard input | [
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 79b629047e674883a9bc04b1bf0b7f09 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$. | 2,000 | For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO". | standard output | |
PASSED | caba0996686e9c7be460205b45bccb72 | train_107.jsonl | 1612535700 | Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m > 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times. | 256 megabytes | // package codeforce.cf699;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class D {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int t = sc.nextInt();
// int t = 1;
for (int i = 0; i < t; i++) {
solve(sc, pw);
}
pw.close();
}
static void solve(Scanner in, PrintWriter out){
int n = in.nextInt(), m = in.nextInt();
char[][] cs = new char[n][];
for (int i = 0; i < n; i++) {
cs[i] = in.next().toCharArray();
}
if (n == 2){
boolean db = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) continue;
if (cs[i][j] == cs[j][i]){
db = true;
break;
}
}
}
if (db){
out.println("YES");
int st = 0;
for (int i = 0; i <= m; i++) {
out.print((st + 1)+" ");
st = 1 - st;
}
}else{
if (m % 2 == 0){
out.println("NO");
}else{
out.println("YES");
int st = 0;
for (int i = 0; i <= m; i++) {
out.print((st + 1)+" ");
st = 1 - st;
}
}
}
}else{
out.println("YES");
boolean db = false;
int tar = -1, l = -1, r = -1;
int dbl = -1, dbr = -1;
for (int i = 0; i < n; i++) {
Map<String, Integer> mp = new HashMap<>();
for (int j = 0; j < n; j++) {
if (i == j) continue;
char cl = cs[i][j], cr = cs[j][i];
if (cl == cr){
db = true;
dbl = i; dbr = j;
break;
}
String neo = cr +" "+cl;
if (mp.containsKey(neo)){
tar = i;
l = mp.get(neo);
r = j;
}
mp.put((cl+" "+cr), j);
}
}
if (db){
boolean start = false;
for (int i = 0; i <= m; i++) {
if (start){
out.print((dbl + 1)+" ");
}else{
out.print((dbr + 1)+" ");
}
start = !start;
}
}else{
if (m % 2 == 0){
int tot = m + 1;
boolean start = true;
if (m % 4 != 0) start = false;
for (int i = 0; i < tot / 2; i++) {
if (start){
out.print((tar + 1)+" ");
}else{
out.print((l + 1)+" ");
}
start = !start;
}
start = true;
for (int i = 0; i < tot - tot / 2; i++) {
if (start){
out.print((tar + 1)+" ");
}else{
out.print((r + 1)+" ");
}
start = !start;
}
}else{
boolean start = false;
for (int i = 0; i <= m; i++) {
if (start){
out.print((1)+" ");
}else{
out.print((2)+" ");
}
start = !start;
}
}
}
}
out.println();
}
}
| Java | ["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"] | 2 seconds | ["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"] | NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba. | Java 11 | standard input | [
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 79b629047e674883a9bc04b1bf0b7f09 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$. | 2,000 | For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO". | standard output | |
PASSED | 9da6d9a0d111aa9b2e0c0ae70871e64b | train_107.jsonl | 1612535700 | Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m > 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times. | 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.InputMismatchException;
import java.util.List;
import java.util.Stack;
public class Main {
private static final String NO = "No";
private static final String YES = "Yes";
InputStream is;
PrintWriter out;
String INPUT = "";
private static final long MOD = 998244353L;
void solve() {
int T = ni();
for (int i = 0; i < T; i++)
solve(i);
}
void solve(int p) {
int n = ni();
int m = ni();
char a[][] = new char[n][];
for (int i = 0; i < n; i++)
a[i] = ns().toCharArray();
if ((m & 1) != 0) {
out.println("YES");
for (int i = 1; i <= m; i += 2) {
out.print("1 2 ");
}
out.println();
} else if (n == 2) {
if (a[1][0] == a[0][1]) {
out.println("YES");
for (int i = 1; i <= m + 1; i++)
out.print(i % 2 + 1 + " ");
out.println();
} else
out.println("NO");
} else {
out.println("YES");
// String s[] = new String[] { "1 2 ", "2 3 ", "1 3 " };
int f;
if (a[0][1] == a[1][2])
f = 1;
else if (a[2][0] == a[0][1])
f = 0;
else
f = 2;
// tr(f);
for (int i = 0; i <= m; i++)
out.print((f + i + m) % 3 + 1 + " ");
out.println();
}
}
// a^b
long power(long a, long b) {
long x = 1, y = a;
while (b > 0) {
if (b % 2 != 0) {
x = (x * y) % MOD;
}
y = (y * y) % MOD;
b /= 2;
}
return x % MOD;
}
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 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 char[] nc(int n) {
char[] ret = new char[n];
for (int i = 0; i < n; i++)
ret[i] = nc();
return ret;
}
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(int n, int m) {
long[][] a = new long[n][];
for (int i = 0; i < n; i++)
a[i] = nl(m);
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 | ["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"] | 2 seconds | ["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"] | NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba. | Java 11 | standard input | [
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 79b629047e674883a9bc04b1bf0b7f09 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$. | 2,000 | For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO". | standard output | |
PASSED | b4934b1501b8213a16f9dbc1673c226d | train_107.jsonl | 1612535700 | Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m > 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static Scanner sc = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
// long mod = 998244353;
long mod = (long)1e9+7;
int inf = Integer.MAX_VALUE/2;
public static void main(String[] args) throws Exception {
Main main = new Main();
// int t = Integer.parseInt(reader.readLine());
int t = sc.nextInt();
// int t = 1;
for(int i=1; i<=t; i++){
main.solve();
}
out.flush();
}
void solve() throws Exception{
int n = neInt(), m = neInt();
char[][] gra = new char[n][];
for(int i=0; i<n; i++){
gra[i] = neS().toCharArray();
}
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
if(i==j) continue;
if(gra[i][j]==gra[j][i]){
out.println("YES");
for(int idx=0; idx<=m; idx++){
if(idx%2==0) out.print((1+i)+" ");
else out.print((1+j)+" ");
}
out.println(); return;
}
}
}
if(m%2==1){
out.println("YES");
for(int i=0; i<=m; i++) {
out.print(i%2+1); out.print(" ");
}
out.println();
return;
}
// then m is an even number
if(n<=2){
out.println("NO"); return;
}
for(int i=0; i<n; i++){
List<Integer> a = new ArrayList<>(), b = new ArrayList<>();
for(int j=0; j<n; j++){
if(j==i) continue;
if(gra[i][j]=='a') a.add(j);
else b.add(j);
}
if(a.size()==0||b.size()==0) continue;
out.println("YES");
int center = i+1, left = a.get(0)+1, right = b.get(0)+1;
if(m%4==0){
// abab | baba
out.print(center+" ");
for(int idx=1; idx<=m/2; idx++){
if(idx%2==0) out.print(center+" ");
else out.print(left+" ");
}
for(int idx=m/2+1; idx<=m; idx++){
if(idx%2==0) out.print(center+" ");
else out.print(right+" ");
}
} else{
// aba | aba
out.print(left+" ");
for(int idx=1; idx<=m/2; idx++){
if(idx%2==1) out.print(center+" ");
else out.print(left+" ");
}
for(int idx=m/2+1; idx<=m; idx++){
if(idx%2==1) out.print(center+" ");
else out.print(right+" ");
}
}
out.println();
return;
}
out.println("NO");
}
String neS(){
return sc.next();
}
int neInt(){
return Integer.parseInt(sc.next());
}
long neLong(){
return Long.parseLong(sc.next());
}
int paIn(String s){return Integer.parseInt(s);}
} | Java | ["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"] | 2 seconds | ["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"] | NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba. | Java 11 | standard input | [
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 79b629047e674883a9bc04b1bf0b7f09 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$. | 2,000 | For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO". | standard output | |
PASSED | 4cd5bbfe1dd4b0e0ba8c038e48eb9f2e | train_107.jsonl | 1612535700 | Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m > 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public final class Codechef {
public static void main(String[] args){
// Scanner sc=new Scanner(System.in);
FastReader sc=new FastReader();
PrintWriter writer=new PrintWriter(System.out);
int t=sc.nextInt();
while(t-->0) {
int n=sc.nextInt(), m=sc.nextInt();
HashMap<String, Character> h=new HashMap<>();
char[][] c=new char[n][];
for(int i=0;i<n;i++) {
String s=sc.next();
c[i]=s.toCharArray();
for(int j=0;j<s.length();j++) {
if(i!=j) {
h.put((i+1)+"-"+(j+1), s.charAt(j));
}
}
}
String ans="No";
if(m%2!=0) {
ans="YES";
System.out.println(ans);
for(int i=0;i<m/2+1;i++) System.out.print("1 2 ");
}else {
int f=0;
for(int i=1;i<=n;i++) {
for(int j=1;j<=n;j++) {
if(i!=j && (h.get(i+"-"+j)==h.get(j+"-"+i))) {
System.out.println("YES");
for(int k=0;k<m/2;k++) System.out.print(i+" "+j+" ");
System.out.print(i);
f=1; break;
}
}
if(f==1) break;
}
if(f==0) {
f=0;
int[][] a=new int[n+1][2];
for(int i=0;i<=n;i++) Arrays.fill(a[i], -1);
for(int i=0;i<n;i++) {
a[i+1][0]=-1; a[i+1][1]=-1;
for(int j=0;j<c[i].length;j++) {
if(c[i][j]=='a') a[i+1][0]=j+1;
else if(c[i][j]=='b') a[i+1][1]=j+1;
}
}
int i=0, j=0, k=-1;
for(i=0;i<n;i++) {
for(j=0;j<c[i].length;j++) {
if(c[i][j]=='a' && a[j+1][0]!=-1) {
k=a[j+1][0];
f=1; break;
}else if(c[i][j]=='b' && a[j+1][1]!=-1) {
k=a[j+1][1];
// System.out.println(i+" "+j+" "+k+"**");
f=1; break;
}
}
if(f==1) break;
}
if(k!=-1) {
ans="YES";
i++; j++;
System.out.println(ans);
if(m%4==0) { // m/2 is even
m/=2;
for(int l=0;l<m/2;l++) System.out.print(j+" "+i+" ");
System.out.print(j+" ");
for(int l=0;l<m/2;l++) System.out.print(k+" "+j+" ");
}else { // m/2 is odd
m=m/2+1;
for(int l=0;l<m/2;l++) System.out.print(i+" "+j+" ");
System.out.print(k+" ");
for(int l=0;l<m/2-1;l++) System.out.print(j+" "+k+" ");
}
}else System.out.print(ans);
}
}
System.out.println();
}
writer.flush();
writer.close();
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
} | Java | ["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"] | 2 seconds | ["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"] | NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba. | Java 11 | standard input | [
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 79b629047e674883a9bc04b1bf0b7f09 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$. | 2,000 | For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO". | standard output | |
PASSED | af30fa82d79b304949636d806c18067a | train_107.jsonl | 1612535700 | Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m > 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static class Scan {
private byte[] buf=new byte[1024];
private int index;
private InputStream in;
private int total;
public Scan()
{
in=System.in;
}
public int scan()throws IOException
{
if(total<0)
throw new InputMismatchException();
if(index>=total)
{
index=0;
total=in.read(buf);
if(total<=0)
return -1;
}
return buf[index++];
}
public int scanInt()throws IOException
{
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();
}
else throw new InputMismatchException();
}
return neg*integer;
}
public double scanDouble()throws IOException
{
double doub=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n)&&n!='.')
{
if(n>='0'&&n<='9')
{
doub*=10;
doub+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
if(n=='.')
{
n=scan();
double temp=1;
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
temp/=10;
doub+=(n-'0')*temp;
n=scan();
}
else throw new InputMismatchException();
}
}
return doub*neg;
}
public String scanString()throws IOException
{
StringBuilder sb=new StringBuilder();
int n=scan();
while(isWhiteSpace(n))
n=scan();
while(!isWhiteSpace(n))
{
sb.append((char)n);
n=scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n)
{
if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
return true;
return false;
}
}
public static void sort(int arr[],int l,int r) { //sort(arr,0,n-1);
if(l==r) {
return;
}
int mid=(l+r)/2;
sort(arr,l,mid);
sort(arr,mid+1,r);
merge(arr,l,mid,mid+1,r);
}
public static void merge(int arr[],int l1,int r1,int l2,int r2) {
int tmp[]=new int[r2-l1+1];
int indx1=l1,indx2=l2;
//sorting the two halves using a tmp array
for(int i=0;i<tmp.length;i++) {
if(indx1>r1) {
tmp[i]=arr[indx2];
indx2++;
continue;
}
if(indx2>r2) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
if(arr[indx1]<arr[indx2]) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
tmp[i]=arr[indx2];
indx2++;
}
//Copying the elements of tmp into the main array
for(int i=0,j=l1;i<tmp.length;i++,j++) {
arr[j]=tmp[i];
}
}
public static void sort(long arr[],int l,int r) { //sort(arr,0,n-1);
if(l==r) {
return;
}
int mid=(l+r)/2;
sort(arr,l,mid);
sort(arr,mid+1,r);
merge(arr,l,mid,mid+1,r);
}
public static void merge(long arr[],int l1,int r1,int l2,int r2) {
long tmp[]=new long[r2-l1+1];
int indx1=l1,indx2=l2;
//sorting the two halves using a tmp array
for(int i=0;i<tmp.length;i++) {
if(indx1>r1) {
tmp[i]=arr[indx2];
indx2++;
continue;
}
if(indx2>r2) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
if(arr[indx1]<arr[indx2]) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
tmp[i]=arr[indx2];
indx2++;
}
//Copying the elements of tmp into the main array
for(int i=0,j=l1;i<tmp.length;i++,j++) {
arr[j]=tmp[i];
}
}
public static void main(String args[]) throws IOException {
Scan input=new Scan();
StringBuilder ans=new StringBuilder("");
int test=input.scanInt();
for(int tt=1;tt<=test;tt++) {
int n=input.scanInt();
int m=input.scanInt();
char arr[][]=new char[n][n];
for(int i=0;i<n;i++) {
String str=input.scanString();
for(int j=0;j<n;j++) {
arr[i][j]=str.charAt(j);
}
}
StringBuilder tmp=solve(n,m,arr);
if(tmp.length()==0) {
ans.append("NO\n");
continue;
}
ans.append("YES\n");
ans.append(tmp+"\n");
}
System.out.println(ans);
}
public static StringBuilder solve(int n,int m,char arr[][]) {
StringBuilder ans=new StringBuilder("");
if(m==1) {
ans.append(1+" "+2);
return ans;
}
int indx1=-1,indx2=-1;
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
if(i==j) {
continue;
}
if(arr[i][j]==arr[j][i]) {
indx1=i;
indx2=j;
}
}
}
if(indx1!=-1) {
for(int i=0;i<m+1;i++) {
if(i%2==0) {
ans.append((indx1+1)+" ");
}
else {
ans.append((indx2+1)+" ");
}
}
return ans;
}
if(m%2==1) {
for(int i=0;i<m+1;i++) {
if(i%2==0) {
ans.append(1+" ");
}
else {
ans.append(2+" ");
}
}
return ans;
}
if(m==2) {
int ca[]=new int[n];
int cb[]=new int[n];
Arrays.fill(ca, -1);
Arrays.fill(cb, -1);
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
if(arr[i][j]=='a') {
ca[i]=j;
}
if(arr[i][j]=='b') {
cb[i]=j;
}
}
}
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
if(i==j) {
continue;
}
if(arr[i][j]=='a' && ca[j]!=-1) {
ans.append((i+1)+" "+(j+1)+" "+(ca[j]+1));
return ans;
}
if(arr[i][j]=='b' && cb[j]!=-1) {
ans.append((i+1)+" "+(j+1)+" "+(cb[j]+1));
return ans;
}
}
}
return ans;
}
int root=-1,ta=-1,tb=-1;
for(int i=0;i<n;i++) {
boolean a=false,b=false;
for(int j=0;j<n;j++) {
if(arr[i][j]=='a') {
ta=j;
a=true;
}
if(arr[i][j]=='b') {
tb=j;
b=true;
}
}
if(a && b) {
root=i;
break;
}
}
if(root==-1) {
return ans;
}
// System.out.println(ta+" "+tb);
if(m%4==0) {
for(int i=0;i<m+1;i++) {
if(i%4==0) {
ans.append((root+1)+" ");
}
if(i%4==1) {
ans.append((ta+1)+" ");
}
if(i%4==2) {
ans.append((root+1)+" ");
}
if(i%4==3) {
ans.append((tb+1)+" ");
}
}
}
else {
for(int i=0;i<m+1;i++) {
if(i%4==0) {
ans.append((ta+1)+" ");
}
if(i%4==1) {
ans.append((root+1)+" ");
}
if(i%4==2) {
ans.append((tb+1)+" ");
}
if(i%4==3) {
ans.append((root+1)+" ");
}
}
}
return ans;
}
}
| Java | ["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"] | 2 seconds | ["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"] | NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba. | Java 11 | standard input | [
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 79b629047e674883a9bc04b1bf0b7f09 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$. | 2,000 | For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO". | standard output | |
PASSED | 6d96af4f43f8c379aea1f09bbbe5ed26 | train_107.jsonl | 1612535700 | Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m > 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times. | 256 megabytes | import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Arrays;
import java.util.Random;
import java.io.FileWriter;
import java.io.PrintWriter;
/*
Solution Created: 14:04:09 06/02/2021
Custom Competitive programming helper.
*/
public class Main {
public static void solve() {
int n = in.nextInt(), m = in.nextInt();
char[][] a = new char[n][n];
for(int i = 0; i<n; i++) a[i] = in.nca();
if(m%2==1){
out.println("YES");
for(int i = 0; i<m+1; i++) out.print((i%2+1)+" ");
out.println();
return;
}
int x = -1, y = -1;
for(int i = 0; i<n && x==-1; i++){
for(int j = 0; j<n && x==-1; j++){
if(i==j) continue;
if(a[i][j]==a[j][i]){
x = i+1;
y = j+1;
}
}
}
if(x!=-1){
out.println("YES");
for(int i = 0; i<m+1; i++){
if(i%2==0) out.print(x+" ");
else out.print(y+" ");
}
out.println();
return;
}
int first = -1;
int A = -1 ,B = -1;
for(int i = 0; i<Math.min(n, 3); i++){
boolean haveA = false, haveB = false;
for(int j = 0; j<n; j++){
if(a[i][j]=='a'){
haveA = true;
A = j;
}
if(a[i][j]=='b') {
haveB = true;
B = j;
}
}
if(haveA&&haveB){
first = i;
break;
}
}
if(first==-1) out.println("NO");
else{
out.println("YES");
int times = m/2;
first++;A++;B++;
if(times%2==1){
for(int i = 0; i<times; i++){
if(i%2==0) out.print(A+" ");
else out.print(first+" ");
}
out.print(first+" ");
for(int i = 0; i<times; i++){
if(i%2==0) out.print(B+" ");
else out.print(first+" ");
}
}else{
for(int i = 0; i<times; i++){
if(i%2==1) out.print(A+" ");
else out.print(first+" ");
}
for(int i = 0; i<times; i++){
if(i%2==1) out.print(B+" ");
else out.print(first+" ");
}
out.print(first+" ");
}
out.println();
}
}
public static void main(String[] args) {
in = new Reader();
out = new Writer();
int t = in.nextInt();
while(t-->0) solve();
out.exit();
}
static Reader in; static Writer out;
static class Reader {
static BufferedReader br;
static StringTokenizer st;
public Reader() {
this.br = new BufferedReader(new InputStreamReader(System.in));
}
public Reader(String f){
try {
this.br = new BufferedReader(new FileReader(f));
} catch (IOException e) {
e.printStackTrace();
}
}
public int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public double[] nd(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++) a[i] = nextDouble();
return a;
}
public long[] nl(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
public char[] nca() {
return next().toCharArray();
}
public String[] ns(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++) a[i] = next();
return a;
}
public int nextInt() {
ensureNext();
return Integer.parseInt(st.nextToken());
}
public double nextDouble() {
ensureNext();
return Double.parseDouble(st.nextToken());
}
public Long nextLong() {
ensureNext();
return Long.parseLong(st.nextToken());
}
public String next() {
ensureNext();
return st.nextToken();
}
public String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private void ensureNext() {
if (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
static class Util{
private static Random random = new Random();
static long[] fact;
public static void initFactorial(int n, long mod) {
fact = new long[n+1];
fact[0] = 1;
for (int i = 1; i < n+1; i++) fact[i] = (fact[i - 1] * i) % mod;
}
public static long modInverse(long a, long MOD) {
long[] gcdE = gcdExtended(a, MOD);
if (gcdE[0] != 1) return -1; // Inverted doesn't exist
long x = gcdE[1];
return (x % MOD + MOD) % MOD;
}
public static long[] gcdExtended(long p, long q) {
if (q == 0) return new long[] { p, 1, 0 };
long[] vals = gcdExtended(q, p % q);
long tmp = vals[2];
vals[2] = vals[1] - (p / q) * vals[2];
vals[1] = tmp;
return vals;
}
public static long nCr(int n, int r, long MOD) {
if (r == 0) return 1;
return (fact[n] * modInverse(fact[r], MOD) % MOD * modInverse(fact[n - r], MOD) % MOD) % MOD;
}
public static long nCr(int n, int r) {
return (fact[n]/fact[r])/fact[n-r];
}
public static long nPr(int n, int r, long MOD) {
if (r == 0) return 1;
return (fact[n] * modInverse(fact[n - r], MOD) % MOD) % MOD;
}
public static long nPr(int n, int r) {
return fact[n]/fact[n-r];
}
public static boolean isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static boolean[] getSieve(int n) {
boolean[] isPrime = new boolean[n+1];
for (int i = 2; i <= n; i++) isPrime[i] = true;
for (int i = 2; i*i <= n; i++) if (isPrime[i])
for (int j = i; i*j <= n; j++) isPrime[i*j] = false;
return isPrime;
}
public static int gcd(int a, int b) {
int tmp = 0;
while(b != 0) {
tmp = b;
b = a%b;
a = tmp;
}
return a;
}
public static long gcd(long a, long b) {
long tmp = 0;
while(b != 0) {
tmp = b;
b = a%b;
a = tmp;
}
return a;
}
public static int random(int min, int max) {
return random.nextInt(max-min+1)+min;
}
public static void dbg(Object... o) {
System.out.println(Arrays.deepToString(o));
}
public static void reverse(int[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
int tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(int[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(long[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
long tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(long[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(float[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
float tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(float[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(double[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
double tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(double[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(char[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
char tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(char[] s) {
reverse(s, 0, s.length-1);
}
public static <T> void reverse(T[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
T tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static <T> void reverse(T[] s) {
reverse(s, 0, s.length-1);
}
public static void shuffle(int[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
int t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(long[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
long t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(float[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
float t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(double[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
double t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(char[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
char t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static <T> void shuffle(T[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
T t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void sortArray(int[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(long[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(float[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(double[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(char[] a) {
shuffle(a);
Arrays.sort(a);
}
public static <T extends Comparable<T>> void sortArray(T[] a) {
Arrays.sort(a);
}
}
static class Writer {
private PrintWriter pw;
public Writer(){
pw = new PrintWriter(System.out);
}
public Writer(String f){
try {
pw = new PrintWriter(new FileWriter(f));
} catch (IOException e) {
e.printStackTrace();
}
}
public void printArray(int[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
}
public void printlnArray(int[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
pw.println();
}
public void printArray(long[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
}
public void printlnArray(long[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
pw.println();
}
public void print(Object o) {
pw.print(o.toString());
}
public void println(Object o) {
pw.println(o.toString());
}
public void println() {
pw.println();
}
public void flush() {
pw.flush();
}
public void exit() {
pw.close();
}
}
}
| Java | ["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"] | 2 seconds | ["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"] | NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba. | Java 11 | standard input | [
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 79b629047e674883a9bc04b1bf0b7f09 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$. | 2,000 | For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO". | standard output | |
PASSED | 4af8aef13bc6ddb8a40de581896e6936 | train_107.jsonl | 1612535700 | Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m > 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class SolutionD extends Thread {
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;
}
}
private static final FastReader scanner = new FastReader();
private static final PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
int t = scanner.nextInt();
for (int i = 0; i < t; i++) {
solve();
}
out.close();
}
private static void solve() {
int n = scanner.nextInt();
int m = scanner.nextInt();
char[][] adjacencyMatrix = new char[n][n];
for (int i = 0; i < n; i++) {
String s = scanner.next();
adjacencyMatrix[i] = s.toCharArray();
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i != j && adjacencyMatrix[i][j] == adjacencyMatrix[j][i]) {
out.println("YES");
StringBuilder s = new StringBuilder();
int node = i;
for (int k = 0; k <= m; k++) {
s.append(node + 1)
.append(" ");
if (node == i) {
node = j;
} else {
node = i;
}
}
out.println(s);
return;
}
}
}
if (n == 2 && m % 2 == 0) {
out.println("NO");
return;
}
out.println("YES");
if (m % 2 == 1) {
StringBuilder s = new StringBuilder();
int node = 0;
for (int k = 0; k <= m; k++) {
s.append(node + 1)
.append(" ");
node = 1 - node;
}
out.println(s);
return;
}
for (int r = 0; r < n; r++) {
boolean isAOut = false;
boolean isBOut = false;
int aOutTo = -1;
int bOutTo = -1;
for (int c = 0; c < n; c++) {
if (adjacencyMatrix[r][c] == 'a') {
isAOut = true;
aOutTo = c;
} else if (adjacencyMatrix[r][c] == 'b') {
isBOut = true;
bOutTo = c;
}
}
if (isAOut && isBOut) {
StringBuilder s = new StringBuilder();
int node = (m % 4 == 0) ? r : aOutTo;
for (int i = 0; i <= m / 2; i++) {
s.append(node + 1)
.append(" ");
if (node == r) {
node = aOutTo;
} else {
node = r;
}
}
node = bOutTo;
for (int i = 0; i < m / 2; i++) {
s.append(node + 1)
.append(" ");
if (node == r) {
node = bOutTo;
} else {
node = r;
}
}
out.println(s);
return;
}
}
}
//REMINDERS:
//- CHECK FOR INTEGER-OVERFLOW BEFORE SUBMITTING
//- CAN U BRUTEFORCE OVER SOMETHING, TO MAKE IT EASIER TO CALCULATE THE SOLUTION
} | Java | ["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"] | 2 seconds | ["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"] | NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba. | Java 11 | standard input | [
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 79b629047e674883a9bc04b1bf0b7f09 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$. | 2,000 | For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO". | standard output | |
PASSED | a0c165c7f7124a28e4c007e4bfcdae63 | train_107.jsonl | 1612535700 | Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m > 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times. | 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);
DABGraph solver = new DABGraph();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class DABGraph {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int g[][] = new int[n][n];
for (int i = 0; i < n; i++) {
String x = in.next();
for (int j = 0; j < n; j++) {
if (j == i) {
g[i][j] = -1;
} else {
if (x.charAt(j) == 'b') g[i][j] = 1;
}
}
}
if (m == 1) {
out.println("YES");
out.println(1 + " " + 2);
return;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (g[i][j] == g[j][i] && i != j) {
out.println("YES");
for (int k = 0; k < m + 1; k++) {
if (k % 2 == 0) {
out.print((i + 1) + " ");
} else {
out.print((j + 1) + " ");
}
}
out.println();
return;
}
}
}
if (m % 2 == 1) {
out.println("YES");
for (int i = 0; i < m + 1; i++) {
if (i % 2 == 0) {
out.print(1 + " ");
} else {
out.print(2 + " ");
}
}
out.println();
return;
}
if ((m / 2) % 2 == 0) {
for (int i = 0; i < n; i++) {
int zero = -1;
int one = -1;
for (int j = 0; j < n; j++) {
if (g[i][j] == 0) {
zero = j;
} else if (g[i][j] == 1) {
one = j;
}
}
if (one != -1 && zero != -1) {
out.println("YES");
for (int j = 0; j < m / 2 + 1; j++) {
if (j % 2 == 0) {
out.print((i + 1) + " ");
} else {
out.print((one + 1) + " ");
}
}
for (int j = 0; j < m / 2; j++) {
if (j % 2 == 0) {
out.print((zero + 1) + " ");
} else {
out.print((i + 1) + " ");
}
}
out.println();
return;
}
}
out.println("NO");
return;
} else {
for (int i = 0; i < n; i++) {
int zero = -1;
int one = -1;
for (int j = 0; j < n; j++) {
if (g[i][j] == 0) {
zero = j;
} else if (g[i][j] == 1) {
one = j;
}
}
if (one != -1 && zero != -1) {
out.println("YES");
// System.out.println(one + " " + zero + " " + i);
for (int j = 0; j < m / 2 + 1; j++) {
if (j % 2 == 0) {
out.print((one + 1) + " ");
} else {
out.print((i + 1) + " ");
}
}
for (int j = 0; j < m / 2; j++) {
if (j % 2 == 0) {
out.print((zero + 1) + " ");
} else {
out.print((i + 1) + " ");
}
}
out.println();
return;
}
}
out.println("NO");
return;
}
}
}
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 | ["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"] | 2 seconds | ["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"] | NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba. | Java 11 | standard input | [
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 79b629047e674883a9bc04b1bf0b7f09 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$. | 2,000 | For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO". | standard output | |
PASSED | fd3aaf6890856405b137cbc6e3de40f9 | train_107.jsonl | 1612535700 | Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m > 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
import java.util.stream.Stream;
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);
solve(in, out);
out.close();
}
static String reverse(String s) {
return (new StringBuilder(s)).reverse().toString();
}
static void sieveOfEratosthenes(int n, int factors[])
{
factors[1]=1;
for(int p = 2; p*p <=n; p++)
{
if(factors[p] == 0)
{
factors[p]=p;
for(int i = p*p; i <= n; i += p)
factors[i] = p;
}
}
}
static void sort(int ar[]) {
int n = ar.length;
ArrayList<Integer> a = new ArrayList<>();
for (int i = 0; i < n; i++)
a.add(ar[i]);
Collections.sort(a);
for (int i = 0; i < n; i++)
ar[i] = a.get(i);
}
static void sort1(long ar[]) {
int n = ar.length;
ArrayList<Long> a = new ArrayList<>();
for (int i = 0; i < n; i++)
a.add(ar[i]);
Collections.sort(a);
for (int i = 0; i < n; i++)
ar[i] = a.get(i);
}
static long ncr(long n, long r, long mod) {
if (r == 0)
return 1;
long val = ncr(n - 1, r - 1, mod);
val = (n * val) % mod;
val = (val * modInverse(r, mod)) % mod;
return val;
}
public static void solve(InputReader sc, PrintWriter pw) {
int i, j = 0;
// int t = 1;
int t = sc.nextInt();
u: while (t-- > 0) {
int n = sc.nextInt();
int m = sc.nextInt();
int a[][] = new int[n][n];
for(i=0;i<n;i++){
char ch[] = sc.next().toCharArray();
for(j=0;j<n;j++){
if(i==j)
continue;
if(ch[j]=='a'){
a[i][j]=1;
}
else{
a[i][j]=2;
}
}
}
for(i=0;i<n;i++){
for(j=0;j<n;j++){
if(j==i)
continue;
if(a[i][j]==a[j][i]){
pw.println("YES");
for(int k=0;k<m+1;k++){
if(k%2==0)
pw.print((i+1)+" ");
else
pw.print((j+1)+" ");
}
pw.println();
continue u;
}
}
}
if(m%2==1){
pw.println("YES");
for(int k=0;k<m+1;k++){
if(k%2==0)
pw.print(1+" ");
else
pw.print(2+" ");
}
pw.println();
continue u;
}
for(i=0;i<n;i++){
int y1 = 0, y2 = 0, c1 = 0, c2 = 0;
for(j=0;j<n;j++){
if(i==j)
continue;
if(a[i][j]==1){
y1++;
if(y1==1)
c1 = j+1;
}
else{
y2++;
if(y2==1)
c2 = j+1;
}
if(y1>0&&y2>0){
pw.println("YES");
m-=2;
if(m%4==0){
pw.print(c1+" ");
for(int k=0;k<m/4;k++){
pw.print((i+1)+" "+c1+" ");
}
pw.print((i+1)+" "+c2+" ");
for(int k=0;k<m/4;k++){
pw.print((i+1)+" "+c2+" ");
}
pw.println();
continue u;
}
else{
pw.print((i+1)+" ");
pw.print(c1+" ");
for(int k=0;k<m/4;k++){
pw.print((i+1)+" "+c1+" ");
}
pw.print((i+1)+" "+c2+" ");
for(int k=0;k<m/4;k++){
pw.print((i+1)+" "+c2+" ");
}
pw.print((i+1)+" ");
pw.println();
continue u;
}
}
}
}
pw.println("NO");
}
}
static class Pair1 {
long a;
long b;
Pair1(long a, long b) {
this.a = a;
this.b = b;
}
}
static class Pair implements Comparable<Pair> {
int a;
int b;
// int i;
Pair(int a, int b) {
this.a = a;
this.b = b;
// this.i = i;
}
public int compareTo(Pair p) {
if(a!=p.a)
return a-p.a;
return b-p.b;
}
}
static boolean isPrime(long n) {
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static long fast_pow(long base, long n, long M) {
if (n == 0)
return 1;
if (n == 1)
return base % M;
long halfn = fast_pow(base, n / 2, M);
if (n % 2 == 0)
return (halfn * halfn) % M;
else
return (((halfn * halfn) % M) * base) % M;
}
static long modInverse(long n, long M) {
return fast_pow(n, M - 2, M);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"] | 2 seconds | ["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"] | NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba. | Java 11 | standard input | [
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 79b629047e674883a9bc04b1bf0b7f09 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$. | 2,000 | For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO". | standard output | |
PASSED | b19bfad32c241c16e75ec163f1fbf356 | train_107.jsonl | 1612535700 | Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m > 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times. | 256 megabytes | import static java.lang.Math.*;
import java.util.stream.*;
public class D {
public Object solve () {
int N = sc.nextInt(), M = sc.nextInt();
char [][] A = sc.nextChars(N);
int [] res = new int [M+1];
if (M % 2 == 1) {
print("YES");
int [] Z = { 1, 2 };
for (int i : req(M))
res[i] = Z[i%2];
return res;
}
for (int j : rep(N))
for (int i : rep(j))
if (A[i][j] == A[j][i]) {
print ("YES");
int [] Z = { i+1, j+1 };
for (int k : req(M))
res[k] = Z[k%2];
return res;
}
if (N == 2)
return "NO";
for (int i : rep(3))
for (int j : rep(3))
for (int k : rep(3))
if (i != j && j != k && k != i && A[i][j] == A[j][k]) {
print("YES");
if (M % 4 == 0) {
int [] Z = { j+1, k+1, j+1, i+1 };
for (int m : req(M))
res[m] = Z[m%4];
return res;
}
else {
int [] Z = { i+1, j+1, k+1, j+1 };
for (int m : req(M))
res[m] = Z[m%4];
return res;
}
}
throw new Error();
}
private static final int CONTEST_TYPE = 2;
private static void init () {
}
private static int [] rep (int N) { return rep(0, N); }
private static int [] rep (int S, int T) { if (S >= T) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; }
private static int [] req (int N) { return req(0, N); }
private static int [] req (int S, int T) { return rep(S, T+1); }
//////////////////////////////////////////////////////////////////////////////////// OFF
private static IOUtils.MyScanner sc = new IOUtils.MyScanner();
private static Object print (Object o, Object ... A) { IOUtils.print(o, A); return null; }
private static class IOUtils {
public static class MyScanner {
public String next () { newLine(); return line[index++]; }
public int nextInt () { return Integer.parseInt(next()); }
public char [] nextChars () { return next ().toCharArray (); }
public char[][] nextChars (int N) { return IntStream.range(0, N).mapToObj(i -> nextChars()).toArray(char[][]::new); }
//////////////////////////////////////////////
private boolean eol () { return index == line.length; }
private String readLine () {
try {
return r.readLine();
} catch (Exception e) {
throw new Error (e);
}
}
private final java.io.BufferedReader r;
private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); }
private MyScanner (java.io.BufferedReader r) {
try {
this.r = r;
while (!r.ready())
Thread.sleep(1);
start();
} catch (Exception e) {
throw new Error(e);
}
}
private String [] line;
private int index;
private void newLine () {
if (line == null || eol()) {
line = split(readLine());
index = 0;
}
}
private String [] split (String s) { return s.length() > 0 ? s.split(" ") : new String [0]; }
}
private static String build (Object o, Object ... A) { return buildDelim(" ", o, A); }
private static String buildDelim (String delim, Object o, Object ... A) {
StringBuilder b = new StringBuilder();
append(b, o, delim);
for (Object p : A)
append(b, p, delim);
return b.substring(min(b.length(), delim.length()));
}
//////////////////////////////////////////////////////////////////////////////////
private static java.text.DecimalFormat formatter = new java.text.DecimalFormat("#.#########");
private static void start () { if (t == 0) t = millis(); }
private static void append (java.util.function.Consumer<Object> f, java.util.function.Consumer<Object> g, final Object o) {
if (o.getClass().isArray()) {
int len = java.lang.reflect.Array.getLength(o);
for (int i = 0; i < len; ++i)
f.accept(java.lang.reflect.Array.get(o, i));
}
else if (o instanceof Iterable<?>)
((Iterable<?>)o).forEach(f::accept);
else
g.accept(o instanceof Double ? formatter.format(o) : o);
}
private static void append (final StringBuilder b, Object o, final String delim) {
append(x -> { append(b, x, delim); }, x -> b.append(delim).append(x), o);
}
private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out);
private static void print (Object o, Object ... A) {
String res = build(o, A);
if (DEBUG == 2)
err(res, '(', time(), ')');
if (res.length() > 0)
pw.println(res);
if (DEBUG == 1) {
pw.flush();
System.out.flush();
}
}
private static void err (Object o, Object ... A) { System.err.println(build(o, A)); }
private static int DEBUG;
private static void exit () {
String end = "------------------" + System.lineSeparator() + time();
switch(DEBUG) {
case 1: print(end); break;
case 2: err(end); break;
}
IOUtils.pw.close();
System.out.flush();
System.exit(0);
}
private static long t;
private static long millis () { return System.currentTimeMillis(); }
private static String time () { return "Time: " + (millis() - t) / 1000.0; }
private static void run (int N) {
try { DEBUG = Integer.parseInt(System.getProperties().get("DEBUG").toString()); }
catch (Throwable t) {}
for (int n = 1; n <= N; ++n) {
Object res = new D().solve();
if (res != null) {
@SuppressWarnings("all")
Object o = CONTEST_TYPE == 0 ? "Case #" + n + ": " + build(res) : res;
print(o);
}
}
exit();
}
}
////////////////////////////////////////////////////////////////////////////////////
public static void main (String[] args) {
init();
@SuppressWarnings("all")
int N = CONTEST_TYPE == 1 ? 1 : sc.nextInt();
IOUtils.run(N);
}
}
| Java | ["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"] | 2 seconds | ["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"] | NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba. | Java 11 | standard input | [
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 79b629047e674883a9bc04b1bf0b7f09 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$. | 2,000 | For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO". | standard output | |
PASSED | 7e8f1b804cab58480d3fcedc0d2e4e89 | train_107.jsonl | 1612535700 | Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m > 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times. | 256 megabytes | import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
public class Main{
//static long MOD = 1_000_000_007L;
static long MOD = 998_244_353L;
//static long MOD = 1_000_000_033L;
static long inv2 = (MOD + 1) / 2;
static long [] fac;
static long [] pow;
static long [] inv;
static int[][] dir = new int[][]{{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
static long lMax = 0x3f3f3f3f3f3f3f3fL;
static int iMax = 0x3f3f3f3f;
static HashMap <Long, Long> memo = new HashMap();
static MyScanner sc = new MyScanner();
//static ArrayList <Integer> primes;
static long[] pow2;
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
public static void main(String[] args) {
out = new PrintWriter(new BufferedOutputStream(System.out));
// Start writing your solution here. -------------------------------------
int nn = 300000;
/*fac = new long[nn + 1];
fac[1] = 1;
for(int i = 2; i <= nn; i++)
fac[i] = fac[i - 1] * 1L * i % MOD;*/
/*pow = new long[nn + 1];
pow[0] = 1L;
for(int i = 1; i <= nn; i++)
pow[i] = pow[i - 1] * 2L % MOD;
pow[1] = 3L;*/
/*pow2 = new long[nn + 1];
pow2[0] = 1L;
for(int i = 1; i <= nn; i++)
pow2[i] = pow2[i - 1] * 2L % (MOD - 1);*/
/*inv = new long[nn + 1];
inv[1] = 1;
for (int i = 2; i <= nn; ++i)
inv[i] = (MOD - MOD / i) * inv[(int)(MOD % i)] % MOD;*/
//primes = sieveOfEratosthenes(100001);
int t = 1;
t = sc.ni();
while(t-- > 0){
int[] resA = solveA();
if(resA.length == 0) out.println("NO");
else {
out.println("YES");
for (long i : resA)
out.print(i + " ");
out.println();
}
/*
int res = solve();
out.println(res);*/
}
out.close();
}
static int[] solveA() {
/*String s = sc.nextLine();
char[] c = s.toCharArray();
int n = c.length;*/
int n = sc.ni();
int k = sc.ni();
char[][] c = new char[n][n];
for(int i = 0; i < n; i++) {
String tmp = sc.next();
c[i] = tmp.toCharArray();
}
if(k % 2 == 1) {
int res[] = new int[k + 1];
for(int i = 0; i < k + 1; i++) res[i] = (i % 2) + 1;
return res;
}
for(int i = 0; i < n; i++) {
for(int j = i + 1; j < n; j++) {
if(c[i][j] == c[j][i]) {
int res[] = new int[k + 1];
for(int ii = 0; ii < k + 1; ii++) res[ii] = 1 + (ii % 2 == 0 ? i : j);
return res;
}
}
}
if(n == 2) return new int[]{};
int[][] order = new int[][]{ {0, 1, 2}, {0, 2, 1}, {1, 0, 2}, {1, 2, 0}, {2, 1, 0}, {2, 0, 1}};
int ord = -1;
for(int i = 0; i < 6; i++) {
if(c[order[i][0]][order[i][1]] == c[order[i][1]][order[i][2]]
&& c[order[i][1]][order[i][2]] == c[order[i][2]][order[i][0]]) {
int res[] = new int[k + 1];
for(int ii = 0; ii < k + 1; ii++) res[ii] = 1 + order[i][ii % 3];
return res;
}
}
for(int i = 0; i < 6; i++) {
if(c[order[i][0]][order[i][1]] == c[order[i][1]][order[i][2]]
&& c[order[i][1]][order[i][2]] == c[order[i][0]][order[i][2]]) {
int res[] = new int[k + 1];
int A = order[i][0] + 1, B = order[i][1] + 1, C = order[i][2] + 1, mid = k / 2;
for(int ii = mid - 2; ii >= 0; ii -= 2) {
res[ii] = C;
}
for(int ii = mid - 1; ii >= 0; ii -= 2) {
res[ii] = A;
}
for(int ii = mid + 1; ii < k + 1; ii += 2) {
res[ii] = C;
}
for(int ii = mid; ii < k + 1; ii += 2) {
res[ii] = B;
}
return res;
}
}
return new int[]{};
}
static int solve() {
/*String s = sc.nextLine();
char[] c = s.toCharArray();
int n = c.length;*/
int n = sc.ni();
int k = sc.ni();
char[][] c = new char[n][n];
for(int i = 0; i < n; i++) {
String tmp = sc.next();
c[i] = tmp.toCharArray();
}
return 0;
}
// SegmentTree From uwi
public class SegmentTreeRMQ {
public int M, H, N;
public int[] st;
public SegmentTreeRMQ(int n)
{
N = n;
M = Integer.highestOneBit(Math.max(N-1, 1))<<2;
H = M>>>1;
st = new int[M];
Arrays.fill(st, 0, M, Integer.MAX_VALUE);
}
public SegmentTreeRMQ(int[] a)
{
N = a.length;
M = Integer.highestOneBit(Math.max(N-1, 1))<<2;
H = M>>>1;
st = new int[M];
for(int i = 0;i < N;i++){
st[H+i] = a[i];
}
Arrays.fill(st, H+N, M, Integer.MAX_VALUE);
for(int i = H-1;i >= 1;i--)propagate(i);
}
public void update(int pos, int x)
{
st[H+pos] = x;
for(int i = (H+pos)>>>1;i >= 1;i >>>= 1)propagate(i);
}
private void propagate(int i)
{
st[i] = Math.min(st[2*i], st[2*i+1]);
}
public int minx(int l, int r){
int min = Integer.MAX_VALUE;
if(l >= r)return min;
while(l != 0){
int f = l&-l;
if(l+f > r)break;
int v = st[(H+l)/f];
if(v < min)min = v;
l += f;
}
while(l < r){
int f = r&-r;
int v = st[(H+r)/f-1];
if(v < min)min = v;
r -= f;
}
return min;
}
public int min(int l, int r){ return l >= r ? 0 : min(l, r, 0, H, 1);}
private int min(int l, int r, int cl, int cr, int cur)
{
if(l <= cl && cr <= r){
return st[cur];
}else{
int mid = cl+cr>>>1;
int ret = Integer.MAX_VALUE;
if(cl < r && l < mid){
ret = Math.min(ret, min(l, r, cl, mid, 2*cur));
}
if(mid < r && l < cr){
ret = Math.min(ret, min(l, r, mid, cr, 2*cur+1));
}
return ret;
}
}
}
public static double dist(double a, double b){
return Math.sqrt(a * a + b * b);
}
public static long inv(long a){
return quickPOW(a, MOD - 2);
}
public class Interval {
int start;
int end;
public Interval(int start, int end) {
this.start = start;
this.end = end;
}
}
public static ArrayList<Integer> sieveOfEratosthenes(int n) {
boolean prime[] = new boolean[n + 1];
Arrays.fill(prime, true);
for (int p = 2; p * p <= n; p++) {
if (prime[p]) {
for (int i = p * 2; i <= n; i += p) {
prime[i] = false;
}
}
}
ArrayList<Integer> primeNumbers = new ArrayList<>();
for (int i = 2; i <= n; i++) {
if (prime[i]) {
primeNumbers.add(i);
}
}
return primeNumbers;
}
public static int lowerBound(int[] a, int v){ return lowerBound(a, 0, a.length, v); }
public static int lowerBound(int[] a, int l, int r, int v)
{
if(l > r || l < 0 || r > a.length)throw new IllegalArgumentException();
int low = l-1, high = r;
while(high-low > 1){
int h = high+low>>>1;
if(a[h] >= v){
high = h;
}else{
low = h;
}
}
return high;
}
public static int rlowerBound(int[] a, int v){ return lowerBound(a, 0, a.length, v); }
public static int rlowerBound(int[] a, int l, int r, int v)
{
if(l > r || l < 0 || r > a.length)throw new IllegalArgumentException();
int low = l-1, high = r;
while(high-low > 1){
int h = high+low>>>1;
if(a[h] <= v){
high = h;
}else{
low = h;
}
}
return high;
}
public static long C(int n, int m)
{
if(m == 0 || m == n) return 1l;
if(m > n || m < 0) return 0l;
long res = fac[n] * quickPOW((fac[m] * fac[n - m]) % MOD, MOD - 2) % MOD;
return res;
}
public static long quickPOW(long n, long m)
{
long ans = 1l;
while(m > 0)
{
if(m % 2 == 1)
ans = (ans * n) % MOD;
n = (n * n) % MOD;
m >>= 1;
}
return ans;
}
public static long quickPOW(long n, long m, long mod)
{
long ans = 1l;
while(m > 0)
{
if(m % 2 == 1)
ans = (ans * n) % mod;
n = (n * n) % mod;
m >>= 1;
}
return ans;
}
public static int gcd(int a, int b)
{
if(a % b == 0) return b;
return gcd(b, a % b);
}
public static long gcd(long a, long b)
{
if(a % b == 0) return b;
return gcd(b, a % b);
}
static class Randomized {
public static void shuffle(int[] data) {
shuffle(data, 0, data.length - 1);
}
public static void shuffle(int[] data, int from, int to) {
to--;
for (int i = from; i <= to; i++) {
int s = nextInt(i, to);
int tmp = data[i];
data[i] = data[s];
data[s] = tmp;
}
}
public static void shuffle(long[] data) {
shuffle(data, 0, data.length - 1);
}
public static void shuffle(long[] data, int from, int to) {
to--;
for (int i = from; i <= to; i++) {
int s = nextInt(i, to);
long tmp = data[i];
data[i] = data[s];
data[s] = tmp;
}
}
public static int nextInt(int l, int r) {
return RandomWrapper.INSTANCE.nextInt(l, r);
}
}
static class RandomWrapper {
private Random random;
public static final RandomWrapper INSTANCE = new RandomWrapper(new Random());
public RandomWrapper() {
this(new Random());
}
public RandomWrapper(Random random) {
this.random = random;
}
public int nextInt(int l, int r) {
return random.nextInt(r - l + 1) + l;
}
}
//-----------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 ni() {
return Integer.parseInt(next());
}
long nl() {
return Long.parseLong(next());
}
double nd() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//--------------------------------------------------------
} | Java | ["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"] | 2 seconds | ["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"] | NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba. | Java 11 | standard input | [
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 79b629047e674883a9bc04b1bf0b7f09 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$. | 2,000 | For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO". | standard output | |
PASSED | af4fd2462e81f35f3b9829d778039b02 | train_107.jsonl | 1612535700 | Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m > 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times. | 256 megabytes | import java.io.*;
import java.util.*;
public class CF1481D extends PrintWriter {
CF1481D() { super(System.out); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1481D o = new CF1481D(); o.main(); o.flush();
}
void main() {
int[] ii = new int[3];
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int m = sc.nextInt();
byte[][] cc = new byte[n][];
for (int i = 0; i < n; i++)
cc[i] = sc.next().getBytes();
int i_ = -1, j_ = -1;
out:
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (cc[i][j] == cc[j][i]) {
i_ = i;
j_ = j;
break out;
}
if (i_ != -1) {
println("YES");
for (int h = 0; h <= m; h++)
print((h % 2 == 0 ? i_ : j_) + 1 + " ");
println();
} else if (m % 2 == 1) {
println("YES");
for (int h = 0; h <= m; h++)
print(h % 2 + 1 + " ");
println();
} else if (n == 2) {
println("NO");
} else {
println("YES");
i_ = -1;
for (int i = 0; i < 3; i++) {
int j = (i + 1) % 3, k = (i + 2) % 3;
if (cc[i][j] == cc[j][k]) {
i_ = i;
break;
}
}
int i = i_, j = (i + 1) % 3, k = (i + 2) % 3;
for (int h = 0; h <= m; h++)
print((h % 2 == m / 2 % 2 ? j : h < m / 2 ? i : k) + 1 + " ");
println();
}
}
}
}
| Java | ["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"] | 2 seconds | ["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"] | NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba. | Java 11 | standard input | [
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 79b629047e674883a9bc04b1bf0b7f09 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$. | 2,000 | For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO". | standard output | |
PASSED | 9041cd534a9301f9926d8c56920cd388 | train_107.jsonl | 1612535700 | Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m > 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times. | 256 megabytes | import java.io.*;
import java.util.*;
public class ABGraph {
public static void main(String[] args) throws Exception {
FastIO in = new FastIO();
int t = in.nextInt();
for (int tc=0; tc<t; tc++) {
int n = in.nextInt();
int m = in.nextInt();
char[][] edges = new char[n][m];
for (int i=0; i<n; i++) {
edges[i] = in.next().toCharArray();
}
if (m%2==1) {
System.out.println("YES");
for (int i=0; i<(m+1)/2; i++) {
System.out.print(1+" "+2+" ");
}
System.out.println();
}
else {
boolean same = false;
for (int i=0; i<n; i++) {
if (same) break;
for (int j=i+1; j<n; j++) {
if (edges[i][j]==edges[j][i]) {
same = true;
System.out.println("YES");
for (int x=0; x<m/2; x++) {
System.out.print((i+1)+" "+(j+1)+" ");
}
System.out.println(i+1);
break;
}
}
}
if (!same) {
boolean works = false;
for (int i=0; i<n; i++) {
int inA = -1;
int outA = -1;
int inB = -1;
int outB = -1;
for (int j=0; j<n; j++) {
if (j==i) continue;
if (edges[i][j]=='a') outA = j;
else outB = j;
if (edges[j][i]=='a') inA = j;
else inB = j;
}
if (inA>=0 && outA>=0) {
System.out.println("YES");
inA++;
outA++;
i++;
if ((m/2)%2==0) {
for (int j=0; j<m/2; j++) {
if (j%2==0) System.out.print(i+" ");
else System.out.print(inA+" ");
}
System.out.print(i+" ");
for (int j=0; j<m/2; j++) {
if (j%2==0) System.out.print(outA+" ");
else System.out.print(i+" ");
}
System.out.println();
}
else {
// System.out.println("YES");
for (int j=0; j<m+1; j++) {
if (j%2==1) System.out.print(i+" ");
else if (j%4==0) System.out.print(inA+" ");
else System.out.print(outA+" ");
}
System.out.println();
}
works = true;
break;
}
else if (inB>=0 && outB>=0) {
System.out.println("YES");
inB++;
outB++;
i++;
if ((m/2)%2==0) {
for (int j=0; j<m/2; j++) {
if (j%2==0) System.out.print(i+" ");
else System.out.print(inB+" ");
}
System.out.print(i+" ");
for (int j=0; j<m/2; j++) {
if (j%2==0) System.out.print(outB+" ");
else System.out.print(i+" ");
}
System.out.println();
}
else {
for (int j=0; j<m+1; j++) {
if (j%2==1) System.out.print(i+" ");
else if (j%4==0) System.out.print(inB+" ");
else System.out.print(outB+" ");
}
System.out.println();
}
works = true;
break;
}
}
if (!works) System.out.println("NO");
}
}
}
}
static class FastIO {
BufferedReader br;
StringTokenizer st;
PrintWriter pr;
public FastIO() throws IOException
{
br = new BufferedReader(
new InputStreamReader(System.in));
pr = new PrintWriter(System.out);
}
public String next() throws IOException
{
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
public int nextInt() throws NumberFormatException, IOException { return Integer.parseInt(next()); }
public long nextLong() throws NumberFormatException, IOException { return Long.parseLong(next()); }
public double nextDouble() throws NumberFormatException, IOException
{
return Double.parseDouble(next());
}
public String nextLine() throws IOException
{
String str = br.readLine();
return str;
}
}
}
| Java | ["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"] | 2 seconds | ["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"] | NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba. | Java 11 | standard input | [
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 79b629047e674883a9bc04b1bf0b7f09 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$. | 2,000 | For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO". | standard output | |
PASSED | 43c7b95a323032fd2641e3302c0f659b | train_107.jsonl | 1612535700 | Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m > 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times. | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class CFTemplate {
public static void main(String[] args) {
UsefulScanner us = new UsefulScanner();
int cases = us.getInt();
for(int i = 0; i < cases; i++) {
int m = us.getInt();
int n = us.getInt();
char[][] edges = new char[m][m];
for(int j = 0; j < m; j++) {
edges[j] = us.getCharArray();
}
if(m ==2) {
if(n %2 == 1 || edges[0][1] == edges[1][0]) {
yes();
for(int j = 0; j <= n; j++) {
System.out.print( j%2 +1 + " ");
}
System.out.println("");
}
else {
no();
}
}
else {
yes();
if(n %2 == 1) {
for(int j = 0; j <= n; j++) {
System.out.print( j%2 +1 + " ");
}
}
else {
if(edges[0][1] == edges[1][0]) {
for(int j = 0; j <= n; j++) {
System.out.print( j%2 +1 + " ");
}
}
else if(edges[1][2] == edges[2][1]) {
for(int j = 0; j <= n; j++) {
System.out.print( j%2 +2 + " ");
}
}
else if(edges[0][2] == edges[2][0]) {
for(int j = 0; j <= n; j++) {
System.out.print( (j%2)*2 +1 + " ");
}
}
else {
if(edges[0][1] == edges[1][2]) {
if(n%4 == 2) {
for(int j = 0; j < n/2; j++) {
System.out.print(j%2 + 1 + " ");
}
for(int j = n/2; j <= n; j++) {
System.out.print((j+1)%2 + 2 + " ");
}
}
else {
for(int j = 0; j < n/2; j++) {
System.out.print((j+1)%2 + 1 + " ");
}
for(int j = n/2; j <= n; j++) {
System.out.print( (j)%2 + 2 + " ");
}
}
}
else if(edges[1][2] == edges[2][0]) {
if(n%4 == 2) {
for(int j = 0; j < n/2; j++) {
System.out.print(j%2 + 2 + " ");
}
for(int j = n/2; j <= n; j++) {
System.out.print(((j)%2)*2 + 1 + " ");
}
}
else {
for(int j = 0; j < n/2; j++) {
System.out.print((j+1)%2 + 2 + " ");
}
for(int j = n/2; j <= n; j++) {
System.out.print( ((j+1)%2)*2 + 1 + " ");
}
}
}
else if(edges[2][0] == edges[0][1]) {
if(n%4 == 2) {
for(int j = 0; j < n/2; j++) {
System.out.print( ((j+1)%2)*2 + 1 + " ");
}
for(int j = n/2; j <= n; j++) {
System.out.print( (j+1)%2 + 1 + " ");
}
}
else {
for(int j = 0; j < n/2; j++) {
System.out.print((j%2)*2 + 1 + " ");
}
for(int j = n/2; j <= n; j++) {
System.out.print( (j)%2 + 1 + " ");
}
}
}
}
}
System.out.println("");
}
}
}
static void no() {
System.out.println("NO");
}
static void yes() {
System.out.println("YES");
}
}
/*int cases = us.getInt();
for(int i = 0; i < cases; i++) {
int n = us.getInt();
int a = us.getInt();
int b = us.getInt();
int da = us.getInt();
int db = us.getInt();
int[][] edges = new int[n-1][2];
for(int j = 0; j < n-1; j++) {
edges[j][0] = us.getInt();
edges[j][1] = us.getInt();
}
ArrayList<ArrayList<Integer>> eg = new ArrayList<ArrayList<Integer>>();
for(int j = 0; j < n; j++) {
ArrayList<Integer> temp = new ArrayList<Integer>();
eg.add(temp);
}
for(int j = 0; j < n-1; j++) {
eg.get(edges[j][0]).add(edges[j][1]);
eg.get(edges[j][1]).add(edges[j][0]);
}
if(getWidth(eg) <= 2*da) {
System.out.println("ALICE");
}
else if(getDistance(a, b, eg) < da) {
System.out.println("ALICE");
}
else if(db < 2*da + 1) {
System.out.println("ALICE");
}
else {
System.out.println("BOB");
}
}
}
static int getDistance(int a, int b, ArrayList<ArrayList<Integer>> eg) {
int[] change = new int[1];
for(int j = 0; j < eg.get(a).size(); j++) {
if(eg.get(a).get(j) == b) {
return 1;
}
else {
dfs(eg.get(a).get(j), b, eg, a, 1, change, false);
}
}
return change[0];
}
static void dfs(int a, int b, ArrayList<ArrayList<Integer>> eg, int parent, int depth, int[] change, boolean found) {
if(!found) {
for(int j = 0; j < eg.get(a).size(); j++) {
if(eg.get(a).get(j) == b) {
change[0] = depth+1;
found = true;
break;
}
else if(eg.get(a).get(j) != parent) {
dfs(eg.get(a).get(j), b, eg, a, depth + 1, change, found);
}
}
}
}
static int getWidth(ArrayList<ArrayList<Integer>> eg) {
int[] maxvertex = {0};
int[] max = {0};
for(int j = 0; j < eg.get(0).size(); j++) {
dfs2(eg.get(0).get(j), eg, 0, 1, max, maxvertex);
}
for(int j = 0; j < eg.get(maxvertex[0]).size(); j++) {
dfs2(eg.get(maxvertex[0]).get(j), eg, 0, 1, max, maxvertex);
}
return max[0];
}
static void dfs2(int a, ArrayList<ArrayList<Integer>> eg, int parent, int depth, int[] max, int[] maxvertex) {
if(eg.get(a).size() == 1) {
if(depth > max[0]) {
max[0] = depth;
maxvertex[0] = a;
}
}
for(int j = 0; j < eg.get(a).size(); j++) {
if(eg.get(a).get(j) != parent) {
dfs2(eg.get(a).get(j), eg, a, depth + 1, max, maxvertex);
}
}
}
*/
class UsefulScanner{
Scanner sc;
String currentLine = "";
int numLines;
int lineCounter;
public UsefulScanner() {
sc = new Scanner(System.in);
}
ArrayList<Integer> getLineOfIntsList() {
update();
String str = currentLine;
ArrayList<Integer> output = new ArrayList<Integer>();
while(!str.isEmpty()) {
if(str.contains(" ")) {
output.add(Integer.parseInt(str.substring(0, str.indexOf(" "))));
str = str.substring(str.indexOf(" ") + 1, str.length());
}
else {
output.add(Integer.parseInt(str));
str = "";
currentLine = "";
}
}
return output;
}
void update() {
if(currentLine.isEmpty()) {
currentLine = sc.nextLine();
}
}
int getInt() {
update();
if(currentLine.contains(" ")) {
String s = currentLine.substring(0, currentLine.indexOf(" "));
currentLine = currentLine.substring(currentLine.indexOf(" ") + 1, currentLine.length());
return Integer.parseInt(s);
}
int x = Integer.parseInt(currentLine);
currentLine = "";
return x;
}
char[] getCharArray() {
update();
int length = currentLine.length();
char[] output = new char[length];
for(int i = 0; i < length; i++) {
output[i] = currentLine.charAt(i);
}
currentLine = "";
return output;
}
String getLine() {
String s = currentLine;
currentLine = "";
return s;
}
String getBlock() {
update();
if(currentLine.contains(" ")) {
String s = currentLine.substring(0, currentLine.indexOf(" "));
currentLine = currentLine.substring(currentLine.indexOf(" ") + 1, currentLine.length());
return s;
}
String s = currentLine;
currentLine = "";
return s;
}
int[] getIntArray() {
ArrayList<Integer> outputList = getLineOfIntsList();
int[] output = new int[outputList.size()];
for(int i = 0; i < outputList.size(); i++) {
output[i] = outputList.get(i);
}
return output;
}
String nextLine() {
lineCounter++;
if(lineCounter <= numLines) {
return sc.next();
}
else return "";
}
void next() {
currentLine = sc.next();
}
} | Java | ["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"] | 2 seconds | ["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"] | NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba. | Java 11 | standard input | [
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 79b629047e674883a9bc04b1bf0b7f09 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$. | 2,000 | For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO". | standard output | |
PASSED | e80e30a3631db2be73bae4f1c2ce9d6c | train_107.jsonl | 1612535700 | Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m > 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times. | 256 megabytes | import java.io.*;
import java.util.*;
public class Codeforces
{
public static void main(String args[])throws Exception
{
BufferedReader bu=new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb=new StringBuilder();
int t=Integer.parseInt(bu.readLine());
while(t-->0)
{
String s[]=bu.readLine().split(" ");
int n=Integer.parseInt(s[0]),m=Integer.parseInt(s[1]);
int i,j;
char g[][]=new char[n][n];
for(i=0;i<n;i++)
{
String st=bu.readLine();
for(j=0;j<n;j++)
g[i][j]=st.charAt(j);
}
if(m%2==1)
{
sb.append("YES\n");
for(i=0;i<=m;i++)
if(i%2==0) sb.append("1 ");
else sb.append("2 ");
sb.append("\n");
continue;
}
int x=-1,y=-1;
for(i=0;i<n;i++)
for(j=0;j<n && x==-1;j++)
if(i!=j && g[i][j]==g[j][i])
{
x=i+1; y=j+1; break;
}
if(x!=-1)
{
sb.append("YES\n");
for(i=0;i<=m;i++)
if(i%2==0) sb.append(x+" ");
else sb.append(y+" ");
sb.append("\n");
continue;
}
int ans[]=new int[3];
for(i=0;i<n;i++)
{
ArrayList<Integer> a=new ArrayList<>(),b=new ArrayList<>();
for(j=0;j<n;j++)
if(j!=i)
{
if(g[i][j]=='a') a.add(j);
else b.add(j);
}
if(a.size()>0 && b.size()>0)
{
ans[0]=i+1;
ans[1]=a.get(0)+1;
ans[2]=b.get(0)+1;
break;
}
}
if(ans[0]!=0)
{
if(m%4==0)
{
sb.append("YES\n");
int ti=m/2;
for(i=0;i<ti;i++)
if(i%2==0) sb.append(ans[0]+" ");
else sb.append(ans[1]+" ");
sb.append(ans[0]+" ");
for(i=0;i<ti;i++)
if(i%2==0) sb.append(ans[2]+" ");
else sb.append(ans[0]+" ");
sb.append("\n");
}
else
{
int ti=m/2;
sb.append("YES\n");
for(i=0;i<ti;i++)
if(i%2==0) sb.append(ans[1]+" ");
else sb.append(ans[0]+" ");
sb.append(ans[0]+" ");
for(i=0;i<ti;i++)
if(i%2==0) sb.append(ans[2]+" ");
else sb.append(ans[0]+" ");
sb.append("\n");
}
}
else sb.append("NO\n");
}
System.out.print(sb);
}
}
| Java | ["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"] | 2 seconds | ["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"] | NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba. | Java 11 | standard input | [
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 79b629047e674883a9bc04b1bf0b7f09 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$. | 2,000 | For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO". | standard output | |
PASSED | cc90e19313cd31a2d380b213b9ed37f8 | train_107.jsonl | 1612535700 | Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m > 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times. | 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);
DABGraph solver = new DABGraph();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class DABGraph {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt(), m = in.nextInt();
String[] X = new String[n];
for (int i = 0; i < n; i++) X[i] = in.next();
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++) {
if (m % 2 == 1 || (X[i].charAt(j) == X[j].charAt(i))) {
out.println("YES");
for (int k = 0; k <= m; k++) out.print((k % 2 == 0 ? i + 1 : j + 1) + " ");
out.println();
return;
}
}
if (n == 2) {
out.println("NO");
return;
}
for (int i = 0; i < n; i++) {
int u = -1, v = -1;
for (int j = 0; j < n; j++)
if (i != j) {
if (X[i].charAt(j) == 'a') u = j;
else v = j;
}
if (u != -1 && v != -1) {
int[] V = {i, v, i, u};
out.println("YES");
for (int j = 0; j <= m; j++) out.println((V[(j + (m % 4) / 2) % 4] + 1) + " ");
out.println();
return;
}
}
}
}
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) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
writer.print('\n');
}
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 next() {
int c;
while (isSpaceChar(c = this.read())) {
;
}
StringBuilder result = new StringBuilder();
result.appendCodePoint(c);
while (!isSpaceChar(c = this.read())) {
result.appendCodePoint(c);
}
return result.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 | ["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"] | 2 seconds | ["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"] | NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba. | Java 11 | standard input | [
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 79b629047e674883a9bc04b1bf0b7f09 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$. | 2,000 | For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO". | standard output | |
PASSED | b3f99873ccd85178e90cecac2e43c0e2 | train_107.jsonl | 1612535700 | Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m > 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times. | 256 megabytes | import java.util.*;import java.io.*;import java.math.*;
public class Main
{
public static void process()throws IOException
{
int n=ni();
int m=ni();
int[][]adj=new int[n+1][n+1];
for(int i=1;i<=n;i++)
{
String s=nln();
for(int j=1;j<=n;j++)
{
if(j==i)
continue;
else adj[i][j]=s.charAt(j-1)-96;
}
}
if(m%2!=0)
{
pn("YES");
for(int i=0;i<=m;i++)
{
if(i%2==0)
p(1+" ");
else p(2+" ");
}
pn("");
return;
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(adj[i][j]==adj[j][i] && j!=i)
{
pn("YES");
for(int k=0;k<=m;k++)
{
if(k%2==0)
p(i+" ");
else p(j+" ");
}
pn("");
return;
}
}
}
for(int i=1;i<=n;i++)
{
int a=0,b=0;
for(int j=1;j<=n;j++)
{
if(adj[i][j]==1)
a=j;
if(adj[i][j]==2)
b=j;
}
if(a>0 && b>0)
{
pn("YES");
if(m%4==0)
{
for(int j=0;j<=m;j++)
{
if(j%2==0)
p(i+" ");
else
{
if(j<m/2)
p(a+" ");
else p(b+" ");
}
}
}
else
{
for(int j=0;j<=m;j++)
{
if(j%2==1)
p(i+" ");
else
{
if(j<m/2)
p(a+" ");
else p(b+" ");
}
}
}
return;
}
}
pn("NO");
}
static AnotherReader sc;
static PrintWriter out;
public static void main(String[]args)throws IOException
{
boolean oj = System.getProperty("ONLINE_JUDGE") != null;
if(oj){sc=new AnotherReader();out=new PrintWriter(System.out);}
else{sc=new AnotherReader(100);out=new PrintWriter("output.txt");}
int t=1;
t=ni();
while(t-->0) {process();}
out.flush();out.close();
}
static void pn(Object o){out.println(o);}
static void p(Object o){out.print(o);}
static void pni(Object o){out.println(o);out.flush();}
static int ni()throws IOException{return sc.nextInt();}
static long nl()throws IOException{return sc.nextLong();}
static double nd()throws IOException{return sc.nextDouble();}
static String nln()throws IOException{return sc.nextLine();}
static int[] nai(int N)throws IOException{int[]A=new int[N];for(int i=0;i!=N;i++){A[i]=ni();}return A;}
static long[] nal(int N)throws IOException{long[]A=new long[N];for(int i=0;i!=N;i++){A[i]=nl();}return A;}
static long gcd(long a, long b)throws IOException{return (b==0)?a:gcd(b,a%b);}
static int gcd(int a, int b)throws IOException{return (b==0)?a:gcd(b,a%b);}
static int bit(long n)throws IOException{return (n==0)?0:(1+bit(n&(n-1)));}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
static class AnotherReader{BufferedReader br; StringTokenizer st;
AnotherReader()throws FileNotFoundException{
br=new BufferedReader(new InputStreamReader(System.in));}
AnotherReader(int a)throws FileNotFoundException{
br = new BufferedReader(new FileReader("input.txt"));}
String next()throws IOException{
while (st == null || !st.hasMoreElements()) {try{
st = new StringTokenizer(br.readLine());}
catch (IOException e){ e.printStackTrace(); }}
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{ String str = ""; try{
str = br.readLine();} catch (IOException e){
e.printStackTrace();} return str;}}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
} | Java | ["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"] | 2 seconds | ["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"] | NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba. | Java 11 | standard input | [
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 79b629047e674883a9bc04b1bf0b7f09 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$. | 2,000 | For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO". | standard output | |
PASSED | dd1c51d428ba08e9796e4511e4568ccc | train_107.jsonl | 1612535700 | Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. You are given a complete directed graph with $$$n$$$ vertices without self-loops. In other words, you have $$$n$$$ vertices and each pair of vertices $$$u$$$ and $$$v$$$ ($$$u \neq v$$$) has both directed edges $$$(u, v)$$$ and $$$(v, u)$$$.Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges $$$(u, v)$$$ and $$$(v, u)$$$ may have different labels).You are also given an integer $$$m > 0$$$. You should find a path of length $$$m$$$ such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it.You can visit the same vertex and the same directed edge any number of times. | 256 megabytes | //package round699;
import java.io.*;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Queue;
public class D {
InputStream is;
FastWriter out;
String INPUT = "";
void solve()
{
for(int T = ni();T > 0;T--)go();
}
void go()
{
int n = ni(), m = ni();
char[][] g = nm(n,n);
for(int i = 0;i < n;i++){
for(int j = i+1;j < n;j++){
if(g[i][j] == g[j][i]){
out.println("YES");
for(int k = 0;k < m+1;k++){
out.print((k % 2 == 0 ? (i+1) : j+1) + " ");
}
out.println();
return;
}
}
}
if(m % 2 == 1){
out.println("YES");
for(int k = 0;k < m+1;k++){
out.print((k % 2 == 0 ? 1 : 2) + " ");
}
out.println();
return;
}
for(int i = 0;i < n;i++){
int aa = -1, bb = -1;
for(int j = 0;j < n;j++){
if(g[i][j] == 'a')aa = j;
if(g[i][j] == 'b')bb = j;
}
if(aa != -1 && bb != -1){
out.println("YES");
for(int k = 0;k < m/2;k++){
out.print(((m/2-k) % 2 == 0 ? (i+1) : (aa+1)) + " ");
}
out.print(i+1 + " ");
for(int k = 0;k < m/2;k++){
out.print(((k) % 2 == 0 ? (bb+1) : (i+1)) + " " );
}
out.println();
return;
}
}
out.println("NO");
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new FastWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new D().run(); }
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 int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private long[] nal(int n)
{
long[] a = new long[n];
for(int i = 0;i < n;i++)a[i] = nl();
return a;
}
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[][] nmi(int n, int m) {
int[][] map = new int[n][];
for(int i = 0;i < n;i++)map[i] = na(m);
return map;
}
private int ni() { return (int)nl(); }
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();
}
}
public static class FastWriter
{
private static final int BUF_SIZE = 1<<13;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastWriter(){out = null;}
public FastWriter(OutputStream os)
{
this.out = os;
}
public FastWriter(String path)
{
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastWriter write(byte b)
{
buf[ptr++] = b;
if(ptr == BUF_SIZE)innerflush();
return this;
}
public FastWriter write(char c)
{
return write((byte)c);
}
public FastWriter write(char[] s)
{
for(char c : s){
buf[ptr++] = (byte)c;
if(ptr == BUF_SIZE)innerflush();
}
return this;
}
public FastWriter write(String s)
{
s.chars().forEach(c -> {
buf[ptr++] = (byte)c;
if(ptr == BUF_SIZE)innerflush();
});
return this;
}
private static int countDigits(int l) {
if (l >= 1000000000) return 10;
if (l >= 100000000) return 9;
if (l >= 10000000) return 8;
if (l >= 1000000) return 7;
if (l >= 100000) return 6;
if (l >= 10000) return 5;
if (l >= 1000) return 4;
if (l >= 100) return 3;
if (l >= 10) return 2;
return 1;
}
public FastWriter write(int x)
{
if(x == Integer.MIN_VALUE){
return write((long)x);
}
if(ptr + 12 >= BUF_SIZE)innerflush();
if(x < 0){
write((byte)'-');
x = -x;
}
int d = countDigits(x);
for(int i = ptr + d - 1;i >= ptr;i--){
buf[i] = (byte)('0'+x%10);
x /= 10;
}
ptr += d;
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L) return 19;
if (l >= 100000000000000000L) return 18;
if (l >= 10000000000000000L) return 17;
if (l >= 1000000000000000L) return 16;
if (l >= 100000000000000L) return 15;
if (l >= 10000000000000L) return 14;
if (l >= 1000000000000L) return 13;
if (l >= 100000000000L) return 12;
if (l >= 10000000000L) return 11;
if (l >= 1000000000L) return 10;
if (l >= 100000000L) return 9;
if (l >= 10000000L) return 8;
if (l >= 1000000L) return 7;
if (l >= 100000L) return 6;
if (l >= 10000L) return 5;
if (l >= 1000L) return 4;
if (l >= 100L) return 3;
if (l >= 10L) return 2;
return 1;
}
public FastWriter write(long x)
{
if(x == Long.MIN_VALUE){
return write("" + x);
}
if(ptr + 21 >= BUF_SIZE)innerflush();
if(x < 0){
write((byte)'-');
x = -x;
}
int d = countDigits(x);
for(int i = ptr + d - 1;i >= ptr;i--){
buf[i] = (byte)('0'+x%10);
x /= 10;
}
ptr += d;
return this;
}
public FastWriter write(double x, int precision)
{
if(x < 0){
write('-');
x = -x;
}
x += Math.pow(10, -precision)/2;
// if(x < 0){ x = 0; }
write((long)x).write(".");
x -= (long)x;
for(int i = 0;i < precision;i++){
x *= 10;
write((char)('0'+(int)x));
x -= (int)x;
}
return this;
}
public FastWriter writeln(char c){
return write(c).writeln();
}
public FastWriter writeln(int x){
return write(x).writeln();
}
public FastWriter writeln(long x){
return write(x).writeln();
}
public FastWriter writeln(double x, int precision){
return write(x, precision).writeln();
}
public FastWriter write(int... xs)
{
boolean first = true;
for(int x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter write(long... xs)
{
boolean first = true;
for(long x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter writeln()
{
return write((byte)'\n');
}
public FastWriter writeln(int... xs)
{
return write(xs).writeln();
}
public FastWriter writeln(long... xs)
{
return write(xs).writeln();
}
public FastWriter writeln(char[] line)
{
return write(line).writeln();
}
public FastWriter writeln(char[]... map)
{
for(char[] line : map)write(line).writeln();
return this;
}
public FastWriter writeln(String s)
{
return write(s).writeln();
}
private void innerflush()
{
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush()
{
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
public FastWriter print(byte b) { return write(b); }
public FastWriter print(char c) { return write(c); }
public FastWriter print(char[] s) { return write(s); }
public FastWriter print(String s) { return write(s); }
public FastWriter print(int x) { return write(x); }
public FastWriter print(long x) { return write(x); }
public FastWriter print(double x, int precision) { return write(x, precision); }
public FastWriter println(char c){ return writeln(c); }
public FastWriter println(int x){ return writeln(x); }
public FastWriter println(long x){ return writeln(x); }
public FastWriter println(double x, int precision){ return writeln(x, precision); }
public FastWriter print(int... xs) { return write(xs); }
public FastWriter print(long... xs) { return write(xs); }
public FastWriter println(int... xs) { return writeln(xs); }
public FastWriter println(long... xs) { return writeln(xs); }
public FastWriter println(char[] line) { return writeln(line); }
public FastWriter println(char[]... map) { return writeln(map); }
public FastWriter println(String s) { return writeln(s); }
public FastWriter println() { return writeln(); }
}
public void trnz(int... o)
{
for(int i = 0;i < o.length;i++)if(o[i] != 0)System.out.print(i+":"+o[i]+" ");
System.out.println();
}
// print ids which are 1
public void trt(long... o)
{
Queue<Integer> stands = new ArrayDeque<>();
for(int i = 0;i < o.length;i++){
for(long x = o[i];x != 0;x &= x-1)stands.add(i<<6|Long.numberOfTrailingZeros(x));
}
System.out.println(stands);
}
public void tf(boolean... r)
{
for(boolean x : r)System.out.print(x?'#':'.');
System.out.println();
}
public void tf(boolean[]... b)
{
for(boolean[] r : b) {
for(boolean x : r)System.out.print(x?'#':'.');
System.out.println();
}
System.out.println();
}
public void tf(long[]... b)
{
if(INPUT.length() != 0) {
for (long[] r : b) {
for (long x : r) {
for (int i = 0; i < 64; i++) {
System.out.print(x << ~i < 0 ? '#' : '.');
}
}
System.out.println();
}
System.out.println();
}
}
public void tf(long... b)
{
if(INPUT.length() != 0) {
for (long x : b) {
for (int i = 0; i < 64; i++) {
System.out.print(x << ~i < 0 ? '#' : '.');
}
}
System.out.println();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| Java | ["5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*"] | 2 seconds | ["YES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO"] | NoteThe graph from the first three test cases is shown below: In the first test case, the answer sequence is $$$[1,2]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is b.In the second test case, the answer sequence is $$$[2,1,3,2]$$$ which means that the path is:$$$$$$2 \xrightarrow{\text{b}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{b}} 2$$$$$$So the string that is obtained by the given path is bab.In the third test case, the answer sequence is $$$[1,3,1,3,1]$$$ which means that the path is:$$$$$$1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1 \xrightarrow{\text{a}} 3 \xrightarrow{\text{a}} 1$$$$$$So the string that is obtained by the given path is aaaa.The string obtained in the fourth test case is abaaba. | Java 11 | standard input | [
"brute force",
"constructive algorithms",
"graphs",
"greedy",
"implementation"
] | 79b629047e674883a9bc04b1bf0b7f09 | The first line contains a single integer $$$t$$$ ($$$1 \le t \le 500$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$2 \leq n \leq 1000$$$; $$$1 \leq m \leq 10^{5}$$$) — the number of vertices in the graph and desirable length of the palindrome. Each of the next $$$n$$$ lines contains $$$n$$$ characters. The $$$j$$$-th character of the $$$i$$$-th line describes the character on the edge that is going from node $$$i$$$ to node $$$j$$$. Every character is either 'a' or 'b' if $$$i \neq j$$$, or '*' if $$$i = j$$$, since the graph doesn't contain self-loops. It's guaranteed that the sum of $$$n$$$ over test cases doesn't exceed $$$1000$$$ and the sum of $$$m$$$ doesn't exceed $$$10^5$$$. | 2,000 | For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of $$$m + 1$$$ integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO". | standard output | |
PASSED | d07ace8e57f64562a6ef225829826f01 | train_107.jsonl | 1612535700 | Kilani and Abd are neighbors for 3000 years, but then the day came and Kilani decided to move to another house. As a farewell gift, Kilani is going to challenge Abd with a problem written by their other neighbor with the same name Abd. The problem is:You are given a connected tree rooted at node $$$1$$$.You should assign a character a or b to every node in the tree so that the total number of a's is equal to $$$x$$$ and the total number of b's is equal to $$$n - x$$$.Let's define a string for each node $$$v$$$ of the tree as follows: if $$$v$$$ is root then the string is just one character assigned to $$$v$$$: otherwise, let's take a string defined for the $$$v$$$'s parent $$$p_v$$$ and add to the end of it a character assigned to $$$v$$$. You should assign every node a character in a way that minimizes the number of distinct strings among the strings of all nodes. | 256 megabytes | import java.io.*;
import java.util.*;
/*
polyakoff
*/
public class Main {
static FastReader in;
static PrintWriter out;
static Random rand = new Random();
static final int oo = (int) 1e9 + 10;
static final long OO = (long) 2e18 + 10;
static final int MOD = (int) 1e9 + 7;
static ArrayList<Integer>[] g;
static ArrayList<Integer>[] level;
static void dfs(int v, int depth) {
level[depth].add(v);
for (int u : g[v]) {
dfs(u, depth + 1);
}
}
static void solve() {
int n = in.nextInt();
int x = in.nextInt();
g = new ArrayList[n]; Arrays.setAll(g, i -> new ArrayList<>());
for (int i = 1; i < n; i++) {
int p = in.nextInt() - 1;
g[p].add(i);
}
if (n == 1) {
out.println(1);
out.println(x == 1 ? 'a' : 'b');
return;
}
level = new ArrayList[n]; Arrays.setAll(level, i -> new ArrayList<>());
dfs(0, 0);
int[] cnt = new int[n];
for (ArrayList<Integer> l : level) {
cnt[l.size()]++;
}
int nLevels = n - cnt[0];
int[] dp = new int[x + 1];
int[] dp2 = new int[x + 1];
int[] last = new int[n];
int[][] memo = new int[n][];
int lasti = -1;
for (int i = 1; i < n; i++) {
if (cnt[i] == 0)
continue;
last[i] = lasti;
memo[i] = new int[x + 1];
if (lasti == -1) {
for (int j = 0; j <= x; j++) {
if (j % i == 0 && j / i <= cnt[i])
dp[j] = 0;
else
dp[j] = -1;
memo[i][j] = 0;
}
} else {
System.arraycopy(dp, 0, dp2, 0, x + 1);
for (int j = 0; j <= x; j++) {
dp[j] = -1;
if (dp2[j] != -1) {
dp[j] = 0;
memo[i][j] = j;
} else if (j >= i && dp[j - i] != -1 && dp[j - i] < cnt[i]) {
dp[j] = dp[j - i] + 1;
memo[i][j] = j - dp[j] * i;
}
}
}
lasti = i;
}
if (dp[x] != -1) {
out.println(nLevels);
int[] withA = new int[n];
int i = lasti;
int j = x;
while (i != -1) {
int i2 = last[i];
int j2 = memo[i][j];
withA[i] = (j - j2) / i;
i = i2;
j = j2;
}
char[] ans = new char[n]; Arrays.fill(ans, 'b');
for (ArrayList<Integer> l : level) {
if (withA[l.size()] > 0) {
withA[l.size()]--;
for (int v : l) {
ans[v] = 'a';
}
}
}
for (int v = 0; v < n; v++) {
out.print(ans[v]);
}
out.println();
return;
}
out.println(nLevels + 1);
char[] ans = new char[n];
int m = n, y = x;
for (ArrayList<Integer> l : level) {
if (l.size() <= y) {
for (int v : l) {
ans[v] = 'a';
}
y -= l.size();
} else if (l.size() <= m - y) {
for (int v : l) {
ans[v] = 'b';
}
} else {
boolean a = y >= m - y;
int z = a ? y : m - y;
for (int v : l) {
if (g[v].size() > 0) {
ans[v] = a ? 'a' : 'b';
z--;
}
}
for (int v : l) {
if (g[v].size() == 0) {
if (z > 0) {
z--;
ans[v] = a ? 'a' : 'b';
} else
ans[v] = a ? 'b' : 'a';
}
}
if (a)
y = 0;
}
m -= l.size();
}
for (int v = 0; v < n; v++) {
out.print(ans[v]);
}
out.println();
}
public static void main(String[] args) {
in = new FastReader();
out = new PrintWriter(System.out);
int T = 1;
// T = in.nextInt();
while (T-- > 0)
solve();
out.flush();
out.close();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
FastReader() {
this(System.in);
}
FastReader(String file) throws FileNotFoundException {
this(new FileInputStream(file));
}
FastReader(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
int 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 line;
try {
line = br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return line;
}
}
} | Java | ["9 3\n1 2 2 4 4 4 3 1"] | 2 seconds | ["4\naabbbbbba"] | NoteThe tree from the sample is shown below: The tree after assigning characters to every node (according to the output) is the following: Strings for all nodes are the following: string of node $$$1$$$ is: a string of node $$$2$$$ is: aa string of node $$$3$$$ is: aab string of node $$$4$$$ is: aab string of node $$$5$$$ is: aabb string of node $$$6$$$ is: aabb string of node $$$7$$$ is: aabb string of node $$$8$$$ is: aabb string of node $$$9$$$ is: aa The set of unique strings is $$$\{\text{a}, \text{aa}, \text{aab}, \text{aabb}\}$$$, so the number of distinct strings is $$$4$$$. | Java 8 | standard input | [
"dp",
"greedy",
"trees"
] | 3ffb3a2ae3e96fc26d539c9676389ae5 | The first line contains two integers $$$n$$$ and $$$x$$$ ($$$1 \leq n \leq 10^5$$$; $$$0 \leq x \leq n$$$) — the number of vertices in the tree the number of a's. The second line contains $$$n - 1$$$ integers $$$p_2, p_3, \dots, p_{n}$$$ ($$$1 \leq p_i \leq n$$$; $$$p_i \neq i$$$), where $$$p_i$$$ is the parent of node $$$i$$$. It is guaranteed that the input describes a connected tree. | 3,100 | In the first line, print the minimum possible total number of distinct strings. In the second line, print $$$n$$$ characters, where all characters are either a or b and the $$$i$$$-th character is the character assigned to the $$$i$$$-th node. Make sure that the total number of a's is equal to $$$x$$$ and the total number of b's is equal to $$$n - x$$$. If there is more than one answer you can print any of them. | standard output | |
PASSED | 5a8cc75da1778ef67a4bd75d3c671dbc | train_107.jsonl | 1630247700 | William is not only interested in trading but also in betting on sports matches. $$$n$$$ teams participate in each match. Each team is characterized by strength $$$a_i$$$. Each two teams $$$i < j$$$ play with each other exactly once. Team $$$i$$$ wins with probability $$$\frac{a_i}{a_i + a_j}$$$ and team $$$j$$$ wins with probability $$$\frac{a_j}{a_i + a_j}$$$.The team is called a winner if it directly or indirectly defeated all other teams. Team $$$a$$$ defeated (directly or indirectly) team $$$b$$$ if there is a sequence of teams $$$c_1$$$, $$$c_2$$$, ... $$$c_k$$$ such that $$$c_1 = a$$$, $$$c_k = b$$$ and team $$$c_i$$$ defeated team $$$c_{i + 1}$$$ for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$. Note that it is possible that team $$$a$$$ defeated team $$$b$$$ and in the same time team $$$b$$$ defeated team $$$a$$$.William wants you to find the expected value of the number of winners. | 256 megabytes | import java.util.*;
import java.util.function.*;
import java.io.*;
// you can compare with output.txt and expected out
public class RoundDeltix2021F {
MyPrintWriter out;
MyScanner in;
// final static long FIXED_RANDOM;
// static {
// FIXED_RANDOM = System.currentTimeMillis();
// }
final static String IMPOSSIBLE = "IMPOSSIBLE";
final static String POSSIBLE = "POSSIBLE";
final static String YES = "YES";
final static String NO = "NO";
private void initIO(boolean isFileIO) {
if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) {
try{
in = new MyScanner(new FileInputStream("input.txt"));
out = new MyPrintWriter(new FileOutputStream("output.txt"));
}
catch(FileNotFoundException e){
e.printStackTrace();
}
}
else{
in = new MyScanner(System.in);
out = new MyPrintWriter(new BufferedOutputStream(System.out));
}
}
public static void main(String[] args){
// Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
// the code for the deep recursion (more than 100k or 3~400k or so)
// Thread t = new Thread(null, new RoundEdu130F(), "threadName", 1<<28);
// t.start();
// t.join();
RoundDeltix2021F sol = new RoundDeltix2021F();
sol.run();
}
private void run() {
boolean isDebug = false;
boolean isFileIO = true;
boolean hasMultipleTests = false;
initIO(isFileIO);
int t = hasMultipleTests? in.nextInt() : 1;
for (int i = 1; i <= t; ++i) {
if(isDebug){
out.printf("Test %d\n", i);
}
getInput();
solve();
printOutput();
}
in.close();
out.close();
}
// use suitable one between matrix(2, n), matrix(n, 2), transposedMatrix(2, n) for graph edges, pairs, ...
int n;
int[] a;
void getInput() {
n = in.nextInt();
a = in.nextIntArray(n);
}
void printOutput() {
out.printlnAns(ans);
}
final long MOD = 1_000_000_007;
long ans;
void solve(){
// suppose a is a winner
// if b won a, then b must be also a winner
// if a chain a -> x -> y -> ... z didn't contain b, then we can prepend b
// if the chain did contain b, we can start there
// hence if a is a sole winner, then a must have won all others, and that's also a sufficient condition
// similarly, if a and b are winners, then they must won all the others
// but this is not enough
// what about connections between winners?
// they should form an scc
// strongly connected tournament -> hamiltonian
// but multiple hamiltonian paths can exist
// if there is a subset X of winners that win each of winners not in X
// then not scc
// looks like this is a sufficient condition as well
// 1 hour until here
// 1 more hour to fill the small details in the idea and the implementation
long[][] winP = new long[n][n];
for(int i=0; i<n; i++)
for(int j=0; j<n; j++) {
if(i != j)
winP[i][j] = a[i] * inverse(a[i] + a[j], MOD) % MOD;
}
long[][] pre = new long[n][1<<n];
for(int i=0; i<n; i++) {
pre[i][0] = 1;
for(int mask=1; mask<(1<<n); mask++) {
pre[i][mask] = pre[i][mask-(mask&-mask)];
pre[i][mask] *= winP[i][Integer.numberOfTrailingZeros(mask)];
pre[i][mask] %= MOD;
}
}
long[] probs2 = new long[1<<n];
// probs2[mask] = the probability that the mask forms winners
// 3
// 1 1 1
// 0->1, 0->2, 1->2: 1
// 0->1, 0->2, 2->1: 1
// 0->1, 2->0, 1->2: 3
// 0->1, 2->0, 2->1: 1
// ...
// 6/8 + 6/8 = 12/8
ans = 0;
for(int mask=0; mask<(1<<n); mask++) {
long prob = 1;
int cnt = 0;
int to = ((1<<n)-1) ^ mask;
int curr = mask;
while(curr > 0) {
int i = Integer.numberOfTrailingZeros(curr);
prob = prob * pre[i][to] % MOD;
curr -= 1<<i;
}
// for(int i=0; i<n; i++) {
// for(int j=0; j<n; j++) {
// if((mask & (1<<i)) > 0 && (mask & (1<<j)) == 0) {
// prob = prob * winP[i][j] % MOD;
// }
// }
// if((mask & (1<<i)) > 0)
// cnt++;
// }
int k = Integer.bitCount(mask);
long prob2 = 1;
for(int submask=(mask-1)&mask; submask>0; submask=(submask-1)&mask) {
to = submask ^ mask;
long p = 1;
curr = submask;
while(curr > 0) {
int i = Integer.numberOfTrailingZeros(curr);
p = p * pre[i][to] % MOD;
curr -= 1<<i;
}
prob2 -= probs2[submask] * p % MOD;
}
// int[] index = new int[cnt];
// for(int i=0; i<n; i++)
// if((mask & (1<<i)) > 0)
// index[--cnt] = i;
// int k = index.length;
// long prob2 = 1;
// for(int submask=1; submask<(1<<k)-1; submask++) {
// long curr = 1;
// for(int i=0; i<k; i++) {
// for(int j=0; j<k; j++) {
// if((submask & (1<<i)) > 0 && (submask & (1<<j)) == 0) {
// curr = curr * winP[index[i]][index[j]] % MOD;
// }
// }
// }
// int sub = 0;
// for(int i=0; i<k; i++)
// if((submask & (1<<i)) > 0)
// sub |= 1<<index[i];
// prob2 -= probs2[sub] * curr % MOD;
// }
prob2 %= MOD;
prob2 += MOD;
prob2 %= MOD;
probs2[mask] = prob2;
prob = prob * prob2 % MOD;
ans += prob * k;
}
ans %= MOD;
}
static long pow(long a, int k, long p) {
long m = k;
long ans = 1;
// curr = k^(2^i)
long curr = a;
// k^(2x+1) = (k^x)^2 * k
while(m > 0) {
if( (m&1) == 1 ) {
ans *= curr;
ans %= p;
}
m >>= 1;
curr *= curr;
curr %= p;
}
return ans;
}
// computes a^(p-2)
static long inverse(int a, long p) {
return pow(a, (int)(p-2), p);
}
// Optional<T> solve()
// return Optional.empty();
static class Pair implements Comparable<Pair>{
final static long FIXED_RANDOM = System.currentTimeMillis();
int first, second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
@Override
public int hashCode() {
// http://xorshift.di.unimi.it/splitmix64.c
long x = first;
x <<= 32;
x += second;
x += FIXED_RANDOM;
x += 0x9e3779b97f4a7c15l;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9l;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebl;
return (int)(x ^ (x >> 31));
}
@Override
public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
Pair other = (Pair) obj;
return first == other.first && second == other.second;
}
@Override
public String toString() {
return "[" + first + "," + second + "]";
}
@Override
public int compareTo(Pair o) {
int cmp = Integer.compare(first, o.first);
return cmp != 0? cmp: Integer.compare(second, o.second);
}
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
// 32768?
public MyScanner(InputStream is, int bufferSize) {
br = new BufferedReader(new InputStreamReader(is), bufferSize);
}
public MyScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
// br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
}
public void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[][] nextMatrix(int n, int m) {
return nextMatrix(n, m, 0);
}
int[][] nextMatrix(int n, int m, int offset) {
int[][] mat = new int[n][m];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
mat[i][j] = nextInt()+offset;
}
}
return mat;
}
int[][] nextTransposedMatrix(int n, int m){
return nextTransposedMatrix(n, m, 0);
}
int[][] nextTransposedMatrix(int n, int m, int offset){
int[][] mat = new int[m][n];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
mat[j][i] = nextInt()+offset;
}
}
return mat;
}
int[] nextIntArray(int len) {
return nextIntArray(len, 0);
}
int[] nextIntArray(int len, int offset){
int[] a = new int[len];
for(int j=0; j<len; j++)
a[j] = nextInt()+offset;
return a;
}
long[] nextLongArray(int len) {
return nextLongArray(len, 0);
}
long[] nextLongArray(int len, int offset){
long[] a = new long[len];
for(int j=0; j<len; j++)
a[j] = nextLong()+offset;
return a;
}
String[] nextStringArray(int len) {
String[] s = new String[len];
for(int i=0; i<len; i++)
s[i] = next();
return s;
}
}
public static class MyPrintWriter extends PrintWriter{
public MyPrintWriter(OutputStream os) {
super(os);
}
// public <T> void printlnAns(Optional<T> ans) {
// if(ans.isEmpty())
// println(-1);
// else
// printlnAns(ans.get());
// }
public void printlnAns(OptionalInt ans) {
println(ans.orElse(-1));
}
public void printlnAns(long ans) {
println(ans);
}
public void printlnAns(int ans) {
println(ans);
}
public void printlnAns(boolean[] ans) {
for(boolean b: ans)
printlnAns(b);
}
public void printlnAns(boolean ans) {
if(ans)
println(YES);
else
println(NO);
}
public void printAns(long[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(long[] arr){
printAns(arr);
println();
}
public void printAns(int[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(int[] arr){
printAns(arr);
println();
}
public <T> void printAns(ArrayList<T> arr){
if(arr != null && arr.size() > 0){
print(arr.get(0));
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i));
}
}
}
public <T> void printlnAns(ArrayList<T> arr){
printAns(arr);
println();
}
public void printAns(int[] arr, int add){
if(arr != null && arr.length > 0){
print(arr[0]+add);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]+add);
}
}
}
public void printlnAns(int[] arr, int add){
printAns(arr, add);
println();
}
public void printAns(ArrayList<Integer> arr, int add) {
if(arr != null && arr.size() > 0){
print(arr.get(0)+add);
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i)+add);
}
}
}
public void printlnAns(ArrayList<Integer> arr, int add){
printAns(arr, add);
println();
}
public void printlnAnsSplit(long[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public void printlnAnsSplit(int[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public <T> void printlnAnsSplit(ArrayList<T> arr, int split){
if(arr != null && !arr.isEmpty()){
for(int i=0; i<arr.size(); i+=split){
print(arr.get(i));
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr.get(j));
}
println();
}
}
}
}
static private void permutateAndSort(long[] a) {
int n = a.length;
Random R = new Random(System.currentTimeMillis());
for(int i=0; i<n; i++) {
int t = R.nextInt(n-i);
long temp = a[n-1-i];
a[n-1-i] = a[t];
a[t] = temp;
}
Arrays.sort(a);
}
static private void permutateAndSort(int[] a) {
int n = a.length;
Random R = new Random(System.currentTimeMillis());
for(int i=0; i<n; i++) {
int t = R.nextInt(n-i);
int temp = a[n-1-i];
a[n-1-i] = a[t];
a[t] = temp;
}
Arrays.sort(a);
}
static private int[][] constructChildren(int n, int[] parent, int parentRoot){
int[][] childrens = new int[n][];
int[] numChildren = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
numChildren[parent[i]]++;
}
for(int i=0; i<n; i++) {
childrens[i] = new int[numChildren[i]];
}
int[] idx = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
childrens[parent[i]][idx[parent[i]]++] = i;
}
return childrens;
}
static private int[][][] constructDirectedNeighborhood(int n, int[][] e){
int[] inDegree = new int[n];
int[] outDegree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outDegree[u]++;
inDegree[v]++;
}
int[][] inNeighbors = new int[n][];
int[][] outNeighbors = new int[n][];
for(int i=0; i<n; i++) {
inNeighbors[i] = new int[inDegree[i]];
outNeighbors[i] = new int[outDegree[i]];
}
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outNeighbors[u][--outDegree[u]] = v;
inNeighbors[v][--inDegree[v]] = u;
}
return new int[][][] {inNeighbors, outNeighbors};
}
static private int[][] constructNeighborhood(int n, int[][] e) {
int[] degree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
degree[u]++;
degree[v]++;
}
int[][] neighbors = new int[n][];
for(int i=0; i<n; i++)
neighbors[i] = new int[degree[i]];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
neighbors[u][--degree[u]] = v;
neighbors[v][--degree[v]] = u;
}
return neighbors;
}
static private void drawGraph(int[][] e) {
makeDotUndirected(e);
try {
final Process process = new ProcessBuilder("dot", "-Tpng", "graph.dot")
.redirectOutput(new File("graph.png"))
.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
static private void makeDotUndirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict graph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "--" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
static private void makeDotDirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict digraph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "->" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
}
| Java | ["2\n1 2", "5\n1 5 2 11 14"] | 4 seconds | ["1", "642377629"] | NoteTo better understand in which situation several winners are possible let's examine the second test:One possible result of the tournament is as follows ($$$a \rightarrow b$$$ means that $$$a$$$ defeated $$$b$$$): $$$1 \rightarrow 2$$$ $$$2 \rightarrow 3$$$ $$$3 \rightarrow 1$$$ $$$1 \rightarrow 4$$$ $$$1 \rightarrow 5$$$ $$$2 \rightarrow 4$$$ $$$2 \rightarrow 5$$$ $$$3 \rightarrow 4$$$ $$$3 \rightarrow 5$$$ $$$4 \rightarrow 5$$$ Or more clearly in the picture: In this case every team from the set $$$\{ 1, 2, 3 \}$$$ directly or indirectly defeated everyone. I.e.: $$$1$$$st defeated everyone because they can get to everyone else in the following way $$$1 \rightarrow 2$$$, $$$1 \rightarrow 2 \rightarrow 3$$$, $$$1 \rightarrow 4$$$, $$$1 \rightarrow 5$$$. $$$2$$$nd defeated everyone because they can get to everyone else in the following way $$$2 \rightarrow 3$$$, $$$2 \rightarrow 3 \rightarrow 1$$$, $$$2 \rightarrow 4$$$, $$$2 \rightarrow 5$$$. $$$3$$$rd defeated everyone because they can get to everyone else in the following way $$$3 \rightarrow 1$$$, $$$3 \rightarrow 1 \rightarrow 2$$$, $$$3 \rightarrow 4$$$, $$$3 \rightarrow 5$$$. Therefore the total number of winners is $$$3$$$. | Java 17 | standard input | [
"bitmasks",
"combinatorics",
"dp",
"graphs",
"math",
"probabilities"
] | 8508d39c069936fb402e4f4433180465 | The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 14$$$), which is the total number of teams participating in a match. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$) — the strengths of teams participating in a match. | 2,500 | Output a single integer — the expected value of the number of winners of the tournament modulo $$$10^9 + 7$$$. Formally, let $$$M = 10^9+7$$$. It can be demonstrated that the answer can be presented as a irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output a single integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output an integer $$$x$$$ such that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$. | standard output | |
PASSED | da7800ef92ee55f1fb2dd2ee7b06c8ae | train_107.jsonl | 1630247700 | William is not only interested in trading but also in betting on sports matches. $$$n$$$ teams participate in each match. Each team is characterized by strength $$$a_i$$$. Each two teams $$$i < j$$$ play with each other exactly once. Team $$$i$$$ wins with probability $$$\frac{a_i}{a_i + a_j}$$$ and team $$$j$$$ wins with probability $$$\frac{a_j}{a_i + a_j}$$$.The team is called a winner if it directly or indirectly defeated all other teams. Team $$$a$$$ defeated (directly or indirectly) team $$$b$$$ if there is a sequence of teams $$$c_1$$$, $$$c_2$$$, ... $$$c_k$$$ such that $$$c_1 = a$$$, $$$c_k = b$$$ and team $$$c_i$$$ defeated team $$$c_{i + 1}$$$ for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$. Note that it is possible that team $$$a$$$ defeated team $$$b$$$ and in the same time team $$$b$$$ defeated team $$$a$$$.William wants you to find the expected value of the number of winners. | 256 megabytes | import java.util.*;
import java.util.function.*;
import java.io.*;
// you can compare with output.txt and expected out
public class RoundDeltix2021F {
MyPrintWriter out;
MyScanner in;
// final static long FIXED_RANDOM;
// static {
// FIXED_RANDOM = System.currentTimeMillis();
// }
final static String IMPOSSIBLE = "IMPOSSIBLE";
final static String POSSIBLE = "POSSIBLE";
final static String YES = "YES";
final static String NO = "NO";
private void initIO(boolean isFileIO) {
if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) {
try{
in = new MyScanner(new FileInputStream("input.txt"));
out = new MyPrintWriter(new FileOutputStream("output.txt"));
}
catch(FileNotFoundException e){
e.printStackTrace();
}
}
else{
in = new MyScanner(System.in);
out = new MyPrintWriter(new BufferedOutputStream(System.out));
}
}
public static void main(String[] args){
// Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
// the code for the deep recursion (more than 100k or 3~400k or so)
// Thread t = new Thread(null, new RoundEdu130F(), "threadName", 1<<28);
// t.start();
// t.join();
RoundDeltix2021F sol = new RoundDeltix2021F();
sol.run();
}
private void run() {
boolean isDebug = false;
boolean isFileIO = true;
boolean hasMultipleTests = false;
initIO(isFileIO);
int t = hasMultipleTests? in.nextInt() : 1;
for (int i = 1; i <= t; ++i) {
if(isDebug){
out.printf("Test %d\n", i);
}
getInput();
solve();
printOutput();
}
in.close();
out.close();
}
// use suitable one between matrix(2, n), matrix(n, 2), transposedMatrix(2, n) for graph edges, pairs, ...
int n;
int[] a;
void getInput() {
n = in.nextInt();
a = in.nextIntArray(n);
}
void printOutput() {
out.printlnAns(ans);
}
final long MOD = 1_000_000_007;
long ans;
void solve(){
// suppose a is a winner
// if b won a, then b must be also a winner
// if a chain a -> x -> y -> ... z didn't contain b, then we can prepend b
// if the chain did contain b, we can start there
// hence if a is a sole winner, then a must have won all others, and that's also a sufficient condition
// similarly, if a and b are winners, then they must won all the others
// but this is not enough
// what about connections between winners?
// they should form an scc
// strongly connected tournament -> hamiltonian
// but multiple hamiltonian paths can exist
// if there is a subset X of winners that win each of winners not in X
// then not scc
// looks like this is a sufficient condition as well
// 1 hour until here
// 1 more hour to fill the small details in the idea and the implementation
long[][] winP = new long[n][n];
for(int i=0; i<n; i++)
for(int j=0; j<n; j++) {
if(i != j)
winP[i][j] = a[i] * inverse(a[i] + a[j], MOD) % MOD;
}
long[][] pre = new long[n][1<<n];
for(int i=0; i<n; i++) {
pre[i][0] = 1;
for(int mask=1; mask<(1<<n); mask++) {
pre[i][mask] = pre[i][mask-(mask&-mask)];
pre[i][mask] *= winP[i][Integer.numberOfTrailingZeros(mask)];
pre[i][mask] %= MOD;
}
}
long[] probs2 = new long[1<<n];
// probs2[mask] = the probability that the mask forms winners
// 3
// 1 1 1
// 0->1, 0->2, 1->2: 1
// 0->1, 0->2, 2->1: 1
// 0->1, 2->0, 1->2: 3
// 0->1, 2->0, 2->1: 1
// ...
// 6/8 + 6/8 = 12/8
ans = 0;
for(int mask=0; mask<(1<<n); mask++) {
long prob = 1;
int cnt = 0;
int to = ((1<<n)-1) ^ mask;
for(int i=0; i<n; i++) {
if((mask & (1<<i)) > 0)
prob = prob * pre[i][to] % MOD;
}
// for(int i=0; i<n; i++) {
// for(int j=0; j<n; j++) {
// if((mask & (1<<i)) > 0 && (mask & (1<<j)) == 0) {
// prob = prob * winP[i][j] % MOD;
// }
// }
// if((mask & (1<<i)) > 0)
// cnt++;
// }
int k = Integer.bitCount(mask);
long prob2 = 1;
for(int submask=(mask-1)&mask; submask>0; submask=(submask-1)&mask) {
to = submask ^ mask;
long curr = 1;
for(int i=0; i<n; i++) {
if((submask & (1<<i)) > 0)
curr = curr * pre[i][to] % MOD;
}
prob2 -= probs2[submask] * curr % MOD;
}
// int[] index = new int[cnt];
// for(int i=0; i<n; i++)
// if((mask & (1<<i)) > 0)
// index[--cnt] = i;
// int k = index.length;
// long prob2 = 1;
// for(int submask=1; submask<(1<<k)-1; submask++) {
// long curr = 1;
// for(int i=0; i<k; i++) {
// for(int j=0; j<k; j++) {
// if((submask & (1<<i)) > 0 && (submask & (1<<j)) == 0) {
// curr = curr * winP[index[i]][index[j]] % MOD;
// }
// }
// }
// int sub = 0;
// for(int i=0; i<k; i++)
// if((submask & (1<<i)) > 0)
// sub |= 1<<index[i];
// prob2 -= probs2[sub] * curr % MOD;
// }
prob2 %= MOD;
prob2 += MOD;
prob2 %= MOD;
probs2[mask] = prob2;
prob = prob * prob2 % MOD;
ans += prob * k;
}
ans %= MOD;
}
static long pow(long a, int k, long p) {
long m = k;
long ans = 1;
// curr = k^(2^i)
long curr = a;
// k^(2x+1) = (k^x)^2 * k
while(m > 0) {
if( (m&1) == 1 ) {
ans *= curr;
ans %= p;
}
m >>= 1;
curr *= curr;
curr %= p;
}
return ans;
}
// computes a^(p-2)
static long inverse(int a, long p) {
return pow(a, (int)(p-2), p);
}
// Optional<T> solve()
// return Optional.empty();
static class Pair implements Comparable<Pair>{
final static long FIXED_RANDOM = System.currentTimeMillis();
int first, second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
@Override
public int hashCode() {
// http://xorshift.di.unimi.it/splitmix64.c
long x = first;
x <<= 32;
x += second;
x += FIXED_RANDOM;
x += 0x9e3779b97f4a7c15l;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9l;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebl;
return (int)(x ^ (x >> 31));
}
@Override
public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
Pair other = (Pair) obj;
return first == other.first && second == other.second;
}
@Override
public String toString() {
return "[" + first + "," + second + "]";
}
@Override
public int compareTo(Pair o) {
int cmp = Integer.compare(first, o.first);
return cmp != 0? cmp: Integer.compare(second, o.second);
}
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
// 32768?
public MyScanner(InputStream is, int bufferSize) {
br = new BufferedReader(new InputStreamReader(is), bufferSize);
}
public MyScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
// br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
}
public void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[][] nextMatrix(int n, int m) {
return nextMatrix(n, m, 0);
}
int[][] nextMatrix(int n, int m, int offset) {
int[][] mat = new int[n][m];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
mat[i][j] = nextInt()+offset;
}
}
return mat;
}
int[][] nextTransposedMatrix(int n, int m){
return nextTransposedMatrix(n, m, 0);
}
int[][] nextTransposedMatrix(int n, int m, int offset){
int[][] mat = new int[m][n];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
mat[j][i] = nextInt()+offset;
}
}
return mat;
}
int[] nextIntArray(int len) {
return nextIntArray(len, 0);
}
int[] nextIntArray(int len, int offset){
int[] a = new int[len];
for(int j=0; j<len; j++)
a[j] = nextInt()+offset;
return a;
}
long[] nextLongArray(int len) {
return nextLongArray(len, 0);
}
long[] nextLongArray(int len, int offset){
long[] a = new long[len];
for(int j=0; j<len; j++)
a[j] = nextLong()+offset;
return a;
}
String[] nextStringArray(int len) {
String[] s = new String[len];
for(int i=0; i<len; i++)
s[i] = next();
return s;
}
}
public static class MyPrintWriter extends PrintWriter{
public MyPrintWriter(OutputStream os) {
super(os);
}
// public <T> void printlnAns(Optional<T> ans) {
// if(ans.isEmpty())
// println(-1);
// else
// printlnAns(ans.get());
// }
public void printlnAns(OptionalInt ans) {
println(ans.orElse(-1));
}
public void printlnAns(long ans) {
println(ans);
}
public void printlnAns(int ans) {
println(ans);
}
public void printlnAns(boolean[] ans) {
for(boolean b: ans)
printlnAns(b);
}
public void printlnAns(boolean ans) {
if(ans)
println(YES);
else
println(NO);
}
public void printAns(long[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(long[] arr){
printAns(arr);
println();
}
public void printAns(int[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(int[] arr){
printAns(arr);
println();
}
public <T> void printAns(ArrayList<T> arr){
if(arr != null && arr.size() > 0){
print(arr.get(0));
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i));
}
}
}
public <T> void printlnAns(ArrayList<T> arr){
printAns(arr);
println();
}
public void printAns(int[] arr, int add){
if(arr != null && arr.length > 0){
print(arr[0]+add);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]+add);
}
}
}
public void printlnAns(int[] arr, int add){
printAns(arr, add);
println();
}
public void printAns(ArrayList<Integer> arr, int add) {
if(arr != null && arr.size() > 0){
print(arr.get(0)+add);
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i)+add);
}
}
}
public void printlnAns(ArrayList<Integer> arr, int add){
printAns(arr, add);
println();
}
public void printlnAnsSplit(long[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public void printlnAnsSplit(int[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public <T> void printlnAnsSplit(ArrayList<T> arr, int split){
if(arr != null && !arr.isEmpty()){
for(int i=0; i<arr.size(); i+=split){
print(arr.get(i));
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr.get(j));
}
println();
}
}
}
}
static private void permutateAndSort(long[] a) {
int n = a.length;
Random R = new Random(System.currentTimeMillis());
for(int i=0; i<n; i++) {
int t = R.nextInt(n-i);
long temp = a[n-1-i];
a[n-1-i] = a[t];
a[t] = temp;
}
Arrays.sort(a);
}
static private void permutateAndSort(int[] a) {
int n = a.length;
Random R = new Random(System.currentTimeMillis());
for(int i=0; i<n; i++) {
int t = R.nextInt(n-i);
int temp = a[n-1-i];
a[n-1-i] = a[t];
a[t] = temp;
}
Arrays.sort(a);
}
static private int[][] constructChildren(int n, int[] parent, int parentRoot){
int[][] childrens = new int[n][];
int[] numChildren = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
numChildren[parent[i]]++;
}
for(int i=0; i<n; i++) {
childrens[i] = new int[numChildren[i]];
}
int[] idx = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
childrens[parent[i]][idx[parent[i]]++] = i;
}
return childrens;
}
static private int[][][] constructDirectedNeighborhood(int n, int[][] e){
int[] inDegree = new int[n];
int[] outDegree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outDegree[u]++;
inDegree[v]++;
}
int[][] inNeighbors = new int[n][];
int[][] outNeighbors = new int[n][];
for(int i=0; i<n; i++) {
inNeighbors[i] = new int[inDegree[i]];
outNeighbors[i] = new int[outDegree[i]];
}
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outNeighbors[u][--outDegree[u]] = v;
inNeighbors[v][--inDegree[v]] = u;
}
return new int[][][] {inNeighbors, outNeighbors};
}
static private int[][] constructNeighborhood(int n, int[][] e) {
int[] degree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
degree[u]++;
degree[v]++;
}
int[][] neighbors = new int[n][];
for(int i=0; i<n; i++)
neighbors[i] = new int[degree[i]];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
neighbors[u][--degree[u]] = v;
neighbors[v][--degree[v]] = u;
}
return neighbors;
}
static private void drawGraph(int[][] e) {
makeDotUndirected(e);
try {
final Process process = new ProcessBuilder("dot", "-Tpng", "graph.dot")
.redirectOutput(new File("graph.png"))
.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
static private void makeDotUndirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict graph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "--" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
static private void makeDotDirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict digraph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "->" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
}
| Java | ["2\n1 2", "5\n1 5 2 11 14"] | 4 seconds | ["1", "642377629"] | NoteTo better understand in which situation several winners are possible let's examine the second test:One possible result of the tournament is as follows ($$$a \rightarrow b$$$ means that $$$a$$$ defeated $$$b$$$): $$$1 \rightarrow 2$$$ $$$2 \rightarrow 3$$$ $$$3 \rightarrow 1$$$ $$$1 \rightarrow 4$$$ $$$1 \rightarrow 5$$$ $$$2 \rightarrow 4$$$ $$$2 \rightarrow 5$$$ $$$3 \rightarrow 4$$$ $$$3 \rightarrow 5$$$ $$$4 \rightarrow 5$$$ Or more clearly in the picture: In this case every team from the set $$$\{ 1, 2, 3 \}$$$ directly or indirectly defeated everyone. I.e.: $$$1$$$st defeated everyone because they can get to everyone else in the following way $$$1 \rightarrow 2$$$, $$$1 \rightarrow 2 \rightarrow 3$$$, $$$1 \rightarrow 4$$$, $$$1 \rightarrow 5$$$. $$$2$$$nd defeated everyone because they can get to everyone else in the following way $$$2 \rightarrow 3$$$, $$$2 \rightarrow 3 \rightarrow 1$$$, $$$2 \rightarrow 4$$$, $$$2 \rightarrow 5$$$. $$$3$$$rd defeated everyone because they can get to everyone else in the following way $$$3 \rightarrow 1$$$, $$$3 \rightarrow 1 \rightarrow 2$$$, $$$3 \rightarrow 4$$$, $$$3 \rightarrow 5$$$. Therefore the total number of winners is $$$3$$$. | Java 17 | standard input | [
"bitmasks",
"combinatorics",
"dp",
"graphs",
"math",
"probabilities"
] | 8508d39c069936fb402e4f4433180465 | The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 14$$$), which is the total number of teams participating in a match. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$) — the strengths of teams participating in a match. | 2,500 | Output a single integer — the expected value of the number of winners of the tournament modulo $$$10^9 + 7$$$. Formally, let $$$M = 10^9+7$$$. It can be demonstrated that the answer can be presented as a irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output a single integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output an integer $$$x$$$ such that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$. | standard output | |
PASSED | 49c08213f0d663a74371692a4f7effc3 | train_107.jsonl | 1630247700 | William is not only interested in trading but also in betting on sports matches. $$$n$$$ teams participate in each match. Each team is characterized by strength $$$a_i$$$. Each two teams $$$i < j$$$ play with each other exactly once. Team $$$i$$$ wins with probability $$$\frac{a_i}{a_i + a_j}$$$ and team $$$j$$$ wins with probability $$$\frac{a_j}{a_i + a_j}$$$.The team is called a winner if it directly or indirectly defeated all other teams. Team $$$a$$$ defeated (directly or indirectly) team $$$b$$$ if there is a sequence of teams $$$c_1$$$, $$$c_2$$$, ... $$$c_k$$$ such that $$$c_1 = a$$$, $$$c_k = b$$$ and team $$$c_i$$$ defeated team $$$c_{i + 1}$$$ for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$. Note that it is possible that team $$$a$$$ defeated team $$$b$$$ and in the same time team $$$b$$$ defeated team $$$a$$$.William wants you to find the expected value of the number of winners. | 256 megabytes | import java.util.*;
import java.util.function.*;
import java.io.*;
// you can compare with output.txt and expected out
public class RoundDeltix2021F {
MyPrintWriter out;
MyScanner in;
// final static long FIXED_RANDOM;
// static {
// FIXED_RANDOM = System.currentTimeMillis();
// }
final static String IMPOSSIBLE = "IMPOSSIBLE";
final static String POSSIBLE = "POSSIBLE";
final static String YES = "YES";
final static String NO = "NO";
private void initIO(boolean isFileIO) {
if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) {
try{
in = new MyScanner(new FileInputStream("input.txt"));
out = new MyPrintWriter(new FileOutputStream("output.txt"));
}
catch(FileNotFoundException e){
e.printStackTrace();
}
}
else{
in = new MyScanner(System.in);
out = new MyPrintWriter(new BufferedOutputStream(System.out));
}
}
public static void main(String[] args){
// Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
// the code for the deep recursion (more than 100k or 3~400k or so)
// Thread t = new Thread(null, new RoundEdu130F(), "threadName", 1<<28);
// t.start();
// t.join();
RoundDeltix2021F sol = new RoundDeltix2021F();
sol.run();
}
private void run() {
boolean isDebug = false;
boolean isFileIO = true;
boolean hasMultipleTests = false;
initIO(isFileIO);
int t = hasMultipleTests? in.nextInt() : 1;
for (int i = 1; i <= t; ++i) {
if(isDebug){
out.printf("Test %d\n", i);
}
getInput();
solve();
printOutput();
}
in.close();
out.close();
}
// use suitable one between matrix(2, n), matrix(n, 2), transposedMatrix(2, n) for graph edges, pairs, ...
int n;
int[] a;
void getInput() {
n = in.nextInt();
a = in.nextIntArray(n);
}
void printOutput() {
out.printlnAns(ans);
}
final long MOD = 1_000_000_007;
long ans;
void solve(){
// suppose a is a winner
// if b won a, then b must be also a winner
// if a chain a -> x -> y -> ... z didn't contain b, then we can prepend b
// if the chain did contain b, we can start there
// hence if a is a sole winner, then a must have won all others, and that's also a sufficient condition
// similarly, if a and b are winners, then they must won all the others
// but this is not enough
// what about connections between winners?
// they should form an scc
// strongly connected tournament -> hamiltonian
// but multiple hamiltonian paths can exist
// if there is a subset X of winners that win each of winners not in X
// then not scc
// looks like this is a sufficient condition as well
// 1 hour until here
long[][] winP = new long[n][n];
for(int i=0; i<n; i++)
for(int j=0; j<n; j++) {
if(i != j)
winP[i][j] = a[i] * inverse(a[i] + a[j], MOD) % MOD;
}
long[] probs2 = new long[1<<n];
// probs[mask] = the probability that the mask forms winners
// 3
// 1 1 1
// 0->1, 0->2, 1->2: 1
// 0->1, 0->2, 2->1: 1
// 0->1, 2->0, 1->2: 3
// 0->1, 2->0, 2->1: 1
// ...
// 6/8 + 6/8 = 12/8
ans = 0;
for(int mask=0; mask<(1<<n); mask++) {
long prob = 1;
int cnt = 0;
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
if((mask & (1<<i)) > 0 && (mask & (1<<j)) == 0) {
prob = prob * winP[i][j] % MOD;
}
}
if((mask & (1<<i)) > 0)
cnt++;
}
int[] index = new int[cnt];
for(int i=0; i<n; i++)
if((mask & (1<<i)) > 0)
index[--cnt] = i;
int k = index.length;
long prob2 = 1;
for(int submask=1; submask<(1<<k)-1; submask++) {
long curr = 1;
for(int i=0; i<k; i++) {
for(int j=0; j<k; j++) {
if((submask & (1<<i)) > 0 && (submask & (1<<j)) == 0) {
curr = curr * winP[index[i]][index[j]] % MOD;
}
}
}
int sub = 0;
for(int i=0; i<k; i++)
if((submask & (1<<i)) > 0)
sub |= 1<<index[i];
prob2 -= probs2[sub] * curr % MOD;
}
prob2 %= MOD;
prob2 += MOD;
prob2 %= MOD;
probs2[mask] = prob2;
prob = prob * prob2 % MOD;
ans += prob * k;
}
ans %= MOD;
}
static long pow(long a, int k, long p) {
long m = k;
long ans = 1;
// curr = k^(2^i)
long curr = a;
// k^(2x+1) = (k^x)^2 * k
while(m > 0) {
if( (m&1) == 1 ) {
ans *= curr;
ans %= p;
}
m >>= 1;
curr *= curr;
curr %= p;
}
return ans;
}
// computes a^(p-2)
static long inverse(int a, long p) {
return pow(a, (int)(p-2), p);
}
// Optional<T> solve()
// return Optional.empty();
static class Pair implements Comparable<Pair>{
final static long FIXED_RANDOM = System.currentTimeMillis();
int first, second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
@Override
public int hashCode() {
// http://xorshift.di.unimi.it/splitmix64.c
long x = first;
x <<= 32;
x += second;
x += FIXED_RANDOM;
x += 0x9e3779b97f4a7c15l;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9l;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebl;
return (int)(x ^ (x >> 31));
}
@Override
public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
Pair other = (Pair) obj;
return first == other.first && second == other.second;
}
@Override
public String toString() {
return "[" + first + "," + second + "]";
}
@Override
public int compareTo(Pair o) {
int cmp = Integer.compare(first, o.first);
return cmp != 0? cmp: Integer.compare(second, o.second);
}
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
// 32768?
public MyScanner(InputStream is, int bufferSize) {
br = new BufferedReader(new InputStreamReader(is), bufferSize);
}
public MyScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
// br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
}
public void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[][] nextMatrix(int n, int m) {
return nextMatrix(n, m, 0);
}
int[][] nextMatrix(int n, int m, int offset) {
int[][] mat = new int[n][m];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
mat[i][j] = nextInt()+offset;
}
}
return mat;
}
int[][] nextTransposedMatrix(int n, int m){
return nextTransposedMatrix(n, m, 0);
}
int[][] nextTransposedMatrix(int n, int m, int offset){
int[][] mat = new int[m][n];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
mat[j][i] = nextInt()+offset;
}
}
return mat;
}
int[] nextIntArray(int len) {
return nextIntArray(len, 0);
}
int[] nextIntArray(int len, int offset){
int[] a = new int[len];
for(int j=0; j<len; j++)
a[j] = nextInt()+offset;
return a;
}
long[] nextLongArray(int len) {
return nextLongArray(len, 0);
}
long[] nextLongArray(int len, int offset){
long[] a = new long[len];
for(int j=0; j<len; j++)
a[j] = nextLong()+offset;
return a;
}
String[] nextStringArray(int len) {
String[] s = new String[len];
for(int i=0; i<len; i++)
s[i] = next();
return s;
}
}
public static class MyPrintWriter extends PrintWriter{
public MyPrintWriter(OutputStream os) {
super(os);
}
// public <T> void printlnAns(Optional<T> ans) {
// if(ans.isEmpty())
// println(-1);
// else
// printlnAns(ans.get());
// }
public void printlnAns(OptionalInt ans) {
println(ans.orElse(-1));
}
public void printlnAns(long ans) {
println(ans);
}
public void printlnAns(int ans) {
println(ans);
}
public void printlnAns(boolean[] ans) {
for(boolean b: ans)
printlnAns(b);
}
public void printlnAns(boolean ans) {
if(ans)
println(YES);
else
println(NO);
}
public void printAns(long[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(long[] arr){
printAns(arr);
println();
}
public void printAns(int[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(int[] arr){
printAns(arr);
println();
}
public <T> void printAns(ArrayList<T> arr){
if(arr != null && arr.size() > 0){
print(arr.get(0));
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i));
}
}
}
public <T> void printlnAns(ArrayList<T> arr){
printAns(arr);
println();
}
public void printAns(int[] arr, int add){
if(arr != null && arr.length > 0){
print(arr[0]+add);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]+add);
}
}
}
public void printlnAns(int[] arr, int add){
printAns(arr, add);
println();
}
public void printAns(ArrayList<Integer> arr, int add) {
if(arr != null && arr.size() > 0){
print(arr.get(0)+add);
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i)+add);
}
}
}
public void printlnAns(ArrayList<Integer> arr, int add){
printAns(arr, add);
println();
}
public void printlnAnsSplit(long[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public void printlnAnsSplit(int[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public <T> void printlnAnsSplit(ArrayList<T> arr, int split){
if(arr != null && !arr.isEmpty()){
for(int i=0; i<arr.size(); i+=split){
print(arr.get(i));
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr.get(j));
}
println();
}
}
}
}
static private void permutateAndSort(long[] a) {
int n = a.length;
Random R = new Random(System.currentTimeMillis());
for(int i=0; i<n; i++) {
int t = R.nextInt(n-i);
long temp = a[n-1-i];
a[n-1-i] = a[t];
a[t] = temp;
}
Arrays.sort(a);
}
static private void permutateAndSort(int[] a) {
int n = a.length;
Random R = new Random(System.currentTimeMillis());
for(int i=0; i<n; i++) {
int t = R.nextInt(n-i);
int temp = a[n-1-i];
a[n-1-i] = a[t];
a[t] = temp;
}
Arrays.sort(a);
}
static private int[][] constructChildren(int n, int[] parent, int parentRoot){
int[][] childrens = new int[n][];
int[] numChildren = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
numChildren[parent[i]]++;
}
for(int i=0; i<n; i++) {
childrens[i] = new int[numChildren[i]];
}
int[] idx = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
childrens[parent[i]][idx[parent[i]]++] = i;
}
return childrens;
}
static private int[][][] constructDirectedNeighborhood(int n, int[][] e){
int[] inDegree = new int[n];
int[] outDegree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outDegree[u]++;
inDegree[v]++;
}
int[][] inNeighbors = new int[n][];
int[][] outNeighbors = new int[n][];
for(int i=0; i<n; i++) {
inNeighbors[i] = new int[inDegree[i]];
outNeighbors[i] = new int[outDegree[i]];
}
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outNeighbors[u][--outDegree[u]] = v;
inNeighbors[v][--inDegree[v]] = u;
}
return new int[][][] {inNeighbors, outNeighbors};
}
static private int[][] constructNeighborhood(int n, int[][] e) {
int[] degree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
degree[u]++;
degree[v]++;
}
int[][] neighbors = new int[n][];
for(int i=0; i<n; i++)
neighbors[i] = new int[degree[i]];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
neighbors[u][--degree[u]] = v;
neighbors[v][--degree[v]] = u;
}
return neighbors;
}
static private void drawGraph(int[][] e) {
makeDotUndirected(e);
try {
final Process process = new ProcessBuilder("dot", "-Tpng", "graph.dot")
.redirectOutput(new File("graph.png"))
.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
static private void makeDotUndirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict graph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "--" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
static private void makeDotDirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict digraph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "->" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
}
| Java | ["2\n1 2", "5\n1 5 2 11 14"] | 4 seconds | ["1", "642377629"] | NoteTo better understand in which situation several winners are possible let's examine the second test:One possible result of the tournament is as follows ($$$a \rightarrow b$$$ means that $$$a$$$ defeated $$$b$$$): $$$1 \rightarrow 2$$$ $$$2 \rightarrow 3$$$ $$$3 \rightarrow 1$$$ $$$1 \rightarrow 4$$$ $$$1 \rightarrow 5$$$ $$$2 \rightarrow 4$$$ $$$2 \rightarrow 5$$$ $$$3 \rightarrow 4$$$ $$$3 \rightarrow 5$$$ $$$4 \rightarrow 5$$$ Or more clearly in the picture: In this case every team from the set $$$\{ 1, 2, 3 \}$$$ directly or indirectly defeated everyone. I.e.: $$$1$$$st defeated everyone because they can get to everyone else in the following way $$$1 \rightarrow 2$$$, $$$1 \rightarrow 2 \rightarrow 3$$$, $$$1 \rightarrow 4$$$, $$$1 \rightarrow 5$$$. $$$2$$$nd defeated everyone because they can get to everyone else in the following way $$$2 \rightarrow 3$$$, $$$2 \rightarrow 3 \rightarrow 1$$$, $$$2 \rightarrow 4$$$, $$$2 \rightarrow 5$$$. $$$3$$$rd defeated everyone because they can get to everyone else in the following way $$$3 \rightarrow 1$$$, $$$3 \rightarrow 1 \rightarrow 2$$$, $$$3 \rightarrow 4$$$, $$$3 \rightarrow 5$$$. Therefore the total number of winners is $$$3$$$. | Java 17 | standard input | [
"bitmasks",
"combinatorics",
"dp",
"graphs",
"math",
"probabilities"
] | 8508d39c069936fb402e4f4433180465 | The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 14$$$), which is the total number of teams participating in a match. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$) — the strengths of teams participating in a match. | 2,500 | Output a single integer — the expected value of the number of winners of the tournament modulo $$$10^9 + 7$$$. Formally, let $$$M = 10^9+7$$$. It can be demonstrated that the answer can be presented as a irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output a single integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output an integer $$$x$$$ such that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$. | standard output | |
PASSED | e5fea4ac2764a34a7d63b86a3c6d69c0 | train_107.jsonl | 1630247700 | William is not only interested in trading but also in betting on sports matches. $$$n$$$ teams participate in each match. Each team is characterized by strength $$$a_i$$$. Each two teams $$$i < j$$$ play with each other exactly once. Team $$$i$$$ wins with probability $$$\frac{a_i}{a_i + a_j}$$$ and team $$$j$$$ wins with probability $$$\frac{a_j}{a_i + a_j}$$$.The team is called a winner if it directly or indirectly defeated all other teams. Team $$$a$$$ defeated (directly or indirectly) team $$$b$$$ if there is a sequence of teams $$$c_1$$$, $$$c_2$$$, ... $$$c_k$$$ such that $$$c_1 = a$$$, $$$c_k = b$$$ and team $$$c_i$$$ defeated team $$$c_{i + 1}$$$ for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$. Note that it is possible that team $$$a$$$ defeated team $$$b$$$ and in the same time team $$$b$$$ defeated team $$$a$$$.William wants you to find the expected value of the number of winners. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
public class F{
static int n;
static long[] a;
static long[] dp2;
static long mod = (int)1e9+7;
static long mi(long a) {
a%=mod;
return pow(a,mod-2);
}
static long pow(long b, long e) {
if (e==0) return 1;
long r = pow(b,e/2);
r = r*r%mod;
if (e%2==1) return r*b%mod;
return r;
}
public static void main(String[] args) throws IOException{
// br = new BufferedReader(new FileReader(".in"));
// out = new PrintWriter(new FileWriter(".out"));
// new Thread(null, new (), "fisa balls", 1<<28).start();
//System.out.println(7 * mi(5)%mod);
//System.out.println(36 * mi(60)%mod);
n =readInt();
dp2 = new long[1<<n];
a = new long[n];
for (int i = 0; i < n; i++) a[i]=readLong();
long ans = 0;
// Thrid dp: What is the probability that team A defeated a subset team B
long[][] dp3 = new long[n][1<<n];
for (int i = 0; i < n; i++) {
for (int bm = 0; bm < (1<<n); bm++) {
dp3[i][bm] = 1;
for (int j = 0; j < n; j++) {
if (((1<<j)&bm)>0) {
dp3[i][bm]*=a[i];
dp3[i][bm]%=mod;
dp3[i][bm]*=mi(a[i]+a[j]);
dp3[i][bm]%=mod;
}
}
}
}
for (int bm = 1; bm < (1<<n); bm++) {
if (Integer.bitCount(bm) == 2) continue;
dp2[bm] = 1;
for (int s = (bm-1)&bm; s > 0; s=(s-1)&bm) {
// We want inner * outer, inner = 1 because doesnt matter
long temp = dp2[bm^s];
if (temp==0) continue;
for (int j = 0; j < n; j++) {
if (((1<<j) & (s^bm)) > 0) {
temp*=dp3[j][s];
temp%=mod;
}
}
dp2[bm]-=temp;
while (dp2[bm] < 0) dp2[bm]+=mod;
}
//System.out.println("Iter " + bm);
}
for (int bm = 1; bm < (1<<n); bm++) {
long temp = 1;
if (Integer.bitCount(bm) == 2) continue;
for (int i = 0; i < n; i++) {
if (((1<<i)&bm)==0) continue;
for (int j = 0; j < n; j++) {
if (((1<<j)&bm) > 0) continue;
temp*= a[i];
temp %= mod;
temp*= mi(a[i]+a[j]);
temp%=mod;
}
}
temp *= dp2[bm];
temp%=mod;
ans += Integer.bitCount(bm) * temp;
}
//906250009
out.println(ans%mod);
//out.println(solve2((1<<n)-1));
out.close();
}
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
static StringTokenizer st = new StringTokenizer("");
static String read() throws IOException{
while (!st.hasMoreElements()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public static int readInt() throws IOException{return Integer.parseInt(read());}
public static long readLong() throws IOException{return Long.parseLong(read());}
} | Java | ["2\n1 2", "5\n1 5 2 11 14"] | 4 seconds | ["1", "642377629"] | NoteTo better understand in which situation several winners are possible let's examine the second test:One possible result of the tournament is as follows ($$$a \rightarrow b$$$ means that $$$a$$$ defeated $$$b$$$): $$$1 \rightarrow 2$$$ $$$2 \rightarrow 3$$$ $$$3 \rightarrow 1$$$ $$$1 \rightarrow 4$$$ $$$1 \rightarrow 5$$$ $$$2 \rightarrow 4$$$ $$$2 \rightarrow 5$$$ $$$3 \rightarrow 4$$$ $$$3 \rightarrow 5$$$ $$$4 \rightarrow 5$$$ Or more clearly in the picture: In this case every team from the set $$$\{ 1, 2, 3 \}$$$ directly or indirectly defeated everyone. I.e.: $$$1$$$st defeated everyone because they can get to everyone else in the following way $$$1 \rightarrow 2$$$, $$$1 \rightarrow 2 \rightarrow 3$$$, $$$1 \rightarrow 4$$$, $$$1 \rightarrow 5$$$. $$$2$$$nd defeated everyone because they can get to everyone else in the following way $$$2 \rightarrow 3$$$, $$$2 \rightarrow 3 \rightarrow 1$$$, $$$2 \rightarrow 4$$$, $$$2 \rightarrow 5$$$. $$$3$$$rd defeated everyone because they can get to everyone else in the following way $$$3 \rightarrow 1$$$, $$$3 \rightarrow 1 \rightarrow 2$$$, $$$3 \rightarrow 4$$$, $$$3 \rightarrow 5$$$. Therefore the total number of winners is $$$3$$$. | Java 11 | standard input | [
"bitmasks",
"combinatorics",
"dp",
"graphs",
"math",
"probabilities"
] | 8508d39c069936fb402e4f4433180465 | The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 14$$$), which is the total number of teams participating in a match. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$) — the strengths of teams participating in a match. | 2,500 | Output a single integer — the expected value of the number of winners of the tournament modulo $$$10^9 + 7$$$. Formally, let $$$M = 10^9+7$$$. It can be demonstrated that the answer can be presented as a irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output a single integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output an integer $$$x$$$ such that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$. | standard output | |
PASSED | bbd3705983dd9872886be3b8f5d59f7a | train_107.jsonl | 1630247700 | William is not only interested in trading but also in betting on sports matches. $$$n$$$ teams participate in each match. Each team is characterized by strength $$$a_i$$$. Each two teams $$$i < j$$$ play with each other exactly once. Team $$$i$$$ wins with probability $$$\frac{a_i}{a_i + a_j}$$$ and team $$$j$$$ wins with probability $$$\frac{a_j}{a_i + a_j}$$$.The team is called a winner if it directly or indirectly defeated all other teams. Team $$$a$$$ defeated (directly or indirectly) team $$$b$$$ if there is a sequence of teams $$$c_1$$$, $$$c_2$$$, ... $$$c_k$$$ such that $$$c_1 = a$$$, $$$c_k = b$$$ and team $$$c_i$$$ defeated team $$$c_{i + 1}$$$ for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$. Note that it is possible that team $$$a$$$ defeated team $$$b$$$ and in the same time team $$$b$$$ defeated team $$$a$$$.William wants you to find the expected value of the number of winners. | 256 megabytes | import java.util.*;
import java.io.*;
import java.text.*;
public class CF_1556_F{
//SOLUTION BEGIN
long MOD = (long)1e9+7;
void pre() throws Exception{}
void solve(int TC) throws Exception{
int N = ni();
long[] A = new long[N];
for(int i = 0; i< N; i++)A[i] = nl();
long[] P = new long[1<<N];
long[][] L = new long[N][1<<N];
//L[i][mask] => Probabilitiy that person i loses to all people in mask. If i is included in mask, L[i][mask] = 0
for(int win = 1; win < 1<<N; win++){
for(int i = 0; i< N; i++){
if(((win>>i)&1)==1)continue;
long sum = 1;
for(int j = 0; j< N; j++){
if(((win>>j)&1)==0)continue;
sum *= A[j]*inv(A[i]+A[j])%MOD;
if(sum >= MOD)sum %= MOD;
}
L[i][win] = sum;
}
}
int ALL = (1<<N)-1;
long ans = 0;
for(int mask = 1; mask < 1<<N; mask++){
long sum = 0;
for(int sub = (mask-1)&mask; sub > 0; sub = (sub-1)&mask){
sum += P[sub]*G(L, sub, mask^sub)%MOD;//G[sub]%MOD;
// sum += F[sub]%MOD;
if(sum > 0)sum -= MOD;
}
P[mask] = (1+MOD-sum)%MOD;
ans += (bit(mask))*P[mask]%MOD * G(L, mask, ALL^mask)%MOD;
if(ans >= MOD)ans -= MOD;
}
pn(ans);
}
long G(long[][] L, int win, int lose){
if((win&lose) > 0)return -1;
long ans = 1;
for(int i = 0; i< L.length; i++){
if(((lose>>i)&1)==0)continue;
ans = ans*L[i][win]%MOD;
}
return ans;
}
long inv(long a){
return pow(a, MOD-2);
}
long pow(long a, long p){
long o = 1;
a %= MOD;
for(; p>0; p>>=1){
if((p&1)==1)o = (o*a)%MOD;
a = (a*a)%MOD;
}
return o;
}
//SOLUTION END
void hold(boolean b)throws Exception{if(!b)throw new Exception("Hold right there, Sparky!");}
void exit(boolean b){if(!b)System.exit(0);}
static void dbg(Object... o){System.err.println(Arrays.deepToString(o));}
final long IINF = (long)1e17;
final int INF = (int)1e9+2;
DecimalFormat df = new DecimalFormat("0.00000000000");
double PI = 3.141592653589793238462643383279502884197169399, eps = 1e-8;
static boolean multipleTC = false, memory = true, fileIO = false;
FastReader in;PrintWriter out;
void run() throws Exception{
long ct = System.currentTimeMillis();
if (fileIO) {
in = new FastReader("");
out = new PrintWriter("");
} 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();
System.err.println(System.currentTimeMillis() - ct);
}
public static void main(String[] args) throws Exception{
if(memory)new Thread(null, new Runnable() {public void run(){try{new CF_1556_F().run();}catch(Exception e){e.printStackTrace();System.exit(1);}}}, "1", 1 << 28).start();
else new CF_1556_F().run();
}
int[][] make(int n, int e, int[] from, int[] to, boolean f){
int[][] g = new int[n][];int[]cnt = new int[n];
for(int i = 0; i< e; i++){
cnt[from[i]]++;
if(f)cnt[to[i]]++;
}
for(int i = 0; i< n; i++)g[i] = new int[cnt[i]];
for(int i = 0; i< e; i++){
g[from[i]][--cnt[from[i]]] = to[i];
if(f)g[to[i]][--cnt[to[i]]] = from[i];
}
return g;
}
int[][][] makeS(int n, int e, int[] from, int[] to, boolean f){
int[][][] g = new int[n][][];int[]cnt = new int[n];
for(int i = 0; i< e; i++){
cnt[from[i]]++;
if(f)cnt[to[i]]++;
}
for(int i = 0; i< n; i++)g[i] = new int[cnt[i]][];
for(int i = 0; i< e; i++){
g[from[i]][--cnt[from[i]]] = new int[]{to[i], i, 0};
if(f)g[to[i]][--cnt[to[i]]] = new int[]{from[i], i, 1};
}
return g;
}
int find(int[] set, int u){return set[u] = (set[u] == u?u:find(set, set[u]));}
int digit(long s){int ans = 0;while(s>0){s/=10;ans++;}return ans;}
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){for(Object oo:o)out.print(oo+" ");}
void pn(Object... o){for(int i = 0; i< o.length; i++)out.print(o[i]+(i+1 < o.length?" ":"\n"));}
void pni(Object... o){for(Object oo:o)out.print(oo+" ");out.println();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 | ["2\n1 2", "5\n1 5 2 11 14"] | 4 seconds | ["1", "642377629"] | NoteTo better understand in which situation several winners are possible let's examine the second test:One possible result of the tournament is as follows ($$$a \rightarrow b$$$ means that $$$a$$$ defeated $$$b$$$): $$$1 \rightarrow 2$$$ $$$2 \rightarrow 3$$$ $$$3 \rightarrow 1$$$ $$$1 \rightarrow 4$$$ $$$1 \rightarrow 5$$$ $$$2 \rightarrow 4$$$ $$$2 \rightarrow 5$$$ $$$3 \rightarrow 4$$$ $$$3 \rightarrow 5$$$ $$$4 \rightarrow 5$$$ Or more clearly in the picture: In this case every team from the set $$$\{ 1, 2, 3 \}$$$ directly or indirectly defeated everyone. I.e.: $$$1$$$st defeated everyone because they can get to everyone else in the following way $$$1 \rightarrow 2$$$, $$$1 \rightarrow 2 \rightarrow 3$$$, $$$1 \rightarrow 4$$$, $$$1 \rightarrow 5$$$. $$$2$$$nd defeated everyone because they can get to everyone else in the following way $$$2 \rightarrow 3$$$, $$$2 \rightarrow 3 \rightarrow 1$$$, $$$2 \rightarrow 4$$$, $$$2 \rightarrow 5$$$. $$$3$$$rd defeated everyone because they can get to everyone else in the following way $$$3 \rightarrow 1$$$, $$$3 \rightarrow 1 \rightarrow 2$$$, $$$3 \rightarrow 4$$$, $$$3 \rightarrow 5$$$. Therefore the total number of winners is $$$3$$$. | Java 11 | standard input | [
"bitmasks",
"combinatorics",
"dp",
"graphs",
"math",
"probabilities"
] | 8508d39c069936fb402e4f4433180465 | The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 14$$$), which is the total number of teams participating in a match. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$) — the strengths of teams participating in a match. | 2,500 | Output a single integer — the expected value of the number of winners of the tournament modulo $$$10^9 + 7$$$. Formally, let $$$M = 10^9+7$$$. It can be demonstrated that the answer can be presented as a irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output a single integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output an integer $$$x$$$ such that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$. | standard output | |
PASSED | 6de2ec90c4b905a110507ba57c044ff8 | train_107.jsonl | 1630247700 | William is not only interested in trading but also in betting on sports matches. $$$n$$$ teams participate in each match. Each team is characterized by strength $$$a_i$$$. Each two teams $$$i < j$$$ play with each other exactly once. Team $$$i$$$ wins with probability $$$\frac{a_i}{a_i + a_j}$$$ and team $$$j$$$ wins with probability $$$\frac{a_j}{a_i + a_j}$$$.The team is called a winner if it directly or indirectly defeated all other teams. Team $$$a$$$ defeated (directly or indirectly) team $$$b$$$ if there is a sequence of teams $$$c_1$$$, $$$c_2$$$, ... $$$c_k$$$ such that $$$c_1 = a$$$, $$$c_k = b$$$ and team $$$c_i$$$ defeated team $$$c_{i + 1}$$$ for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$. Note that it is possible that team $$$a$$$ defeated team $$$b$$$ and in the same time team $$$b$$$ defeated team $$$a$$$.William wants you to find the expected value of the number of winners. | 256 megabytes | //package deltixs2021;
import java.io.*;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Queue;
public class F2 {
InputStream is;
FastWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int[] a = na(n);
final int mod = 1000000007;
long[][] ps = new long[n][n];
for(int i = 0;i < n;i++){
for(int j = 0;j < n;j++){
ps[i][j] = a[i] * invl(a[i] + a[j], mod) % mod;
}
}
long[][] tps = new long[n][1<<n];
for(int j = 0;j < n;j++){
tps[j][0] = 1;
for(int i = 1;i < 1<<n;i++){
tps[j][i] = tps[j][i&i-1] * ps[Integer.numberOfTrailingZeros(i)][j] % mod;
}
}
long[] dp = new long[1<<n];
for(int i = 0;i < 1<<n;i++){
long P = 1;
for(int j = 0;j < n;j++){
if(i<<~j<0) {
P = P * tps[j][~i&(1<<n)-1] % mod;
}
}
dp[i] = P;
}
long ans = 0;
int[] ms = new int[1<<n];
long[] temp = new long[1<<n];
for(int z = 0;z < n;z++){
long[] ep = new long[1<<n];
for(int i = 0;i < 1<<n;i++){
if(i<<~z>=0){
ep[i] = 0;
continue;
}
ep[i] = dp[i];
int mask = i;
int p = 0;
for(int j = mask;j > 0;j=j-1&mask){
ms[p++] = j;
}
ms[p++] = 0;
temp[0] = 1;
for(int k = p-2;k >= 0;k--){
temp[ms[k]] = temp[ms[k]&ms[k]-1] * tps[Integer.numberOfTrailingZeros(ms[k])][~i&(1<<n)-1] % mod;
}
for(int j = mask;j > 0;j=j-1&mask){
ep[i] -= ep[i^j] * temp[j];
ep[i] %= mod;
} // not include i=0
ep[i] %= mod;
if(ep[i] < 0)ep[i] += mod;
}
ans += ep[(1<<n)-1];
}
out.println(ans%mod);
}
public static long invl(long a, long mod) {
long b = mod;
long p = 1, q = 0;
while (b > 0) {
long c = a / b;
long d;
d = a;
a = b;
b = d % b;
d = p;
p = q;
q = d - c * q;
}
return p < 0 ? p + mod : p;
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new FastWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new F2().run(); }
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 int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private long[] nal(int n)
{
long[] a = new long[n];
for(int i = 0;i < n;i++)a[i] = nl();
return a;
}
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[][] nmi(int n, int m) {
int[][] map = new int[n][];
for(int i = 0;i < n;i++)map[i] = na(m);
return map;
}
private int ni() { return (int)nl(); }
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();
}
}
public static class FastWriter
{
private static final int BUF_SIZE = 1<<13;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastWriter(){out = null;}
public FastWriter(OutputStream os)
{
this.out = os;
}
public FastWriter(String path)
{
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastWriter write(byte b)
{
buf[ptr++] = b;
if(ptr == BUF_SIZE)innerflush();
return this;
}
public FastWriter write(char c)
{
return write((byte)c);
}
public FastWriter write(char[] s)
{
for(char c : s){
buf[ptr++] = (byte)c;
if(ptr == BUF_SIZE)innerflush();
}
return this;
}
public FastWriter write(String s)
{
s.chars().forEach(c -> {
buf[ptr++] = (byte)c;
if(ptr == BUF_SIZE)innerflush();
});
return this;
}
private static int countDigits(int l) {
if (l >= 1000000000) return 10;
if (l >= 100000000) return 9;
if (l >= 10000000) return 8;
if (l >= 1000000) return 7;
if (l >= 100000) return 6;
if (l >= 10000) return 5;
if (l >= 1000) return 4;
if (l >= 100) return 3;
if (l >= 10) return 2;
return 1;
}
public FastWriter write(int x)
{
if(x == Integer.MIN_VALUE){
return write((long)x);
}
if(ptr + 12 >= BUF_SIZE)innerflush();
if(x < 0){
write((byte)'-');
x = -x;
}
int d = countDigits(x);
for(int i = ptr + d - 1;i >= ptr;i--){
buf[i] = (byte)('0'+x%10);
x /= 10;
}
ptr += d;
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L) return 19;
if (l >= 100000000000000000L) return 18;
if (l >= 10000000000000000L) return 17;
if (l >= 1000000000000000L) return 16;
if (l >= 100000000000000L) return 15;
if (l >= 10000000000000L) return 14;
if (l >= 1000000000000L) return 13;
if (l >= 100000000000L) return 12;
if (l >= 10000000000L) return 11;
if (l >= 1000000000L) return 10;
if (l >= 100000000L) return 9;
if (l >= 10000000L) return 8;
if (l >= 1000000L) return 7;
if (l >= 100000L) return 6;
if (l >= 10000L) return 5;
if (l >= 1000L) return 4;
if (l >= 100L) return 3;
if (l >= 10L) return 2;
return 1;
}
public FastWriter write(long x)
{
if(x == Long.MIN_VALUE){
return write("" + x);
}
if(ptr + 21 >= BUF_SIZE)innerflush();
if(x < 0){
write((byte)'-');
x = -x;
}
int d = countDigits(x);
for(int i = ptr + d - 1;i >= ptr;i--){
buf[i] = (byte)('0'+x%10);
x /= 10;
}
ptr += d;
return this;
}
public FastWriter write(double x, int precision)
{
if(x < 0){
write('-');
x = -x;
}
x += Math.pow(10, -precision)/2;
// if(x < 0){ x = 0; }
write((long)x).write(".");
x -= (long)x;
for(int i = 0;i < precision;i++){
x *= 10;
write((char)('0'+(int)x));
x -= (int)x;
}
return this;
}
public FastWriter writeln(char c){
return write(c).writeln();
}
public FastWriter writeln(int x){
return write(x).writeln();
}
public FastWriter writeln(long x){
return write(x).writeln();
}
public FastWriter writeln(double x, int precision){
return write(x, precision).writeln();
}
public FastWriter write(int... xs)
{
boolean first = true;
for(int x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter write(long... xs)
{
boolean first = true;
for(long x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter writeln()
{
return write((byte)'\n');
}
public FastWriter writeln(int... xs)
{
return write(xs).writeln();
}
public FastWriter writeln(long... xs)
{
return write(xs).writeln();
}
public FastWriter writeln(char[] line)
{
return write(line).writeln();
}
public FastWriter writeln(char[]... map)
{
for(char[] line : map)write(line).writeln();
return this;
}
public FastWriter writeln(String s)
{
return write(s).writeln();
}
private void innerflush()
{
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush()
{
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
public FastWriter print(byte b) { return write(b); }
public FastWriter print(char c) { return write(c); }
public FastWriter print(char[] s) { return write(s); }
public FastWriter print(String s) { return write(s); }
public FastWriter print(int x) { return write(x); }
public FastWriter print(long x) { return write(x); }
public FastWriter print(double x, int precision) { return write(x, precision); }
public FastWriter println(char c){ return writeln(c); }
public FastWriter println(int x){ return writeln(x); }
public FastWriter println(long x){ return writeln(x); }
public FastWriter println(double x, int precision){ return writeln(x, precision); }
public FastWriter print(int... xs) { return write(xs); }
public FastWriter print(long... xs) { return write(xs); }
public FastWriter println(int... xs) { return writeln(xs); }
public FastWriter println(long... xs) { return writeln(xs); }
public FastWriter println(char[] line) { return writeln(line); }
public FastWriter println(char[]... map) { return writeln(map); }
public FastWriter println(String s) { return writeln(s); }
public FastWriter println() { return writeln(); }
}
public void trnz(int... o)
{
for(int i = 0;i < o.length;i++)if(o[i] != 0)System.out.print(i+":"+o[i]+" ");
System.out.println();
}
// print ids which are 1
public void trt(long... o)
{
Queue<Integer> stands = new ArrayDeque<>();
for(int i = 0;i < o.length;i++){
for(long x = o[i];x != 0;x &= x-1)stands.add(i<<6|Long.numberOfTrailingZeros(x));
}
System.out.println(stands);
}
public void tf(boolean... r)
{
for(boolean x : r)System.out.print(x?'#':'.');
System.out.println();
}
public void tf(boolean[]... b)
{
for(boolean[] r : b) {
for(boolean x : r)System.out.print(x?'#':'.');
System.out.println();
}
System.out.println();
}
public void tf(long[]... b)
{
if(INPUT.length() != 0) {
for (long[] r : b) {
for (long x : r) {
for (int i = 0; i < 64; i++) {
System.out.print(x << ~i < 0 ? '#' : '.');
}
}
System.out.println();
}
System.out.println();
}
}
public void tf(long... b)
{
if(INPUT.length() != 0) {
for (long x : b) {
for (int i = 0; i < 64; i++) {
System.out.print(x << ~i < 0 ? '#' : '.');
}
}
System.out.println();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| Java | ["2\n1 2", "5\n1 5 2 11 14"] | 4 seconds | ["1", "642377629"] | NoteTo better understand in which situation several winners are possible let's examine the second test:One possible result of the tournament is as follows ($$$a \rightarrow b$$$ means that $$$a$$$ defeated $$$b$$$): $$$1 \rightarrow 2$$$ $$$2 \rightarrow 3$$$ $$$3 \rightarrow 1$$$ $$$1 \rightarrow 4$$$ $$$1 \rightarrow 5$$$ $$$2 \rightarrow 4$$$ $$$2 \rightarrow 5$$$ $$$3 \rightarrow 4$$$ $$$3 \rightarrow 5$$$ $$$4 \rightarrow 5$$$ Or more clearly in the picture: In this case every team from the set $$$\{ 1, 2, 3 \}$$$ directly or indirectly defeated everyone. I.e.: $$$1$$$st defeated everyone because they can get to everyone else in the following way $$$1 \rightarrow 2$$$, $$$1 \rightarrow 2 \rightarrow 3$$$, $$$1 \rightarrow 4$$$, $$$1 \rightarrow 5$$$. $$$2$$$nd defeated everyone because they can get to everyone else in the following way $$$2 \rightarrow 3$$$, $$$2 \rightarrow 3 \rightarrow 1$$$, $$$2 \rightarrow 4$$$, $$$2 \rightarrow 5$$$. $$$3$$$rd defeated everyone because they can get to everyone else in the following way $$$3 \rightarrow 1$$$, $$$3 \rightarrow 1 \rightarrow 2$$$, $$$3 \rightarrow 4$$$, $$$3 \rightarrow 5$$$. Therefore the total number of winners is $$$3$$$. | Java 11 | standard input | [
"bitmasks",
"combinatorics",
"dp",
"graphs",
"math",
"probabilities"
] | 8508d39c069936fb402e4f4433180465 | The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 14$$$), which is the total number of teams participating in a match. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$) — the strengths of teams participating in a match. | 2,500 | Output a single integer — the expected value of the number of winners of the tournament modulo $$$10^9 + 7$$$. Formally, let $$$M = 10^9+7$$$. It can be demonstrated that the answer can be presented as a irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output a single integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output an integer $$$x$$$ such that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$. | standard output | |
PASSED | 4b98163d57255d47f3238b9a308386f5 | train_107.jsonl | 1630247700 | William is not only interested in trading but also in betting on sports matches. $$$n$$$ teams participate in each match. Each team is characterized by strength $$$a_i$$$. Each two teams $$$i < j$$$ play with each other exactly once. Team $$$i$$$ wins with probability $$$\frac{a_i}{a_i + a_j}$$$ and team $$$j$$$ wins with probability $$$\frac{a_j}{a_i + a_j}$$$.The team is called a winner if it directly or indirectly defeated all other teams. Team $$$a$$$ defeated (directly or indirectly) team $$$b$$$ if there is a sequence of teams $$$c_1$$$, $$$c_2$$$, ... $$$c_k$$$ such that $$$c_1 = a$$$, $$$c_k = b$$$ and team $$$c_i$$$ defeated team $$$c_{i + 1}$$$ for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$. Note that it is possible that team $$$a$$$ defeated team $$$b$$$ and in the same time team $$$b$$$ defeated team $$$a$$$.William wants you to find the expected value of the number of winners. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.io.UncheckedIOException;
import java.io.Closeable;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 29);
thread.start();
thread.join();
}
static class TaskAdapter implements Runnable {
@Override
public void run() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInput in = new FastInput(inputStream);
FastOutput out = new FastOutput(outputStream);
FSportsBetting solver = new FSportsBetting();
solver.solve(1, in, out);
out.close();
}
}
static class FSportsBetting {
int mod = (int) 1e9 + 7;
Power pow = new Power(mod);
Debug debug = new Debug(false);
public void solve(int testNumber, FastInput in, FastOutput out) {
int n = in.ri();
int[] a = in.ri(n);
long[] I = new long[1 << n];
long[] invI = new long[1 << n];
long[][] fp = new long[n][n];
for (int i = 0; i < n; i++) {
fp[i][0] = 1;
for (int j = 1; j < n; j++) {
fp[i][j] = fp[i][j - 1] * a[i] % mod;
}
}
long[][] subsetfp = new long[n][1 << n];
for (int j = 0; j < n; j++) {
subsetfp[j][0] = 1;
}
for (int i = 1; i < 1 << n; i++) {
int lb = Integer.lowestOneBit(i);
int log = Log2.floorLog(lb);
for (int j = 0; j < n; j++) {
subsetfp[j][i] = subsetfp[j][i - lb] * fp[log][j] % mod;
}
}
I[0] = 1;
invI[0] = 1;
for (int i = 1; i < 1 << n; i++) {
int lb = Integer.lowestOneBit(i);
int log = Log2.floorLog(lb);
I[i] = I[i - lb];
for (int j = 0; j < n; j++) {
if (Bits.get(i, j) == 0 || j == log) {
continue;
}
I[i] = I[i] * (a[log] + a[j]) % mod;
}
invI[i] = pow.inverse((int) I[i]);
}
debug.debug("I", I);
long[] f = new long[1 << n];
f[0] = 1;
for (int i = 1; i < 1 << n; i++) {
int lb = Integer.lowestOneBit(i);
if (lb == i) {
f[i] = 1;
continue;
}
long invalid = 0;
int subset = i;
while (subset > 0) {
subset = (subset - 1) & i;
if (subset == 0) {
continue;
}
int other = i - subset;
int remain = FastBitCount2.count(other);
invalid += f[subset] * subsetfp[remain][subset] % mod
* I[other] % mod;
}
invalid %= mod;
f[i] = I[i] - invalid;
f[i] = DigitUtils.mod(f[i], mod);
}
debug.debug("f", f);
long[] prob = new long[n];
int mask = (1 << n) - 1;
for (int i = 1; i < 1 << n; i++) {
int other = mask - i;
int remain = FastBitCount2.count(other);
long p = f[i] * subsetfp[remain][i] % mod * I[other] % mod;
for (int j = 0; j < n; j++) {
if (Bits.get(i, j) == 0) {
continue;
}
prob[j] += p;
}
}
debug.debug("prob", prob);
long ans = 0;
for (int i = 0; i < n; i++) {
ans += prob[i] % mod;
}
debug.debug("3/2", 3L * pow.inverse(2) % mod);
ans = ans % mod * invI[mask] % mod;
ans = DigitUtils.mod(ans, mod);
out.println(ans);
}
}
static class SequenceUtils {
public static void swap(long[] data, int i, int j) {
long tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
}
static class Log2 {
public static int floorLog(int x) {
if (x <= 0) {
throw new IllegalArgumentException();
}
return 31 - Integer.numberOfLeadingZeros(x);
}
}
static class FastInput {
private final InputStream is;
private byte[] buf = new byte[1 << 13];
private int bufLen;
private int bufOffset;
private int next;
public FastInput(InputStream is) {
this.is = is;
}
public void populate(int[] data) {
for (int i = 0; i < data.length; i++) {
data[i] = readInt();
}
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read(buf);
} catch (IOException e) {
bufLen = -1;
}
if (bufLen == -1) {
return -1;
}
}
return buf[bufOffset++];
}
public void skipBlank() {
while (next >= 0 && next <= 32) {
next = read();
}
}
public int ri() {
return readInt();
}
public int[] ri(int n) {
int[] ans = new int[n];
populate(ans);
return ans;
}
public int readInt() {
boolean rev = false;
skipBlank();
if (next == '+' || next == '-') {
rev = next == '-';
next = read();
}
int val = 0;
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
return rev ? val : -val;
}
}
static class Debug {
private boolean offline;
private PrintStream out = System.err;
static int[] empty = new int[0];
public Debug(boolean enable) {
offline = enable && System.getSecurityManager() == null;
}
public Debug debug(String name, long x) {
if (offline) {
debug(name, "" + x);
}
return this;
}
public Debug debug(String name, String x) {
if (offline) {
out.printf("%s=%s", name, x);
out.println();
}
return this;
}
public Debug debug(String name, Object x) {
return debug(name, x, empty);
}
public Debug debug(String name, Object x, int... indexes) {
if (offline) {
if (x == null || !x.getClass().isArray()) {
out.append(name);
for (int i : indexes) {
out.printf("[%d]", i);
}
out.append("=").append("" + x);
out.println();
} else {
indexes = Arrays.copyOf(indexes, indexes.length + 1);
if (x instanceof byte[]) {
byte[] arr = (byte[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug(name, arr[i], indexes);
}
} else if (x instanceof short[]) {
short[] arr = (short[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug(name, arr[i], indexes);
}
} else if (x instanceof boolean[]) {
boolean[] arr = (boolean[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug(name, arr[i], indexes);
}
} else if (x instanceof char[]) {
char[] arr = (char[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug(name, arr[i], indexes);
}
} else if (x instanceof int[]) {
int[] arr = (int[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug(name, arr[i], indexes);
}
} else if (x instanceof float[]) {
float[] arr = (float[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug(name, arr[i], indexes);
}
} else if (x instanceof double[]) {
double[] arr = (double[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug(name, arr[i], indexes);
}
} else if (x instanceof long[]) {
long[] arr = (long[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug(name, arr[i], indexes);
}
} else {
Object[] arr = (Object[]) x;
for (int i = 0; i < arr.length; i++) {
indexes[indexes.length - 1] = i;
debug(name, arr[i], indexes);
}
}
}
}
return this;
}
}
static class ExtGCD {
public static long extGCD(long a, long b, long[] xy) {
if (a >= b) {
return extGCD0(a, b, xy);
}
long ans = extGCD0(b, a, xy);
SequenceUtils.swap(xy, 0, 1);
return ans;
}
private static long extGCD0(long a, long b, long[] xy) {
if (b == 0) {
xy[0] = 1;
xy[1] = 0;
return a;
}
long ans = extGCD0(b, a % b, xy);
long x = xy[0];
long y = xy[1];
xy[0] = y;
xy[1] = x - a / b * y;
return ans;
}
}
static class FastBitCount2 {
private static byte[] size = new byte[1 << 16];
static final int MASK = (1 << 16) - 1;
static {
for (int i = 0; i < size.length; i++) {
size[i] = (byte) Integer.bitCount(i);
}
}
public static int count(int x) {
return size[x & MASK] + size[(x >>> 16) & MASK];
}
}
static class Power implements InverseNumber {
int mod;
public Power(int mod) {
this.mod = mod;
}
public int inverse(int x) {
int ans = inverseExtGCD(x);
// if(modular.mul(ans, x) != 1){
// throw new IllegalStateException();
// }
return ans;
}
public int inverseExtGCD(int x) {
return (int) DigitUtils.modInverse(x, mod);
}
}
static class Bits {
private Bits() {
}
public static int get(int x, int i) {
return (x >>> i) & 1;
}
}
static class LongExtGCDObject {
private long[] xy = new long[2];
public long extgcd(long a, long b) {
return ExtGCD.extGCD(a, b, xy);
}
public long getX() {
return xy[0];
}
}
static class FastOutput implements AutoCloseable, Closeable, Appendable {
private static final int THRESHOLD = 32 << 10;
private OutputStream writer;
private StringBuilder cache = new StringBuilder(THRESHOLD * 2);
private static Field stringBuilderValueField;
private char[] charBuf = new char[THRESHOLD * 2];
private byte[] byteBuf = new byte[THRESHOLD * 2];
static {
try {
stringBuilderValueField = StringBuilder.class.getSuperclass().getDeclaredField("value");
stringBuilderValueField.setAccessible(true);
} catch (Exception e) {
stringBuilderValueField = null;
}
stringBuilderValueField = null;
}
public FastOutput append(CharSequence csq) {
cache.append(csq);
return this;
}
public FastOutput append(CharSequence csq, int start, int end) {
cache.append(csq, start, end);
return this;
}
private void afterWrite() {
if (cache.length() < THRESHOLD) {
return;
}
flush();
}
public FastOutput(OutputStream writer) {
this.writer = writer;
}
public FastOutput append(char c) {
cache.append(c);
afterWrite();
return this;
}
public FastOutput append(long c) {
cache.append(c);
afterWrite();
return this;
}
public FastOutput println(long c) {
return append(c).println();
}
public FastOutput println() {
return append('\n');
}
public FastOutput flush() {
try {
if (stringBuilderValueField != null) {
try {
byte[] value = (byte[]) stringBuilderValueField.get(cache);
writer.write(value, 0, cache.length());
} catch (Exception e) {
stringBuilderValueField = null;
}
}
if (stringBuilderValueField == null) {
int n = cache.length();
if (n > byteBuf.length) {
//slow
writer.write(cache.toString().getBytes(StandardCharsets.UTF_8));
// writer.append(cache);
} else {
cache.getChars(0, n, charBuf, 0);
for (int i = 0; i < n; i++) {
byteBuf[i] = (byte) charBuf[i];
}
writer.write(byteBuf, 0, n);
}
}
writer.flush();
cache.setLength(0);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return this;
}
public void close() {
flush();
try {
writer.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public String toString() {
return cache.toString();
}
}
static class DigitUtils {
private static LongExtGCDObject longExtGCDObject = new LongExtGCDObject();
private DigitUtils() {
}
public static int mod(long x, int mod) {
if (x < -mod || x >= mod) {
x %= mod;
}
if (x < 0) {
x += mod;
}
return (int) x;
}
public static long mod(long x, long mod) {
if (x < -mod || x >= mod) {
x %= mod;
}
if (x < 0) {
x += mod;
}
return x;
}
public static long modInverse(long x, long mod) {
long g = longExtGCDObject.extgcd(x, mod);
assert g == 1;
long a = longExtGCDObject.getX();
return DigitUtils.mod(a, mod);
}
}
static interface InverseNumber {
}
}
| Java | ["2\n1 2", "5\n1 5 2 11 14"] | 4 seconds | ["1", "642377629"] | NoteTo better understand in which situation several winners are possible let's examine the second test:One possible result of the tournament is as follows ($$$a \rightarrow b$$$ means that $$$a$$$ defeated $$$b$$$): $$$1 \rightarrow 2$$$ $$$2 \rightarrow 3$$$ $$$3 \rightarrow 1$$$ $$$1 \rightarrow 4$$$ $$$1 \rightarrow 5$$$ $$$2 \rightarrow 4$$$ $$$2 \rightarrow 5$$$ $$$3 \rightarrow 4$$$ $$$3 \rightarrow 5$$$ $$$4 \rightarrow 5$$$ Or more clearly in the picture: In this case every team from the set $$$\{ 1, 2, 3 \}$$$ directly or indirectly defeated everyone. I.e.: $$$1$$$st defeated everyone because they can get to everyone else in the following way $$$1 \rightarrow 2$$$, $$$1 \rightarrow 2 \rightarrow 3$$$, $$$1 \rightarrow 4$$$, $$$1 \rightarrow 5$$$. $$$2$$$nd defeated everyone because they can get to everyone else in the following way $$$2 \rightarrow 3$$$, $$$2 \rightarrow 3 \rightarrow 1$$$, $$$2 \rightarrow 4$$$, $$$2 \rightarrow 5$$$. $$$3$$$rd defeated everyone because they can get to everyone else in the following way $$$3 \rightarrow 1$$$, $$$3 \rightarrow 1 \rightarrow 2$$$, $$$3 \rightarrow 4$$$, $$$3 \rightarrow 5$$$. Therefore the total number of winners is $$$3$$$. | Java 11 | standard input | [
"bitmasks",
"combinatorics",
"dp",
"graphs",
"math",
"probabilities"
] | 8508d39c069936fb402e4f4433180465 | The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 14$$$), which is the total number of teams participating in a match. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$) — the strengths of teams participating in a match. | 2,500 | Output a single integer — the expected value of the number of winners of the tournament modulo $$$10^9 + 7$$$. Formally, let $$$M = 10^9+7$$$. It can be demonstrated that the answer can be presented as a irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output a single integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output an integer $$$x$$$ such that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$. | standard output | |
PASSED | ea2ebd0303ff217d4609b5ab41a376f9 | train_107.jsonl | 1630247700 | William is not only interested in trading but also in betting on sports matches. $$$n$$$ teams participate in each match. Each team is characterized by strength $$$a_i$$$. Each two teams $$$i < j$$$ play with each other exactly once. Team $$$i$$$ wins with probability $$$\frac{a_i}{a_i + a_j}$$$ and team $$$j$$$ wins with probability $$$\frac{a_j}{a_i + a_j}$$$.The team is called a winner if it directly or indirectly defeated all other teams. Team $$$a$$$ defeated (directly or indirectly) team $$$b$$$ if there is a sequence of teams $$$c_1$$$, $$$c_2$$$, ... $$$c_k$$$ such that $$$c_1 = a$$$, $$$c_k = b$$$ and team $$$c_i$$$ defeated team $$$c_{i + 1}$$$ for all $$$i$$$ from $$$1$$$ to $$$k - 1$$$. Note that it is possible that team $$$a$$$ defeated team $$$b$$$ and in the same time team $$$b$$$ defeated team $$$a$$$.William wants you to find the expected value of the number of winners. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskF solver = new TaskF();
solver.solve(1, in, out);
out.close();
}
static class TaskF {
final int MOD = (int) (1e9 + 7);
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
int[][] p = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
p[i][j] = (int) (a[i] * (long) inv(a[i] + a[j]) % MOD);
}
}
long[] probIsScc = new long[1 << n];
long ans = 0;
for (int sccMask = 0; sccMask < 1 << n; sccMask++) {
long probLeadingScc = 1;
for (int i = 0; i < n; i++) {
if (((sccMask >> i) & 1) == 0) {
continue;
}
for (int j = 0; j < n; j++) {
if (((sccMask >> j) & 1) != 0) {
continue;
}
probLeadingScc = probLeadingScc * p[i][j] % MOD;
}
}
probIsScc[sccMask] = 1;
for (int m = (sccMask - 1) & sccMask; m > 0; m = (m - 1) & sccMask) {
long x = probIsScc[m];
for (int i = 0; i < n; i++) {
if (((m >> i) & 1) == 0) {
continue;
}
for (int j = 0; j < n; j++) {
if (((sccMask >> j) & 1) == 0) {
continue;
}
if (((m >> j) & 1) != 0) {
continue;
}
x = x * p[i][j] % MOD;
}
}
probIsScc[sccMask] -= x;
if (probIsScc[sccMask] < 0) {
probIsScc[sccMask] += MOD;
}
}
long cur = 1;
cur = cur * probIsScc[sccMask] % MOD;
cur = cur * probLeadingScc % MOD;
cur = cur * Integer.bitCount(sccMask) % MOD;
ans = (ans + cur) % MOD;
}
out.println(ans);
}
private int inv(int x) {
return pow(x, MOD - 2);
}
private int pow(long a, long n) {
long r = 1;
while (n > 0) {
if (n % 2 == 1) {
r = r * a % MOD;
}
a = a * a % MOD;
n /= 2;
}
return (int) r;
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
String rl = in.readLine();
if (rl == null) {
return null;
}
st = new StringTokenizer(rl);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["2\n1 2", "5\n1 5 2 11 14"] | 4 seconds | ["1", "642377629"] | NoteTo better understand in which situation several winners are possible let's examine the second test:One possible result of the tournament is as follows ($$$a \rightarrow b$$$ means that $$$a$$$ defeated $$$b$$$): $$$1 \rightarrow 2$$$ $$$2 \rightarrow 3$$$ $$$3 \rightarrow 1$$$ $$$1 \rightarrow 4$$$ $$$1 \rightarrow 5$$$ $$$2 \rightarrow 4$$$ $$$2 \rightarrow 5$$$ $$$3 \rightarrow 4$$$ $$$3 \rightarrow 5$$$ $$$4 \rightarrow 5$$$ Or more clearly in the picture: In this case every team from the set $$$\{ 1, 2, 3 \}$$$ directly or indirectly defeated everyone. I.e.: $$$1$$$st defeated everyone because they can get to everyone else in the following way $$$1 \rightarrow 2$$$, $$$1 \rightarrow 2 \rightarrow 3$$$, $$$1 \rightarrow 4$$$, $$$1 \rightarrow 5$$$. $$$2$$$nd defeated everyone because they can get to everyone else in the following way $$$2 \rightarrow 3$$$, $$$2 \rightarrow 3 \rightarrow 1$$$, $$$2 \rightarrow 4$$$, $$$2 \rightarrow 5$$$. $$$3$$$rd defeated everyone because they can get to everyone else in the following way $$$3 \rightarrow 1$$$, $$$3 \rightarrow 1 \rightarrow 2$$$, $$$3 \rightarrow 4$$$, $$$3 \rightarrow 5$$$. Therefore the total number of winners is $$$3$$$. | Java 8 | standard input | [
"bitmasks",
"combinatorics",
"dp",
"graphs",
"math",
"probabilities"
] | 8508d39c069936fb402e4f4433180465 | The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 14$$$), which is the total number of teams participating in a match. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \leq a_i \leq 10^6$$$) — the strengths of teams participating in a match. | 2,500 | Output a single integer — the expected value of the number of winners of the tournament modulo $$$10^9 + 7$$$. Formally, let $$$M = 10^9+7$$$. It can be demonstrated that the answer can be presented as a irreducible fraction $$$\frac{p}{q}$$$, where $$$p$$$ and $$$q$$$ are integers and $$$q \not \equiv 0 \pmod{M}$$$. Output a single integer equal to $$$p \cdot q^{-1} \bmod M$$$. In other words, output an integer $$$x$$$ such that $$$0 \le x < M$$$ and $$$x \cdot q \equiv p \pmod{M}$$$. | standard output | |
PASSED | 4fd6eaaa16fc03f608915b9339087c75 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) throws IOException
{
FastScanner f= new FastScanner();
int ttt=1;
// ttt=f.nextInt();
PrintWriter out=new PrintWriter(System.out);
outer: for(int tt=0;tt<ttt;tt++) {
int n=f.nextInt();
int k=f.nextInt();
int[][] or=new int[n][30];
int[][] and=new int[n][30];
for(int i=1;i<n;i++) {
System.out.println("or 1 "+(i+1));
int num=f.nextInt();
int ind=0;
while(num>0) {
or[i][ind]=num%2;
ind++;
num/=2;
}
}
for(int i=1;i<n;i++) {
System.out.println("and 1 "+(i+1));
int num=f.nextInt();
int ind=0;
while(num>0) {
and[i][ind]=num%2;
ind++;
num/=2;
}
}
System.out.println("and 2 3 ");
int num=f.nextInt();
int ind=0;
int[] spare=new int[30];
while(num>0) {
spare[ind]=num%2;
ind++;
num/=2;
}
int[][] nums=new int[n][30];
int[] count1=new int[30];
int[] count2=new int[30];
for(int i=1;i<n;i++) {
for(int j=0;j<30;j++) {
count1[j]+=or[i][j];
count2[j]+=and[i][j];
}
}
for(int i=0;i<30;i++) {
if(count1[i]==n-1) {
nums[0][i]=1;
}
if(count1[i]==n-1 && count2[i]==0 && spare[i]==1) {
nums[0][i]=0;
}
}
for(int i=1;i<n;i++) {
for(int j=0;j<30;j++) {
if(nums[0][j]==0) {
if(or[i][j]==1) {
nums[i][j]=1;
}
}
else {
if(and[i][j]==1) {
nums[i][j]=1;
}
}
}
}
int[] save=new int[n];
for(int i=0;i<n;i++) {
num=0;
for(int j=0;j<30;j++) {
num+=nums[i][j]*Math.pow(2, j);
}
save[i]=num;
}
sort(save);
// System.out.println(Arrays.toString(save));
System.out.println("finish "+save[k-1]);
}
out.close();
}
static void sort(int[] p) {
ArrayList<Integer> q = new ArrayList<>();
for (int i: p) q.add( i);
Collections.sort(q);
for (int i = 0; i < p.length; i++) p[i] = q.get(i);
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long[] readLongArray(int n) {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 7caefeb6c3b9daa132dbafce8b106d15 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 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.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(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, FastScanner in, PrintWriter out) {
final int BITS = 31;
int n = in.nextInt();
int k = in.nextInt();
int[][] and3 = new int[3][3];
int[][] or3 = new int[3][3];
for (int i = 0; i < 3; i++) {
for (int j = i + 1; j < 3; j++) {
out.printf("or %d %d\n", i + 1, j + 1);
out.flush();
or3[i][j] = in.nextInt();
out.printf("and %d %d\n", i + 1, j + 1);
out.flush();
and3[i][j] = in.nextInt();
}
}
int[] a = new int[n];
outer:
for (int bit = 0; bit < BITS; bit++) {
int[] v = new int[3];
for (v[0] = 0; v[0] < 2; v[0]++) {
for (v[1] = 0; v[1] < 2; v[1]++) {
for (v[2] = 0; v[2] < 2; v[2]++) {
boolean ok = true;
for (int i = 0; i < 3; i++) {
for (int j = i + 1; j < 3; j++) {
int or = (or3[i][j] >> bit) & 1;
int and = (and3[i][j] >> bit) & 1;
if (or != (v[i] | v[j])) {
ok = false;
break;
}
if (and != (v[i] & v[j])) {
ok = false;
break;
}
}
}
if (ok) {
for (int i = 0; i < 3; i++) {
a[i] |= v[i] << bit;
}
continue outer;
}
}
}
}
}
for (int i = 3; i < n; i++) {
out.printf("or %d %d\n", 1, i + 1);
out.flush();
int or = in.nextInt();
out.printf("and %d %d\n", 1, i + 1);
out.flush();
int and = in.nextInt();
for (int bit = 0; bit < BITS; bit++) {
int bo = (or >> bit) & 1;
int ba = (and >> bit) & 1;
if (ba == 1) {
a[i] |= 1 << bit;
} else if (bo == 0) {
} else if (((a[0] >> bit) & 1) == 0) {
a[i] |= 1 << bit;
}
}
}
Arrays.sort(a);
out.printf("finish %d\n", a[k - 1]);
out.flush();
}
}
static class FastScanner {
private BufferedReader in;
private StringTokenizer st;
public FastScanner(InputStream stream) {
in = new BufferedReader(new InputStreamReader(stream));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
String rl = in.readLine();
if (rl == null) {
return null;
}
st = new StringTokenizer(rl);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | effd88e6b95d1bb4993fa1f72b18b7b6 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class cfContest1556 {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int k = scan.nextInt();
int[] arr = new int[n];
for (int i = 1; i <= n; i += 3) {
if (i + 2 > n) {
break;
}
System.out.println("and " + i + " " + (i + 1));
int fa = scan.nextInt();
System.out.println("or " + i + " " + (i + 1));
int fo = scan.nextInt();
System.out.println("and " + (i + 1) + " " + (i + 2));
int ma = scan.nextInt();
System.out.println("or " + (i + 1) + " " + (i + 2));
int mo = scan.nextInt();
System.out.println("and " + i + " " + (i + 2));
int la = scan.nextInt();
System.out.println("or " + i + " " + (i + 2));
int lo = scan.nextInt();
int a = (fa + fo);
int b = (ma + mo);
int c = (la + lo);
int x = ((a + c) - b) / 2;
int y = (c - x);
int z = (b - y);
arr[i] = z;
arr[i + 1] = y;
arr[i - 1] = x;
}
int p = (n / 3) * 3;
++p;
if (n % 3 >= 1) {
System.out.println("and " + (p - 1) + " " + (p));
int fa = scan.nextInt();
System.out.println("or " + (p - 1) + " " + (p));
int fo = scan.nextInt();
int c = (fa + fo);
arr[p - 1] = c - arr[p - 2];
++p;
}
if (n % 3 >= 2) {
System.out.println("and " + (p - 1) + " " + (p));
int fa = scan.nextInt();
System.out.println("or " + (p - 1) + " " + (p));
int fo = scan.nextInt();
int c = (fa + fo);
arr[p - 1] = c - arr[p - 2];
++p;
}
sort(arr);
System.out.println("finish " + arr[k - 1]);
}
static void sort(int[] a) {
ArrayList<Integer> l = new ArrayList<>();
for (int i : a) {
l.add(i);
}
Collections.sort(l);
for (int i = 0; i < a.length; i++) {
a[i] = l.get(i);
}
}
}
| Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 000f7e9e3c0f80c2b5c9b712b7b51aca | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.concurrent.CompletableFuture;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.copyOfRange;
import static java.util.Arrays.fill;
public class Main {
public static void main(String[] args) throws Exception {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(in, out);
out.close();
}
}
class Task {
long mod = 998244353;
void print(PrintWriter out, int a, int b, int op) {
out.println((op == 1 ? "and " : "or ") + a + " " + b);
out.flush();
}
public void solve(InputReader in, PrintWriter out) throws Exception {
int n = in.nextInt();
int K = in.nextInt();
int ab, ab1, ac, ac1, bc, bc1;
print(out, 1, 2, 1);
ab = in.nextInt();
print(out, 1, 2, 0);
ab1 = in.nextInt();
print(out, 1, 3, 1);
ac = in.nextInt();
print(out, 1, 3, 0);
ac1 = in.nextInt();
print(out, 2, 3, 1);
bc = in.nextInt();
print(out, 2, 3, 0);
bc1 = in.nextInt();
int[] a = new int[n];
for (int b = 0; b <= 30; b++) {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
if ((i & j) == (ab >> b & 1) && (i | j) == (ab1 >> b & 1)) {
for (int k = 0; k < 2; k++) {
if ((i & k) != (ac >> b & 1) || (i | k) != (ac1 >> b & 1)) continue;
if ((j & k) != (bc >> b & 1) || (j | k) != (bc1 >> b & 1)) continue;
a[0] |= i << b;
a[1] |= j << b;
a[2] |= k << b;
}
}
}
}
}
for (int i = 3; i < n; i++) {
print(out, 1, i + 1, 1);
int x = in.nextInt();
print(out, 1, i + 1, 0);
int y = in.nextInt();
for (int b = 0; b <= 30; b++) {
int k = a[0] >> b & 1;
for (int j = 0; j < 2; j++) {
if ((k & j) == (x >> b & 1) && (k | j) == (y >> b & 1)) {
a[i] |= j << b;
}
}
}
}
Arrays.sort(a);
out.println("finish " + a[K - 1]);
out.flush();
}
}
class InputReader {
private final BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(nextLine());
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | f7eaf42b10e49cb2de1cc4221be830fa | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[])
{
FastReader input=new FastReader();
PrintWriter out=new PrintWriter(System.out);
int T=1;
while(T-->0)
{
int n=input.nextInt();
int k=input.nextInt();
long arr[]=new long[n+1];
for(int i=1;i<=n-1;i++)
{
System.out.println("and "+i+" "+(i+1));
System.out.flush();
long and=input.nextInt();
System.out.println("or "+i+" "+(i+1));
System.out.flush();
long or=input.nextInt();
long s=or+and;
arr[i]=s;
}
System.out.println("and "+1+" "+3);
System.out.flush();
long and=input.nextInt();
System.out.println("or "+1+" "+3);
System.out.flush();
long or=input.nextInt();
long s=or+and;
long sum=arr[1]+arr[2]+s;
sum/=2;
sum-=arr[1];
long c=sum;
long b=arr[2]-c;
long a=arr[1]-b;
ArrayList<Long> list=new ArrayList<>();
list.add(a);list.add(b);list.add(c);
for(int i=3;i<=n-1;i++)
{
long v=arr[i]-list.get(list.size()-1);
list.add(v);
}
Collections.sort(list);
System.out.println("finish "+(list.get(k-1)));
System.out.flush();
}
out.close();
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str="";
try
{
str=br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | ba952b22956ede50a7a67197dfa446c4 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.*;
public class codeforcesC{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String args[]){
FastReader sc=new FastReader();
int n=sc.nextInt();
int k=sc.nextInt();
System.out.println("or "+2+" "+3);
int a1=sc.nextInt();
System.out.println("and "+2+" "+3);
int a2=sc.nextInt();
int sum1=a1+a2;
System.out.println("or "+1+" "+2);
int b1=sc.nextInt();
System.out.println("and "+1+" "+2);
int b2=sc.nextInt();
int sum2=b1+b2;
System.out.println("or "+1+" "+3);
int c1=sc.nextInt();
System.out.println("and "+1+" "+3);
int c2=sc.nextInt();
int sum3=c1+c2;
int ele1=(sum3+sum2-sum1)/2;
List<Integer> list=new ArrayList<>();list.add(ele1);list.add(sum2-ele1);list.add(sum3-ele1);
for(int i=4;i<=n;i++){
System.out.println("or "+1+" "+i);
int a=sc.nextInt();
System.out.println("and "+1+" "+i);
int b=sc.nextInt();
int sum=a+b;
list.add(sum-ele1);
}
Collections.sort(list);
System.out.println("finish "+list.get(k-1));
System.out.flush();
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 75369478eb4e121e470934dad7e8415f | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | ///package codeforce.div2.deltix.summer2021;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import static java.lang.System.out;
import static java.util.stream.Collectors.joining;
/**
* @author pribic (Priyank Doshi)
* @see <a href="https://codeforces.com/contest/1556/problem/D" target="_top">https://codeforces.com/contest/1556/problem/D</a>
* @since 30/08/21 7:57 AM
*/
public class D {
static FastScanner sc = new FastScanner(System.in);
public static void main(String[] args) {
try (PrintWriter out = new PrintWriter(System.out)) {
int T = 1;//sc.nextInt();
for (int tt = 1; tt <= T; tt++) {
int n = sc.nextInt();
int k = sc.nextInt();
int[] nums = new int[n];
int s12 = and(1, 2) + or(1, 2);
int s13 = and(1, 3) + or(1, 3);
int s23 = and(3, 2) + or(3, 2);
nums[0] = ((s12 + s13) - s23) / 2;
nums[1] = s12 - nums[0];
nums[2] = s13 - nums[0];
for (int i = 3; i < n; i++) {
int si0 = and(i + 1, 1) + or(i + 1, 1);
nums[i] = si0 - nums[0];
}
nums = Arrays.stream(nums).sorted().toArray();
System.out.println("finish " + nums[k - 1]);
System.out.flush();
}
}
}
static int and(int i, int j) {
out.println("and " + i + " " + j);
System.out.flush();
return sc.nextInt();
}
static int or(int i, int j) {
out.println("or " + i + " " + j);
System.out.flush();
return sc.nextInt();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f), 32768);
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 2cfb669e272927c0c5da8cfdcdcfe42f | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | //package codeforce.div2.deltix.summer2021;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import static java.lang.System.out;
import static java.util.stream.Collectors.joining;
/**
* @author pribic (Priyank Doshi)
* @see <a href="https://codeforces.com/contest/1556/problem/D" target="_top">https://codeforces.com/contest/1556/problem/D</a>
* @since 30/08/21 7:57 AM
*/
public class D {
static FastScanner sc = new FastScanner(System.in);
public static void main(String[] args) {
try (PrintWriter out = new PrintWriter(System.out)) {
int T = 1;//sc.nextInt();
for (int tt = 1; tt <= T; tt++) {
int n = sc.nextInt();
int k = sc.nextInt();
Integer[] nums = new Integer[n];
int s12 = and(1, 2) + or(1, 2);
int s13 = and(1, 3) + or(1, 3);
int s23 = and(3, 2) + or(3, 2);
nums[0] = ((s12 + s13) - s23) / 2;
nums[1] = s12 - nums[0];
nums[2] = s13 - nums[0];
for (int i = 3; i < n; i++) {
int si0 = and(i + 1, 1) + or(i + 1, 1);
nums[i] = si0 - nums[0];
}
List<Integer> aa = Arrays.asList(nums);
Collections.sort(aa);
nums = aa.toArray(new Integer[n]);
System.out.println("finish " + nums[k - 1]);
System.out.flush();
}
}
}
static int and(int i, int j) {
out.println("and " + i + " " + j);
System.out.flush();
return sc.nextInt();
}
static int or(int i, int j) {
out.println("or " + i + " " + j);
System.out.flush();
return sc.nextInt();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f), 32768);
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | ef215a4633557268d637a0dfa65f6622 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | //package codeforce.div2.deltix.summer2021;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import static java.lang.System.out;
import static java.util.stream.Collectors.joining;
/**
* @author pribic (Priyank Doshi)
* @see <a href="https://codeforces.com/contest/1556/problem/D" target="_top">https://codeforces.com/contest/1556/problem/D</a>
* @since 30/08/21 7:57 AM
*/
public class D {
static FastScanner sc = new FastScanner(System.in);
public static void main(String[] args) {
try (PrintWriter out = new PrintWriter(System.out)) {
int T = 1;//sc.nextInt();
for (int tt = 1; tt <= T; tt++) {
int n = sc.nextInt();
int k = sc.nextInt();
int[] nums = new int[n];
int s12 = and(1, 2) + or(1, 2);
int s13 = and(1, 3) + or(1, 3);
int s23 = and(3, 2) + or(3, 2);
nums[0] = ((s12 + s13) - s23) / 2;
nums[1] = s12 - nums[0];
nums[2] = s13 - nums[0];
for (int i = 3; i < n; i++) {
int si0 = and(i + 1, 1) + or(i + 1, 1);
nums[i] = si0 - nums[0];
}
Arrays.sort(nums);
System.out.println("finish " + nums[k - 1]);
System.out.flush();
}
}
}
static int and(int i, int j) {
out.println("and " + i + " " + j);
System.out.flush();
return sc.nextInt();
}
static int or(int i, int j) {
out.println("or " + i + " " + j);
System.out.flush();
return sc.nextInt();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f), 32768);
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 12c9f5ed31f142f180413f6a22afeb85 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | //package codeforce.div2.deltix.summer2021;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.HashSet;
import static java.lang.System.out;
import static java.util.stream.Collectors.joining;
/**
* @author pribic (Priyank Doshi)
* @see <a href="https://codeforces.com/contest/1556/problem/D" target="_top">https://codeforces.com/contest/1556/problem/D</a>
* @since 30/08/21 7:57 AM
*/
public class D {
static FastScanner sc = new FastScanner(System.in);
public static void main(String[] args) {
try (PrintWriter out = new PrintWriter(System.out)) {
int T = 1;//sc.nextInt();
for (int tt = 1; tt <= T; tt++) {
int n = sc.nextInt();
int k = sc.nextInt();
int[] nums = new int[n];
int s12 = and(1, 2) + or(1, 2);
int s13 = and(1, 3) + or(1, 3);
int s23 = and(3, 2) + or(3, 2);
nums[0] = ((s12 + s13) - s23) / 2;
nums[1] = s12 - nums[0];
nums[2] = s13 - nums[0];
for (int i = 3; i < n; i++) {
int si0 = and(i + 1, 1) + or(i + 1, 1);
nums[i] = si0 - nums[0];
}
Arrays.sort(nums);
System.out.println("finish " + nums[k - 1]);
System.out.flush();
}
}
}
static int and(int i, int j) {
out.println("and " + i + " " + j);
return sc.nextInt();
}
static int or(int i, int j) {
out.println("or " + i + " " + j);
return sc.nextInt();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f), 32768);
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 27373cdae61ff8cb7493f0e79f168837 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
/**
* @author Naitik
*
*/
public class Main
{
static FastReader sc=new FastReader();
static int dp[][][];
static int mod=1000000007;
static int mod1=998244353;
static int max;
static long bit[];
// static long seg[];
// static long fact[];
// static long A[];
static PrintWriter out=new PrintWriter(System.out);
public static void main(String[] args)
{
// StringBuffer sb=new StringBuffer("");
int ttt=1;
// ttt =i();
outer :while (ttt-- > 0)
{
int n=i();
int k=i();
long p=and(1, 2);
long q=or(1, 2);
long a_b=(p^q)+p*2;
p=and(2, 3);
q=or(2, 3);
long b_c=(p^q)+p*2;
p=and(1, 3);
q=or(1, 3);
long a_c=(p^q)+p*2;
long a=(a_b-b_c+a_c)/2;
long c=a_c-a;
long b=b_c-c;
ArrayList<Long> l=new ArrayList<Long>();
l.add(a);
l.add(b);
l.add(c);
for(int i=4;i<=n;i++) {
p=and(1, i);
q=or(1, i);
long y= (p^q);
y^=a;
l.add(y);
}
l.sort(null);
System.out.println("finish "+l.get(k-1));
}
//System.out.println(sb.toString());
out.close();
//CHECK FOR N=1 //CHECK FOR M=0
//CHECK FOR N=1 //CHECK FOR M=0
//CHECK FOR N=1
}
static long and(int i,int j) {
System.out.println("and "+i+" "+j);
long y=l();
return y;
}
static long or(int i,int j) {
System.out.println("or "+i+" "+j);
long y=l();
return y;
}
static class Pair implements Comparable<Pair>
{
int x;
int y;
// int z;
Pair(int x,int y,int z){
this.x=x;
this.y=y;
//this.z=z;
}
@Override
public int compareTo(Pair o) {
if(this.x>o.x)
return +1;
else if(this.x<o.x)
return -1;
else {
if(this.y>o.y)
return -1;
else if(this.y<o.y)
return +1;
else
return 0;
}
}
// public int hashCode()
// {
// final int temp = 14;
// int ans = 1;
// ans =x*31+y*13;
// return ans;
// }
// @Override
// public boolean equals(Object o)
// {
// if (this == o) {
// return true;
// }
// if (o == null) {
// return false;
// }
// if (this.getClass() != o.getClass()) {
// return false;
// }
// Pair other = (Pair)o;
// if (this.x != other.x || this.y!=other.y) {
// return false;
// }
// return true;
// }
//
/* FOR TREE MAP PAIR USE */
// public int compareTo(Pair o) {
// if (x > o.x) {
// return 1;
// }
// if (x < o.x) {
// return -1;
// }
// if (y > o.y) {
// return 1;
// }
// if (y < o.y) {
// return -1;
// }
// return 0;
// }
}
static int find(int A[],int a) {
if(A[a]<0)
return a;
return A[a]=find(A, A[a]);
}
//static int find(int A[],int a) {
// if(A[a]==a)
// return a;
// return A[a]=find(A, A[a]);
//}
//FENWICK TREE
static void update(int i, int x){
for(; i < bit.length; i += (i&-i))
bit[i] += x;
}
static int sum(int i){
int ans = 0;
for(; i > 0; i -= (i&-i))
ans += bit[i];
return ans;
}
//END
//static void add(int v) {
// if(!map.containsKey(v)) {
// map.put(v, 1);
// }
// else {
// map.put(v, map.get(v)+1);
// }
//}
//static void remove(int v) {
// if(map.containsKey(v)) {
// map.put(v, map.get(v)-1);
// if(map.get(v)==0)
// map.remove(v);
// }
//}
public static int upper(int A[],int k,int si,int ei)
{
int l=si;
int u=ei;
int ans=-1;
while(l<=u) {
int mid=(l+u)/2;
if(A[mid]<=k) {
ans=mid;
l=mid+1;
}
else {
u=mid-1;
}
}
return ans;
}
public static int lower(int A[],int k,int si,int ei)
{
int l=si;
int u=ei;
int ans=-1;
while(l<=u) {
int mid=(l+u)/2;
if(A[mid]<=k) {
l=mid+1;
}
else {
ans=mid;
u=mid-1;
}
}
return ans;
}
static int[] copy(int A[]) {
int B[]=new int[A.length];
for(int i=0;i<A.length;i++) {
B[i]=A[i];
}
return B;
}
static long[] copy(long A[]) {
long B[]=new long[A.length];
for(int i=0;i<A.length;i++) {
B[i]=A[i];
}
return B;
}
static int[] input(int n) {
int A[]=new int[n];
for(int i=0;i<n;i++) {
A[i]=sc.nextInt();
}
return A;
}
static long[] inputL(int n) {
long A[]=new long[n];
for(int i=0;i<n;i++) {
A[i]=sc.nextLong();
}
return A;
}
static String[] inputS(int n) {
String A[]=new String[n];
for(int i=0;i<n;i++) {
A[i]=sc.next();
}
return A;
}
static long sum(int A[]) {
long sum=0;
for(int i : A) {
sum+=i;
}
return sum;
}
static long sum(long A[]) {
long sum=0;
for(long i : A) {
sum+=i;
}
return sum;
}
static void reverse(long A[]) {
int n=A.length;
long B[]=new long[n];
for(int i=0;i<n;i++) {
B[i]=A[n-i-1];
}
for(int i=0;i<n;i++)
A[i]=B[i];
}
static void reverse(int A[]) {
int n=A.length;
int B[]=new int[n];
for(int i=0;i<n;i++) {
B[i]=A[n-i-1];
}
for(int i=0;i<n;i++)
A[i]=B[i];
}
static void input(int A[],int B[]) {
for(int i=0;i<A.length;i++) {
A[i]=sc.nextInt();
B[i]=sc.nextInt();
}
}
static int[][] input(int n,int m){
int A[][]=new int[n][m];
for(int i=0;i<n;i++) {
for(int j=0;j<m;j++) {
A[i][j]=i();
}
}
return A;
}
static char[][] charinput(int n,int m){
char A[][]=new char[n][m];
for(int i=0;i<n;i++) {
String s=s();
for(int j=0;j<m;j++) {
A[i][j]=s.charAt(j);
}
}
return A;
}
static int max(int A[]) {
int max=Integer.MIN_VALUE;
for(int i=0;i<A.length;i++) {
max=Math.max(max, A[i]);
}
return max;
}
static int min(int A[]) {
int min=Integer.MAX_VALUE;
for(int i=0;i<A.length;i++) {
min=Math.min(min, A[i]);
}
return min;
}
static long max(long A[]) {
long max=Long.MIN_VALUE;
for(int i=0;i<A.length;i++) {
max=Math.max(max, A[i]);
}
return max;
}
static long min(long A[]) {
long min=Long.MAX_VALUE;
for(int i=0;i<A.length;i++) {
min=Math.min(min, A[i]);
}
return min;
}
static long [] prefix(long A[]) {
long p[]=new long[A.length];
p[0]=A[0];
for(int i=1;i<A.length;i++)
p[i]=p[i-1]+A[i];
return p;
}
static long [] prefix(int A[]) {
long p[]=new long[A.length];
p[0]=A[0];
for(int i=1;i<A.length;i++)
p[i]=p[i-1]+A[i];
return p;
}
static long [] suffix(long A[]) {
long p[]=new long[A.length];
p[A.length-1]=A[A.length-1];
for(int i=A.length-2;i>=0;i--)
p[i]=p[i+1]+A[i];
return p;
}
static long [] suffix(int A[]) {
long p[]=new long[A.length];
p[A.length-1]=A[A.length-1];
for(int i=A.length-2;i>=0;i--)
p[i]=p[i+1]+A[i];
return p;
}
static void fill(int dp[]) {
Arrays.fill(dp, -1);
}
static void fill(int dp[][]) {
for(int i=0;i<dp.length;i++)
Arrays.fill(dp[i], -1);
}
static void fill(int dp[][][]) {
for(int i=0;i<dp.length;i++) {
for(int j=0;j<dp[0].length;j++) {
Arrays.fill(dp[i][j],-1);
}
}
}
static void fill(int dp[][][][]) {
for(int i=0;i<dp.length;i++) {
for(int j=0;j<dp[0].length;j++) {
for(int k=0;k<dp[0][0].length;k++) {
Arrays.fill(dp[i][j][k],-1);
}
}
}
}
static void fill(long dp[]) {
Arrays.fill(dp, -1);
}
static void fill(long dp[][]) {
for(int i=0;i<dp.length;i++)
Arrays.fill(dp[i], -1);
}
static void fill(long dp[][][]) {
for(int i=0;i<dp.length;i++) {
for(int j=0;j<dp[0].length;j++) {
Arrays.fill(dp[i][j],-1);
}
}
}
static void fill(long dp[][][][]) {
for(int i=0;i<dp.length;i++) {
for(int j=0;j<dp[0].length;j++) {
for(int k=0;k<dp[0][0].length;k++) {
Arrays.fill(dp[i][j][k],-1);
}
}
}
}
static int min(int a,int b) {
return Math.min(a, b);
}
static int min(int a,int b,int c) {
return Math.min(a, Math.min(b, c));
}
static int min(int a,int b,int c,int d) {
return Math.min(a, Math.min(b, Math.min(c, d)));
}
static int max(int a,int b) {
return Math.max(a, b);
}
static int max(int a,int b,int c) {
return Math.max(a, Math.max(b, c));
}
static int max(int a,int b,int c,int d) {
return Math.max(a, Math.max(b, Math.max(c, d)));
}
static long min(long a,long b) {
return Math.min(a, b);
}
static long min(long a,long b,long c) {
return Math.min(a, Math.min(b, c));
}
static long min(long a,long b,long c,long d) {
return Math.min(a, Math.min(b, Math.min(c, d)));
}
static long max(long a,long b) {
return Math.max(a, b);
}
static long max(long a,long b,long c) {
return Math.max(a, Math.max(b, c));
}
static long max(long a,long b,long c,long d) {
return Math.max(a, Math.max(b, Math.max(c, d)));
}
static long power(long x, long y, long p)
{
if(y==0)
return 1;
if(x==0)
return 0;
long res = 1;
x = x % p;
while (y > 0) {
if (y % 2 == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static void print(int A[]) {
for(int i : A) {
System.out.print(i+" ");
}
System.out.println();
}
static void print(long A[]) {
for(long i : A) {
System.out.print(i+" ");
}
System.out.println();
}
static long mod(long x) {
return ((x%mod + mod)%mod);
}
static String reverse(String s) {
StringBuffer p=new StringBuffer(s);
p.reverse();
return p.toString();
}
static int i() {
return sc.nextInt();
}
static String s() {
return sc.next();
}
static long l() {
return sc.nextLong();
}
static void sort(int[] A){
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i){
int tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
static void sort(long[] A){
int n = A.length;
Random rnd = new Random();
for(int i=0; i<n; ++i){
long tmp = A[i];
int randomPos = i + rnd.nextInt(n-i);
A[i] = A[randomPos];
A[randomPos] = tmp;
}
Arrays.sort(A);
}
static String sort(String s) {
Character ch[]=new Character[s.length()];
for(int i=0;i<s.length();i++) {
ch[i]=s.charAt(i);
}
Arrays.sort(ch);
StringBuffer st=new StringBuffer("");
for(int i=0;i<s.length();i++) {
st.append(ch[i]);
}
return st.toString();
}
static HashMap<Integer,Integer> hash(int A[]){
HashMap<Integer,Integer> map=new HashMap<Integer, Integer>();
for(int i : A) {
if(map.containsKey(i)) {
map.put(i, map.get(i)+1);
}
else {
map.put(i, 1);
}
}
return map;
}
static TreeMap<Integer,Integer> tree(int A[]){
TreeMap<Integer,Integer> map=new TreeMap<Integer, Integer>();
for(int i : A) {
if(map.containsKey(i)) {
map.put(i, map.get(i)+1);
}
else {
map.put(i, 1);
}
}
return map;
}
static boolean prime(int n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static boolean prime(long n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
double sq=Math.sqrt(n);
for (int i = 5; i <= sq; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
| Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 3c2a00815e682bc46fef3224e8f49ec1 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
public class TaskD {
static long mod = 1000000007;
static FastScanner scanner;
static final StringBuilder result = new StringBuilder();
public static void main(String[] args) {
scanner = new FastScanner();
solve();
}
static void solve() {
int n = scanner.nextInt();
int k = scanner.nextInt();
int[] and = new int[n];
int[] or = new int[n];
for (int i = 1; i < n; i++) {
and[i] = ask("and", 0, i);
or[i] = ask("or", 0, i);
}
int[] a = new int[n];
a[0] = calcFirst(and, or, ask("and", 1, 2), ask("or", 1, 2));
for (int i = 1; i < n; i++) {
a[i] = calcNext(i, and, or, a[0]);
}
Arrays.sort(a);
System.out.println("finish " + a[k - 1]);
}
static int calcNext(int i, int[] and, int[] or, int first) {
int result = 0;
int mask = 1;
for (int bit = 0; bit < 31; bit++) {
int cur = 0;
if ((and[i] & mask) == (or[i] & mask)) {
cur = Math.min(and[i] & mask, 1);
} else {
cur = (first & mask) > 0 ? 0 : 1;
}
if (cur == 1) {
result |= mask;
}
mask <<= 1;
}
return result;
}
static int calcFirst(int[] and, int[] or, int and23, int or23) {
int result = 0;
int mask = 1;
for (int bit = 0; bit < 31; bit++) {
int cur = 0;
if ((and[1] & mask) == (or[1] & mask)) {
cur = Math.min(and[1] & mask, 1);
} else {
if ((and[2] & mask) == (or[2] & mask)) {
cur = Math.min(and[2] & mask, 1);
}
if ((and23 & mask) == (or23 & mask)) {
cur = 1 - Math.min(and23 & mask, 1);
}
}
if (cur == 1) {
result |= mask;
}
mask <<= 1;
}
return result;
}
static int ask(String op, int i, int j) {
StringBuilder builder = new StringBuilder();
builder.append(op).append(" ").append(i + 1).append(" ").append(j + 1);
System.out.println(builder.toString());
System.out.flush();
return scanner.nextInt();
}
static class WithIdx implements Comparable<WithIdx> {
static int[] order = {0, 1, 3, 2, 4};
int val, idx;
public WithIdx(int val, int idx) {
this.val = val;
this.idx = idx;
}
@Override
public int compareTo(WithIdx o) {
if (val == o.val) {
return Integer.compare(idx, o.idx);
}
return Integer.compare(order[val], order[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,
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;
}
static long modInverse(long a, long m) {
long g = gcdF(a, m);
if (g != 1) {
throw new IllegalArgumentException("Inverse doesn't exist");
} else {
// If a and m are relatively prime, then modulo
// inverse is a^(m-2) mode m
return modpow(a, m - 2, m);
}
}
static public long gcdF(long a, long b) {
while (b != 0) {
long na = b;
long nb = a % b;
a = na;
b = nb;
}
return a;
}
}
}
//25 18 47
//11 | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 90a611bbfc03ac4d122d3c93c74b942e | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
import static java.lang.Math.*;
/* Name of the class has to be "Main" only if the class is public. */
// class Codechef
public class TakeaGuess{
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
// static OutputWriter out = new OutputWriter(System.out);
static int query(String op, int i, int j) throws Exception {
i++;j++;
System.out.println(op+" "+i+" "+j);
System.out.flush();
int t = Integer.parseInt(in.readLine());
return t;
}
public static void main(String[] args) throws java.lang.Exception {
String inp[] = in.readLine().split(" ");
int n = Integer.parseInt(inp[0]);
int k = Integer.parseInt(inp[1]);
int ab = query("or", 0, 1) + query("and", 0, 1);
int bc = query("or", 2, 1) + query("and", 2, 1);
int ac = query("or", 0, 2) + query("and", 0, 2);
int b = (ab+bc-ac)/2;
int ar[] = new int[n];
ar[1] = b;
ar[0] = ab-b;
ar[2] = bc-b;
for(int i=3;i<n;i++){
if(i==1)continue;
int res = query("or", i, 1) + query("and", i, 1);
ar[i] = res-b;
}
Arrays.sort(ar);
System.out.println("finish "+ar[k-1]);
System.out.flush();
}
}
| Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 7d41c785574d7c7a2ccf6137535f7a6b | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class D_Take_a_Guess{
public static void main(String[] args) {
FastScanner s= new FastScanner();
StringBuilder res = new StringBuilder();
int n=s.nextInt();
int k=s.nextInt();
System.out.println("and 1 2");
System.out.println();
System.out.flush();
long a=s.nextLong();
System.out.println("or 1 2");
System.out.println();
System.out.flush();
long b=s.nextLong();
long c=a+b;
System.out.println("and 2 3");
System.out.println();
System.out.flush();
long a1=s.nextLong();
System.out.println("or 2 3");
System.out.println();
System.out.flush();
long b1=s.nextLong();
long c1=a1+b1;
System.out.println("and 1 3");
System.out.println();
System.out.flush();
long a2=s.nextLong();
System.out.println("or 1 3");
System.out.println();
System.out.flush();
long b2=s.nextLong();
long c2=a2+b2;
ArrayList<Long> list = new ArrayList<Long>();
long sum=(c+c1+c2)/2;
long num1=sum-c1;
list.add(num1);
list.add(sum-c);
list.add(sum-c2);
for(int i=4;i<=n;i++){
System.out.println("and 1 "+i);
System.out.println();
System.out.flush();
long yo1=s.nextInt();
System.out.println("or 1 "+i);
System.out.println();
System.out.flush();
long yo2=s.nextInt();
long yoyo=yo1+yo2;
list.add(yoyo-num1);
}
Collections.sort(list);
long ans=list.get(k-1);
System.out.println("finish "+ans);
System.out.println();
System.out.flush();
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 93c5da7796745dfc99005d961012b415 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.util.*;
import java.util.ResourceBundle.Control;
import javax.management.openmbean.KeyAlreadyExistsException;
// import java.lang.invoke.ConstantBootstraps;
// import java.math.BigInteger;
// import java.beans.IndexedPropertyChangeEvent;
import java.io.*;
@SuppressWarnings("unchecked")
public class Main implements Runnable {
static FastReader in;
static PrintWriter out;
static int bit(long n) {
return (n == 0) ? 0 : (1 + bit(n & (n - 1)));
}
static void p(Object o) {
out.print(o);
}
static void pn(Object o) {
out.println(o);
}
static void pni(Object o) {
out.println(o);
out.flush();
}
static String n() throws Exception {
return in.next();
}
static String nln() throws Exception {
return in.nextLine();
}
static int ni() throws Exception {
return Integer.parseInt(in.next());
}
static long nl() throws Exception {
return Long.parseLong(in.next());
}
static double nd() throws Exception {
return Double.parseDouble(in.next());
}
static class FastReader {
static BufferedReader br;
static 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;
}
}
static long power(long a, long b) {
if (a == 0L)
return 0L;
if (b == 0)
return 1;
long val = power(a, b / 2);
val = val * val;
if ((b % 2) != 0)
val = val * a;
return val;
}
static long power(long a, long b, long mod) {
if (a == 0L)
return 0L;
if (b == 0)
return 1;
long val = power(a, b / 2L, mod) % mod;
val = (val * val) % mod;
if ((b % 2) != 0)
val = (val * a) % mod;
return val;
}
static ArrayList<Long> prime_factors(long n) {
ArrayList<Long> ans = new ArrayList<Long>();
while (n % 2 == 0) {
ans.add(2L);
n /= 2L;
}
for (long i = 3; i * i <= n; i++) {
while (n % i == 0) {
ans.add(i);
n /= i;
}
}
if (n > 2) {
ans.add(n);
}
return ans;
}
static void sort(ArrayList<Long> a) {
Collections.sort(a);
}
static void reverse_sort(ArrayList<Long> a) {
Collections.sort(a, Collections.reverseOrder());
}
static void swap(long[] a, int i, int j) {
long temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static void swap(List<Long> a, int i, int j) {
long temp = a.get(i);
a.set(j, a.get(i));
a.set(j, temp);
}
static void sieve(boolean[] prime) {
int n = prime.length - 1;
Arrays.fill(prime, true);
for (int i = 2; i * i <= n; i++) {
if (prime[i]) {
for (int j = 2 * i; j <= n; j += i) {
prime[j] = false;
}
}
}
}
static long gcd(long a, long b) {
if (a < b) {
long temp = a;
a = b;
b = temp;
}
if (b == 0)
return a;
return gcd(b, a % b);
}
static HashMap<Long, Long> map_prime_factors(long n) {
HashMap<Long, Long> map = new HashMap<>();
while (n % 2 == 0) {
map.put(2L, map.getOrDefault(2L, 0L) + 1L);
n /= 2L;
}
for (long i = 3; i * i <= n; i++) {
while (n % i == 0) {
map.put(i, map.getOrDefault(i, 0L) + 1L);
n /= i;
}
}
if (n > 2) {
map.put(n, map.getOrDefault(n, 0L) + 1L);
}
return map;
}
static List<Long> divisor(long n) {
List<Long> ans = new ArrayList<>();
ans.add(1L);
long count = 0;
for (long i = 2L; i * i <= n; i++) {
if (n % i == 0) {
if (i == n / i)
ans.add(i);
else {
ans.add(i);
ans.add(n / i);
}
}
}
return ans;
}
static void sum_of_divisors(int n) {
int[] dp = new int[n + 1];
for (int i = 1; i <= n; i++) {
dp[i] += i;
for (int j = i + i; j <= n; j += i) {
dp[j] += i;
}
}
}
static void prime_factorization_using_sieve(int n) {
int[] dp = new int[n + 1];
Arrays.fill(dp, Integer.MAX_VALUE);
for (int i = 2; i <= n; i++) {
dp[i] = Math.min(dp[i], i);// dp[i] stores smallest prime number which divides number i
for (int j = 2 * i; j <= n; j++) {// can calculate prime factorization in O(logn) time by dividing
// val/=dp[val]; till 1 is obtained
dp[j] = Math.min(dp[j], i);
}
}
}
/*
* ----------------------------------------------------Sorting------------------
* ------------------------------------------------
*/
public static void sort(long[] arr, int l, int r) {
if (l >= r)
return;
int mid = (l + r) / 2;
sort(arr, l, mid);
sort(arr, mid + 1, r);
merge(arr, l, mid, r);
}
public static void sort(int[] arr, int l, int r) {
if (l >= r)
return;
int mid = (l + r) / 2;
sort(arr, l, mid);
sort(arr, mid + 1, r);
merge(arr, l, mid, r);
}
static void merge(int[] arr, int l, int mid, int r) {
int[] left = new int[mid - l + 1];
int[] right = new int[r - mid];
for (int i = l; i <= mid; i++) {
left[i - l] = arr[i];
}
for (int i = mid + 1; i <= r; i++) {
right[i - (mid + 1)] = arr[i];
}
int left_start = 0;
int right_start = 0;
int left_length = mid - l + 1;
int right_length = r - mid;
int temp = l;
while (left_start < left_length && right_start < right_length) {
if (left[left_start] < right[right_start]) {
arr[temp] = left[left_start++];
} else {
arr[temp] = right[right_start++];
}
temp++;
}
while (left_start < left_length) {
arr[temp++] = left[left_start++];
}
while (right_start < right_length) {
arr[temp++] = right[right_start++];
}
}
static void merge(long[] arr, int l, int mid, int r) {
long[] left = new long[mid - l + 1];
long[] right = new long[r - mid];
for (int i = l; i <= mid; i++) {
left[i - l] = arr[i];
}
for (int i = mid + 1; i <= r; i++) {
right[i - (mid + 1)] = arr[i];
}
int left_start = 0;
int right_start = 0;
int left_length = mid - l + 1;
int right_length = r - mid;
int temp = l;
while (left_start < left_length && right_start < right_length) {
if (left[left_start] < right[right_start]) {
arr[temp] = left[left_start++];
} else {
arr[temp] = right[right_start++];
}
temp++;
}
while (left_start < left_length) {
arr[temp++] = left[left_start++];
}
while (right_start < right_length) {
arr[temp++] = right[right_start++];
}
}
// static int[] smallest_prime_factor;
// static int count = 1;
// static int[] p = new int[100002];
// static long[] flat_tree = new long[300002];
// static int[] in_time = new int[1000002];
// static int[] out_time = new int[1000002];
// static long[] subtree_gcd = new long[100002];
// static int w = 0;
// static boolean poss = true;
/*
* (a^b^c)%mod
* Using fermats Little theorem
* x^(mod-1)=1(mod)
* so b^c can be written as b^c=x*(mod-1)+y
* then (a^(x*(mod-1)+y))%mod=(a^(x*(mod-1))*a^(y))mod
* the term (a^(x*(mod-1)))%mod=a^(mod-1)*a^(mod-1)
*
*/
// ---------------------------------------------------Segment_Tree----------------------------------------------------------------//
// static class comparator implements Comparator<node> {
// public int compare(node a, node b) {
// return a.a - b.a > 0 ? 1 : -1;
// }
// }
static class Segment_Tree {
private long[] segment_tree;
public Segment_Tree(int n) {
this.segment_tree = new long[4 * n + 1];
}
void build(int index, int left, int right, int[] a) {
if (left == right) {
segment_tree[index] = a[left];
return;
}
int mid = (left + right) / 2;
build(2 * index + 1, left, mid, a);
build(2 * index + 2, mid + 1, right, a);
segment_tree[index] = segment_tree[2 * index + 1] + segment_tree[2 * index + 2];
}
long query(int index, int left, int right, int l, int r) {
if (left > right)
return 0;
if (left >= l && r >= right) {
return segment_tree[index];
}
if (l > right || left > r)
return 0;
int mid = (left + right) / 2;
return query(2 * index + 1, left, mid, l, r) + query(2 * index + 2, mid + 1, right, l, r);
}
void update(int index, int left, int right, int node, int val) {
if (left == right) {
segment_tree[index] = val;
return;
}
int mid = (left + right) / 2;
if (node <= mid)
update(2 * index + 1, left, mid, node, val);
else
update(2 * index + 2, mid + 1, right, node, val);
segment_tree[index] = segment_tree[2 * index + 1] + segment_tree[2 * index + 2];
}
}
static class min_Segment_Tree {
private long[] segment_tree;
public min_Segment_Tree(int n) {
this.segment_tree = new long[4 * n + 1];
Arrays.fill(segment_tree, Integer.MAX_VALUE);
}
void build(int index, int left, int right, long[] a) {
if (left == right) {
segment_tree[index] = a[left];
return;
}
int mid = (left + right) / 2;
build(2 * index + 1, left, mid, a);
build(2 * index + 2, mid + 1, right, a);
segment_tree[index] = Math.min(segment_tree[2 * index + 1], segment_tree[2 * index + 2]);
}
long query(int index, int left, int right, int l, int r) {
if (left > right)
return Integer.MAX_VALUE;
if (left >= l && r >= right) {
return segment_tree[index];
}
if (l > right || left > r)
return Integer.MAX_VALUE;
int mid = (left + right) / 2;
return Math.min(query(2 * index + 1, left, mid, l, r), query(2 * index + 2, mid + 1, right, l, r));
}
void update(int index, int left, int right, int node, int val) {
if (left == right) {
segment_tree[index] = val;
return;
}
int mid = (left + right) / 2;
if (node <= mid)
update(2 * index + 1, left, mid, node, val);
else
update(2 * index + 2, mid + 1, right, node, val);
segment_tree[index] = Math.min(segment_tree[2 * index + 1], segment_tree[2 * index + 2]);
}
}
static class max_Segment_Tree {
public long[] segment_tree;
public max_Segment_Tree(int n) {
this.segment_tree = new long[4 * n + 1];
}
void build(int index, int left, int right, long[] a) {
// pn(index+" "+left+" "+right);
if (left == right) {
segment_tree[index] = a[left];
return;
}
int mid = (left + right) / 2;
build(2 * index + 1, left, mid, a);
build(2 * index + 2, mid + 1, right, a);
segment_tree[index] = Math.max(segment_tree[2 * index + 1], segment_tree[2 * index + 2]);
}
long query(int index, int left, int right, int l, int r) {
if (left >= l && r >= right) {
return segment_tree[index];
}
if (l > right || left > r)
return Long.MIN_VALUE;
int mid = (left + right) / 2;
long ans1 = query(2 * index + 1, left, mid, l, r);
long ans2 = query(2 * index + 2, mid + 1, right, l, r);
long max = Math.max(ans1, ans2);
// pn(index+" "+left+" "+right+" "+max+" "+l+" "+r+" "+ans1+" "+ans2);
return max;
}
void update(int index, int left, int right, int node, int val) {
if (left == right) {
segment_tree[index] += val;
return;
}
int mid = (left + right) / 2;
if (node <= mid)
update(2 * index + 1, left, mid, node, val);
else
update(2 * index + 2, mid + 1, right, node, val);
segment_tree[index] = Math.max(segment_tree[2 * index + 1], segment_tree[2 * index + 2]);
}
}
// // ------------------------------------------------------ DSU
// // --------------------------------------------------------------------//
static class dsu {
private int[] parent;
private int[] rank;
private int[] size;
public dsu(int n) {
this.parent = new int[n + 1];
this.rank = new int[n + 1];
this.size = new int[n + 1];
for (int i = 0; i <= n; i++) {
parent[i] = i;
rank[i] = 1;
size[i] = 1;
}
}
int findParent(int a) {
if (parent[a] == a)
return a;
else
return parent[a] = findParent(parent[a]);
}
void join(int a, int b) {
int parent_a = findParent(a);
int parent_b = findParent(b);
if (parent_a == parent_b)
return;
if (rank[parent_a] > rank[parent_b]) {
parent[parent_b] = parent_a;
size[parent_a] += size[parent_b];
} else if (rank[parent_a] < rank[parent_b]) {
parent[parent_a] = parent_b;
size[parent_b] += size[parent_a];
} else {
parent[parent_a] = parent_b;
size[parent_b] += size[parent_a];
rank[parent_b]++;
}
}
}
// ------------------------------------------------Comparable---------------------------------------------------------------------//
public static class rectangle {
int x1, x3, y1, y3;// lower left and upper rigth coordinates
int x2, y2, x4, y4;// remaining coordinates
/*
* (x4,y4) (x3,y3)
* ____________
* | |
* |____________|
*
* (x1,y1) (x2,y2)
*/
public rectangle(int x1, int y1, int x3, int y3) {
this.x1 = x1;
this.y1 = y1;
this.x3 = x3;
this.y3 = y3;
this.x2 = x3;
this.y2 = y1;
this.x4 = x1;
this.y4 = y3;
}
public long area() {
if (x3 < x1 || y3 < y1)
return 0;
return (long) Math.abs(x1 - x3) * (long) Math.abs(y1 - y3);
}
}
static long intersection(rectangle a, rectangle b) {
if (a.x3 < a.x1 || a.y3 < a.y1 || b.x3 < b.x1 || b.y3 < b.y1)
return 0;
long l1 = ((long) Math.min(a.x3, b.x3) - (long) Math.max(a.x1, b.x1));
long l2 = ((long) Math.min(a.y3, b.y3) - (long) Math.max(a.y1, b.y1));
if (l1 < 0 || l2 < 0)
return 0;
long area = ((long) Math.min(a.x3, b.x3) - (long) Math.max(a.x1, b.x1))
* ((long) Math.min(a.y3, b.y3) - (long) Math.max(a.y1, b.y1));
if (area < 0)
return 0;
return area;
}
// --------------------------------------------------------------Multiset---------------------------------------------------------------//
public static class multiset {
public TreeMap<Integer, Integer> map;
public int size = 0;
public multiset() {
map = new TreeMap<>();
}
public multiset(int[] a) {
map = new TreeMap<>();
size = a.length;
for (int i = 0; i < a.length; i++) {
map.put(a[i], map.getOrDefault(a[i], 0) + 1);
}
}
void add(int a) {
size++;
map.put(a, map.getOrDefault(a, 0) + 1);
}
void remove(int a) {
size--;
int val = map.get(a);
map.put(a, val - 1);
if (val == 1)
map.remove(a);
}
void removeAll(int a) {
if (map.containsKey(a)) {
size -= map.get(a);
map.remove(a);
}
}
int ceiling(int a) {
if (map.ceilingKey(a) != null) {
int find = map.ceilingKey(a);
return find;
} else
return Integer.MIN_VALUE;
}
int floor(int a) {
if (map.floorKey(a) != null) {
int find = map.floorKey(a);
return find;
} else
return Integer.MAX_VALUE;
}
int lower(int a) {
if (map.lowerKey(a) != null) {
int find = map.lowerKey(a);
return find;
} else
return Integer.MAX_VALUE;
}
int higher(int a) {
if (map.higherKey(a) != null) {
int find = map.higherKey(a);
return find;
} else
return Integer.MIN_VALUE;
}
int first() {
return map.firstKey();
}
int last() {
return map.lastKey();
}
boolean contains(int a) {
if (map.containsKey(a))
return true;
return false;
}
int size() {
return size;
}
void clear() {
map.clear();
}
int poll() {
if (map.size() == 0) {
return Integer.MAX_VALUE;
}
size--;
int first = map.firstKey();
if (map.get(first) == 1) {
map.pollFirstEntry();
} else
map.put(first, map.get(first) - 1);
return first;
}
int polllast() {
if (map.size() == 0) {
return Integer.MAX_VALUE;
}
size--;
int last = map.lastKey();
if (map.get(last) == 1) {
map.pollLastEntry();
} else
map.put(last, map.get(last) - 1);
return last;
}
}
static class pair implements Comparable<pair> {
int a;
int b;
int dir;
public pair(int a, int b, int dir) {
this.a = a;
this.b = b;
this.dir = dir;
}
public int compareTo(pair p) {
// if (this.b == Integer.MIN_VALUE || p.b == Integer.MIN_VALUE)
// return (int) (this.index - p.index);
return (int) (this.a - p.a);
}
}
static class pair2 implements Comparable<pair2> {
long a;
int index;
public pair2(long a, int index) {
this.a = a;
this.index = index;
}
public int compareTo(pair2 p) {
return (int) (this.a - p.a);
}
}
static class node implements Comparable<node> {
int l;
int r;
public node(int l, int r) {
this.l = l;
this.r = r;
}
public int compareTo(node a) {
if (this.l == a.l) {
return this.r - a.r;
}
return (int) (this.l - a.l);
}
}
static long ans = 0;
static int leaf = 0;
static boolean poss = true;
static long mod = 1000000007L;
static int[] dx = { -1, 0, 0, 1, -1, -1, 1, 1 };
static int[] dy = { 0, -1, 1, 0, -1, 1, -1, 1 };
static Set<Integer> path_nodes;
static int[] parent;
static boolean[] visited;
static int[] map_x;
static int[] map_y;
static int[][] map_x_visited;
static int[][] map_y_visited;
int count = 0;
public static void main(String[] args) throws Exception {
// new Thread(null, new Main(), "1", 1 << 26).start();
long start = System.nanoTime();
in = new FastReader();
out = new PrintWriter(System.out, true);
int tc = 1;
while (tc-- > 0) {
int n=ni();
int k=ni();
long[] a=new long[n];
long sum=0;
long first,second,third;
pn("and "+1+" "+2);
first=ni();
pn("or "+1+" "+2);
first+=ni();
pn("and "+2+" "+3);
second=ni();
pn("or "+2+" "+3);
second+=ni();
pn("and "+3+" "+1);
third=ni();
pn("or "+3+" "+1);
third+=ni();
sum=(first+second+third)/2;
// pn(sum+" "+first+" "+second+" "+third);
a[0]=sum-second;
a[1]=sum-third;
a[2]=sum-first;
for(int i=3;i<n;i++){
sum=0;
pn("and "+(i+1)+" "+1);
sum+=ni();
pn("or "+(i+1)+" "+1);
sum+=ni();
a[i]=sum-a[0];
}
sort(a, 0, n-1);
// for(int i=0;i<n;i++){
// p(a[i]+" ");
// }
// pn("");
pn("finish "+a[k-1]);
}
long end = System.nanoTime();
// pn((end-start)*1.0/1000000000);
out.flush();
out.close();
}
static void dfs(int i, int p, List<Set<Integer>> arr, int[] ans, int depth) {
parent[i] = p;
ans[i] = depth;
for (int nei : arr.get(i)) {
if (visited[nei] || nei == p)
continue;
dfs(nei, i, arr, ans, depth + 1);
}
}
public void run() {
try {
} catch (Exception e) {
pn("Excetiom");
}
}
static boolean dfs(int i, int p, int x, int y, Set<Integer> k_nodes, boolean[] visited, List<TreeSet<Integer>> arr,
int[] dp) {
visited[i] = true;
boolean found = false;
if (k_nodes.contains(i)) {
found = true;
}
List<Integer> remove = new ArrayList<>();
for (int nei : arr.get(i)) {
if (visited[nei] || nei == p)
continue;
boolean yes = dfs(nei, i, x, y, k_nodes, visited, arr, dp);
if (!yes)
remove.add(nei);
// pn(i+" "+nei+" "+yes);
found = found || yes;
}
for (int nei : remove) {
arr.get(i).remove(nei);
}
return found;
}
static boolean inside(int i, int j, int n, int m) {
if (i >= 0 && j >= 0 && i < n && j < m)
return true;
return false;
}
static long ncm(long[] fact, long[] fact_inv, int n, int m) {
if (n < m)
return 0L;
long a = fact[n];
long b = fact_inv[n - m];
long c = fact_inv[m];
a = (a * b) % mod;
return (a * c) % mod;
}
static int binary_search(int[] a, int val) {
int l = 0;
int r = a.length - 1;
int ans = 0;
while (l <= r) {
int mid = l + (r - l) / 2;
if (a[mid] <= val) {
ans = mid;
l = mid + 1;
} else
r = mid - 1;
}
return ans;
}
static int[] longest_common_prefix(String s) {
int m = s.length();
int[] lcs = new int[m];
int len = 0;
int i = 1;
lcs[0] = 0;
while (i < m) {
if (s.charAt(i) == s.charAt(len)) {
lcs[i++] = ++len;
} else {
if (len == 0) {
lcs[i] = 0;
i++;
} else
len = lcs[len - 1];
}
}
return lcs;
}
static void swap(char[] a, char[] b, int i, int j) {
char temp = a[i];
a[i] = b[j];
b[j] = temp;
}
static void factorial(long[] fact, long[] fact_inv, int n, long mod) {
fact[0] = 1;
for (int i = 1; i < n; i++) {
fact[i] = (i * fact[i - 1]) % mod;
}
for (int i = 0; i < n; i++) {
fact_inv[i] = power(fact[i], mod - 2, mod);// (1/x)%m can be calculated by fermat's little theoram which is
// (x**(m-2))%m when m is prime
}
// (a^(b^c))%m is equal to, let res=(b^c)%(m-1) then (a^res)%m
// https://www.geeksforgeeks.org/find-power-power-mod-prime/?ref=rp
}
static void find(int i, int n, int[] row, int[] col, int[] d1, int[] d2) {
if (i >= n) {
ans++;
return;
}
for (int j = 0; j < n; j++) {
if (col[j] == 0 && d1[i - j + n - 1] == 0 && d2[i + j] == 0) {
col[j] = 1;
d1[i - j + n - 1] = 1;
d2[i + j] = 1;
find(i + 1, n, row, col, d1, d2);
col[j] = 0;
d1[i - j + n - 1] = 0;
d2[i + j] = 0;
}
}
}
static int answer(int l, int r, int[][] dp) {
if (l > r)
return 0;
if (l == r) {
dp[l][r] = 1;
return 1;
}
if (dp[l][r] != -1)
return dp[l][r];
int val = Integer.MIN_VALUE;
int mid = l + (r - l) / 2;
val = 1 + Math.max(answer(l, mid - 1, dp), answer(mid + 1, r, dp));
return dp[l][r] = val;
}
static void print(int[] a) {
for (int i = 0; i < a.length; i++)
p(a[i] + " ");
pn("");
}
static long count(long n) {
long count = 0;
while (n != 0) {
count += n % 10;
n /= 10;
}
return count;
}
static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
static int LcsOfPrefix(String a, String b) {
int i = 0;
int j = 0;
int count = 0;
while (i < a.length() && j < b.length()) {
if (a.charAt(i) == b.charAt(j)) {
j++;
count++;
}
i++;
}
return a.length() + b.length() - 2 * count;
}
static void reverse(int[] a, int n) {
for (int i = 0; i < n / 2; i++) {
int temp = a[i];
a[i] = a[n - i - 1];
a[n - i - 1] = temp;
}
}
static char get_char(int a) {
return (char) (a + 'a');
}
static int find1(int[] a, int val) {
int ans = -1;
int l = 0;
int r = a.length - 1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (a[mid] <= val) {
l = mid + 1;
ans = mid;
} else
r = mid - 1;
}
return ans;
}
static int find2(int[] a, int val) {
int l = 0;
int r = a.length - 1;
int ans = -1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (a[mid] <= val) {
ans = mid;
l = mid + 1;
} else
r = mid - 1;
}
return ans;
}
// static void dfs(List<List<Integer>> arr, int node, int parent, long[] val) {
// p[node] = parent;
// in_time[node] = count;
// flat_tree[count] = val[node];
// subtree_gcd[node] = val[node];
// count++;
// for (int adj : arr.get(node)) {
// if (adj == parent)
// continue;
// dfs(arr, adj, node, val);
// subtree_gcd[node] = gcd(subtree_gcd[adj], subtree_gcd[node]);
// }
// out_time[node] = count;
// flat_tree[count] = val[node];
// count++;
// }
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | c0b5223d9bfd736a7ef5e5d41e1ce100 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class codeforces1556C{
public static void main (String[] args) throws IOException
{
FastReader in = new FastReader();
PrintWriter pw = new PrintWriter(System.out);
int n = in.nextInt();
int k = in.nextInt();
long a = 0;
pw.println("or 1 2");
pw.flush();
a+=in.nextLong();
pw.println("and 1 2");
pw.flush();
a += in.nextLong();
long b = 0;
pw.println("or 2 3");
pw.flush();
b+=in.nextLong();
pw.println("and 2 3");
pw.flush();
b += in.nextLong();
long c = 0;
pw.println("or 1 3");
pw.flush();
c+=in.nextLong();
pw.println("and 1 3");
pw.flush();
c += in.nextLong();
long sum = a+b+c;
sum/=2;
long one = sum-b;
long two = sum-c;
long three = sum-a;
ArrayList<Long> arr = new ArrayList<>();
arr.add(one);
arr.add(two);
arr.add(three);
for (int i = 4; i<=n;i++)
{
pw.println("or 1 "+i);
pw.flush();
long s = 0;
s+=in.nextLong();
pw.println("and 1 "+i);
pw.flush();
s+=in.nextLong();
arr.add(s-one);
}
Collections.sort(arr);
pw.println("finish "+arr.get(k-1));
pw.close();
}
static class FastReader {
StringTokenizer st;
BufferedReader br;
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 s = "";
while (st == null || st.hasMoreElements()) {
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
}
return s;
}
}
}
| Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | ed5f138bc4e2b7ca8dbf60b09ae0a0a8 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
public class c731{
public static void main(String[] args) throws IOException {
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(System.out));
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
PrintWriter pt = new PrintWriter(System.out);
FastReader sc = new FastReader();
//int t = sc.nextInt();
//for(int o = 0; o<t;o++){
//}
int n = sc.nextInt();
int k = sc.nextInt();
ArrayList<Integer> al = new ArrayList<Integer>();
for(int j = 3 ; j<=n;j+=3) {
int v1 = j-2;
int v2 = j-1;
System.out.println("and " + v1 + " " + v2 );
System.out.flush();
int x1 = sc.nextInt();
System.out.println("or " + v1 + " " + v2 );
System.out.flush();
int y1 = sc.nextInt();
System.out.println("and " + v1 + " " + j );
System.out.flush();
int x2 = sc.nextInt();
System.out.println("or " + v1 + " " + j );
System.out.flush();
int y2 = sc.nextInt();
System.out.println("and " + v2 + " " + j );
System.out.flush();
int x3 = sc.nextInt();
System.out.println("or " + v2 + " " + j );
System.out.flush();
int y3 = sc.nextInt();
int k1 = x1 + y1;
int k2 = x2 + y2;
int k3 = x3 + y3;
al.add((k1 - k2 +k3)/2);
al.add((k1 + k2 - k3)/2);
al.add((-k1 + k2 + k3)/2);
}
if(n%3 == 1) {
int l = n-1;
System.out.println("and " + l + " " + n );
System.out.flush();
int x = sc.nextInt();
System.out.println("or " + l + " " + n );
System.out.flush();
int y = sc.nextInt();
int v = x + y;
v -= al.get(al.size()-1);
al.add(v);
}else if(n%3 == 2) {
int l = n-1;
System.out.println("and " + l + " " + n );
System.out.flush();
int x = sc.nextInt();
System.out.println("or " + l + " " + n );
System.out.flush();
int y = sc.nextInt();
int c = n-2;
System.out.println("and " + c + " " + l );
System.out.flush();
int x2 = sc.nextInt();
System.out.println("or " + c + " " + l );
System.out.flush();
int y2 = sc.nextInt();
int k1 = x + y;
int k2 = x2 + y2;
int p = al.get(al.size()-1);
al.add(k2 - p);
al.add(k1 + p - k2);
}
//System.out.println(al);
Collections.sort(al);
//System.out.println(al);
System.out.println("finish " + al.get(k-1));
System.out.flush();
}
//------------------------------------------------------------------------------------------------------------------------------------------------
public static boolean check(ArrayList<Integer> al , int d , int v) {
int n = al.size();
for(int i = 1 ; i<n;i++) {
int df = al.get(i) - al.get(i-1)-1;
if(al.get(i) - al.get(i-1)-1<v) {
return false;
}
}
if(d-al.get(n-1)-1>=v) {
return true;
}
for(int i = 1 ; i<n;i++) {
int df = al.get(i) - al.get(i-1)-1;
if(df>2*v) {
return true;
}
}
return false;
}
public static int cnt_set(long x) {
long v = 1l;
int c =0;
int f = 0;
while(v<=x) {
if((v&x)!=0) {
c++;
}
v = v<<1;
}
return c;
}
public static int lis(int[] arr,int[] dp) {
int n = arr.length;
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(arr[0]);
dp[0]= 1;
for(int i = 1 ; i<n;i++) {
int x = al.get(al.size()-1);
if(arr[i]>x) {
al.add(arr[i]);
}else {
int v = lower_bound(al, 0, al.size(), arr[i]);
// System.out.println(v);
al.set(v, arr[i]);
}
dp[i] = al.size();
}
//return al.size();
return al.size();
}
public static int lis2(int[] arr,int[] dp) {
int n = arr.length;
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(-arr[n-1]);
dp[n-1] = 1;
// System.out.println(al);
for(int i = n-2 ; i>=0;i--) {
int x = al.get(al.size()-1);
// System.out.println(-arr[i] + " " + i + " " + x);
if((-arr[i])>x) {
al.add(-arr[i]);
}else {
int v = lower_bound(al, 0, al.size(), -arr[i]);
// System.out.println(v);
al.set(v, -arr[i]);
}
dp[i] = al.size();
}
//return al.size();
return al.size();
}
static int cntDivisors(int n){
int cnt = 0;
for (int i=1; i<=Math.sqrt(n); i++)
{
if (n%i==0)
{
if (n/i == i)
cnt++;
else
cnt+=2;
}
}
return cnt;
}
public static long power(long x, long y, long p){
long res = 1;
x = x % p;
if (x == 0)
return 0;
while (y > 0){
if ((y & 1) != 0)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
public static long ncr(long[] fac, int n , int r , long m) {
if(r>n) {
return 0;
}
return fac[n]*(modInverse(fac[r], m))%m *(modInverse(fac[n-r], m))%m;
}
public static int lower_bound(ArrayList<Integer> arr,int lo , int hi, int k)
{
int s=lo;
int e=hi;
while (s !=e)
{
int mid = s+e>>1;
if (arr.get(mid) <k)
{
s=mid+1;
}
else
{
e=mid;
}
}
if(s==arr.size())
{
return -1;
}
return s;
}
public static int upper_bound(ArrayList<Integer> arr,int lo , int hi, int k)
{
int s=lo;
int e=hi;
while (s !=e)
{
int mid = s+e>>1;
if (arr.get(mid) <=k)
{
s=mid+1;
}
else
{
e=mid;
}
}
if(s==arr.size())
{
return -1;
}
return s;
}
// -----------------------------------------------------------------------------------------------------------------------------------------------
public static long gcd(long a, long b){
if (a == 0)
return b;
return gcd(b % a, a);
}
//--------------------------------------------------------------------------------------------------------------------------------------------------------
public static long modInverse(long a, long m){
long m0 = m;
long y = 0, x = 1;
if (m == 1)
return 0;
while (a > 1) {
// q is quotient
long q = a / m;
long t = m;
// m is remainder now, process
// same as Euclid's algo
m = a % m;
a = t;
t = y;
// Update x and y
y = x - q * y;
x = t;
}
// Make x positive
if (x < 0)
x += m0;
return x;
}
//_________________________________________________________________________________________________________________________________________________________________
// private static int[] parent;
// private static int[] size;
public static int find(int[] parent, int u) {
while(u != parent[u]) {
parent[u] = parent[parent[u]];
u = parent[u];
}
return u;
}
private static void union(int[] parent,int[] size,int u, int v) {
int rootU = find(parent,u);
int rootV = find(parent,v);
if(rootU == rootV) {
return;
}
if(size[rootU] < size[rootV]) {
parent[rootU] = rootV;
size[rootV] += size[rootU];
} else {
parent[rootV] = rootU;
size[rootU] += size[rootV];
}
}
//-----------------------------------------------------------------------------------------------------------------------------------
//segment tree
//for finding minimum in range
public static void build(boolean [] seg,boolean []arr,int idx, int lo , int hi) {
if(lo == hi) {
seg[idx] = arr[lo];
return;
}
int mid = (lo + hi)/2;
build(seg,arr,2*idx+1, lo, mid);
build(seg,arr,idx*2+2, mid +1, hi);
// seg[idx] = Math.min(seg[2*idx+1],seg[2*idx+2]);
// seg[idx] = seg[idx*2+1]+ seg[idx*2+2];
// seg[idx] = Math.min(seg[idx*2+1], seg[idx*2+2]);
seg[idx] = seg[idx*2+1] && seg[idx*2+2];
}
//for finding minimum in range
public static boolean query(boolean[]seg,int idx , int lo , int hi , int l , int r) {
if(lo>=l && hi<=r) {
return seg[idx];
}
if(hi<l || lo>r) {
return true;
}
int mid = (lo + hi)/2;
boolean left = query(seg,idx*2 +1, lo, mid, l, r);
boolean right = query(seg,idx*2 + 2, mid + 1, hi, l, r);
// return Math.min(left, right);
//return gcd(left, right);
// return Math.min(left, right);
return left && right;
}
// // for sum
//
//public static void update(int[]seg,int idx, int lo , int hi , int node , int val) {
// if(lo == hi) {
// seg[idx] += val;
// }else {
//int mid = (lo + hi )/2;
//if(node<=mid && node>=lo) {
// update(seg, idx * 2 +1, lo, mid, node, val);
//}else {
// update(seg, idx*2 + 2, mid + 1, hi, node, val);
//}
//seg[idx] = seg[idx*2 + 1] + seg[idx*2 + 2];
//
//}
//}
//---------------------------------------------------------------------------------------------------------------------------------------
//
//static void shuffleArray(long[] ar)
//{
// // If running on Java 6 or older, use `new Random()` on RHS here
// 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;
// }
//}
// static void shuffleArray(coup[] ar)
// {
// // If running on Java 6 or older, use `new Random()` on RHS here
// Random rnd = ThreadLocalRandom.current();
// for (int i = ar.length - 1; i > 0; i--)
// {
// int index = rnd.nextInt(i + 1);
// // Simple swap
// coup a = ar[index];
// ar[index] = ar[i];
// ar[i] = a;
// }
// }
//-----------------------------------------------------------------------------------------------------------------------------------------------------------
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(
new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//------------------------------------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------------------------------
class coup{
int a;
int b;
public coup(int a , int b) {
this.a = a;
this.b = b;
}
}
class trip{
int a , b, c;
public trip(int a , int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 6aadc3622888f1a94ab524fa2cb1572a | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class Bfs {
static Scanner sc = new Scanner(System.in);
static PrintWriter pw = new PrintWriter(System.out);
public static int ask(int i,int j,boolean f) throws IOException {
if(f) {
pw.println("or "+i+" "+j);
pw.flush();
return sc.nextInt();
}
else {
pw.println("and "+i+" "+j);
pw.flush();
return sc.nextInt();
}
}
public static void main(String[] args) throws IOException, InterruptedException {
int n=sc.nextInt(),k=sc.nextInt();
Integer []arr=new Integer[n];
int ans1=ask(1, 2, false)+ask(1, 2, true);
int ans2=ask(2, 3, false)+ask(2, 3, true);
int ans3=ask(1, 3, false)+ask(1, 3, true);
arr[0]=(ans3+ans1-ans2)/2;
arr[2]=ans3-arr[0];
arr[1]=ans2-arr[2];
for(int i=3;i<n;i++) {
int ans=ask(1, i+1, false)+ask(1, i+1, true);
arr[i]=ans-arr[0];
}
Arrays.sort(arr);
pw.println("finish "+ arr[k-1]);
pw.flush();
}
static class SegmentTree{
triple []arr,sg;
int N;
public SegmentTree(triple [] a) {
arr=a;
N=a.length-1;
sg=new triple[N<<1];
}
public void build(int node,int l,int r) {
if(l==r) {
sg[node]=arr[l];
}
else {
int mid=l+r >>1,left=node >> 1, right=left | 1;
build(left, l, mid);
build(right, mid+1, r);
if(sg[left]==null && sg[right]==null);
else if(sg[left]==null) {
sg[node]=sg[right];
}
else if(sg[right]==null) {
sg[node]=sg[left];
}
else {
four suf,pre;
int ans;
if(sg[left].pre.val<=sg[left].suf.val && sg[left].suf.val<=sg[right].pre.val && sg[right].pre.val<=sg[right].suf.val) {
pre=new four(sg[left].pre.len*2, sg[left].pre.start, sg[right].suf.end, sg[left].pre.val);
suf=new four(sg[left].pre.len*2, sg[left].pre.start, sg[right].suf.end, sg[right].suf.val);
ans=sg[left].ans+sg[right].ans;
}
else if(sg[left].pre.val<=sg[left].suf.val && sg[left].suf.val<=sg[right].pre.val) {
}
}
}
}
}
static class triple{
int ans;
four pre,suf;
public triple(int an,four x,four y) {
ans=an;
pre=x;suf=y;
}
public String toString() {
return ans + " " + pre.toString() + " " + suf.toString() ;
}
}
static class four {
long len, start, end, val;
public four(long w, long x, long y, long z) {
len = w;
start = x;
end = y;
val = z;
}
public String toString() {
return len + " " + start + " " + end + " " + val + " ";
}
}
static class tuble {
long x;
long y;
long z;
public tuble(long x, long y, long z) {
this.x = x;
this.y = y;
this.z = z;
}
public String toString() {
return x + " " + y + " " + z;
}
}
static class pair implements Comparable<pair> {
long x;
long y;
public pair(long x, long y) {
this.x = x;
this.y = y;
}
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 Double(x).hashCode() * 31 + new Double(y).hashCode();
}
public int compareTo(pair other) {
if (this.x == other.x) {
return Long.compare(other.y, this.y);
}
return Long.compare(this.x, other.x);
}
}
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 long[] nextlongArray(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public Long[] nextLongArray(int n) throws IOException {
Long[] a = new Long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 80470ebdd876002fbfe00080344e1226 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Test1 {
static PrintWriter pr = new PrintWriter(new OutputStreamWriter(System.out));
static int nextByteIndex, bytesRead;
static byte buffer[] = new byte[1<<16];
static byte nextByte() throws IOException {
if (nextByteIndex >= bytesRead){
bytesRead = System.in.read(buffer);
if (bytesRead == -1) return -1;
nextByteIndex = 0;
}
if (buffer[nextByteIndex] == ' ' || buffer[nextByteIndex] == '\n' || buffer[nextByteIndex] == '\r'){
++nextByteIndex;
return -1;
}
return buffer[nextByteIndex++];
}
static int readInt() throws IOException {
int ret = 0;
boolean neg = false;
byte next = nextByte();
while (next == -1) next = nextByte();
if (next == '-'){
next = nextByte();
neg = true;
}
while (next != -1){
ret = 10*ret + next - '0';
next = nextByte();
}
return neg ? -ret : ret;
}
static long readLong() throws IOException {
long ret = 0;
boolean neg = false;
byte next = nextByte();
while (next == -1) next = nextByte();
if (next == '-'){
next = nextByte();
neg = true;
}
while (next != -1){
ret = 10*ret + next - '0';
next = nextByte();
}
return neg ? -ret : ret;
}
static class Pair implements Comparable<Pair> {
int f, s;
Pair(int f, int s) {
this.f = f; this.s = s;
}
public int compareTo(Pair other) {
if (this.f != other.f) return this.f - other.f;
return this.s - other.s;
}
}
static void solve() throws IOException {
int n = readInt(), k = readInt(), sum[] = new int[n + 1];
for (int i = 2; i <= n; ++i) {
pr.println("or 1 " + i);
pr.flush();
sum[i] += readInt();
pr.println("and 1 " + i);
pr.flush();
sum[i] += readInt();
}
pr.println("or 2 3");
pr.flush();
int x = readInt();
pr.println("and 2 3");
pr.flush();
x += readInt();
int a[] = new int[n + 1];
a[1] = (sum[2] + sum[3] - x)>>1;
for (int i = 2; i <= n; ++i) a[i] = sum[i] - a[1];
Arrays.sort(a, 1, n + 1);
pr.println("finish " + a[k]);
pr.flush();
}
public static void main(String[] args) throws IOException {
solve();
//for (int t = readInt(); t > 0; --t) solve();
pr.close();
}
}
| Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | d7251a98bd7928488fd49ec047dd2f23 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static PrintWriter pr = new PrintWriter(new OutputStreamWriter(System.out));
static String readLine() throws IOException {
return br.readLine();
}
static String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(readLine());
return st.nextToken();
}
static int readInt() throws IOException {
return Integer.parseInt(next());
}
static long readLong() throws IOException {
return Long.parseLong(next());
}
static double readDouble() throws IOException {
return Double.parseDouble(next());
}
static char readChar() throws IOException {
return next().charAt(0);
}
static class Pair implements Comparable<Pair> {
int f, s;
Pair(int f, int s) {
this.f = f; this.s = s;
}
public int compareTo(Pair other) {
if (this.f != other.f) return this.f - other.f;
return this.s - other.s;
}
}
static void solve() throws IOException {
int n = readInt(), k = readInt(), sum[] = new int[n + 1];
for (int i = 2; i <= n; ++i) {
pr.println("or 1 " + i);
pr.flush();
sum[i] += readInt();
pr.println("and 1 " + i);
pr.flush();
sum[i] += readInt();
}
pr.println("or 2 3");
pr.flush();
int x = readInt();
pr.println("and 2 3");
pr.flush();
x += readInt();
int a[] = new int[n + 1];
a[1] = (sum[2] + sum[3] - x)>>1;
for (int i = 2; i <= n; ++i) a[i] = sum[i] - a[1];
Arrays.sort(a, 1, n + 1);
pr.println("finish " + a[k]);
pr.flush();
}
public static void main(String[] args) throws IOException {
solve();
//for (int t = readInt(); t > 0; --t) solve();
pr.close();
}
}
| Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | a8b9b71abe268185da9b0ec416547329 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class CC {
//--------------------------INPUT READER--------------------------------//
static class fs {
public BufferedReader br;
StringTokenizer st = new StringTokenizer("");
public fs() { this(System.in); }
public fs(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
String next() {
while (!st.hasMoreTokens()) {
try { st = new StringTokenizer(br.readLine()); }
catch (IOException e) { e.printStackTrace(); }
}
return st.nextToken();
}
int ni() { return Integer.parseInt(next()); }
long nl() { return Long.parseLong(next()); }
double nd() { return Double.parseDouble(next()); }
String ns() { return next(); }
int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
}
//-----------------------------------------------------------------------//
//---------------------------PRINTER-------------------------------------//
static class Printer {
static PrintWriter w;
public Printer() {this(System.out);}
public Printer(OutputStream os) {
w = new PrintWriter(os, true);
}
public void p(int i) {w.println(i);};
public void p(long l) {w.println(l);};
public void p(double d) {w.println(d);};
public void p(String s) { w.println(s);};
public void pr(int i) {w.println(i);};
public void pr(long l) {w.print(l);};
public void pr(double d) {w.print(d);};
public void pr(String s) { w.print(s);};
public void pl() {w.println();};
public void close() {w.close();};
}
//------------------------------------------------------------------------//
//--------------------------VARIABLES------------------------------------//
static fs sc = new fs();
static OutputStream outputStream = System.out;
static Printer w = new Printer(outputStream);
//-----------------------------------------------------------------------//
//--------------------------ADMIN_MODE-----------------------------------//
private static void ADMIN_MODE() throws IOException {
if (System.getProperty("ONLINE_JUDGE") == null) {
w = new Printer(new FileOutputStream("output.txt"));
sc = new fs(new FileInputStream("input.txt"));
}
}
//-----------------------------------------------------------------------//
//----------------------------START--------------------------------------//
public static void main(String[] args)
throws IOException {
// ADMIN_MODE();
// int t = sc.ni();
// while(t-->0)
solve();
w.close();
}
static void solve() throws IOException {
int n = sc.ni();
Long[] arr = new Long[n+1];
arr[0] = Long.MIN_VALUE;
int k = sc.ni();
query(true, 1, 2);
long one = sc.nl();
query(false, 1, 2);
one += sc.nl();
query(true, 2, 3);
long two = sc.nl();
query(false, 2, 3);
two += sc.nl();
query(true, 1, 3);
long three = sc.nl();
query(false, 1, 3);
three += sc.nl();
arr[2] = (two + (one - three))/2;
arr[1] = one-arr[2];
arr[3] = two-arr[2];
// w.p(Arrays.toString(arr));
for(int i = 3; i < n; i++) {
query(true, i, i+1);
long curr = sc.nl();
query(false, i, i+1);
curr += sc.nl();
arr[i+1] = curr-arr[i];
}
Arrays.sort(arr);
// w.p(Arrays.toString(arr));
w.p("finish "+arr[k]);
}
static void query(boolean f, int i, int j) {
if(f) {
w.p("and "+i+" "+j);
} else {
w.p("or "+i+" "+j);
}
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | d676e0b7e5b019d96c7030457c8ba817 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class new1
{
static FastReader s = new FastReader();
static int invert(int n) {
return ~n;
}
public static int ask(int i, int j, int query) {
int ret = 0;
if(query == 0) {
System.out.println("or " + i + " " + j);
System.out.flush();
ret = s.nextInt();
}
else {
System.out.println("and " + i + " " + j);
System.out.flush();
ret = s.nextInt();
}
return ret;
}
public static void main (String[] args)
{
int t = 1;//s.nextInt();
for(int i = 0; i < t; i++) {
int n = s.nextInt();
int k = s.nextInt();
ArrayList<Integer> aList = new ArrayList<Integer>();
int j = 1;
int a = 0; int b = 0; int c = 0;
int A = 0, B = 0, C = 0, D = 0, E = 0, F = 0;
int a1 = 0, b2 = 0, c3 = 0;
while(j <= n / 3 * 3) {
a = j;
b = j + 1;
c = j + 2;
//System.out.println(a + " " + b + " " + c + " " + j);
A = ask(a, b, 0);
B = ask(a, b, 1);
C = ask(b, c, 0);
D = ask(b, c, 1);
E = ask(c, a, 0);
F = ask(c, a, 1);
b2 = (A | C | E) & (invert(E)) | B | D;
a1 = (A | C | E) & (invert(C)) | B | F;
c3 = (A | C | E) & (invert(A)) | F | D;
aList.add(a1); aList.add(b2); aList.add(c3);
j = j + 3;
}
if(n % 3 == 1) {
//System.out.println("hello");
c = j;
j++;
C = ask(b, c, 0);
D = ask(b, c, 1);
int c1 = (C) & (invert(b2)) | D;
aList.add(c1);
}
else if(n % 3 == 2) {
c = j;
j++;
C = ask(b, c, 0);
D = ask(b, c, 1);
int c1 = (C) & (invert(b2)) | D;
aList.add(c1);
c = j;
C = ask(b, c, 0);
D = ask(b, c, 1);
c1 = (C) & (invert(b2)) | D;
//System.out.println(b + " b ");
aList.add(c1);
}
aList.sort(null);
System.out.println("finish " + aList.get(k - 1));
System.out.flush();
}
}
}
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();
}
public int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | fa6719807a9a77217bbf2b3b382a227e | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes |
import java.io.*;
import java.util.*;
public class DeltixSU21D {
public static void solve(IO io) {
int n = io.getInt();
int k = io.getInt();
int [][] arr = new int[n][32]; // 0 is unknown, 1 is 1, -1 is 0
for (int i = 1; i < n; i++) {
io.println("or " + i + " " + (i + 1));
io.flush();
int a = io.getInt();
io.println("and " + i + " " + (i + 1));
io.flush();
int b = io.getInt();
for (int j = 31; j >= 0; j--) {
if (a % 2 == b % 2) {
if (a % 2 == 1) {
arr[i][j] = 1;
arr[i - 1][j] = 1;
} else {
arr[i][j] = -1;
arr[i - 1][j] = -1;
}
}
a /= 2;
b /= 2;
}
}
io.println("or " + 1 + " " + n);
io.flush();
int a = io.getInt();
io.println("and " + 1 + " " + n);
io.flush();
int b = io.getInt();
for (int j = 31; j >= 0; j--) {
if (a % 2 == b % 2) {
if (a % 2 == 1) {
arr[0][j] = 1;
arr[n - 1][j] = 1;
} else {
arr[0][j] = -1;
arr[n - 1][j] = -1;
}
}
a /= 2;
b /= 2;
}
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < 32; j++) {
if (arr[i + 1][j] == 0) {
arr[i + 1][j] = - arr[i][j];
}
}
}
for (int i = n - 1; i > 0; i--) {
for (int j = 0; j < 32; j++) {
if (arr[i - 1][j] == 0) {
arr[i - 1][j] = - arr[i][j];
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < 32; j++) {
arr[i][j] += 1;
arr[i][j] /= 2;
}
}
int [] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = 0;
for (int j = 0; j < 31; j++) {
nums[i] += (arr[i][j] + 1)/2;
nums[i] *= 2;
}
nums[i] += (arr[i][31] + 1)/2;
}
Arrays.sort(nums);
io.println("finish " + nums[k - 1]);
io.flush();
}
public static void main(String[] args) {
IO io = new IO();
solve(io);
io.close();
}
static class IO extends PrintWriter {
public IO() {
super(new BufferedOutputStream(System.out));
r = new BufferedReader(new InputStreamReader(System.in));
}
public IO(InputStream i) {
super(new BufferedOutputStream(System.out));
r = new BufferedReader(new InputStreamReader(i));
}
public IO(InputStream i, OutputStream o) {
super(new BufferedOutputStream(o));
r = new BufferedReader(new InputStreamReader(i));
}
public boolean hasMoreTokens() {
return peekToken() != null;
}
public int getInt() {
return Integer.parseInt(nextToken());
}
public double getDouble() {
return Double.parseDouble(nextToken());
}
public long getLong() {
return Long.parseLong(nextToken());
}
public String getWord() {
return nextToken();
}
private BufferedReader r;
private String line;
private StringTokenizer st;
private String token;
private String peekToken() {
if (token == null)
try {
while (st == null || !st.hasMoreTokens()) {
line = r.readLine();
if (line == null)
return null;
st = new StringTokenizer(line);
}
token = st.nextToken();
} catch (IOException e) {
}
return token;
}
private String nextToken() {
String ans = peekToken();
token = null;
return ans;
}
}
}
| Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | f5036c9e6526b8a5ab70a85cdbc76314 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.util.*;
import javax.swing.plaf.synth.SynthSpinnerUI;
import java.io.*;
import java.net.StandardSocketOptions;
public class tr0 {
static PrintWriter out;
static StringBuilder sb;
static long mod = (long) 1e9 + 7;
static long inf = (long) 1e16;
static int n, k;
static ArrayList<Integer>[] ad;
static int[][] remove, add;
static int[][] memo;
static boolean vis[];
static long[] inv, ncr[];
static HashMap<Integer, Integer> hm;
static int[] pre, suf, Smax[], Smin[];
static int idmax, idmin;
static ArrayList<Integer> av;
static HashMap<Integer, Integer> mm;
static boolean[] msks;
static int[] lazy[], lazyCount;
static int[] dist;
static int[][] P;
static long N;
static ArrayList<Integer> gl;
static int[] a;
static String s;
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
out = new PrintWriter(System.out);
int n = sc.nextInt();
int k = sc.nextInt();
int[] ands = new int[n];
int start = 0;
for (int i = 2; i <= n; i++) {
System.out.println("and " + 1 + " " + i);
int x = sc.nextInt();
ands[i - 1] = x;
start |= x;
}
System.out.println("or " + 2 + " " + 3);
int orz = sc.nextInt();
System.out.println("or " + 1 + " " + 2);
int or2 = sc.nextInt();
System.out.println("or " + 1 + " " + 3);
int or3 = sc.nextInt();
for (int bit = 0; bit < 31; bit++) {
if ((start & 1 << bit) != 0)
continue;
if ((orz & 1 << bit) == 0 && (or2 & 1 << bit) != 0 && (or3 & 1 << bit) != 0)
start |= 1 << bit;
}
int[] ors = new int[n];
Arrays.fill(ors, -1);
ors[1] = or2;
ors[2] = or3;
Integer[] nums = new Integer[n];
nums[0] = start;
for (int i = 1; i < n; i++) {
if (ors[i] == -1) {
System.out.println("or " + 1 + " " + (i + 1));
ors[i] = sc.nextInt();
}
int v = ands[i];
v |= (ors[i] ^ v) ^ start;
nums[i] = v;
}
Arrays.sort(nums);
System.out.println("finish "+nums[k - 1]);
out.flush();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public int[] nextArrInt(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long[] nextArrLong(int n) throws IOException {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
public int[] nextArrIntSorted(int n) throws IOException {
int[] a = new int[n];
Integer[] a1 = new Integer[n];
for (int i = 0; i < n; i++)
a1[i] = nextInt();
Arrays.sort(a1);
for (int i = 0; i < n; i++)
a[i] = a1[i].intValue();
return a;
}
public long[] nextArrLongSorted(int n) throws IOException {
long[] a = new long[n];
Long[] a1 = new Long[n];
for (int i = 0; i < n; i++)
a1[i] = nextLong();
Arrays.sort(a1);
for (int i = 0; i < n; i++)
a[i] = a1[i].longValue();
return a;
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 555412d53fab0da55bc88077bba7cb96 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Arrays;
import java.util.Random;
import java.io.FileWriter;
import java.io.PrintWriter;
/*
Solution Created: 19:10:45 29/08/2021
Custom Competitive programming helper.
*/
public class Main {
public static void solve() {
int n = in.nextInt(), k = in.nextInt();
int[] a = new int[n];
int u = n-1, v = n-2;
for(int i = 1; i<n; i++) a[i] = getSum(0, i);
int firstVal = (a[u]+a[v]-getSum(u, v)) /2;
a[0] = firstVal;
for(int i = 1; i<n; i++) a[i] -= firstVal;
Util.sortArray(a);
done(a[k-1]);
}
public static int getSum(int i, int j) {
return askOr(i, j) + askAnd(i, j);
}
public static int askOr(int i, int j) {
i++;j++;
out.println("or "+i+" "+j);
out.flush();
return in.nextInt();
}
public static int askAnd(int i, int j) {
i++;j++;
out.println("and "+i+" "+j);
out.flush();
return in.nextInt();
}
public static void done(int i) {
out.println("finish "+i);
out.exit();
System.exit(0);
}
public static void main(String[] args) {
in = new Reader();
out = new Writer();
int t = 1;
while(t-->0) solve();
out.exit();
}
static Reader in; static Writer out;
static class Reader {
static BufferedReader br;
static StringTokenizer st;
public Reader() {
this.br = new BufferedReader(new InputStreamReader(System.in));
}
public Reader(String f){
try {
this.br = new BufferedReader(new FileReader(f));
} catch (IOException e) {
e.printStackTrace();
}
}
public int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public double[] nd(int n) {
double[] a = new double[n];
for (int i = 0; i < n; i++) a[i] = nextDouble();
return a;
}
public long[] nl(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
public char[] nca() {
return next().toCharArray();
}
public String[] ns(int n) {
String[] a = new String[n];
for (int i = 0; i < n; i++) a[i] = next();
return a;
}
public int nextInt() {
ensureNext();
return Integer.parseInt(st.nextToken());
}
public double nextDouble() {
ensureNext();
return Double.parseDouble(st.nextToken());
}
public Long nextLong() {
ensureNext();
return Long.parseLong(st.nextToken());
}
public String next() {
ensureNext();
return st.nextToken();
}
public String nextLine() {
try {
return br.readLine();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private void ensureNext() {
if (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
static class Util{
private static Random random = new Random();
static long[] fact;
public static void initFactorial(int n, long mod) {
fact = new long[n+1];
fact[0] = 1;
for (int i = 1; i < n+1; i++) fact[i] = (fact[i - 1] * i) % mod;
}
public static long modInverse(long a, long MOD) {
long[] gcdE = gcdExtended(a, MOD);
if (gcdE[0] != 1) return -1; // Inverted doesn't exist
long x = gcdE[1];
return (x % MOD + MOD) % MOD;
}
public static long[] gcdExtended(long p, long q) {
if (q == 0) return new long[] { p, 1, 0 };
long[] vals = gcdExtended(q, p % q);
long tmp = vals[2];
vals[2] = vals[1] - (p / q) * vals[2];
vals[1] = tmp;
return vals;
}
public static long nCr(int n, int r, long MOD) {
if (r == 0) return 1;
return (fact[n] * modInverse(fact[r], MOD) % MOD * modInverse(fact[n - r], MOD) % MOD) % MOD;
}
public static long nCr(int n, int r) {
return (fact[n]/fact[r])/fact[n-r];
}
public static long nPr(int n, int r, long MOD) {
if (r == 0) return 1;
return (fact[n] * modInverse(fact[n - r], MOD) % MOD) % MOD;
}
public static long nPr(int n, int r) {
return fact[n]/fact[n-r];
}
public static boolean isPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static boolean[] getSieve(int n) {
boolean[] isPrime = new boolean[n+1];
for (int i = 2; i <= n; i++) isPrime[i] = true;
for (int i = 2; i*i <= n; i++) if (isPrime[i])
for (int j = i; i*j <= n; j++) isPrime[i*j] = false;
return isPrime;
}
static long pow(long x, long pow, long mod){
long res = 1;
x = x % mod;
if (x == 0) return 0;
while (pow > 0){
if ((pow & 1) != 0) res = (res * x) % mod;
pow >>= 1;
x = (x * x) % mod;
}
return res;
}
public static int gcd(int a, int b) {
int tmp = 0;
while(b != 0) {
tmp = b;
b = a%b;
a = tmp;
}
return a;
}
public static long gcd(long a, long b) {
long tmp = 0;
while(b != 0) {
tmp = b;
b = a%b;
a = tmp;
}
return a;
}
public static int random(int min, int max) {
return random.nextInt(max-min+1)+min;
}
public static void dbg(Object... o) {
System.out.println(Arrays.deepToString(o));
}
public static void reverse(int[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
int tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(int[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(long[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
long tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(long[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(float[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
float tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(float[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(double[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
double tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(double[] s) {
reverse(s, 0, s.length-1);
}
public static void reverse(char[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
char tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static void reverse(char[] s) {
reverse(s, 0, s.length-1);
}
public static <T> void reverse(T[] s, int l , int r) {
for(int i = l; i<=(l+r)/2; i++) {
T tmp = s[i];
s[i] = s[r+l-i];
s[r+l-i] = tmp;
}
}
public static <T> void reverse(T[] s) {
reverse(s, 0, s.length-1);
}
public static void shuffle(int[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
int t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(long[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
long t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(float[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
float t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(double[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
double t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void shuffle(char[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
char t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static <T> void shuffle(T[] s) {
for (int i = 0; i < s.length; ++i) {
int j = random.nextInt(i + 1);
T t = s[i];
s[i] = s[j];
s[j] = t;
}
}
public static void sortArray(int[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(long[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(float[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(double[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void sortArray(char[] a) {
shuffle(a);
Arrays.sort(a);
}
public static <T extends Comparable<T>> void sortArray(T[] a) {
Arrays.sort(a);
}
}
static class Writer {
private PrintWriter pw;
public Writer(){
pw = new PrintWriter(System.out);
}
public Writer(String f){
try {
pw = new PrintWriter(new FileWriter(f));
} catch (IOException e) {
e.printStackTrace();
}
}
public void yesNo(boolean condition) {
println(condition?"YES":"NO");
}
public void printArray(int[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
}
public void printlnArray(int[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
pw.println();
}
public void printArray(long[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
}
public void printlnArray(long[] a) {
for(int i = 0; i<a.length; i++) print(a[i]+" ");
pw.println();
}
public void print(Object o) {
pw.print(o.toString());
}
public void println(Object o) {
pw.println(o.toString());
}
public void println() {
pw.println();
}
public void flush() {
pw.flush();
}
public void exit() {
pw.close();
}
}
}
| Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 14d061c30230252f4e50e11af84d037a | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | /*
stream Butter!
eggyHide eggyVengeance
I need U
xiao rerun when
*/
import static java.lang.Math.*;
import java.util.*;
import java.io.*;
import java.math.*;
public class x1556D
{
public static void main(String hi[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int N = Integer.parseInt(st.nextToken());
int K = Integer.parseInt(st.nextToken());
int[] arr = new int[N+1];
arr[0] = -1;
//get first 3 numbers [x,y,z,...]
int xyAND = query("and", 1, 2, infile);
int xzAND = query("and", 1, 3, infile);
int yzAND = query("and", 2, 3, infile);
int xyOR = query("or", 1, 2, infile);
int xzOR = query("or", 1, 3, infile);
int yzOR = query("or", 2, 3, infile);
for(int bit=29; bit >= 0; bit--)
{
int a = min((xyAND&(1<<bit)), 1);
int b = min((yzAND&(1<<bit)), 1);
int c = min((xyOR&(1<<bit)), 1);
int d = min((yzOR&(1<<bit)), 1);
int mask = d+2*c+4*b+8*a;
//System.out.println(mask+" "+bit);
if(mask == 0); //lol
else if(mask == 1)
arr[3] |= 1<<bit;
else if(mask == 2)
arr[1] |= 1<<bit;
else if(mask == 11)
{
arr[1] |= 1<<bit;
arr[2] |= 1<<bit;
}
else if(mask == 7)
{
arr[2] |= 1<<bit;
arr[3] |= 1<<bit;
}
else if(mask == 15)
{
arr[1] |= 1<<bit;
arr[2] |= 1<<bit;
arr[3] |= 1<<bit;
}
else
{
//System.out.println("! "+mask);
if((xzAND&(1<<bit)) > 0)
{
arr[1] |= 1<<bit;
arr[3] |= 1<<bit;
}
else
arr[2] |= 1<<bit;
}
}
//System.out.println(arr[1]+" "+arr[2]+" "+arr[3]);
for(int i=4; i <= N; i++)
{
int and = query("and", 1, i, infile);
int or = query("or", 1, i, infile);
for(int b=29; b >= 0; b--)
{
if((arr[1]&(1<<b)) > 0)
{
if((and&(1<<b)) > 0)
arr[i] |= 1<<b;
}
else
{
if((or&(1<<b)) > 0)
arr[i] |= 1<<b;
}
}
}
sort(arr);
System.out.println("finish "+arr[K]);
}
public static int query(String message, int a, int b, BufferedReader infile) throws Exception
{
System.out.println(message+" "+a+" "+b);
return Integer.parseInt(infile.readLine());
}
public static void sort(int[] arr)
{
//because Arrays.sort() uses quicksort which is dumb
//Collections.sort() uses merge sort
ArrayList<Integer> ls = new ArrayList<Integer>();
for(int x: arr)
ls.add(x);
Collections.sort(ls);
for(int i=0; i < arr.length; i++)
arr[i] = ls.get(i);
}
}
/*
0
0
4
7
5
6
*/ | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | c505e90b217fd1d7abb7a6f7df8227d3 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.io.*;import java.util.*;import java.math.*;import static java.lang.Math.*;import static java.
util.Map.*;import static java.util.Arrays.*;import static java.util.Collections.*;
import static java.lang.System.*;
public class Main
{
public void tq()throws Exception
{
st=new StringTokenizer(bq.readLine());
int tq=1;
sb=new StringBuilder(2000000);
o:
while(tq-->0)
{
int n=i();
int k=i();
int f[]=new int[n];
pl("and 1 2");f();
int a=i();
pl("or 1 2");f();
int aa=i();
int aaa=a+aa;
pl("and 1 3");f();
int b=i();
pl("or 1 3");f();
int bb=i();
int bbb=b+bb;
pl("and 2 3");f();
int c=i();
pl("or 2 3");f();
int cc=i();
int ccc=c+cc;
f[0]=(aaa+bbb-ccc)/2;
f[1]=aaa-f[0];
f[2]=bbb-f[0];
for(int x=3;x<n;x++)
{
pl("and "+(x)+" "+(x+1));f();
c=i();
pl("or "+(x)+" "+(x+1));f();
cc=i();
ccc=c+cc;
f[x]=ccc-f[x-1];
}
//p(f);
so(f);
pl("finish "+f[k-1]);
f();
}
p(sb);
}
void f(){System.out.flush();}
int di[][]={{-1,0},{1,0},{0,-1},{0,1}};
int de[][]={{-1,0},{1,0},{0,-1},{0,1},{-1,-1},{1,1},{-1,1},{1,-1}};
long mod=1000000007l;int max=Integer.MAX_VALUE,min=Integer.MIN_VALUE;long maxl=Long.MAX_VALUE, minl=Long.
MIN_VALUE;BufferedReader bq=new BufferedReader(new InputStreamReader(in));StringTokenizer st;
StringBuilder sb;public static void main(String[] a)throws Exception{new Main().tq();}int[] so(int ar[])
{Integer r[]=new Integer[ar.length];for(int x=0;x<ar.length;x++)r[x]=ar[x];sort(r);for(int x=0;x<ar.length;
x++)ar[x]=r[x];return ar;}long[] so(long ar[]){Long r[]=new Long[ar.length];for(int x=0;x<ar.length;x++)
r[x]=ar[x];sort(r);for(int x=0;x<ar.length;x++)ar[x]=r[x];return ar;}
char[] so(char ar[]) {Character
r[]=new Character[ar.length];for(int x=0;x<ar.length;x++)r[x]=ar[x];sort(r);for(int x=0;x<ar.length;x++)
ar[x]=r[x];return ar;}void s(String s){sb.append(s);}void s(int s){sb.append(s);}void s(long s){sb.
append(s);}void s(char s){sb.append(s);}void s(double s){sb.append(s);}void ss(){sb.append(' ');}void sl
(String s){sb.append(s);sb.append("\n");}void sl(int s){sb.append(s);sb.append("\n");}void sl(long s){sb
.append(s);sb.append("\n");}void sl(char s) {sb.append(s);sb.append("\n");}void sl(double s){sb.append(s)
;sb.append("\n");}void sl(){sb.append("\n");}int l(int v){return 31-Integer.numberOfLeadingZeros(v);}
long l(long v){return 63-Long.numberOfLeadingZeros(v);}int sq(int a){return (int)sqrt(a);}long sq(long a)
{return (long)sqrt(a);}long gcd(long a,long b){while(b>0l){long c=a%b;a=b;b=c;}return a;}int gcd(int a,int b)
{while(b>0){int c=a%b;a=b;b=c;}return a;}boolean pa(String s,int i,int j){while(i<j)if(s.charAt(i++)!=
s.charAt(j--))return false;return true;}boolean[] si(int n) {boolean bo[]=new boolean[n+1];bo[0]=true;bo[1]
=true;for(int x=4;x<=n;x+=2)bo[x]=true;for(int x=3;x*x<=n;x+=2){if(!bo[x]){int vv=(x<<1);for(int y=x*x;y<=n;
y+=vv)bo[y]=true;}}return bo;}long mul(long a,long b,long m) {long r=1l;a%=m;while(b>0){if((b&1)==1)
r=(r*a)%m;b>>=1;a=(a*a)%m;}return r;}int i()throws IOException{if(!st.hasMoreTokens())st=new
StringTokenizer(bq.readLine());return Integer.parseInt(st.nextToken());}long l()throws IOException
{if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine());return Long.parseLong(st.nextToken());}String
s()throws IOException {if (!st.hasMoreTokens())st=new StringTokenizer(bq.readLine());return st.nextToken();}
double d()throws IOException{if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine());return Double.
parseDouble(st.nextToken());}void p(Object p){out.print(p);}void p(String p){out.print(p);}void p(int p)
{out.print(p);}void p(double p){out.print(p);}void p(long p){out.print(p);}void p(char p){out.print(p);}void
p(boolean p){out.print(p);}void pl(Object p){out.println(p);}void pl(String p){out.println(p);}void pl(int p)
{out.println(p);}void pl(char p){out.println(p);}void pl(double p){out.println(p);}void pl(long p){out.
println(p);}void pl(boolean p)
{out.println(p);}void pl(){out.println();}void s(int a[]){for(int e:a)
{sb.append(e);sb.append(' ');}sb.append("\n");}
void s(long a[])
{for(long e:a){sb.append(e);sb.append(' ')
;}sb.append("\n");}void s(int ar[][]){for(int a[]:ar){for(int e:a){sb.append(e);sb.append(' ');}sb.append
("\n");}}
void s(char a[])
{for(char e:a){sb.append(e);sb.append(' ');}sb.append("\n");}void s(char ar[][])
{for(char a[]:ar){for(char e:a){sb.append(e);sb.append(' ');}sb.append("\n");}}int[] ari(int n)throws
IOException {int ar[]=new int[n];if(!st.hasMoreTokens())st=new StringTokenizer(bq.readLine());for(int x=0;
x<n;x++)ar[x]=Integer.parseInt(st.nextToken());return ar;}int[][] ari(int n,int m)throws
IOException {int ar[][]=new int[n][m];for(int x=0;x<n;x++){if (!st.hasMoreTokens())st=new StringTokenizer
(bq.readLine());for(int y=0;y<m;y++)ar[x][y]=Integer.parseInt(st.nextToken());}return ar;}long[] arl
(int n)throws IOException {long ar[]=new long[n];if(!st.hasMoreTokens()) st=new StringTokenizer(bq.readLine())
;for(int x=0;x<n;x++)ar[x]=Long.parseLong(st.nextToken());return ar;}long[][] arl(int n,int m)throws
IOException {long ar[][]=new long[n][m];for(int x=0;x<n;x++) {if(!st.hasMoreTokens()) st=new
StringTokenizer(bq.readLine());for(int y=0;y<m;y++)ar[x][y]=Long.parseLong(st.nextToken());}return ar;}
String[] ars(int n)throws IOException {String ar[] =new String[n];if(!st.hasMoreTokens())st=new
StringTokenizer(bq.readLine());for(int x=0;x<n;x++)ar[x]=st.nextToken();return ar;}double[] ard
(int n)throws IOException {double ar[] =new double[n];if(!st.hasMoreTokens())st=new StringTokenizer
(bq.readLine());for(int x=0;x<n;x++)ar[x]=Double.parseDouble(st.nextToken());return ar;}double[][] ard
(int n,int m)throws IOException{double ar[][]=new double[n][m];for(int x=0;x<n;x++) {if(!st.hasMoreTokens())
st=new StringTokenizer(bq.readLine());for(int y=0;y<m;y++) ar[x][y]=Double.parseDouble(st.nextToken());}
return ar;}char[] arc(int n)throws IOException{char ar[]=new char[n];if(!st.hasMoreTokens())st=new
StringTokenizer(bq.readLine());for(int x=0;x<n;x++)ar[x]=st.nextToken().charAt(0);return ar;}char[][]
arc(int n,int m)throws IOException {char ar[][]=new char[n][m];for(int x=0;x<n;x++){String s=bq.readLine();
for(int y=0;y<m;y++)ar[x][y]=s.charAt(y);}return ar;}void p(int ar[])
{StringBuilder sb=new StringBuilder
(2*ar.length);for(int a:ar){sb.append(a);sb.append(' ');}out.println(sb);}void p(int ar[][])
{StringBuilder sb=new StringBuilder(2*ar.length*ar[0].length);for(int a[]:ar){for(int aa:a){sb.append(aa);
sb.append(' ');}sb.append("\n");}p(sb);}void p(long ar[]){StringBuilder sb=new StringBuilder
(2*ar.length);for(long a:ar){ sb.append(a);sb.append(' ');}out.println(sb);}
void p(long ar[][])
{StringBuilder sb=new StringBuilder(2*ar.length*ar[0].length);for(long a[]:ar){for(long aa:a){sb.append(aa);
sb.append(' ');}sb.append("\n");}p(sb);}void p(String ar[]){int c=0;for(String s:ar)c+=s.length()+1;
StringBuilder sb=new StringBuilder(c);for(String a:ar){sb.append(a);sb.append(' ');}out.println(sb);}
void p(double ar[])
{StringBuilder sb=new StringBuilder(2*ar.length);for(double a:ar){sb.append(a);
sb.append(' ');}out.println(sb);}void p
(double ar[][]){StringBuilder sb=new StringBuilder(2*
ar.length*ar[0].length);for(double a[]:ar){for(double aa:a){sb.append(aa);sb.append(' ');}sb.append("\n")
;}p(sb);}void p(char ar[])
{StringBuilder sb=new StringBuilder(2*ar.length);for(char aa:ar){sb.append(aa);
sb.append(' ');}out.println(sb);}void p(char ar[][]){StringBuilder sb=new StringBuilder(2*ar.length*ar[0]
.length);for(char a[]:ar){for(char aa:a){sb.append(aa);sb.append(' ');}sb.append("\n");}p(sb);}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | a95181178ed9debfbfcf0e04397599c0 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 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.Collections;
import java.util.Scanner;
import java.util.StringTokenizer;
/*
4 1
0
2
1
3
3
3
7 6
1 6 4 2 3 5 4
*/
public class D {
static Scanner fs;
static int[] realAns= {1, 6, 4, 2, 3, 5, 4};
public static void main(String[] args) {
// FastScanner fs=new FastScanner();
fs=new Scanner(System.in);
// int T=fs.nextInt();
int T=1;
for (int tt=0; tt<T; tt++) {
int n=fs.nextInt();
int k=fs.nextInt();
int abAnd=queryAnd(0, 1);
int bcAnd=queryAnd(1, 2);
int caAnd=queryAnd(0, 2);
int abOr=queryOr(0, 1);
int bcOr=queryOr(1, 2);
int caOr=queryOr(0, 2);
int[] values=new int[n];
for (int bit=0; bit<=30; bit++) {
// System.out.println("Checking bit "+bit);
int perfectCount=0;
for (int mask=0; mask<1<<3; mask++) {
boolean[] has=new boolean[3];
for (int i=0; i<3; i++) has[i]=(mask&(1<<i))!=0;
if (((abAnd&(1<<bit))!=0) !=(has[0] && has[1])) continue;
if (((caAnd&(1<<bit))!=0) !=(has[0] && has[2])) continue;
if (((bcAnd&(1<<bit))!=0) !=(has[1] && has[2])) continue;
if (((abOr&(1<<bit))!=0) !=(has[0] || has[1])) continue;
if (((caOr&(1<<bit))!=0) !=(has[0] || has[2])) continue;
if (((bcOr&(1<<bit))!=0) !=(has[1] || has[2])) continue;
for (int i=0; i<3; i++)
if (has[i]) values[i]+=1<<bit;
// System.out.println("Mask "+mask+" is perfect");
perfectCount++;
}
if (perfectCount!=1) throw null;
}
for (int i=3; i<n; i++) {
int and=queryAnd(0, i);
int or=queryOr(0, i);
int xor=and^or;
values[i]=values[0]^xor;
}
Arrays.sort(values);
// System.err.println("Values: "+Arrays.toString(values));
System.out.println("finish "+(values[k-1]));
}
}
static int queryAnd(int a, int b) {
System.out.println("and "+(a+1)+" "+(b+1));
// return realAns[a]&realAns[b];
return fs.nextInt();
}
static int queryOr(int a, int b) {
System.out.println("or "+(a+1)+" "+(b+1));
// return realAns[a]|realAns[b];
return fs.nextInt();
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 77d70b832516584ec9cc7d16d92ebf4a | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes |
import java.io.*;
import java.util.*;
public class DeltixSU21D {
public static void solve(IO io) {
int n = io.getInt();
int k = io.getInt();
int [][] arr = new int[n][32]; // 0 is unknown, 1 is 1, -1 is 0
for (int i = 1; i < n; i++) {
io.println("or " + i + " " + (i + 1));
io.flush();
int a = io.getInt();
io.println("and " + i + " " + (i + 1));
io.flush();
int b = io.getInt();
for (int j = 31; j >= 0; j--) {
if (a % 2 == b % 2) {
if (a % 2 == 1) {
arr[i][j] = 1;
arr[i - 1][j] = 1;
} else {
arr[i][j] = -1;
arr[i - 1][j] = -1;
}
}
a /= 2;
b /= 2;
}
}
io.println("or " + 1 + " " + n);
io.flush();
int a = io.getInt();
io.println("and " + 1 + " " + n);
io.flush();
int b = io.getInt();
for (int j = 31; j >= 0; j--) {
if (a % 2 == b % 2) {
if (a % 2 == 1) {
arr[0][j] = 1;
arr[n - 1][j] = 1;
} else {
arr[0][j] = -1;
arr[n - 1][j] = -1;
}
}
a /= 2;
b /= 2;
}
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < 32; j++) {
if (arr[i + 1][j] == 0) {
arr[i + 1][j] = - arr[i][j];
}
}
}
for (int i = n - 1; i > 0; i--) {
for (int j = 0; j < 32; j++) {
if (arr[i - 1][j] == 0) {
arr[i - 1][j] = - arr[i][j];
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < 32; j++) {
arr[i][j] += 1;
arr[i][j] /= 2;
}
}
int [] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = 0;
for (int j = 0; j < 31; j++) {
nums[i] += (arr[i][j] + 1)/2;
nums[i] *= 2;
}
nums[i] += (arr[i][31] + 1)/2;
}
Arrays.sort(nums);
io.println("finish " + nums[k - 1]);
io.flush();
}
public static void main(String[] args) {
IO io = new IO();
solve(io);
io.close();
}
static class IO extends PrintWriter {
public IO() {
super(new BufferedOutputStream(System.out));
r = new BufferedReader(new InputStreamReader(System.in));
}
public IO(InputStream i) {
super(new BufferedOutputStream(System.out));
r = new BufferedReader(new InputStreamReader(i));
}
public IO(InputStream i, OutputStream o) {
super(new BufferedOutputStream(o));
r = new BufferedReader(new InputStreamReader(i));
}
public boolean hasMoreTokens() {
return peekToken() != null;
}
public int getInt() {
return Integer.parseInt(nextToken());
}
public double getDouble() {
return Double.parseDouble(nextToken());
}
public long getLong() {
return Long.parseLong(nextToken());
}
public String getWord() {
return nextToken();
}
private BufferedReader r;
private String line;
private StringTokenizer st;
private String token;
private String peekToken() {
if (token == null)
try {
while (st == null || !st.hasMoreTokens()) {
line = r.readLine();
if (line == null)
return null;
st = new StringTokenizer(line);
}
token = st.nextToken();
} catch (IOException e) {
}
return token;
}
private String nextToken() {
String ans = peekToken();
token = null;
return ans;
}
}
}
| Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | d4b3fd40c043753e1c225de258877337 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 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.HashSet;
import java.util.Random;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
// CFPS -> CodeForcesProblemSet
public final class CFPS {
static FastReader fr = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
static final int gigamod = 1000000007;
static int t = 1;
static double epsilon = 0.00000001;
static boolean[] isPrime;
static int[] smallestFactorOf;
@SuppressWarnings("unused")
public static void main(String[] args) {
OUTER:
for (int tc = 0; tc < t; tc++) {
int n = fr.nextInt(), k = fr.nextInt();
// Observations:
// 1. The task is to determine the 'k'th smallest number.
// 2. We'll find the first 3 elements in 6 queries and then use
// XOR = (OR and !AND) to find rest in 2 queries each.
int a = 0, b = 1, c = 2;
long a_and_b = and(a, b);
long b_and_c = and(b, c);
long a_and_c = and(a, c);
long a_or_b = or(a, b);
long a_or_c = or(a, c);
long b_or_c = or(b, c);
long[] arr = new long[n];
for (int lvl = 29; lvl > -1; lvl--) {
long shift = (1L << lvl);
boolean aob = ((a_or_b) & (shift)) > 0;
boolean aab = ((a_and_b)& (shift)) > 0;
boolean aoc = ((a_or_c) & (shift)) > 0;
boolean aac = ((a_and_c)& (shift)) > 0;
boolean boc = ((b_or_c) & (shift)) > 0;
boolean bac = ((b_and_c)& (shift)) > 0;
// 001
if (!aob && boc) {
arr[c] |= (shift);
}
// 010
if (!aoc && boc) {
arr[b] |= (shift);
}
// 011
if (bac && !aab) {
arr[b] |= shift;
arr[c] |= shift;
}
// 100
if (!boc && aob) {
arr[a] |= shift;
}
// 101
if (aac && !bac) {
arr[a] |= shift;
arr[c] |= shift;
}
// 110
if (aab && !bac) {
arr[a] |= shift;
arr[b] |= shift;
}
// 111
if (aab && bac) {
arr[a] |= shift;
arr[b] |= shift;
arr[c] |= shift;
}
}
// System.out.println(arr[0] + " " + arr[1] + " " + arr[2]);
// rest will be found using XOR
for (int i = 3; i < n; i++) {
arr[i] = arr[a] ^ xor(a, i);
}
sort(arr);
out.println("finish " + arr[k - 1]);
/*
* 0
*
* 4
*
* 0
*
* 7
*
* 5
*
* 6
*
* 3
*
* 0
*
* 3
*
* 1
*
* 5
*
* 1
*
* 5
*
* 0
*/
}
out.close();
}
static long and(int i, int j) {
out.println("and " + (i + 1) + " " + (j + 1));
out.flush();
return fr.nextLong();
}
static long or(int i, int j) {
out.println("or " + (i + 1) + " " + (j + 1));
out.flush();
return fr.nextLong();
}
static long xor(int i, int j) {
long or = or(i, j);
long and = and(i, j);
return or & ~and;
}
static int check(char[] tgt, char[] src) {
int n = tgt.length;
if (src.length != n) return 0;
// 'X' check
char xDig = 0;
for (int i = 0; i < n; i++)
if (src[i] == 'X') {
if (xDig == 0) {
xDig = tgt[i];
} else {
if (tgt[i] != xDig) return 0;
}
}
// assert all 'X's have same digit;
// no leading zeroes plz
if (tgt[0] == '0') return 0;
// all non _s have to be equal
for (int i = 0; i < n; i++)
if (src[i] != '_' && src[i] != 'X' && tgt[i] != src[i]) return 0;
return 1;
}
static class Edge implements Comparable<Edge> {
int from, to;
long weight;
int id;
// int hash;
Edge(int fro, int t, long weigh, int i) {
from = fro;
to = t;
weight = weigh;
id = i;
// hash = Objects.hash(from, to, weight);
}
/*public int hashCode() {
return hash;
}*/
public int compareTo(Edge that) {
return Long.compare(this.id, that.id);
}
}
public static long[][] sparseTable(long[] a)
{
int n = a.length;
int b = 32-Integer.numberOfLeadingZeros(n);
long[][] ret = new long[b][];
for(int i = 0, l = 1;i < b;i++, l*=2) {
if(i == 0) {
ret[i] = a;
}else {
ret[i] = new long[n-l+1];
for(int j = 0;j < n-l+1;j++) {
ret[i][j] = Math.min(ret[i-1][j], ret[i-1][j+l/2]);
}
}
}
return ret;
}
public static long sparseRMQ(long[][] table, int l, int r)
{
// [a,b)
assert l <= r;
if(l >= r)return Integer.MAX_VALUE;
// 1:0, 2:1, 3:1, 4:2, 5:2, 6:2, 7:2, 8:3
int t = 31-Integer.numberOfLeadingZeros(r-l);
return Math.min(table[t][l], table[t][r-(1<<t)]);
}
static class Point implements Comparable<Point> {
long x;
long y;
long z;
long id;
// private int hashCode;
Point() {
x = z = y = 0;
// this.hashCode = Objects.hash(x, y, cost);
}
Point(Point p) {
this.x = p.x;
this.y = p.y;
this.z = p.z;
this.id = p.id;
// this.hashCode = Objects.hash(x, y, cost);
}
Point(long x, long y, long z, long id) {
this.x = x;
this.y = y;
this.z = z;
this.id = id;
// this.hashCode = Objects.hash(x, y, id);
}
Point(long a, long b) {
this.x = a;
this.y = b;
this.z = 0;
// this.hashCode = Objects.hash(a, b);
}
Point(long x, long y, long id) {
this.x = x;
this.y = y;
this.id = id;
}
@Override
public int compareTo(Point o) {
if (this.x < o.x)
return -1;
if (this.x > o.x)
return 1;
if (this.y < o.y)
return -1;
if (this.y > o.y)
return 1;
if (this.z < o.z)
return -1;
if (this.z > o.z)
return 1;
return 0;
}
@Override
public boolean equals(Object that) {
return this.compareTo((Point) that) == 0;
}
/*@Override
public int hashCode() {
return this.hashCode;
}*/
}
static class BinaryLift {
// FUNCTIONS: k-th ancestor and LCA in log(n)
int[] parentOf;
int maxJmpPow;
int[][] binAncestorOf;
int n;
int[] lvlOf;
// How this works?
// a. For every node, we store the b-ancestor for b in {1, 2, 4, 8, .. log(n)}.
// b. When we need k-ancestor, we represent 'k' in binary and for each set bit, we
// lift level in the tree.
public BinaryLift(UGraph tree) {
n = tree.V();
maxJmpPow = logk(n, 2) + 1;
parentOf = new int[n];
binAncestorOf = new int[n][maxJmpPow];
lvlOf = new int[n];
for (int i = 0; i < n; i++)
Arrays.fill(binAncestorOf[i], -1);
parentConstruct(0, -1, tree, 0);
binConstruct();
}
// TODO: Implement lvlOf[] initialization
public BinaryLift(int[] parentOf) {
this.parentOf = parentOf;
n = parentOf.length;
maxJmpPow = logk(n, 2) + 1;
binAncestorOf = new int[n][maxJmpPow];
lvlOf = new int[n];
for (int i = 0; i < n; i++)
Arrays.fill(binAncestorOf[i], -1);
UGraph tree = new UGraph(n);
for (int i = 1; i < n; i++)
tree.addEdge(i, parentOf[i]);
binConstruct();
parentConstruct(0, -1, tree, 0);
}
private void parentConstruct(int current, int from, UGraph tree, int depth) {
parentOf[current] = from;
lvlOf[current] = depth;
for (int adj : tree.adj(current))
if (adj != from)
parentConstruct(adj, current, tree, depth + 1);
}
private void binConstruct() {
for (int node = 0; node < n; node++)
for (int lvl = 0; lvl < maxJmpPow; lvl++)
binConstruct(node, lvl);
}
private int binConstruct(int node, int lvl) {
if (node < 0)
return -1;
if (lvl == 0)
return binAncestorOf[node][lvl] = parentOf[node];
if (node == 0)
return binAncestorOf[node][lvl] = -1;
if (binAncestorOf[node][lvl] != -1)
return binAncestorOf[node][lvl];
return binAncestorOf[node][lvl] = binConstruct(binConstruct(node, lvl - 1), lvl - 1);
}
// return ancestor which is 'k' levels above this one
public int ancestor(int node, int k) {
if (node < 0)
return -1;
if (node == 0)
if (k == 0) return node;
else return -1;
if (k > (1 << maxJmpPow) - 1)
return -1;
if (k == 0)
return node;
int ancestor = node;
int highestBit = Integer.highestOneBit(k);
while (k > 0 && ancestor != -1) {
ancestor = binAncestorOf[ancestor][logk(highestBit, 2)];
k -= highestBit;
highestBit = Integer.highestOneBit(k);
}
return ancestor;
}
public int lca(int u, int v) {
if (u == v)
return u;
// The invariant will be that 'u' is below 'v' initially.
if (lvlOf[u] < lvlOf[v]) {
int temp = u;
u = v;
v = temp;
}
// Equalizing the levels.
u = ancestor(u, lvlOf[u] - lvlOf[v]);
if (u == v)
return u;
// We will now raise level by largest fitting power of two until possible.
for (int power = maxJmpPow - 1; power > -1; power--)
if (binAncestorOf[u][power] != binAncestorOf[v][power]) {
u = binAncestorOf[u][power];
v = binAncestorOf[v][power];
}
return ancestor(u, 1);
}
}
static class DFSTree {
// NOTE: The thing is made keeping in mind that the whole
// input graph is connected.
UGraph tree;
UGraph backUG;
int hasBridge;
int n;
DFSTree(UGraph ug) {
this.n = ug.V();
tree = new UGraph(n);
hasBridge = -1;
backUG = new UGraph(n);
treeCalc(0, -1, new boolean[n], ug);
}
private void treeCalc(int current, int from, boolean[] marked, UGraph ug) {
if (marked[current]) {
// This is a backEdge.
backUG.addEdge(from, current);
return;
}
if (from != -1)
tree.addEdge(from, current);
marked[current] = true;
for (int adj : ug.adj(current))
if (adj != from)
treeCalc(adj, current, marked, ug);
}
public boolean hasBridge() {
if (hasBridge != -1)
return (hasBridge == 1);
// We have to determine the bridge.
bridgeFinder();
return (hasBridge == 1);
}
int[] levelOf;
int[] dp;
private void bridgeFinder() {
// Finding the level of each node.
levelOf = new int[n];
// Applying DP solution.
// dp[i] -> Highest level reachable from subtree of 'i' using
// some backEdge.
dp = new int[n];
Arrays.fill(dp, Integer.MAX_VALUE / 100);
dpDFS(0, -1, 0);
// Now, we will check each edge and determine whether its a
// bridge.
for (int i = 0; i < n; i++)
for (int adj : tree.adj(i)) {
// (i -> adj) is the edge.
if (dp[adj] > levelOf[i])
hasBridge = 1;
}
if (hasBridge != 1)
hasBridge = 0;
}
private int dpDFS(int current, int from, int lvl) {
levelOf[current] = lvl;
dp[current] = levelOf[current];
for (int back : backUG.adj(current))
dp[current] = Math.min(dp[current], levelOf[back]);
for (int adj : tree.adj(current))
if (adj != from)
dp[current] = Math.min(dp[current], dpDFS(adj, current, lvl + 1));
return dp[current];
}
}
static class UnionFind {
// Uses weighted quick-union with path compression.
private int[] parent; // parent[i] = parent of i
private int[] size; // size[i] = number of sites in tree rooted at i
// Note: not necessarily correct if i is not a root node
private int count; // number of components
public UnionFind(int n) {
count = n;
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
}
// Number of connected components.
public int count() {
return count;
}
// Find the root of p.
public int find(int p) {
while (p != parent[p])
p = parent[p];
return p;
}
public boolean connected(int p, int q) {
return find(p) == find(q);
}
public int numConnectedTo(int node) {
return size[find(node)];
}
// Weighted union.
public void union(int p, int q) {
int rootP = find(p);
int rootQ = find(q);
if (rootP == rootQ) return;
// make smaller root point to larger one
if (size[rootP] < size[rootQ]) {
parent[rootP] = rootQ;
size[rootQ] += size[rootP];
}
else {
parent[rootQ] = rootP;
size[rootP] += size[rootQ];
}
count--;
}
public static int[] connectedComponents(UnionFind uf) {
// We can do this in nlogn.
int n = uf.size.length;
int[] compoColors = new int[n];
for (int i = 0; i < n; i++)
compoColors[i] = uf.find(i);
HashMap<Integer, Integer> oldToNew = new HashMap<>();
int newCtr = 0;
for (int i = 0; i < n; i++) {
int thisOldColor = compoColors[i];
Integer thisNewColor = oldToNew.get(thisOldColor);
if (thisNewColor == null)
thisNewColor = newCtr++;
oldToNew.put(thisOldColor, thisNewColor);
compoColors[i] = thisNewColor;
}
return compoColors;
}
}
static class UGraph {
// Adjacency list.
private HashSet<Integer>[] adj;
private static final String NEWLINE = "\n";
private int E;
@SuppressWarnings("unchecked")
public UGraph(int V) {
adj = (HashSet<Integer>[]) new HashSet[V];
E = 0;
for (int i = 0; i < V; i++)
adj[i] = new HashSet<Integer>();
}
public void addEdge(int from, int to) {
if (adj[from].contains(to)) return;
E++;
adj[from].add(to);
adj[to].add(from);
}
public HashSet<Integer> adj(int from) {
return adj[from];
}
public int degree(int v) {
return adj[v].size();
}
public int V() {
return adj.length;
}
public int E() {
return E;
}
public String toString() {
StringBuilder s = new StringBuilder();
s.append(V() + " vertices, " + E() + " edges " + NEWLINE);
for (int v = 0; v < V(); v++) {
s.append(v + ": ");
for (int w : adj[v]) {
s.append(w + " ");
}
s.append(NEWLINE);
}
return s.toString();
}
public static void dfsMark(int current, boolean[] marked, UGraph g) {
if (marked[current]) return;
marked[current] = true;
Iterable<Integer> adj = g.adj(current);
for (int adjc : adj)
dfsMark(adjc, marked, g);
}
public static void dfsMark(int current, int from, long[] distTo, boolean[] marked, UGraph g, ArrayList<Integer> endPoints) {
if (marked[current]) return;
marked[current] = true;
if (from != -1)
distTo[current] = distTo[from] + 1;
HashSet<Integer> adj = g.adj(current);
int alreadyMarkedCtr = 0;
for (int adjc : adj) {
if (marked[adjc]) alreadyMarkedCtr++;
dfsMark(adjc, current, distTo, marked, g, endPoints);
}
if (alreadyMarkedCtr == adj.size())
endPoints.add(current);
}
public static void bfsOrder(int current, UGraph g) {
}
public static void dfsMark(int current, int[] colorIds, int color, UGraph g) {
if (colorIds[current] != -1) return;
colorIds[current] = color;
Iterable<Integer> adj = g.adj(current);
for (int adjc : adj)
dfsMark(adjc, colorIds, color, g);
}
public static int[] connectedComponents(UGraph g) {
int n = g.V();
int[] componentId = new int[n];
Arrays.fill(componentId, -1);
int colorCtr = 0;
for (int i = 0; i < n; i++) {
if (componentId[i] != -1) continue;
dfsMark(i, componentId, colorCtr, g);
colorCtr++;
}
return componentId;
}
public static boolean hasCycle(UGraph ug) {
int n = ug.V();
boolean[] marked = new boolean[n];
boolean[] hasCycleFirst = new boolean[1];
for (int i = 0; i < n; i++) {
if (marked[i]) continue;
hcDfsMark(i, ug, marked, hasCycleFirst, -1);
}
return hasCycleFirst[0];
}
// Helper for hasCycle.
private static void hcDfsMark(int current, UGraph ug, boolean[] marked, boolean[] hasCycleFirst, int parent) {
if (marked[current]) return;
if (hasCycleFirst[0]) return;
marked[current] = true;
HashSet<Integer> adjc = ug.adj(current);
for (int adj : adjc) {
if (marked[adj] && adj != parent && parent != -1) {
hasCycleFirst[0] = true;
return;
}
hcDfsMark(adj, ug, marked, hasCycleFirst, current);
}
}
}
static class Digraph {
// Adjacency list.
private HashSet<Integer>[] adj;
private static final String NEWLINE = "\n";
private int E;
@SuppressWarnings("unchecked")
public Digraph(int V) {
adj = (HashSet<Integer>[]) new HashSet[V];
E = 0;
for (int i = 0; i < V; i++)
adj[i] = new HashSet<Integer>();
}
public void addEdge(int from, int to) {
if (adj[from].contains(to)) return;
E++;
adj[from].add(to);
}
public HashSet<Integer> adj(int from) {
return adj[from];
}
public int V() {
return adj.length;
}
public int E() {
return E;
}
public Digraph reversed() {
Digraph dg = new Digraph(V());
for (int i = 0; i < V(); i++)
for (int adjVert : adj(i)) dg.addEdge(adjVert, i);
return dg;
}
public String toString() {
StringBuilder s = new StringBuilder();
s.append(V() + " vertices, " + E() + " edges " + NEWLINE);
for (int v = 0; v < V(); v++) {
s.append(v + ": ");
for (int w : adj[v]) {
s.append(w + " ");
}
s.append(NEWLINE);
}
return s.toString();
}
public static int[] KosarajuSharirSCC(Digraph dg) {
int[] id = new int[dg.V()];
Digraph reversed = dg.reversed();
// Gotta perform topological sort on this one to get the stack.
Stack<Integer> revStack = Digraph.topologicalSort(reversed);
// Initializing id and idCtr.
id = new int[dg.V()];
int idCtr = -1;
// Creating a 'marked' array.
boolean[] marked = new boolean[dg.V()];
while (!revStack.isEmpty()) {
int vertex = revStack.pop();
if (!marked[vertex])
sccDFS(dg, vertex, marked, ++idCtr, id);
}
return id;
}
private static void sccDFS(Digraph dg, int source, boolean[] marked, int idCtr, int[] id) {
marked[source] = true;
id[source] = idCtr;
for (Integer adjVertex : dg.adj(source))
if (!marked[adjVertex]) sccDFS(dg, adjVertex, marked, idCtr, id);
}
public static Stack<Integer> topologicalSort(Digraph dg) {
// dg has to be a directed acyclic graph.
// We'll have to run dfs on the digraph and push the deepest nodes on stack first.
// We'll need a Stack<Integer> and a int[] marked.
Stack<Integer> topologicalStack = new Stack<Integer>();
boolean[] marked = new boolean[dg.V()];
// Calling dfs
for (int i = 0; i < dg.V(); i++)
if (!marked[i])
runDfs(dg, topologicalStack, marked, i);
return topologicalStack;
}
static void runDfs(Digraph dg, Stack<Integer> topologicalStack, boolean[] marked, int source) {
marked[source] = true;
for (Integer adjVertex : dg.adj(source))
if (!marked[adjVertex])
runDfs(dg, topologicalStack, marked, adjVertex);
topologicalStack.add(source);
}
}
static class FastReader {
private BufferedReader bfr;
private StringTokenizer st;
public FastReader() {
bfr = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
if (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(bfr.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
return next().toCharArray()[0];
}
String nextString() {
return next();
}
int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
double[] nextDoubleArray(int n) {
double[] arr = new double[n];
for (int i = 0; i < arr.length; i++)
arr[i] = nextDouble();
return arr;
}
long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nextLong();
return arr;
}
int[][] nextIntGrid(int n, int m) {
int[][] grid = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++)
grid[i][j] = fr.nextInt();
}
return grid;
}
}
static class LCA {
int[] height, first, segtree;
ArrayList<Integer> euler;
boolean[] visited;
int n;
LCA(UGraph ug, int root) {
n = ug.V();
height = new int[n];
first = new int[n];
euler = new ArrayList<>();
visited = new boolean[n];
dfs(ug, root, 0);
int m = euler.size();
segtree = new int[m * 4];
build(1, 0, m - 1);
}
void dfs(UGraph ug, int node, int h) {
visited[node] = true;
height[node] = h;
first[node] = euler.size();
euler.add(node);
for (int adj : ug.adj(node)) {
if (!visited[adj]) {
dfs(ug, adj, h + 1);
euler.add(node);
}
}
}
void build(int node, int b, int e) {
if (b == e) {
segtree[node] = euler.get(b);
} else {
int mid = (b + e) / 2;
build(node << 1, b, mid);
build(node << 1 | 1, mid + 1, e);
int l = segtree[node << 1], r = segtree[node << 1 | 1];
segtree[node] = (height[l] < height[r]) ? l : r;
}
}
int query(int node, int b, int e, int L, int R) {
if (b > R || e < L)
return -1;
if (b >= L && e <= R)
return segtree[node];
int mid = (b + e) >> 1;
int left = query(node << 1, b, mid, L, R);
int right = query(node << 1 | 1, mid + 1, e, L, R);
if (left == -1) return right;
if (right == -1) return left;
return height[left] < height[right] ? left : right;
}
int lca(int u, int v) {
int left = first[u], right = first[v];
if (left > right) {
int temp = left;
left = right;
right = temp;
}
return query(1, 0, euler.size() - 1, left, right);
}
}
static class FenwickTree {
long[] array; // 1-indexed array, In this array We save cumulative information to perform efficient range queries and updates
public FenwickTree(int size) {
array = new long[size + 1];
}
public long rsq(int ind) {
assert ind > 0;
long sum = 0;
while (ind > 0) {
sum += array[ind];
//Extracting the portion up to the first significant one of the binary representation of 'ind' and decrementing ind by that number
ind -= ind & (-ind);
}
return sum;
}
public long rsq(int a, int b) {
assert b >= a && a > 0 && b > 0;
return rsq(b) - rsq(a - 1);
}
public void update(int ind, long value) {
assert ind > 0;
while (ind < array.length) {
array[ind] += value;
//Extracting the portion up to the first significant one of the binary representation of 'ind' and incrementing ind by that number
ind += ind & (-ind);
}
}
public int size() {
return array.length - 1;
}
}
static class SegmentTree {
private Node[] heap;
private long[] array;
private int size;
public SegmentTree(long[] array) {
this.array = Arrays.copyOf(array, array.length);
//The max size of this array is about 2 * 2 ^ log2(n) + 1
size = (int) (2 * Math.pow(2.0, Math.floor((Math.log((double) array.length) / Math.log(2.0)) + 1)));
heap = new Node[size];
build(1, 0, array.length);
}
public int size() {
return array.length;
}
//Initialize the Nodes of the Segment tree
private void build(int v, int from, int size) {
heap[v] = new Node();
heap[v].from = from;
heap[v].to = from + size - 1;
if (size == 1) {
heap[v].sum = array[from];
heap[v].min = array[from];
heap[v].max = array[from];
} else {
//Build childs
build(2 * v, from, size / 2);
build(2 * v + 1, from + size / 2, size - size / 2);
heap[v].sum = heap[2 * v].sum + heap[2 * v + 1].sum;
//min = min of the children
heap[v].min = Math.min(heap[2 * v].min, heap[2 * v + 1].min);
heap[v].max = Math.max(heap[2 * v].max, heap[2 * v + 1].max);
}
}
public long rsq(int from, int to) {
return rsq(1, from, to);
}
private long rsq(int v, int from, int to) {
Node n = heap[v];
//If you did a range update that contained this node, you can infer the Sum without going down the tree
if (n.pendingVal != null && contains(n.from, n.to, from, to)) {
return (to - from + 1) * n.pendingVal;
}
if (contains(from, to, n.from, n.to)) {
return heap[v].sum;
}
if (intersects(from, to, n.from, n.to)) {
propagate(v);
long leftSum = rsq(2 * v, from, to);
long rightSum = rsq(2 * v + 1, from, to);
return leftSum + rightSum;
}
return 0;
}
public long rMinQ(int from, int to) {
return rMinQ(1, from, to);
}
private long rMinQ(int v, int from, int to) {
Node n = heap[v];
//If you did a range update that contained this node, you can infer the Min value without going down the tree
if (n.pendingVal != null && contains(n.from, n.to, from, to)) {
return n.pendingVal;
}
if (contains(from, to, n.from, n.to)) {
return heap[v].min;
}
if (intersects(from, to, n.from, n.to)) {
propagate(v);
long leftMin = rMinQ(2 * v, from, to);
long rightMin = rMinQ(2 * v + 1, from, to);
return Math.min(leftMin, rightMin);
}
return Integer.MAX_VALUE;
}
public long rMaxQ(int from, int to) {
return rMaxQ(1, from, to);
}
private long rMaxQ(int v, int from, int to) {
Node n = heap[v];
//If you did a range update that contained this node, you can infer the Min value without going down the tree
if (n.pendingVal != null && contains(n.from, n.to, from, to)) {
return n.pendingVal;
}
if (contains(from, to, n.from, n.to)) {
return heap[v].max;
}
if (intersects(from, to, n.from, n.to)) {
propagate(v);
long leftMax = rMaxQ(2 * v, from, to);
long rightMax = rMaxQ(2 * v + 1, from, to);
return Math.max(leftMax, rightMax);
}
return Integer.MIN_VALUE;
}
public void update(int from, int to, long value) {
update(1, from, to, value);
}
private void update(int v, int from, int to, long value) {
//The Node of the heap tree represents a range of the array with bounds: [n.from, n.to]
Node n = heap[v];
if (contains(from, to, n.from, n.to)) {
change(n, value);
}
if (n.size() == 1) return;
if (intersects(from, to, n.from, n.to)) {
propagate(v);
update(2 * v, from, to, value);
update(2 * v + 1, from, to, value);
n.sum = heap[2 * v].sum + heap[2 * v + 1].sum;
n.min = Math.min(heap[2 * v].min, heap[2 * v + 1].min);
n.max = Math.max(heap[2 * v].max, heap[2 * v + 1].max);
}
}
//Propagate temporal values to children
private void propagate(int v) {
Node n = heap[v];
if (n.pendingVal != null) {
change(heap[2 * v], n.pendingVal);
change(heap[2 * v + 1], n.pendingVal);
n.pendingVal = null; //unset the pending propagation value
}
}
//Save the temporal values that will be propagated lazily
private void change(Node n, long value) {
n.pendingVal = value;
n.sum = n.size() * value;
n.min = value;
n.max = value;
array[n.from] = value;
}
//Test if the range1 contains range2
private boolean contains(int from1, int to1, int from2, int to2) {
return from2 >= from1 && to2 <= to1;
}
//check inclusive intersection, test if range1[from1, to1] intersects range2[from2, to2]
private boolean intersects(int from1, int to1, int from2, int to2) {
return from1 <= from2 && to1 >= from2 // (.[..)..] or (.[...]..)
|| from1 >= from2 && from1 <= to2; // [.(..]..) or [..(..)..
}
//The Node class represents a partition range of the array.
static class Node {
long sum;
long min;
long max;
//Here we store the value that will be propagated lazily
Long pendingVal = null;
int from;
int to;
int size() {
return to - from + 1;
}
}
}
@SuppressWarnings("serial")
static class CountMap<T> extends TreeMap<T, Integer>{
CountMap() {
}
CountMap(T[] arr) {
this.putCM(arr);
}
public Integer putCM(T key) {
return super.put(key, super.getOrDefault(key, 0) + 1);
}
public Integer removeCM(T key) {
int count = super.getOrDefault(key, -1);
if (count == -1) return -1;
if (count == 1)
return super.remove(key);
else
return super.put(key, count - 1);
}
public Integer getCM(T key) {
return super.getOrDefault(key, 0);
}
public void putCM(T[] arr) {
for (T l : arr)
this.putCM(l);
}
}
static long dioGCD(long a, long b, long[] x0, long[] y0) {
if (b == 0) {
x0[0] = 1;
y0[0] = 0;
return a;
}
long[] x1 = new long[1], y1 = new long[1];
long d = dioGCD(b, a % b, x1, y1);
x0[0] = y1[0];
y0[0] = x1[0] - y1[0] * (a / b);
return d;
}
static boolean diophantine(long a, long b, long c, long[] x0, long[] y0, long[] g) {
g[0] = dioGCD(Math.abs(a), Math.abs(b), x0, y0);
if (c % g[0] > 0) {
return false;
}
x0[0] *= c / g[0];
y0[0] *= c / g[0];
if (a < 0) x0[0] = -x0[0];
if (b < 0) y0[0] = -y0[0];
return true;
}
static long[][] prod(long[][] mat1, long[][] mat2) {
int n = mat1.length;
long[][] prod = new long[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
// determining prod[i][j]
// it will be the dot product of mat1[i][] and mat2[][i]
for (int k = 0; k < n; k++)
prod[i][j] += mat1[i][k] * mat2[k][j];
return prod;
}
static long[][] matExpo(long[][] mat, long power) {
int n = mat.length;
long[][] ans = new long[n][n];
if (power == 0)
return null;
if (power == 1)
return mat;
long[][] half = matExpo(mat, power / 2);
ans = prod(half, half);
if (power % 2 == 1) {
ans = prod(ans, mat);
}
return ans;
}
static int KMPNumOcc(char[] text, char[] pat) {
int n = text.length;
int m = pat.length;
char[] patPlusText = new char[n + m + 1];
for (int i = 0; i < m; i++)
patPlusText[i] = pat[i];
patPlusText[m] = '^'; // Seperator
for (int i = 0; i < n; i++)
patPlusText[m + i] = text[i];
int[] fullPi = piCalcKMP(patPlusText);
int answer = 0;
for (int i = 0; i < n + m + 1; i++)
if (fullPi[i] == m)
answer++;
return answer;
}
static int[] piCalcKMP(char[] s) {
int n = s.length;
int[] pi = new int[n];
for (int i = 1; i < n; i++) {
int j = pi[i - 1];
while (j > 0 && s[i] != s[j])
j = pi[j - 1];
if (s[i] == s[j])
j++;
pi[i] = j;
}
return pi;
}
static long hash(long key) {
long h = Long.hashCode(key);
h ^= (h >>> 20) ^ (h >>> 12) ^ (h >>> 7) ^ (h >>> 4);
return h & (gigamod-1);
}
static int mapTo1D(int row, int col, int n, int m) {
// Maps elements in a 2D matrix serially to elements in
// a 1D array.
return row * m + col;
}
static int[] mapTo2D(int idx, int n, int m) {
// Inverse of what the one above does.
int[] rnc = new int[2];
rnc[0] = idx / m;
rnc[1] = idx % m;
return rnc;
}
static boolean[] primeGenerator(int upto) {
// Sieve of Eratosthenes:
isPrime = new boolean[upto + 1];
smallestFactorOf = new int[upto + 1];
Arrays.fill(smallestFactorOf, 1);
Arrays.fill(isPrime, true);
isPrime[1] = isPrime[0] = false;
for (long i = 2; i < upto + 1; i++)
if (isPrime[(int) i]) {
smallestFactorOf[(int) i] = (int) i;
// Mark all the multiples greater than or equal
// to the square of i to be false.
for (long j = i; j * i < upto + 1; j++) {
if (isPrime[(int) j * (int) i]) {
isPrime[(int) j * (int) i] = false;
smallestFactorOf[(int) j * (int) i] = (int) i;
}
}
}
return isPrime;
}
static HashMap<Integer, Integer> smolNumPrimeFactorization(int num) {
if (smallestFactorOf == null)
primeGenerator(num + 1);
HashMap<Integer, Integer> fnps = new HashMap<>();
while (num != 1) {
fnps.put(smallestFactorOf[num], fnps.getOrDefault(smallestFactorOf[num], 0) + 1);
num /= smallestFactorOf[num];
}
return fnps;
}
static HashMap<Long, Integer> primeFactorization(long num) {
// Returns map of factor and its power in the number.
HashMap<Long, Integer> map = new HashMap<>();
while (num % 2 == 0) {
num /= 2;
Integer pwrCnt = map.get(2L);
map.put(2L, pwrCnt != null ? pwrCnt + 1 : 1);
}
for (long i = 3; i * i <= num; i += 2) {
while (num % i == 0) {
num /= i;
Integer pwrCnt = map.get(i);
map.put(i, pwrCnt != null ? pwrCnt + 1 : 1);
}
}
// If the number is prime, we have to add it to the
// map.
if (num != 1)
map.put(num, 1);
return map;
}
static HashSet<Long> divisors(long num) {
HashSet<Long> divisors = new HashSet<Long>();
divisors.add(1L);
divisors.add(num);
for (long i = 2; i * i <= num; i++) {
if (num % i == 0) {
divisors.add(num/i);
divisors.add(i);
}
}
return divisors;
}
static void coprimeGenerator(int m, int n, ArrayList<Point> coprimes, int limit, int numCoprimes) {
if (m > limit) return;
if (m <= limit && n <= limit)
coprimes.add(new Point(m, n));
if (coprimes.size() > numCoprimes) return;
coprimeGenerator(2 * m - n, m, coprimes, limit, numCoprimes);
coprimeGenerator(2 * m + n, m, coprimes, limit, numCoprimes);
coprimeGenerator(m + 2 * n, n, coprimes, limit, numCoprimes);
}
static int bsearch(int[] arr, int val, int lo, int hi) {
// Returns the index of the first element
// larger than or equal to val.
int idx = -1;
while (lo <= hi) {
int mid = lo + (hi - lo)/2;
if (arr[mid] >= val) {
idx = mid;
hi = mid - 1;
} else
lo = mid + 1;
}
return idx;
}
static int bsearch(long[] arr, long val, int lo, int hi) {
// Returns the index of the first element
// larger than or equal to val.
int idx = -1;
while (lo <= hi) {
int mid = lo + (hi - lo)/2;
if (arr[mid] >= val) {
idx = mid;
hi = mid - 1;
} else
lo = mid + 1;
}
return idx;
}
static int bsearch(long[] arr, long val, int lo, int hi, boolean sMode) {
// Returns the index of the last element
// smaller than or equal to val.
int idx = -1;
while (lo <= hi) {
int mid = lo + (hi - lo)/2;
if (arr[mid] > val) {
hi = mid - 1;
} else {
idx = mid;
lo = mid + 1;
}
}
return idx;
}
static int bsearch(int[] arr, long val, int lo, int hi, boolean sMode) {
int idx = -1;
while (lo <= hi) {
int mid = lo + (hi - lo)/2;
if (arr[mid] > val) {
hi = mid - 1;
} else {
idx = mid;
lo = mid + 1;
}
}
return idx;
}
static long nCr(long n, long r, long[] fac) { long p = gigamod; if (r == 0) return 1; return (fac[(int)n] * modInverse(fac[(int)r], p) % p * modInverse(fac[(int)n - (int)r], p) % p) % p; }
static long modInverse(long n, long p) { return power(n, p - 2, p); }
static long modDiv(long a, long b){return mod(a * power(b, gigamod - 2, gigamod));}
static long power(long x, long y, long p) { long res = 1; x = x % p; while (y > 0) { if ((y & 1)==1) res = (res * x) % p; y = y >> 1; x = (x * x) % p; } return res; }
static int logk(long n, long k) { return (int)(Math.log(n) / Math.log(k)); }
static long gcd(long a, long b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static int gcd(int a, int b) { if (b == 0) { return a; } else { return gcd(b, a % b); } } static long gcd(long[] arr) { int n = arr.length; long gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static int gcd(int[] arr) { int n = arr.length; int gcd = arr[0]; for (int i = 1; i < n; i++) { gcd = gcd(gcd, arr[i]); } return gcd; } static long lcm(long[] arr) { long lcm = arr[0]; int n = arr.length; for (int i = 1; i < n; i++) { lcm = (lcm * arr[i]) / gcd(lcm, arr[i]); } return lcm; } static long lcm(long a, long b) { return (a * b)/gcd(a, b); } static boolean less(int a, int b) { return a < b ? true : false; } static boolean isSorted(int[] a) { for (int i = 1; i < a.length; i++) { if (less(a[i], a[i - 1])) return false; } return true; } static boolean isSorted(long[] a) { for (int i = 1; i < a.length; i++) { if (a[i] < a[i - 1]) return false; } return true; } static void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(long[] a, int i, int j) { long temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(double[] a, int i, int j) { double temp = a[i]; a[i] = a[j]; a[j] = temp; } static void swap(char[] a, int i, int j) { char temp = a[i]; a[i] = a[j]; a[j] = temp; }
static void sort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void sort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); } static void reverseSort(int[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(char[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverse(char[] arr) { int n = arr.length; for (int i = 0; i < n / 2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(long[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); } static void reverseSort(double[] arr) { shuffleArray(arr, 0, arr.length - 1); Arrays.sort(arr); int n = arr.length; for (int i = 0; i < n/2; i++) swap(arr, i, n - 1 - i); }
static void shuffleArray(long[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { long tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } } static void shuffleArray(int[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { int tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } }
static void shuffleArray(double[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { double tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } }
static void shuffleArray(char[] arr, int startPos, int endPos) { Random rnd = new Random(); for (int i = startPos; i < endPos; ++i) { char tmp = arr[i]; int randomPos = i + rnd.nextInt(endPos - i); arr[i] = arr[randomPos]; arr[randomPos] = tmp; } }
static boolean isPrime(long n) {if (n<=1)return false;if(n<=3)return true;if(n%2==0||n%3==0)return false;for(long i=5;i*i<=n;i=i+6)if(n%i==0||n%(i+2)==0)return false;return true;}
static String toString(int[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();}
static String toString(boolean[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();}
static String toString(long[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+" ");return sb.toString();}
static String toString(char[] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++)sb.append(dp[i]+"");return sb.toString();}
static String toString(int[][] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++){for(int j=0;j<dp[i].length;j++){sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();}
static String toString(long[][] dp){StringBuilder sb=new StringBuilder();for(int i=0;i<dp.length;i++){for(int j=0;j<dp[i].length;j++) {sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();}
static String toString(double[][] dp){StringBuilder sb=new StringBuilder();for(int i = 0;i<dp.length;i++){for(int j = 0;j<dp[i].length;j++){sb.append(dp[i][j]+" ");}sb.append('\n');}return sb.toString();}
static String toString(char[][] dp){StringBuilder sb = new StringBuilder();for(int i = 0;i<dp.length;i++){for(int j = 0;j<dp[i].length;j++){sb.append(dp[i][j]+"");}sb.append('\n');}return sb.toString();}
static long mod(long a, long m){return(a%m+1000000L*m)%m;}
static long mod(long num){return(num%gigamod+gigamod)%gigamod;}
}
// NOTES:
// ASCII VALUE OF 'A': 65
// ASCII VALUE OF 'a': 97
// Range of long: 9 * 10^18
// ASCII VALUE OF '0': 48
// Primes upto 'n' can be given by (n / (logn)). | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 105b13f53994d44a3833cc58fdf3e42a | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Ishu
{
static Scanner scan = new Scanner(System.in);
static BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
static void tc() throws Exception
{
int n = scan.nextInt();
int k = scan.nextInt();
int i;
output.write("and 1 2\n");
output.flush();
int fir_and = scan.nextInt();
output.write("and 2 3\n");
output.flush();
int sec_and = scan.nextInt();
output.write("and 1 3\n");
output.flush();
int third_and = scan.nextInt();
output.write("or 1 2\n");
output.flush();
int fir_or = scan.nextInt();
output.write("or 2 3\n");
output.flush();
int sec_or = scan.nextInt();
output.write("or 1 3\n");
output.flush();
int third_or = scan.nextInt();
int a_zero = 0;
int a_one = 0;
int a_two = 0;
int bit = 0;
while(bit <= 30)
{
int pow = (1 << bit);
++bit;
if((fir_and & pow) > 0)
{
a_zero += pow;
a_one += pow;
if((sec_and & pow) > 0)
a_two += pow;
}
else
{
if((fir_or & pow) == 0 && (sec_or & pow) == 0 && (third_or & pow) == 0);
else if((sec_and & pow) > 0)
{
a_one += pow;
a_two += pow;
}
else if((third_and & pow) > 0)
{
a_zero += pow;
a_two += pow;
}
else if((sec_or & pow) == 0)
a_zero += pow;
else if((fir_or & pow) == 0)
a_two += pow;
else
a_one += pow;
}
}
int[] a = new int[n];
a[0] = a_zero;
a[1] = a_one;
a[2] = a_two;
for(i=4;i<=n;++i)
{
output.write("or 1 " + i + "\n");
output.flush();
int cor = scan.nextInt();
output.write("and 1 " + i + "\n");
output.flush();
int cand = scan.nextInt();
int ce = 0;
bit = 0;
while(bit <= 30)
{
int pow = 1 << bit;
++bit;
if((cor & pow) == 0);
else if((cand & pow) > 0)
ce += pow;
else
{
if((a_zero & pow) == 0)
ce += pow;
}
}
a[i - 1] = ce;
}
Arrays.sort(a, 0, n);
int ans = a[k - 1];
output.write("finish " + ans + "\n");
output.flush();
}
public static void main(String[] args) throws Exception
{
int t = 1;
//t = scan.nextInt();
while(t-- > 0)
tc();
}
}
/*
0 0 1 = 0 0 0 // done
0 0 0 = 0 0 0 // done
0 1 1 = 0 1 0 // done
0 1 0 = 0 0 0 // done
1 0 1 = 0 0 1 // done
1 0 0 = 0 0 0 // done
*/
| Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | b568214bae3a9a35cbbe1e8c183cd820 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Scanner;
import java.io.IOException;
import java.util.InputMismatchException;
import java.io.InputStreamReader;
import java.io.Writer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Nipuna Samarasekara
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
public void solve(int testNumber, FastScanner in, FastPrinter out) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
System.out.println("and 1 2");
int ab = sc.nextInt();
System.out.println("and 1 3");
int ac = sc.nextInt();
System.out.println("or 1 2");
int a1b = sc.nextInt();
System.out.println("or 1 3");
int a1c = sc.nextInt();
System.out.println("or 2 3");
int b1c = sc.nextInt();
int[] a = new int[n];
int x1 = (a1b | a1c) ^ b1c;
a[0] = (ab) | (ac) | x1;
a[1] = ab | (a1b ^ a[0]);
a[2] = ac | (a1c ^ a[0]);
for (int i = 3; i < n; i++) {
System.out.println("and 1 " + (i + 1));
int ax = sc.nextInt();
System.out.println("or 1 " + (i + 1));
int a1x = sc.nextInt();
a[i] = ax | (a1x ^ a[0]);
}
Arrays.sort(a);
System.out.println("finish " + a[k - 1]);
}
}
static class FastPrinter extends PrintWriter {
public FastPrinter(OutputStream out) {
super(out);
}
public FastPrinter(Writer out) {
super(out);
}
}
static class FastScanner extends BufferedReader {
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try {
int ret = super.read();
// if (isEOF && ret < 0) {
// throw new InputMismatchException();
// }
// isEOF = ret == -1;
return ret;
} catch (IOException e) {
throw new InputMismatchException();
}
}
public String readLine() {
try {
return super.readLine();
} catch (IOException e) {
return null;
}
}
}
}
| Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | cb91e4c455ea622a1d2a34038b30f42c | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | /*
* akshaygupta26
*/
import java.io.*;
import java.util.*;
public class D
{
static long mod =(long)(1e9+7);
static FastReader sc=new FastReader();
static ArrayList<Integer> li;
public static void main(String[] args)
{
StringBuilder ans=new StringBuilder();
int test=1;
while(test-->0)
{
int n=sc.nextInt(),k=sc.nextInt();
li=new ArrayList<>();
solve();
int a=li.get(0);
for(int i=4;i<=n;i++) {
System.out.println("and 1 "+i);
System.out.flush();
int and = sc.nextInt();
System.out.flush();
System.out.println("or 1 "+i);
int or =sc.nextInt();
int c=0;
for(int bit=0;bit<31;bit++) {
if(((and>>bit)&1) == 1) {
c|=(1<<bit);
}
else if(((or>>bit)&1) == 1){
if(((a>>bit)&1) == 0) {
c|=(1<<bit);
}
}
}
li.add(c);
}
// System.out.println(li);
Collections.sort(li);
System.out.println("finish "+li.get(k-1));
}
// System.out.print(ans);
}
static void solve() {
System.out.println("and 1 2");
System.out.flush();
int and = sc.nextInt();
System.out.println("or 1 2");
System.out.flush();
int or =sc.nextInt();
int a =0,b=0,c=0;int diff=0;
for(int bit=0;bit<31;bit++) {
if(((and>>bit)&1) == 1)
{
a|=(1<<bit);
b|=(1<<bit);
}
else if(((or>>bit)&1) == 1){
diff|=(1<<bit);
}
}
//1 0 0 0 1 1 0 0 1
System.out.println("or 1 3");System.out.flush();
int or13 =sc.nextInt();
System.out.println("or 2 3");System.out.flush();
int or23=sc.nextInt();
System.out.println("and 1 3");System.out.flush();
int and13=sc.nextInt();
for(int bit=0;bit<31;bit++) {
if(((diff>>bit)&1) == 1) {
// decide a has 1 or b has 1
//if or13 has 0 -> b has 1
if(((or13>>bit)&1) == 0) {
b|=(1<<bit);
}
//if or23 has 0 -> a has 1
else if(((or23>>bit)&1) == 0) {
a|=(1<<bit);
}
//if and13 has 0 -> b has 1
else if(((and13>>bit)&1) == 0) {
b|=(1<<bit);
}
//if and13 has 1 -> a has 1
else {
a|=(1<<bit);
}
}
}
for(int bit=0;bit<31;bit++) {
if(((and13>>bit)&1) == 1) {
c|=(1<<bit);
}
else if(((or13>>bit)&1) == 1){
if(((a>>bit)&1) == 0) {
c|=(1<<bit);
}
}
}
li.add(a);
li.add(b);
li.add(c);
return;
}
static long ceil(double a,double b) {
return (long)Math.ceil(a/b);
}
static long add(long a,long b) {
return (a+b)%mod;
}
static long mult(long a,long b) {
return (a*b)%mod;
}
static long _gcd(long a,long b) {
if(b == 0) return a;
return _gcd(b,a%b);
}
static final Random random=new Random();
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static void ruffleSort(long[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n);
long temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
| Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 95bbe1cd9da58463c9cffe40a070ee42 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static Scanner scn = new Scanner(System.in);
static int query(String op, int i, int j){
System.out.println(op+" "+i+" "+j);
System.out.flush();
return scn.nextInt();
}
public static void main(String[] args) throws IOException {
int n = scn.nextInt();
int k = scn.nextInt();
int ar[] = new int[n+1];
int ab = query("or", 1, 2) + query("and", 1, 2);
int bc = query("or", 3, 2) + query("and", 3, 2);
int ac = query("or", 1, 3) + query("and", 1, 3);
int b = (ab+bc-ac)/2;
ar[2] = b;
ar[1] = ab-b;
ar[3] = bc-b;
for(int i=4;i<=n;i++){
ar[i] = query("or", i, 2) + query("and", i, 2) - b;
}
Arrays.sort(ar);
System.out.println("finish "+ar[k]);
System.out.flush();
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 1a3e78d4adafd7077e5ad6fb2e93ddae | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main{
static int ask(int i,int j,boolean or) throws IOException {
if(or) {
pw.printf("or %d %d\n", i, j);
pw.flush();
return sc.nextInt();
}
pw.printf("and %d %d\n", i, j);
pw.flush();
return sc.nextInt();
}
static void print(int ans) {
pw.printf("finish %d\n", ans);
pw.flush();
}
static void main() throws Exception{
int n=sc.nextInt(),k=sc.nextInt();
int and01=ask(1, 2, false);
int or01=ask(1, 2, true);
int and02=ask(1, 3, false);
int or02=ask(1, 3, true);
int and12=ask(3, 2, false);
int or12=ask(3, 2, true);
int[]ans=new int[n];
for(int bit=0;bit<30;bit++) {
int and=((and01>>bit)&1);
int or=((or01>>bit)&1);
if(and==or) {
ans[0]|=(and<<bit);
ans[1]|=(and<<bit);
continue;
}
int and02b=(and02>>bit)&1;
int or02b=(or02>>bit)&1;
int and12b=(and12>>bit)&1;
int or12b=(or12>>bit)&1;
if(and02b+or02b+and12b+or12b==3) {
//bit in third number is 1
ans[0]|=(and02b<<(bit));
ans[1]|=(and12b<<(bit));
}
else {
//bit is 0
ans[0]|=(or02b<<(bit));
ans[1]|=(or12b<<(bit));
}
}
for(int i=2;i<n;i++) {
int and=(i==2?and02:ask(1, i+1, false));
int or=(i==2?or02:ask(1, i+1, true));
for(int bit=0;bit<30;bit++) {
int bit0=(ans[0]>>bit)&1;
if(bit0==1) {
ans[i]|=(((and>>bit)&1)<<(bit));
}
else {
ans[i]|=(((or>>bit)&1)<<(bit));
}
}
}
shuffle(ans);
Arrays.sort(ans);
print(ans[k-1]);
}
public static void main(String[] args) throws Exception{
sc=new MScanner(System.in);
pw = new PrintWriter(System.out);
int tc=1;
// tc=sc.nextInt();
for(int i=1;i<=tc;i++) {
// pw.printf("Case %d:\n", i);
main();
}
pw.flush();
}
static PrintWriter pw;
static MScanner sc;
static class MScanner {
StringTokenizer st;
BufferedReader br;
public MScanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public MScanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int[] intArr(int n) throws IOException {
int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public long[] longArr(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public int[] intSortedArr(int n) throws IOException {
int[]in=new int[n];for(int i=0;i<n;i++)in[i]=nextInt();
shuffle(in);
Arrays.sort(in);
return in;
}
public long[] longSortedArr(int n) throws IOException {
long[]in=new long[n];for(int i=0;i<n;i++)in[i]=nextLong();
shuffle(in);
Arrays.sort(in);
return in;
}
public Integer[] IntegerArr(int n) throws IOException {
Integer[]in=new Integer[n];for(int i=0;i<n;i++)in[i]=nextInt();
return in;
}
public Long[] LongArr(int n) throws IOException {
Long[]in=new Long[n];for(int i=0;i<n;i++)in[i]=nextLong();
return in;
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
static void shuffle(int[]in) {
for(int i=0;i<in.length;i++) {
int idx=(int)(Math.random()*in.length);
int tmp=in[i];
in[i]=in[idx];
in[idx]=tmp;
}
}
static void shuffle(long[]in) {
for(int i=0;i<in.length;i++) {
int idx=(int)(Math.random()*in.length);
long tmp=in[i];
in[i]=in[idx];
in[idx]=tmp;
}
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | bea66e1a3b69d642b8e2e5824105235f | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
public class Practice {
public static long mod = (long) Math.pow(10, 9) + 7;
// public static long mod2 = 998244353;
// public static int tt = 1;
public static ArrayList<Long> one;
public static ArrayList<Long> two;
// public static long[] fac = new long[200005];
// public static long[] invfac = new long[200005];
public static void main(String[] args) throws Exception {
PrintWriter pw = new PrintWriter(System.out);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// int t = Integer.parseInt(br.readLine());
// int p = 1;
// while (t-- > 0) {
String[] s2 = br.readLine().split(" ");
int n = Integer.valueOf(s2[0]);
int k = Integer.valueOf(s2[1]);
long[] arr = new long[n];
System.out.println("and 1 2");
System.out.flush();
long and12 = Long.valueOf(br.readLine());
System.out.println("and 2 3");
System.out.flush();
long and23 = Long.valueOf(br.readLine());
System.out.println("and 1 3");
System.out.flush();
long and13 = Long.valueOf(br.readLine());
System.out.println("or 1 2");
System.out.flush();
long or12 = Long.valueOf(br.readLine());
System.out.println("or 2 3");
System.out.flush();
long or23 = Long.valueOf(br.readLine());
System.out.println("or 1 3");
System.out.flush();
long or13 = Long.valueOf(br.readLine());
for (int i = 0; i <= 31; i++) {
if (((and13 >> i) & 1) == 1 || ((and12 >> i) & 1) == 1
|| (((and23 >> i) & 1) == 0 && ((or12 >> i) & 1) == 1 && ((or13 >> i) & 1) == 1)) {
arr[0] = arr[0] | (1l << i);
}
if (((and23 >> i) & 1) == 1 || ((and12 >> i) & 1) == 1
|| (((and13 >> i) & 1) == 0) && ((or23 >> i) & 1) == 1 && ((or12 >> i) & 1) == 1) {
arr[1] = arr[1] | (1l << i);
}
if (((and13 >> i) & 1) == 1 || ((and23 >> i) & 1) == 1
|| (((and12 >> i) & 1) == 0) && ((or23 >> i) & 1) == 1 && ((or13 >> i) & 1) == 1) {
arr[2] = arr[2] | (1l << i);
}
// System.out.println(arr[0]);
}
for (int i = 3; i < n; i++) {
System.out.println("and " + (i) + " " + (i + 1));
System.out.flush();
long and = Long.valueOf(br.readLine());
System.out.println("or " + (i) + " " + (i + 1));
System.out.flush();
long or = Long.valueOf(br.readLine());
for (int j = 0; j <= 31; j++) {
if (((and >> j) & 1) == 1 || (((or >> j) & 1) == 1 && ((arr[i - 1] >> j) & 1) == 0)) {
arr[i] = arr[i] | (1 << j);
}
}
}
// System.out.println();
Arrays.sort(arr);
System.out.println("finish " + arr[k - 1]);
System.out.flush();
// }
pw.close();
}
//
// private static long power(long a, long p) {
// // TODO Auto-generated method stub
// long res = 1;
// while (p > 0) {
// if (p % 2 == 1) {
// res = (res * a) % mod;
// }
// p = p / 2;
// a = (a * a) % mod;
// }
// return res;
// }
// private static int kmp(String str) {
// // TODO Auto-generated method stub
// // System.out.println(str);
// int[] pi = new int[str.length()];
// pi[0] = 0;
// for (int i = 1; i < str.length(); i++) {
// int j = pi[i - 1];
// while (j > 0 && str.charAt(i) != str.charAt(j)) {
// j = pi[j - 1];
// }
// if (str.charAt(j) == str.charAt(i)) {
// j++;
// }
// pi[i] = j;
// System.out.print(pi[i]);
// }
// System.out.println();
// return pi[str.length() - 1];
// }
}
// private static void getFac(long n, PrintWriter pw) {
// // TODO Auto-generated method stub
// int a = 0;
// while (n % 2 == 0) {
// a++;
// n = n / 2;
// }
// if (n == 1) {
// a--;
// }
// for (int i = 3; i <= Math.sqrt(n); i += 2) {
// while (n % i == 0) {
// n = n / i;
// a++;
// }
// }
// if (n > 1) {
// a++;
// }
// if (a % 2 == 0) {
// pw.println("Bob");
// } else {
// pw.println("Alice");
// }
// //System.out.println(a);
// return;
// }
// private static long power(long a, long p) {
// // TODO Auto-generated method stub
// long res = 1;
// while (p > 0) {
// if (p % 2 == 1) {
// res = (res * a) % mod;
// }
// p = p / 2;
// a = (a * a) % mod;
// }
// return res;
// }
//
// private static void fac() {
// fac[0] = 1;
// // TODO Auto-generated method stub
// for (int i = 1; i < fac.length; i++) {
// if (i == 1) {
// fac[i] = 1;
// } else {
// fac[i] = i * fac[i - 1];
// }
// if (fac[i] > mod) {
// fac[i] = fac[i] % mod;
// }
// }
// }
//
// private static int getLower(Long long1, Long[] st) {
// // TODO Auto-generated method stub
// int left = 0, right = st.length - 1;
// int ans = -1;
// while (left <= right) {
// int mid = (left + right) / 2;
// if (st[mid] <= long1) {
// ans = mid;
// left = mid + 1;
// } else {
// right = mid - 1;
// }
// }
// return ans;
// }
//private static long getGCD(long l, long m) {
//
// long t1 = Math.min(l, m);
// long t2 = Math.max(l, m);
// if (t1 == 0) {
// return t2;
// }
// while (true) {
// long temp = t2 % t1;
// if (temp == 0) {
// return t1;
// }
// t2 = t1;
// t1 = temp;
// }
//} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 7706efeab257bb96b6331f74b08f7f83 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class D {
public static void main(String[] args) {
FastReader f = new FastReader();
StringBuffer sb=new StringBuffer();
int n=f.nextInt(),k=f.nextInt();
List<Integer> list=new ArrayList<>();
// get sum of 1,2
System.out.println("and 1 2");
int sum12=f.nextInt();
System.out.println("or 1 2");
sum12+=f.nextInt();
System.out.println("and 2 3");
int sum23=f.nextInt();
System.out.println("or 2 3");
sum23+=f.nextInt();
System.out.println("and 1 3");
int sum13=f.nextInt();
System.out.println("or 1 3");
sum13+=f.nextInt();
int a1=Math.abs(sum12-sum23+sum13)/2;
list.add(a1);
int a3=sum13-a1;
list.add(a3);
int prev=0;
if(sum12>sum23)
{
int max=Math.max(a1,a3);
int a2=sum12-max;
list.add(a2);
prev=sum23-a2;
}
else
{
int max=Math.max(a1,a3);
int a2=sum23-max;
list.add(a2);
prev=sum23-a2;
}
int i=3;
while(i<n)
{
System.out.println("and "+i+" "+(i+1));
int and=f.nextInt();
System.out.println("or "+i+" "+(i+1));
int or=f.nextInt();
int sum=and+or;
int curr=sum-prev;
list.add(curr);
prev=curr;
i++;
}
Collections.sort(list);
System.out.println("finish "+list.get(k-1));
}
static int calc(int a)
{
int count=0;
while(a>0)
{
if(a%2==1)
count++;
a/=2;
}
return count;
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try{
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try{
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | c1e5e137b2ddc6e0fdd89d78fca69551 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class CC {
//--------------------------INPUT READER--------------------------------//
static class fs {
public BufferedReader br;
StringTokenizer st = new StringTokenizer("");
public fs() { this(System.in); }
public fs(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
String next() {
while (!st.hasMoreTokens()) {
try { st = new StringTokenizer(br.readLine()); }
catch (IOException e) { e.printStackTrace(); }
}
return st.nextToken();
}
int ni() { return Integer.parseInt(next()); }
long nl() { return Long.parseLong(next()); }
double nd() { return Double.parseDouble(next()); }
String ns() { return next(); }
int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = ni();
return a;
}
}
//-----------------------------------------------------------------------//
//---------------------------PRINTER-------------------------------------//
static class Printer {
static PrintWriter w;
public Printer() {this(System.out);}
public Printer(OutputStream os) {
w = new PrintWriter(os, true);
}
public void p(int i) {w.println(i);};
public void p(long l) {w.println(l);};
public void p(double d) {w.println(d);};
public void p(String s) { w.println(s);};
public void pr(int i) {w.println(i);};
public void pr(long l) {w.print(l);};
public void pr(double d) {w.print(d);};
public void pr(String s) { w.print(s);};
public void pl() {w.println();};
public void close() {w.close();};
}
//------------------------------------------------------------------------//
//--------------------------VARIABLES------------------------------------//
static fs sc = new fs();
static OutputStream outputStream = System.out;
static Printer w = new Printer(outputStream);
//-----------------------------------------------------------------------//
//--------------------------ADMIN_MODE-----------------------------------//
private static void ADMIN_MODE() throws IOException {
if (System.getProperty("ONLINE_JUDGE") == null) {
w = new Printer(new FileOutputStream("output.txt"));
sc = new fs(new FileInputStream("input.txt"));
}
}
//-----------------------------------------------------------------------//
//----------------------------START--------------------------------------//
public static void main(String[] args)
throws IOException {
// ADMIN_MODE();
// int t = sc.ni();
// while(t-->0)
solve();
w.close();
}
static void solve() throws IOException {
int n = sc.ni();
Long[] arr = new Long[n+1];
arr[0] = Long.MIN_VALUE;
int k = sc.ni();
query(true, 1, 2);
long one = sc.nl();
query(false, 1, 2);
one += sc.nl();
query(true, 2, 3);
long two = sc.nl();
query(false, 2, 3);
two += sc.nl();
query(true, 1, 3);
long three = sc.nl();
query(false, 1, 3);
three += sc.nl();
arr[2] = (two + (one - three))/2;
arr[1] = one-arr[2];
arr[3] = two-arr[2];
// w.p(Arrays.toString(arr));
for(int i = 3; i < n; i++) {
query(true, i, i+1);
long curr = sc.nl();
query(false, i, i+1);
curr += sc.nl();
arr[i+1] = curr-arr[i];
}
Arrays.sort(arr);
// w.p(Arrays.toString(arr));
w.p("finish "+arr[k]);
}
static void query(boolean f, int i, int j) {
if(f) {
w.p("and "+i+" "+j);
} else {
w.p("or "+i+" "+j);
}
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 42febb79fc9c9a1316f2a095bb3517a2 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Sol {
final static int LINE_SIZE = 128;
FastReader in = new FastReader();
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out), false);
void solve() throws Exception {
int n = in.nextInt();
int k = in.nextInt();
int[][] pairs = {{1, 2}, {1, 3}, {2, 3}};
List<Integer> sums = new ArrayList<>();
for (int[] pair : pairs) {
System.out.println("or " + pair[0] + " " + pair[1]);
int or = in.nextInt();
System.out.println("and " + pair[0] + " " + pair[1]);
int and = in.nextInt();
sums.add(or + and);
}
int fi = (sums.get(0) + sums.get(1) - sums.get(2)) / 2;
int se = sums.get(0) - fi;
int ti = sums.get(1) - fi;
List<Integer> ar = new ArrayList<>(Arrays.asList(fi, se, ti));
for (int i = 4; i <= n; i++) {
System.out.println("or 1 " + i);
int or = in.nextInt();
System.out.println("and 1 " + i);
int and = in.nextInt();
ar.add(or + and - fi);
}
Collections.sort(ar);
System.out.println("finish " + ar.get(k - 1));
}
void runCases() throws Exception {
int tt = 1;
//tt = in.nextInt();
while (tt-- > 0) {
solve();
}
in.close();
out.close();
}
public static void main(String[] args) throws Exception {
Sol solver = new Sol();
solver.runCases();
}
static class Pii implements Comparable<Pii> {
public int fi, se;
public Pii(int fi, int se) {
this.fi = fi;
this.se = se;
}
public int compareTo(Pii other) {
if (fi == other.fi) return se - other.se;
return fi - other.fi;
}
}
static class Pll implements Comparable<Pll> {
public long fi, se;
public Pll(long fi, long se) {
this.fi = fi;
this.se = se;
}
public int compareTo(Pll other) {
if (fi == other.fi) return se < other.se ? -1 : 1;
return fi < other.fi ? -1 : 1;
}
}
static class Pair<T extends Comparable<T>, U extends Comparable<U>> implements Comparable<Pair<T, U>> {
T fi;
U se;
public Pair(T fi, U se) {
this.fi = fi;
this.se = se;
}
public int compareTo(Pair<T, U> other) {
if (fi == other.fi) return se.compareTo(other.se);
return fi.compareTo(other.fi);
}
}
static class FastReader {
private final DataInputStream din = new DataInputStream(System.in);
private final byte[] buffer = new byte[65536];
private int bufferPointer = 0, bytesRead = 0;
public String readLine() throws IOException {
byte[] buf = new byte[LINE_SIZE];
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n') {
if (cnt != 0) break;
else continue;
}
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');
return neg ? -ret : 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');
return neg ? -ret : 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);
return neg ? -ret : ret;
}
public int[] intArray(int n) throws IOException {
int[] array = new int[n];
for (int i = 0; i < n; i++) array[i] = nextInt();
return array;
}
public long[] longArray(int n) throws IOException {
long[] array = new long[n];
for (int i = 0; i < n; i++) array[i] = nextLong();
return array;
}
public double[] doubleArray(int n) throws IOException {
double[] array = new double[n];
for (int i = 0; i < n; i++) array[i] = nextDouble();
return array;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, 65536);
if (bytesRead == -1) buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead) fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
din.close();
}
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String next() {
while (!st.hasMoreTokens())
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | bda04f528f96c4262c0bced9badba51c | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.util.*;
public class Deltix2021D {
public static Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws Exception {
int n = sc.nextInt();
int k = sc.nextInt();
int[] a = new int[n];
int[] b = getFirst();
System.arraycopy(b, 0, a, 0, 3);
for (int i = 3; i < n; i++) {
a[i] = getNext(a[0], i + 1);
}
Arrays.sort(a);
System.out.println("finish " + a[k - 1]);
}
public static int query(String query) {
System.out.println(query);
System.out.flush();
return sc.nextInt();
}
public static int[] getFirst() {
int o12 = query("or 1 2");
int o13 = query("or 1 3");
int o23 = query("or 2 3");
int a12 = query("and 1 2");
int a13 = query("and 1 3");
int a23 = query("and 2 3");
int x1 = 0;
int x2 = 0;
int x3 = 0;
for (int i = 0; i < 31; i++) {
int mask = 1 << i;
int mx1 = -1;
int mx2 = -1;
int mx3 = -1;
if ((a12 & mask) != 0) {
mx1 = mask;
mx2 = mask;
} else if ((o12 & mask) == 0) {
mx1 = 0;
mx2 = 0;
}
if ((a13 & mask) != 0) {
mx1 = mask;
mx3 = mask;
} else if ((o13 & mask) == 0) {
mx1 = 0;
mx3 = 0;
}
if ((a23 & mask) != 0) {
mx2 = mask;
mx3 = mask;
} else if ((o23 & mask) == 0) {
mx2 = 0;
mx3 = 0;
}
if (mx1 == -1) {
mx1 = mx2 == 0 ? mask : 0;
}
if (mx2 == -1) {
mx2 = mx3 == 0 ? mask : 0;
}
if (mx3 == -1) {
mx3 = mx1 == 0 ? mask : 0;
}
x1 += mx1;
x2 += mx2;
x3 += mx3;
}
return new int[]{x1, x2, x3};
}
public static int getNext(int x1, int id) {
int o = query("or 1 " + id);
int a = query("and 1 " + id);
int x2 = 0;
for (int i = 0; i < 31; i++) {
int mask = 1 << i;
if ((a & mask) != 0 || (x1 & mask) == 0 && (o & mask) != 0) {
x2 += mask;
}
}
return x2;
}
}
| Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | da1869627ea756de020510a682d4c257 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 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.InputMismatchException;
import java.io.IOException;
import java.util.Random;
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);
DPoprobuiUgadai solver = new DPoprobuiUgadai();
solver.solve(1, in, out);
out.close();
}
static class DPoprobuiUgadai {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int k = in.nextInt();
out.println("and 1 2");
out.flush();
long aba = in.nextInt();
out.println("or 1 2");
out.flush();
long abo = in.nextInt();
out.println("or 1 3");
out.flush();
long aco = in.nextInt();
out.println("and 2 3");
out.flush();
long bca = in.nextInt();
long p = 1;
long a = 0;
long b = 0;
for (int i = 0; i <= 40; i++) {
if (p >= Integer.MAX_VALUE) {
break;
}
if ((aba & p) > 0) {
a |= p;
b |= p;
} else if ((abo & p) != 0) {
if ((aco & p) != 0) {
if ((bca & p) == 0) {
a |= p;
} else {
b |= p;
}
} else {
b |= p;
}
}
p <<= 1;
}
long[] l = new long[n];
l[0] = a;
l[1] = b;
for (int h = 3; h <= n; h++) {
out.println("and 1 " + h);
out.flush();
long and = in.nextInt();
out.println("or 1 " + h);
out.flush();
long or = in.nextInt();
int cur = h - 1;
p = 1;
for (int i = 0; i <= 40; i++) {
if (p >= Integer.MAX_VALUE) {
break;
}
if ((and & p) > 0) {
l[cur] |= p;
} else if ((or & p) != 0) {
if ((l[0] & p) == 0) {
l[cur] |= p;
}
}
p <<= 1;
}
}
ArrayUtils.sort(l);
out.println("finish " + l[k - 1]);
out.flush();
}
}
static class InputReader {
private static final int BUFFER_LENGTH = 1 << 10;
private InputStream stream;
private byte[] buf = new byte[BUFFER_LENGTH];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int nextC() {
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 = skipWhileSpace();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = nextC();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = nextC();
} while (!isSpaceChar(c));
return res * sgn;
}
public int skipWhileSpace() {
int c = nextC();
while (isSpaceChar(c)) {
c = nextC();
}
return c;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
static class ArrayUtils {
static final long seed = System.nanoTime();
static final Random rand = new Random(seed);
public static void sort(long[] a) {
shuffle(a);
Arrays.sort(a);
}
public static void shuffle(long[] a) {
for (int i = 0; i < a.length; i++) {
int j = rand.nextInt(i + 1);
long t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
}
| Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | e9ef95fea14fa3db96ea4c5eb2aeb2f3 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class D {
public static void main(String[] args) throws IOException {
/**/
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
/*/
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(new FileInputStream("src/d.in"))));
/**/
int n = sc.nextInt();
int k = sc.nextInt();
int[] s0 = new int[n-1];
int s12 = 0;
for (int i = 0; i < n-1; ++i) {
System.out.println("or 1 "+(i+2));
System.out.flush();
s0[i] += sc.nextInt();
System.out.println("and 1 "+(i+2));
System.out.flush();
s0[i] += sc.nextInt();
}
System.out.println("or 2 3");
System.out.flush();
s12 += sc.nextInt();
System.out.println("and 2 3");
System.out.flush();
s12 += sc.nextInt();
int[] nums = new int[n];
nums[0] = (s0[0]-s12+s0[1])/2;
for (int i = 1; i < n; ++i) {
nums[i] = s0[i-1]-nums[0];
}
nums = Arrays.stream(nums).sorted().toArray();
System.out.println("finish "+nums[k-1]);
System.out.flush();
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 277c30c6c8743c3bb720693aa91d2d9b | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.math.BigInteger;
public final class A
{
static PrintWriter out = new PrintWriter(System.out);
static StringBuilder ans=new StringBuilder();
static FastReader in=new FastReader();
static ArrayList<Pair> g[];
static long mod=(long)998244353,INF=Long.MAX_VALUE;
static boolean set[],col[];
static int par[],tot[],partial[];
static int D[],P[][];
static int dp[][],sum=0,size[];
static int seg[];
static ArrayList<Long> A;
// static HashSet<Integer> set;
// static node1 seg[];
//static pair moves[]= {new pair(-1,0),new pair(1,0), new pair(0,-1), new pair(0,1)};
public static void main(String args[])throws IOException
{
int N=i();
int K=i()-1;
long A[]=new long[N];
long and1=and(1,2),and2=and(1,3),and3=and(2,3);
long or1=or(1,2),or2=or(1,3),or3=or(2,3);
long s1=and1+or1;
long s2=and2+or2;
long s3=and3+or3;
long a=(s1+s2-s3)/2;
long b=(s1+s3-s2)/2;
long c=(s2+s3-s1)/2;
A[0]=a;
A[1]=b;
A[2]=c;
for(int i=3; i<N; i++)
{
long and=and(1,i+1),or=or(1,i+1);
long s=and+or;
A[i]=s-a;
}
sort(A);
System.out.println("finish " +A[K]);
// out.close();
}
static long and(int i,int j)
{
System.out.println("and "+i+" "+j);
return l();
}
static long or(int i,int j)
{
System.out.println("or "+i+" "+j);
return l();
}
static int len=0,number=0;
static void f(char X[],int i,int num,int l)
{
if(i==X.length)
{
if(num==0)return;
//update our num
if(isPrime(num))return;
if(l<len)
{
len=l;
number=num;
}
return;
}
int a=X[i]-'0';
f(X,i+1,num*10+a,l+1);
f(X,i+1,num,l);
}
static boolean is_Sorted(int A[])
{
int N=A.length;
for(int i=1; i<=N; i++)if(A[i-1]!=i)return false;
return true;
}
static boolean f(StringBuilder sb,String Y,String order)
{
StringBuilder res=new StringBuilder(sb.toString());
HashSet<Character> set=new HashSet<>();
for(char ch:order.toCharArray())
{
set.add(ch);
for(int i=0; i<sb.length(); i++)
{
char x=sb.charAt(i);
if(set.contains(x))continue;
res.append(x);
}
}
String str=res.toString();
return str.equals(Y);
}
static boolean all_Zero(int f[])
{
for(int a:f)if(a!=0)return false;
return true;
}
static long form(int a,int l)
{
long x=0;
while(l-->0)
{
x*=10;
x+=a;
}
return x;
}
static int count(String X)
{
HashSet<Integer> set=new HashSet<>();
for(char x:X.toCharArray())set.add(x-'0');
return set.size();
}
static int f(long K)
{
long l=0,r=K;
while(r-l>1)
{
long m=(l+r)/2;
if(m*m<K)l=m;
else r=m;
}
return (int)l;
}
// static void build(int v,int tl,int tr,long A[])
// {
// if(tl==tr)
// {
// seg[v]=A[tl];
// }
// else
// {
// int tm=(tl+tr)/2;
// build(v*2,tl,tm,A);
// build(v*2+1,tm+1,tr,A);
// seg[v]=Math.min(seg[v*2], seg[v*2+1]);
// }
// }
static long ask(int v,int tl,int tr,int l,int r)
{
if(l>r)return (long)(1e10);
if(tl==l && tr==r)
{
return seg[v];
}
int tm=(tl+tr)/2;
return Math.min(ask(v*2,tl,tm,l,Math.min(tm, r)), ask(v*2+1,tm+1,tr,Math.max(l,tm+1),r));
}
static int [] sub(int A[],int B[])
{
int N=A.length;
int f[]=new int[N];
for(int i=N-1; i>=0; i--)
{
if(B[i]<A[i])
{
B[i]+=26;
B[i-1]-=1;
}
f[i]=B[i]-A[i];
}
for(int i=0; i<N; i++)
{
if(f[i]%2!=0)f[i+1]+=26;
f[i]/=2;
}
return f;
}
static int[] f(int N)
{
char X[]=in.next().toCharArray();
int A[]=new int[N];
for(int i=0; i<N; i++)A[i]=X[i]-'a';
return A;
}
static int max(int a ,int b,int c,int d)
{
a=Math.max(a, b);
c=Math.max(c,d);
return Math.max(a, c);
}
static int min(int a ,int b,int c,int d)
{
a=Math.min(a, b);
c=Math.min(c,d);
return Math.min(a, c);
}
static HashMap<Integer,Integer> Hash(int A[])
{
HashMap<Integer,Integer> mp=new HashMap<>();
for(int a:A)
{
int f=mp.getOrDefault(a,0)+1;
mp.put(a, f);
}
return mp;
}
static long mul(long a, long b)
{
return ( a %mod * 1L * b%mod )%mod;
}
static void swap(int A[],int a,int b)
{
int t=A[a];
A[a]=A[b];
A[b]=t;
}
static int find(int a)
{
if(par[a]<0)return a;
return par[a]=find(par[a]);
}
static void union(int a,int b)
{
a=find(a);
b=find(b);
if(a!=b)
{
par[a]+=par[b];
par[b]=a;
}
}
static boolean isSorted(int A[])
{
for(int i=1; i<A.length; i++)
{
if(A[i]<A[i-1])return false;
}
return true;
}
static boolean isDivisible(StringBuilder X,int i,long num)
{
long r=0;
for(; i<X.length(); i++)
{
r=r*10+(X.charAt(i)-'0');
r=r%num;
}
return r==0;
}
static int lower_Bound(int A[],int low,int high, int x)
{
if (low > high)
if (x >= A[high])
return A[high];
int mid = (low + high) / 2;
if (A[mid] == x)
return A[mid];
if (mid > 0 && A[mid - 1] <= x && x < A[mid])
return A[mid - 1];
if (x < A[mid])
return lower_Bound( A, low, mid - 1, x);
return lower_Bound(A, mid + 1, high, x);
}
static String f(String A)
{
String X="";
for(int i=A.length()-1; i>=0; i--)
{
int c=A.charAt(i)-'0';
X+=(c+1)%2;
}
return X;
}
static void sort(long[] a) //check for long
{
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static String swap(String X,int i,int j)
{
char ch[]=X.toCharArray();
char a=ch[i];
ch[i]=ch[j];
ch[j]=a;
return new String(ch);
}
static int sD(long n)
{
if (n % 2 == 0 )
return 2;
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0 )
return i;
}
return (int)n;
}
static void setGraph(int N)
{
tot=new int[N+1];
partial=new int[N+1];
D=new int[N+1];
P=new int[N+1][(int)(Math.log(N)+10)];
// set=new boolean[N+1];
g=new ArrayList[N+1];
for(int i=0; i<=N; i++)
{
g[i]=new ArrayList<>();
D[i]=Integer.MAX_VALUE;
//D2[i]=INF;
}
}
static long pow(long a,long b)
{
//long mod=1000000007;
long pow=1;
long x=a;
while(b!=0)
{
if((b&1)!=0)pow=(pow*x)%mod;
x=(x*x)%mod;
b/=2;
}
return pow;
}
static long toggleBits(long x)//one's complement || Toggle bits
{
int n=(int)(Math.floor(Math.log(x)/Math.log(2)))+1;
return ((1<<n)-1)^x;
}
static int countBits(long a)
{
return (int)(Math.log(a)/Math.log(2)+1);
}
static long fact(long N)
{
long n=2;
if(N<=1)return 1;
else
{
for(int i=3; i<=N; i++)n=(n*i)%mod;
}
return n;
}
static int kadane(int A[])
{
int lsum=A[0],gsum=A[0];
for(int i=1; i<A.length; i++)
{
lsum=Math.max(lsum+A[i],A[i]);
gsum=Math.max(gsum,lsum);
}
return gsum;
}
static void sort(int[] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static boolean isPrime(long N)
{
if (N<=1) return false;
if (N<=3) return true;
if (N%2 == 0 || N%3 == 0) return false;
for (int i=5; i*i<=N; i=i+6)
if (N%i == 0 || N%(i+2) == 0)
return false;
return true;
}
static void print(char A[])
{
for(char c:A)System.out.print(c+" ");
System.out.println();
}
static void print(boolean A[])
{
for(boolean c:A)System.out.print(c+" ");
System.out.println();
}
static void print(int A[])
{
for(int a:A)System.out.print(a+" ");
System.out.println();
}
static void print(long A[])
{
for(long i:A)System.out.print(i+ " ");
System.out.println();
}
static void print(boolean A[][])
{
for(boolean a[]:A)print(a);
}
static void print(long A[][])
{
for(long a[]:A)print(a);
}
static void print(int A[][])
{
for(int a[]:A)print(a);
}
static void print(ArrayList<Integer> A)
{
for(int a:A)System.out.print(a+" ");
System.out.println();
}
static int i()
{
return in.nextInt();
}
static long l()
{
return in.nextLong();
}
static int[] input(int N){
int A[]=new int[N];
for(int i=0; i<N; i++)
{
A[i]=in.nextInt();
}
return A;
}
static long[] inputLong(int N) {
long A[]=new long[N];
for(int i=0; i<A.length; i++)A[i]=in.nextLong();
return A;
}
static long GCD(long a,long b)
{
if(b==0)
{
return a;
}
else return GCD(b,a%b );
}
}
class Pair implements Comparable<Pair>
{
long min,size;
Pair(long min,long size)
{
this.min=min;
this.size=size;
}
public int compareTo(Pair x)
{
if(this.min==x.min)
{
return 0;
}
if(this.min>x.min)return 1;
else return -1;
}
}
//Code For FastReader
//Code For FastReader
//Code For FastReader
//Code For FastReader
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br=new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while(st==null || !st.hasMoreElements())
{
try
{
st=new StringTokenizer(br.readLine());
}
catch(IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str="";
try
{
str=br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 8 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 506e3e84e2541dba244f99df01daee3a | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes |
import java.util.*;
import java.io.*;
public class A {
public static void main(String[] args) throws IOException {
Soumit sc = new Soumit();
int n = sc.nextInt();
int k = sc.nextInt();
StringBuilder sb = new StringBuilder();
sb.append("and 1 2\n");
sb.append("or 1 2\n");
sb.append("and 3 2\n");
sb.append("or 3 2\n");
sb.append("and 1 3\n");
sb.append("or 1 3\n");
for(int i=4;i<=n;i++){
sb.append("and 1 ").append(i).append("\n");
sb.append("or 1 ").append(i).append("\n");
}
System.out.println(sb);
System.out.flush();
int[][] query = new int[n][2];
for(int i=0;i<n;i++){
query[i][0] = sc.nextInt();
query[i][1] = sc.nextInt();
}
int[] vals = new int[n];
int a_plus_b = query[0][0] + query[0][1];
int b_plus_c = query[1][0] + query[1][1];
int a_plus_c = query[2][0] + query[2][1];
int a_minus_c = a_plus_b - b_plus_c;
vals[0] = (a_minus_c + a_plus_c) / 2;
vals[1] = (a_plus_b - vals[0]);
vals[2] = (a_plus_c - vals[0]);
for(int i=3;i<n;i++){
vals[i] = (query[i][0] + query[i][1] - vals[0]);
}
sc.sort(vals);
System.out.println("finish "+vals[k-1]);
System.out.flush();
sc.close();
}
static class Soumit {
final private int BUFFER_SIZE = 1 << 18;
final private DataInputStream din;
final private byte[] buffer;
private PrintWriter pw;
private int bufferPointer, bytesRead;
StringTokenizer st;
public Soumit() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Soumit(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public void streamOutput(String file) throws IOException {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
pw = new PrintWriter(bw);
}
public void println(String a) {
pw.println(a);
}
public void print(String a) {
pw.print(a);
}
public String readLine() throws IOException {
byte[] buf = new byte[3000064]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public void sort(int[] arr) {
ArrayList<Integer> arlist = new ArrayList<>();
for (int i : arr)
arlist.add(i);
Collections.sort(arlist);
for (int i = 0; i < arr.length; i++)
arr[i] = arlist.get(i);
}
public void sort(long[] arr) {
ArrayList<Long> arlist = new ArrayList<>();
for (long i : arr)
arlist.add(i);
Collections.sort(arlist);
for (int i = 0; i < arr.length; i++)
arr[i] = arlist.get(i);
}
public int[] nextIntArray(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
public double[] nextDoubleArray(int n) throws IOException {
double[] arr = new double[n];
for (int i = 0; i < n; i++) {
arr[i] = nextDouble();
}
return arr;
}
public 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;*/
if (din != null) din.close();
if (pw != null) pw.close();
}
}
}
| Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 17 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 55b1e6d4113dc66d454201e0fe907339 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.util.*;
import java.util.function.*;
import java.io.*;
// you can compare with output.txt and expected out
public class RoundDeltix2021D {
MyPrintWriter out;
MyScanner in;
// final static long FIXED_RANDOM;
// static {
// FIXED_RANDOM = System.currentTimeMillis();
// }
final static String IMPOSSIBLE = "IMPOSSIBLE";
final static String POSSIBLE = "POSSIBLE";
final static String YES = "YES";
final static String NO = "NO";
private void initIO(boolean isFileIO) {
if (System.getProperty("ONLINE_JUDGE") == null && isFileIO) {
try{
in = new MyScanner(new FileInputStream("input.txt"));
out = new MyPrintWriter(new FileOutputStream("output.txt"));
}
catch(FileNotFoundException e){
e.printStackTrace();
}
}
else{
in = new MyScanner(System.in);
out = new MyPrintWriter(new BufferedOutputStream(System.out));
}
}
public static void main(String[] args){
// Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
// the code for the deep recursion (more than 100k or 3~400k or so)
// Thread t = new Thread(null, new RoundEdu130F(), "threadName", 1<<28);
// t.start();
// t.join();
RoundDeltix2021D sol = new RoundDeltix2021D();
sol.run();
}
private void run() {
boolean isDebug = false;
boolean isFileIO = false;
boolean hasMultipleTests = false;
initIO(isFileIO);
int t = hasMultipleTests? in.nextInt() : 1;
for (int i = 1; i <= t; ++i) {
if(isDebug){
out.printf("Test %d\n", i);
}
getInput();
solve();
}
in.close();
out.close();
}
// use suitable one between matrix(2, n), matrix(n, 2), transposedMatrix(2, n) for graph edges, pairs, ...
int n, k;
int[] ans;
void getInput() {
n = in.nextInt();
k = in.nextInt()-1;
// Random rand = new Random();
// ans = new int[n];
// final int MAX = 100; //1_000_000_000;
// for(int i=0; i<n; i++)
// ans[i] = rand.nextInt(MAX+1);
// out.printlnAns(ans);
}
int askOr(int i, int j) {
i++;
j++;
out.println("or " + i + " " + j);
out.flush();
return in.nextInt();
// return ans[i-1] | ans[j-1];
}
int askAnd(int i, int j) {
i++;
j++;
out.println("and " + i + " " + j);
out.flush();
return in.nextInt();
// return ans[i-1] & ans[j-1];
}
void answer(int res) {
out.println("finish " + res);
out.flush();
return;
}
void solve(){
// a[0] | a[1] = x
// a[0] & a[1] = y
// for each bit
// x = 0, y = 0 -> neither contains
// x = 1, y = 0 -> only one contains
// x = 1, y = 1 -> both contain
int[] a = new int[n];
final int BITS = 30;
int or01 = askOr(0, 1);
int or02 = askOr(0, 2);
int or12 = askOr(1, 2);
int and01 = askAnd(0, 1);
int and02 = askAnd(0, 2);
int and12 = askAnd(1, 2);
for(int pos=0; pos<BITS; pos++) {
if((or01 & (1<<pos)) == 0) {
a[2] |= or02 & (1<<pos);
}
else if((and01 & (1<<pos)) > 0) {
a[0] |= 1<<pos;
a[1] |= 1<<pos;
a[2] |= and02 & (1<<pos);
}
else {
if((or12 & (1<<pos)) == 0) {
a[0] |= 1<<pos;
}
else if((and12 & (1<<pos)) > 0) {
a[1] |= 1<<pos;
a[2] |= 1<<pos;
}
else {
// one of 0, 1
// one of 1, 2
if((or02 & (1<<pos)) > 0) {
a[0] |= 1<<pos;
a[2] |= 1<<pos;
}
else
a[1] |= 1<<pos;
}
}
}
for(int i=3; i<n; i++) {
int or = askOr(0, i);
int and = askAnd(0, i);
a[i] = (or ^ a[0]) | and;
}
permutateAndSort(a);
answer(a[k]);
}
// Optional<T> solve()
// return Optional.empty();
static class Pair implements Comparable<Pair>{
final static long FIXED_RANDOM = System.currentTimeMillis();
int first, second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
@Override
public int hashCode() {
// http://xorshift.di.unimi.it/splitmix64.c
long x = first;
x <<= 32;
x += second;
x += FIXED_RANDOM;
x += 0x9e3779b97f4a7c15l;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9l;
x = (x ^ (x >> 27)) * 0x94d049bb133111ebl;
return (int)(x ^ (x >> 31));
}
@Override
public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
Pair other = (Pair) obj;
return first == other.first && second == other.second;
}
@Override
public String toString() {
return "[" + first + "," + second + "]";
}
@Override
public int compareTo(Pair o) {
int cmp = Integer.compare(first, o.first);
return cmp != 0? cmp: Integer.compare(second, o.second);
}
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
// 32768?
public MyScanner(InputStream is, int bufferSize) {
br = new BufferedReader(new InputStreamReader(is), bufferSize);
}
public MyScanner(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
// br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt")));
}
public void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[][] nextMatrix(int n, int m) {
return nextMatrix(n, m, 0);
}
int[][] nextMatrix(int n, int m, int offset) {
int[][] mat = new int[n][m];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
mat[i][j] = nextInt()+offset;
}
}
return mat;
}
int[][] nextTransposedMatrix(int n, int m){
return nextTransposedMatrix(n, m, 0);
}
int[][] nextTransposedMatrix(int n, int m, int offset){
int[][] mat = new int[m][n];
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
mat[j][i] = nextInt()+offset;
}
}
return mat;
}
int[] nextIntArray(int len) {
return nextIntArray(len, 0);
}
int[] nextIntArray(int len, int offset){
int[] a = new int[len];
for(int j=0; j<len; j++)
a[j] = nextInt()+offset;
return a;
}
long[] nextLongArray(int len) {
return nextLongArray(len, 0);
}
long[] nextLongArray(int len, int offset){
long[] a = new long[len];
for(int j=0; j<len; j++)
a[j] = nextLong()+offset;
return a;
}
String[] nextStringArray(int len) {
String[] s = new String[len];
for(int i=0; i<len; i++)
s[i] = next();
return s;
}
}
public static class MyPrintWriter extends PrintWriter{
public MyPrintWriter(OutputStream os) {
super(os);
}
// public <T> void printlnAns(Optional<T> ans) {
// if(ans.isEmpty())
// println(-1);
// else
// printlnAns(ans.get());
// }
public void printlnAns(OptionalInt ans) {
println(ans.orElse(-1));
}
public void printlnAns(long ans) {
println(ans);
}
public void printlnAns(int ans) {
println(ans);
}
public void printlnAns(boolean[] ans) {
for(boolean b: ans)
printlnAns(b);
}
public void printlnAns(boolean ans) {
if(ans)
println(YES);
else
println(NO);
}
public void printAns(long[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(long[] arr){
printAns(arr);
println();
}
public void printAns(int[] arr){
if(arr != null && arr.length > 0){
print(arr[0]);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]);
}
}
}
public void printlnAns(int[] arr){
printAns(arr);
println();
}
public <T> void printAns(ArrayList<T> arr){
if(arr != null && arr.size() > 0){
print(arr.get(0));
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i));
}
}
}
public <T> void printlnAns(ArrayList<T> arr){
printAns(arr);
println();
}
public void printAns(int[] arr, int add){
if(arr != null && arr.length > 0){
print(arr[0]+add);
for(int i=1; i<arr.length; i++){
print(" ");
print(arr[i]+add);
}
}
}
public void printlnAns(int[] arr, int add){
printAns(arr, add);
println();
}
public void printAns(ArrayList<Integer> arr, int add) {
if(arr != null && arr.size() > 0){
print(arr.get(0)+add);
for(int i=1; i<arr.size(); i++){
print(" ");
print(arr.get(i)+add);
}
}
}
public void printlnAns(ArrayList<Integer> arr, int add){
printAns(arr, add);
println();
}
public void printlnAnsSplit(long[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public void printlnAnsSplit(int[] arr, int split){
if(arr != null){
for(int i=0; i<arr.length; i+=split){
print(arr[i]);
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr[j]);
}
println();
}
}
}
public <T> void printlnAnsSplit(ArrayList<T> arr, int split){
if(arr != null && !arr.isEmpty()){
for(int i=0; i<arr.size(); i+=split){
print(arr.get(i));
for(int j=i+1; j<i+split; j++){
print(" ");
print(arr.get(j));
}
println();
}
}
}
}
static private void permutateAndSort(long[] a) {
int n = a.length;
Random R = new Random(System.currentTimeMillis());
for(int i=0; i<n; i++) {
int t = R.nextInt(n-i);
long temp = a[n-1-i];
a[n-1-i] = a[t];
a[t] = temp;
}
Arrays.sort(a);
}
static private void permutateAndSort(int[] a) {
int n = a.length;
Random R = new Random(System.currentTimeMillis());
for(int i=0; i<n; i++) {
int t = R.nextInt(n-i);
int temp = a[n-1-i];
a[n-1-i] = a[t];
a[t] = temp;
}
Arrays.sort(a);
}
static private int[][] constructChildren(int n, int[] parent, int parentRoot){
int[][] childrens = new int[n][];
int[] numChildren = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
numChildren[parent[i]]++;
}
for(int i=0; i<n; i++) {
childrens[i] = new int[numChildren[i]];
}
int[] idx = new int[n];
for(int i=0; i<parent.length; i++) {
if(parent[i] != parentRoot)
childrens[parent[i]][idx[parent[i]]++] = i;
}
return childrens;
}
static private int[][][] constructDirectedNeighborhood(int n, int[][] e){
int[] inDegree = new int[n];
int[] outDegree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outDegree[u]++;
inDegree[v]++;
}
int[][] inNeighbors = new int[n][];
int[][] outNeighbors = new int[n][];
for(int i=0; i<n; i++) {
inNeighbors[i] = new int[inDegree[i]];
outNeighbors[i] = new int[outDegree[i]];
}
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
outNeighbors[u][--outDegree[u]] = v;
inNeighbors[v][--inDegree[v]] = u;
}
return new int[][][] {inNeighbors, outNeighbors};
}
static private int[][] constructNeighborhood(int n, int[][] e) {
int[] degree = new int[n];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
degree[u]++;
degree[v]++;
}
int[][] neighbors = new int[n][];
for(int i=0; i<n; i++)
neighbors[i] = new int[degree[i]];
for(int i=0; i<e.length; i++) {
int u = e[i][0];
int v = e[i][1];
neighbors[u][--degree[u]] = v;
neighbors[v][--degree[v]] = u;
}
return neighbors;
}
static private void drawGraph(int[][] e) {
makeDotUndirected(e);
try {
final Process process = new ProcessBuilder("dot", "-Tpng", "graph.dot")
.redirectOutput(new File("graph.png"))
.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
static private void makeDotUndirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict graph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "--" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
static private void makeDotDirected(int[][] e) {
MyPrintWriter out2 = null;
try {
out2 = new MyPrintWriter(new FileOutputStream("graph.dot"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
out2.println("strict digraph {");
for(int i=0; i<e.length; i++){
out2.println(e[i][0] + "->" + e[i][1] + ";");
}
out2.println("}");
out2.close();
}
}
| Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 17 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | cade429461313295385946f365707619 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 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.PrintStream;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
DTakeAGuess solver = new DTakeAGuess();
solver.solve(1, in, out);
out.close();
}
static class DTakeAGuess {
static int[][] num;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt(), k = in.nextInt();
num = new int[n][32];
for (int[] row : num) Arrays.fill(row, -1);
int or = 0;
int and = 0;
or(0, 1);
or = in.nextInt();
and(0, 1);
and = in.nextInt();
int s1 = or + and;
or(1, 2);
or = in.nextInt();
and(1, 2);
and = in.nextInt();
int s2 = or + and;
or(0, 2);
or = in.nextInt();
and(0, 2);
and = in.nextInt();
int s3 = or + and;
int a = (s1 - s2 + s3) / 2;
int c = s3 - a;
int b = s2 - c;
ArrayList<Integer> list = new ArrayList<>();
list.add(a);
list.add(b);
list.add(c);
for (int i = 3; i < n; i++) {
or(0, i);
or = in.nextInt();
and(0, i);
and = in.nextInt();
list.add(or + and - a);
}
Collections.sort(list);
out.println("finish " + list.get(k - 1));
}
static void or(int i, int j) {
System.out.println("or " + (i + 1) + " " + (j + 1));
}
static void and(int i, int j) {
System.out.println("and " + (i + 1) + " " + (j + 1));
}
}
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 {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 11 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | c4e6ff22a2197bd40a89f5e2a8c1f500 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
DTakeAGuess solver = new DTakeAGuess();
solver.solve(1, in, out);
out.close();
}
static class DTakeAGuess {
static int[][] num;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt(), k = in.nextInt();
num = new int[n][32];
for (int[] row : num) Arrays.fill(row, -1);
int or = 0;
int and = 0;
or(0, 1);
or = in.nextInt();
and(0, 1);
and = in.nextInt();
fill(or, and, 0, 1);
or(1, 2);
or = in.nextInt();
and(1, 2);
and = in.nextInt();
fill(or, and, 1, 2);
or(0, 2);
or = in.nextInt();
and(0, 2);
and = in.nextInt();
fill(or, and, 0, 2);
for (int i = 0; i < 32; i++) {
if (num[1][i] == -1) {
if (num[0][i] == 0)
num[1][i] = 1;
else
num[1][i] = 0;
}
}
for (int i = 3; i < n; i++) {
or(i, i - 1);
or = in.nextInt();
and(i, i - 1);
and = in.nextInt();
fill(or, and, i - 1, i);
}
ArrayList<Integer> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
String s = "";
for (int j = 0; j < 32; j++) {
s += num[i][j];
}
list.add(Integer.parseInt(s, 2));
}
Collections.sort(list);
System.out.println("finish" + " " + list.get(k - 1));
}
static void or(int i, int j) {
System.out.println("or " + (i + 1) + " " + (j + 1));
}
static void and(int i, int j) {
System.out.println("and " + (i + 1) + " " + (j + 1));
}
static void fill(int x, int y, int ind1, int ind2) {
String s = Integer.toBinaryString(x);
String t = Integer.toBinaryString(y);
int i = s.length();
while (i < 32) {
s = "0" + s;
i++;
}
i = t.length();
while (i < 32) {
t = "0" + t;
i++;
}
for (int j = 0; j < 32; j++) {
if ((s.charAt(j) == '0')) {
num[ind1][j] = 0;
num[ind2][j] = 0;
} else if (t.charAt(j) == '1') {
num[ind1][j] = 1;
num[ind2][j] = 1;
} else {
if (num[ind1][j] == 0) {
num[ind2][j] = 1;
} else if (num[ind2][j] == 0) {
num[ind1][j] = 1;
} else if (num[ind1][j] == 1) {
num[ind2][j] = 0;
} else if (num[ind2][j] == 1) {
num[ind1][j] = 0;
}
}
}
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
}
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 11 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 222a386ea50d0c7ae1b63525b8983def | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | //package codeforces;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class solution{
public static void main(String[] args) throws Exception{
FastScanner s=new FastScanner();
PrintWriter out=new PrintWriter(System.out);
int t=1;
for(int tt=0;tt<t;tt++) {
int n=s.nextInt(),k=s.nextInt();;
ArrayList<Long> a=new ArrayList<>();
long and1=0,and2=0,and3=0,or1=0,or2=0,or3=0;
System.out.println("or "+(1)+" "+2);
or1=s.nextInt();
System.out.flush();
System.out.println("or "+(2)+" "+3);
or2=s.nextInt();
System.out.flush();
System.out.println("or "+(3)+" "+1);
or3=s.nextInt();
System.out.flush();
System.out.println("and "+(1)+" "+2);
and1=s.nextInt();
System.out.flush();
System.out.println("and "+(2)+" "+3);
and2=s.nextInt();
System.out.flush();
System.out.println("and "+(3)+" "+1);
and3=s.nextInt();
System.out.flush();
long to=(and1+and2+and3+or1+or2+or3)/2;
long fsum=and1+or1;
long ssum=and2+or2;
long tsum=and3+or3;
a.add(to-ssum);
a.add(to-tsum);
a.add(to-fsum);
for(int i=4;i<=n;i++) {
System.out.println("or "+(1)+" "+i);
or1=s.nextInt();
System.out.flush();
System.out.println("and "+(1)+" "+i);
and1=s.nextInt();
System.out.flush();
a.add(or1+and1-a.get(0));
}
Collections.sort(a);
System.out.println("finish "+a.get(k-1));
}
out.close();
}
public static void printb(boolean ans) {
if(ans) {
System.out.println("Yes");
}else {
System.out.println("No");
}
}
static class DisjointSet {
int parent[],rank[];
public DisjointSet(int n) {
parent=new int[n];
rank=new int[n];
for(int i=0;i<n;i++) {
parent[i]=i;
rank[i]=0;
}
}
public int find(int i) {
if(parent[i]==i) {
return i;
}
return find(parent[i]);
}
public void union(int a, int b) {
int x=find(a);
int y=find(b);
if(x==y) {
return;
}
if(rank[x]<rank[y]) {
parent[x]=y;
}else if(rank[y]<rank[x]) {
parent[y]=x;
}else {
parent[y]=x;
rank[x]++;
}
}
}
static boolean isPrime(int n){
if (n <= 1)
return false;
else if (n == 2)
return true;
else if (n % 2 == 0)
return false;
for (int i = 3; i <= Math.sqrt(n); i += 2){
if (n % i == 0)
return false;
}
return true;
}
static void sort(long [] a) {
ArrayList<Long> l=new ArrayList<>();
for (long i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static void sort(int [] a) {
ArrayList<Integer> l=new ArrayList<>();
for (int i:a) l.add(i);
Collections.sort(l);
for (int i=0; i<a.length; i++) a[i]=l.get(i);
}
static int gcd(int a, int b){
if (b == 0)
return a;
return gcd(b, a % b);
}
static void sortcol(int a[][],int c) {
Arrays.sort(a, (x, y) -> {
if(x[c]>y[c]) {
return 1;
}else {
return -1;
}
});
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
double nextDouble() {
return Double.parseDouble(next());
}
int nextInt() {
return Integer.parseInt(next());
}
boolean nextBoolean() {
return Boolean.parseBoolean(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
long[] readLongArray(int n) {
long[] a=new long[n];
for (int i=0; i<n; i++) a[i]=nextLong();
return a;
}
}
}
class Pair implements Comparable<Pair>{
int a,b ;
Pair(int a,int b){
this.a=a;
this.b=b;
}
public int compareTo(Pair o) {
return b-o.b;
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 11 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 7936292d6c31ce1cd89b40c6a29686bb | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes |
import java.io.*;
import java.util.*;
public class D {
static long queryOr(int a,int b,PrintWriter pw,FastScanner sc) {
a++;
b++;
pw.println("or"+" "+a+" "+b);
pw.flush();
return sc.nextLong();
}
static long queryAnd(int a,int b,PrintWriter pw,FastScanner sc) {
a++;
b++;
pw.println("and"+" "+a+" "+b);
pw.flush();
return sc.nextLong();
}
public static void main(String[] args)
{
FastScanner sc=new FastScanner();
int t=1;
PrintWriter pw=new PrintWriter(System.out);
while(t-->0) {
int n=sc.nextInt();
int k=sc.nextInt();
ArrayList<Long> ors=new ArrayList<>();
ArrayList<Long> ands=new ArrayList<>();
for(int i=1;i<n;i++) {
ors.add(queryOr(0,i,pw,sc));
}
for(int i=1;i<n;i++) {
ands.add(queryAnd(0,i,pw,sc));
}
ArrayList<Long> ans=new ArrayList<>();
long a12=queryAnd(1,2,pw,sc)+queryOr(1,2,pw,sc);
long a01=ors.get(0)+ands.get(0);
long a02=ors.get(1)+ands.get(1);
long num=(a01+a02-a12)/2;
ans.add(num);
for(int i=0;i<n-1;i++) {
ans.add(ors.get(i)-num+ands.get(i));
}
Collections.sort(ans);
pw.println("finish"+" "+(ans.get(k-1)));
}
pw.flush();
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 11 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 5025f4de8c0ece50883575ab2819c920 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
static Scanner sc=new Scanner(System.in);
// static int a[];
static int ask1(int i,int j){
System.out.println("and"+" "+i+" "+j);
System.out.flush();
//return a[i-1]&a[j-1];
return sc.nextInt();
}
static int ask2(int i,int j){
System.out.println("or"+" "+i+" "+j);
System.out.flush();
// return a[i-1]|a[j-1];
return sc.nextInt();
}
static void print(int ans){
System.out.println("finish "+ans);
System.out.flush();
}
public static void main (String[] args) throws java.lang.Exception
{
// BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t=1;
// t=sc.nextInt();
// int t=Integer.parseInt(br.readLine());
while(--t>=0){
int n=sc.nextInt();
int k=sc.nextInt();
int a12=ask1(1,2);
int o12=ask2(1,2);
ArrayList<Integer> arr=new ArrayList<>();
int a13=ask1(1,3);
int a23=ask1(2,3);
int o13=ask2(1,3);
int o23=ask2(2,3);
long l=a12^o12;
int first=0,second=0,third=0;
for(long i=0;i<=30;i++){
if(((1<<i)&l)==0){
first=first|((1<<i)&a12);
}
else{
if((((1<<i)&o13)>0)&&(((1<<i)&o23)>0)){
first=first+((1<<i)&a13);
}
else if((((1<<i)&a13)==0)&&(((1<<i)&a23)==0)){
first=first+((1<<i)&o13);
}
}
}
arr.add(first);
arr.add((o12^a12)^first);
arr.add((o13^a13)^first);
for(int i=4;i<=n;i++){
int x1=ask1(1,i);
int x2=ask2(1,i);
int q=x1^x2;
arr.add(q^first);
}
Collections.sort(arr);
print(arr.get(k-1));
}
}
}
| Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 11 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | c5116d0ea57b4d0dfe7e6985951d7a7c | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.io.BufferedReader;
import java.util.StringTokenizer;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
public class D {
public static void main(String[] args) {
FastReader fr = new FastReader();
PrintWriter out = new PrintWriter(System.out, true);
int n = fr.nextInt();
int k = fr.nextInt();
int[] curand = new int[n];
int[] firstthree = new int[3];
for(int i = 0; i < 3; i++) {
if(i < 2) {
System.out.println("and " + (i + 1) + " " + (i + 2));
System.out.flush();
firstthree[i] = fr.nextInt();
System.out.println("or " + (i + 1) + " " + (i + 2));
System.out.flush();
firstthree[i] += fr.nextInt();
} else {
System.out.println("and " + (1) + " " + (3));
System.out.flush();
firstthree[i] = fr.nextInt();
System.out.println("or " + (1) + " " + (3));
System.out.flush();
firstthree[i] += fr.nextInt();
}
}
curand[1] = (firstthree[0] + firstthree[1] - firstthree[2])/2;
curand[2] = (firstthree[1] + firstthree[2] - firstthree[0])/2;
curand[0] = (firstthree[0] + firstthree[2] - firstthree[1])/2;
for(int i = 3; i < n; i++) {
int cur = 0;
System.out.println("and " + (i) + " " + (i+1));
System.out.flush();
cur += fr.nextInt();
System.out.println("or " + (i) + " " + (i+1));
System.out.flush();
cur += fr.nextInt();
curand[i] = (cur - curand[i-1]);
}
Arrays.sort(curand);
out.write("finish " + curand[k-1]+ "\n");
System.out.flush();
out.close();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
this.br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try{
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() { return Integer.parseInt(next()); }
long nextLong() { return Long.parseLong(next()); }
double nextDouble() { return Double.parseDouble(next()); }
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 11 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | e25e1228a9042afead3712c73088e144 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
var sc = new Scanner(System.in);
int n = Integer.parseInt(sc.next());
int k = Integer.parseInt(sc.next());
System.out.println("or 1 2");
System.out.flush();
int or12 = Integer.parseInt(sc.next());
System.out.println("or 2 3");
System.out.flush();
int or23 = Integer.parseInt(sc.next());
System.out.println("or 3 1");
System.out.flush();
int or31 = Integer.parseInt(sc.next());
System.out.println("and 1 2");
System.out.flush();
int and12 = Integer.parseInt(sc.next());
System.out.println("and 2 3");
System.out.flush();
int and23 = Integer.parseInt(sc.next());
System.out.println("and 3 1");
System.out.flush();
int and31 = Integer.parseInt(sc.next());
var a = new long[n];
long addAB = or12 + and12;
long addBC = or23 + and23;
long addCA = or31 + and31;
long addABC = (addAB + addBC + addCA) / 2;
a[0] = addABC - addBC;
a[1] = addABC - addCA;
a[2] = addABC - addAB;
for(int i = 4; i <= n; i++){
System.out.println("or 1 " + i);
System.out.flush();
int or = Integer.parseInt(sc.next());
System.out.println("and 1 " + i);
System.out.flush();
int and = Integer.parseInt(sc.next());
a[i-1] = (or + and) - a[0];
}
shuffle(a);
Arrays.sort(a);
System.out.println("finish " + a[k-1]);
}
static void shuffle(long[] a){
int n = a.length;
Random r = new Random();
for(int i = n-1; i >= 1; i--){
int j = r.nextInt(i+1);
long tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 11 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 686e615f8f7046c6ed9c5b3b5769b989 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static StringBuilder sb;
static dsu dsu;
static long fact[];
static int mod = (int) (1e9 + 7);
static void solve() {
int n = i();
int k = i();
int arr[] = new int[n+1];
int sum12 = query(1,2);
int sum23 = query(2,3);
int sum13 = query(1,3);
int diff13 = sum12-sum23;
arr[1] = (sum13+diff13)/2;
arr[2] = sum12-arr[1];
arr[3] = sum13-arr[1];
for(int i = 4;i<=n;i++){
arr[i] = query(i-1,i)-arr[i-1];
}
Arrays.sort(arr);
System.out.println("finish "+arr[k]);
System.out.flush();
}
private static int query(int i,int j){
int sum = 0;
System.out.println("or "+i+" "+j);
System.out.flush();
sum+=i();
System.out.println("and "+i+" "+j);
System.out.flush();
sum+=i();
return sum;
}
public static void main(String[] args) {
sb = new StringBuilder();
int test = 1;
while (test-- > 0) {
solve();
}
System.out.println(sb);
}
/*
* fact=new long[(int)1e6+10]; fact[0]=fact[1]=1; for(int i=2;i<fact.length;i++)
* { fact[i]=((long)(i%mod)1L(long)(fact[i-1]%mod))%mod; }
*/
//**************NCR%P******************
static long ncr(int n, int r) {
if (r > n)
return (long) 0;
long res = fact[n] % mod;
// System.out.println(res);
res = ((long) (res % mod) * (long) (p(fact[r], mod - 2) % mod)) % mod;
res = ((long) (res % mod) * (long) (p(fact[n - r], mod - 2) % mod)) % mod;
// System.out.println(res);
return res;
}
static long p(long x, long y)// POWER FXN //
{
if (y == 0)
return 1;
long res = 1;
while (y > 0) {
if (y % 2 == 1) {
res = (res * x) % mod;
y--;
}
x = (x * x) % mod;
y = y / 2;
}
return res;
}
//**************END******************
// *************Disjoint set
// union*********//
static class dsu {
int parent[];
dsu(int n) {
parent = new int[n];
for (int i = 0; i < n; i++)
parent[i] = -1;
}
int find(int a) {
if (parent[a] < 0)
return a;
else {
int x = find(parent[a]);
parent[a] = x;
return x;
}
}
void merge(int a, int b) {
a = find(a);
b = find(b);
if (a == b)
return;
parent[b] = a;
}
}
//**************PRIME FACTORIZE **********************************//
static TreeMap<Integer, Integer> prime(long n) {
TreeMap<Integer, Integer> h = new TreeMap<>();
long num = n;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (n % i == 0) {
int nt = 0;
while (n % i == 0) {
n = n / i;
nt++;
}
h.put(i, nt);
}
}
if (n != 1)
h.put((int) n, 1);
return h;
}
//****CLASS PAIR ************************************************
static class Pair implements Comparable<Pair> {
int x;
long y;
Pair(int x, long y) {
this.x = x;
this.y = y;
}
public int compareTo(Pair o) {
return (int) (this.y - o.y);
}
}
//****CLASS PAIR **************************************************
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 int Int() {
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 String() {
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 String();
}
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 printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
static InputReader in = new InputReader(System.in);
static OutputWriter out = new OutputWriter(System.out);
public static long[] sort(long[] a2) {
int n = a2.length;
ArrayList<Long> l = new ArrayList<>();
for (long i : a2)
l.add(i);
Collections.sort(l);
for (int i = 0; i < l.size(); i++)
a2[i] = l.get(i);
return a2;
}
public static char[] sort(char[] a2) {
int n = a2.length;
ArrayList<Character> l = new ArrayList<>();
for (char i : a2)
l.add(i);
Collections.sort(l);
for (int i = 0; i < l.size(); i++)
a2[i] = l.get(i);
return a2;
}
public static long pow(long x, long y) {
long res = 1;
while (y > 0) {
if (y % 2 != 0) {
res = (res * x);// % modulus;
y--;
}
x = (x * x);// % modulus;
y = y / 2;
}
return res;
}
//GCD___+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public static long gcd(long x, long y) {
if (x == 0)
return y;
else
return gcd(y % x, x);
}
// ******LOWEST COMMON MULTIPLE
// *********************************************
public static long lcm(long x, long y) {
return (x * (y / gcd(x, y)));
}
//INPUT PATTERN********************************************************
public static int i() {
return in.Int();
}
public static long l() {
String s = in.String();
return Long.parseLong(s);
}
public static String s() {
return in.String();
}
public static int[] readArrayi(int n) {
int A[] = new int[n];
for (int i = 0; i < n; i++) {
A[i] = i();
}
return A;
}
public static long[] readArray(long n) {
long A[] = new long[(int) n];
for (int i = 0; i < n; i++) {
A[i] = l();
}
return A;
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 11 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 404ddf45cb2c26842f56d360e83e8db4 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static StringBuilder sb;
static dsu dsu;
static long fact[];
static int mod = (int) (1e9 + 7);
static void solve() {
int n =i();
int k = i();
int ar[] = new int[n+1];
int ab = query("or",1,2) + query("and",1,2);
int bc = query("or",2,3) + query("and",2,3);
int ac = query("or",1,3) + query("and",1,3);
int b = (ab+bc-ac)/2;
ar[2] = b;
ar[1] = ab-b;
ar[3] = ac-ar[1];
for(int i = 4;i<=n;i++){
ar[i] = (query("or",i-1,i) + query("and",i-1,i))-ar[i-1];
}
Arrays.sort(ar);
System.out.println("finish "+ar[k]);
System.out.flush();
}
static int query(String op,int i,int j){
System.out.println(op+" "+i+" "+j);
System.out.flush();
int res = i();
return res;
}
public static void main(String[] args) {
sb = new StringBuilder();
int test = 1;
while (test-- > 0) {
solve();
}
System.out.println(sb);
}
/*
* fact=new long[(int)1e6+10]; fact[0]=fact[1]=1; for(int i=2;i<fact.length;i++)
* { fact[i]=((long)(i%mod)1L(long)(fact[i-1]%mod))%mod; }
*/
//**************NCR%P******************
static long ncr(int n, int r) {
if (r > n)
return (long) 0;
long res = fact[n] % mod;
// System.out.println(res);
res = ((long) (res % mod) * (long) (p(fact[r], mod - 2) % mod)) % mod;
res = ((long) (res % mod) * (long) (p(fact[n - r], mod - 2) % mod)) % mod;
// System.out.println(res);
return res;
}
static long p(long x, long y)// POWER FXN //
{
if (y == 0)
return 1;
long res = 1;
while (y > 0) {
if (y % 2 == 1) {
res = (res * x) % mod;
y--;
}
x = (x * x) % mod;
y = y / 2;
}
return res;
}
//**************END******************
// *************Disjoint set
// union*********//
static class dsu {
int parent[];
dsu(int n) {
parent = new int[n];
for (int i = 0; i < n; i++)
parent[i] = -1;
}
int find(int a) {
if (parent[a] < 0)
return a;
else {
int x = find(parent[a]);
parent[a] = x;
return x;
}
}
void merge(int a, int b) {
a = find(a);
b = find(b);
if (a == b)
return;
parent[b] = a;
}
}
//**************PRIME FACTORIZE **********************************//
static TreeMap<Integer, Integer> prime(long n) {
TreeMap<Integer, Integer> h = new TreeMap<>();
long num = n;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (n % i == 0) {
int nt = 0;
while (n % i == 0) {
n = n / i;
nt++;
}
h.put(i, nt);
}
}
if (n != 1)
h.put((int) n, 1);
return h;
}
//****CLASS PAIR ************************************************
static class Pair implements Comparable<Pair> {
int x;
long y;
Pair(int x, long y) {
this.x = x;
this.y = y;
}
public int compareTo(Pair o) {
return (int) (this.y - o.y);
}
}
//****CLASS PAIR **************************************************
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 int Int() {
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 String() {
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 String();
}
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 printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
static InputReader in = new InputReader(System.in);
static OutputWriter out = new OutputWriter(System.out);
public static long[] sort(long[] a2) {
int n = a2.length;
ArrayList<Long> l = new ArrayList<>();
for (long i : a2)
l.add(i);
Collections.sort(l);
for (int i = 0; i < l.size(); i++)
a2[i] = l.get(i);
return a2;
}
public static char[] sort(char[] a2) {
int n = a2.length;
ArrayList<Character> l = new ArrayList<>();
for (char i : a2)
l.add(i);
Collections.sort(l);
for (int i = 0; i < l.size(); i++)
a2[i] = l.get(i);
return a2;
}
public static long pow(long x, long y) {
long res = 1;
while (y > 0) {
if (y % 2 != 0) {
res = (res * x);// % modulus;
y--;
}
x = (x * x);// % modulus;
y = y / 2;
}
return res;
}
//GCD___+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public static long gcd(long x, long y) {
if (x == 0)
return y;
else
return gcd(y % x, x);
}
// ******LOWEST COMMON MULTIPLE
// *********************************************
public static long lcm(long x, long y) {
return (x * (y / gcd(x, y)));
}
//INPUT PATTERN********************************************************
public static int i() {
return in.Int();
}
public static long l() {
String s = in.String();
return Long.parseLong(s);
}
public static String s() {
return in.String();
}
public static int[] readArrayi(int n) {
int A[] = new int[n];
for (int i = 0; i < n; i++) {
A[i] = i();
}
return A;
}
public static long[] readArray(long n) {
long A[] = new long[(int) n];
for (int i = 0; i < n; i++) {
A[i] = l();
}
return A;
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 11 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | d2f4c40167ed508c54e6c75aeed7cf1a | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class Codeforces {
static int mod=1000000007;
static int brr[]= {};
public static void main(String[] args) throws Exception {
PrintWriter out=new PrintWriter(System.out);
FastScanner fs=new FastScanner();
int n=fs.nextInt(),k=fs.nextInt();
int arr[]=new int[n];
System.out.println("and 1 2");
int and12=fs.nextInt();
System.out.println("or 1 2");
int or12=fs.nextInt();
System.out.println("and 2 3");
int and23=fs.nextInt();
System.out.println("or 2 3");
int or23=fs.nextInt();
System.out.println("and 1 3");
int and13=fs.nextInt();
System.out.println("or 1 3");
int or13=fs.nextInt();
int a12= or12+and12;
int a23 = or23+and23;
int a13 = or13+and13;
arr[1]= (a12+a23-a13)/2;
arr[0]= a12-arr[1];
arr[2]= a23-arr[1];
for(int i=3;i<n;i++) {
System.out.println("or "+i+" "+(i+1));
int or=fs.nextInt();
System.out.println("and "+i+" "+(i+1));
int and=fs.nextInt();
int sum= or+and;
arr[i]=sum-arr[i-1];
}
sort(arr);
System.out.println("finish "+arr[k-1]);
out.close();
}
static int and(int l,int r) {
int cur=brr[l-1];
for(int i=l;i<r;i++) cur&=brr[i];
return cur;
}
static int or(int l,int r) {
int cur=brr[l-1];
for(int i=l;i<r;i++) cur|=brr[i];
return cur;
}
static long pow(long a,long b) {
if(b<0) return 1;
long res=1;
while(b!=0) {
if((b&1)!=0) {
res*=a;
res%=mod;
}
a*=a;
a%=mod;
b=b>>1;
}
return res;
}
static long gcd(long a,long b) {
if(b==0) return a;
return gcd(b,a%b);
}
static long nck(int n,int k) {
if(k>n) return 0;
long res=1;
res*=fact(n);
res%=mod;
res*=modInv(fact(k));
res%=mod;
res*=modInv(fact(n-k));
res%=mod;
return res;
}
static long fact(long n) {
long res=1;
for(int i=2;i<=n;i++) {
res*=i;
res%=mod;
}
return res;
}
static long modInv(long n) {
return pow(n,mod-2);
}
static void sort(int[] a) {
//suffle
int n=a.length;
Random r=new Random();
for (int i=0; i<a.length; i++) {
int oi=r.nextInt(n);
int temp=a[i];
a[i]=a[oi];
a[oi]=temp;
}
//then sort
Arrays.sort(a);
}
// Use this to input code since it is faster than a Scanner
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long[] lreadArray(int n) {
long a[]=new long[n];
for(int i=0;i<n;i++) a[i]=nextLong();
return a;
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 11 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 95914de86e5f354cca94925392cba2cb | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class B{
public static void main(String[] args)
{
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = fs.nextInt(); int k = fs.nextInt();
long[] arr = new long[n+1];
arr[0] = -1;
System.out.println("and 1 2");
int temp1 = fs.nextInt();
System.out.println("or 1 2");
int temp2 = fs.nextInt();
long ab = (long)temp1 + temp2;
System.out.println("and 1 3");
temp1 = fs.nextInt();
System.out.println("or 1 3");
temp2 = fs.nextInt();
long ac = (long)temp1 + temp2;
System.out.println("and 2 3");
temp1 = fs.nextInt();
System.out.println("or 2 3");
temp2 = fs.nextInt();
long bc = (long)temp1 + temp2;
long abc = (ab+ac+bc)/2;
arr[1] = abc - (bc);
arr[2] = abc - (ac);
arr[3] = abc - (ab);
for(int i=4;i<=n;i++)
{
System.out.println("and "+(1)+" "+(i));
int and = fs.nextInt();
System.out.println("or "+(1)+" "+(i));
int or = fs.nextInt();
long sum = ((long)and+(long)or);
arr[i] = sum - arr[1];
}
arr = sort(arr);
System.out.println("finish "+arr[k]);
out.close();
}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!st.hasMoreTokens())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
public static long[] sort(long[] arr)
{
List<Long> temp = new ArrayList();
for(long i:arr)temp.add(i);
Collections.sort(temp);
int start = 0;
for(long i:temp)arr[start++]=i;
return arr;
}
public static String rev(String str)
{
char[] arr = str.toCharArray();
char[] ret = new char[arr.length];
int start = arr.length-1;
for(char i:arr)ret[start--] = i;
String ret1 = "";
for(char ch:ret)ret1+=ch;
return ret1;
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 11 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 4b817a947e17ccdef9bfee055e9cc0c2 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Practice
{
static int mod=1000000007;
static HashSet<Integer> pr;
static FastReader sc=new FastReader(System.in);
// static Reader sc=new Reader();
static PrintWriter out=new PrintWriter(System.out);
public static void main(String[] args) throws IOException
{
int t=1;
// t=sc.nextInt();
// StringBuilder sb=new StringBuilder();
while(t-->0)
{
solve();
// sb.append("\n");
}
// out.print(sb);
out.close();
out.flush();
}
static class Pair
{
int x;
int y;
Pair(int a,int b)
{
x=a;
y=b;
}
@Override
public String toString()
{
return x+" "+y;
}
}
static void arraySort(int arr[])
{
ArrayList<Integer> a=new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++) {
a.add(arr[i]);
}
Collections.sort(a);
for (int i = 0; i < arr.length; i++) {
arr[i]=a.get(i);
}
}
static void solve() throws IOException
{
int n=sc.nextInt(),k=sc.nextInt(),pos=0;
int arr[]=new int[n];
out.println("and "+1+" "+(1+1));
out.flush();
int x=sc.nextInt();
out.println("or "+1+" "+(1+1));
out.flush();
int y=sc.nextInt();
long a=(x+y);
out.println("and "+(1+1)+" "+(1+2));
out.flush();
x=sc.nextInt();
out.println("or "+(1+1)+" "+(1+2));
out.flush();
y=sc.nextInt();
long b=x+y;
out.println("and "+(1)+" "+(1+2));
out.flush();
x=sc.nextInt();
out.println("or "+(1)+" "+(1+2));
out.flush();
y=sc.nextInt();
long c=x+y;
arr[1]=(int)((a+b-c)>>1);
arr[0]=(int)(a-arr[1]);
arr[2]=(int)(c-arr[0]);
// out.println(Arrays.toString(arr));
for(int i=3;i<n;i++)
{
out.println("and "+1+" "+(i+1));
out.flush();
x=sc.nextInt();
out.println("or "+1+" "+(i+1));
out.flush();
y=sc.nextInt();
long sum=(x+y);
arr[i]=(int)(sum-arr[0]);
// out.println(Arrays.toString(arr));
}
arraySort(arr);
// out.println(Arrays.toString(arr));
out.println("finish "+arr[k-1]);
out.flush();
}
static double dfs(Node ver,Node par)
{
if(ver.adj.size()==1 && ver.adj.get(0)==par)
{
return 0;
}
else
{
double sum=0,c=0;
for(Node child: ver.adj)
if(child!=par)
{
c++;
sum+=dfs(child, ver);
}
return 1+(sum/c);
}
}
static int LOWER_BOUND(ArrayList<Integer> arr,int x)
{
int low=0,high=arr.size();
int ans=0;
while(low<=high)
{
int mid=(low+high)/2;
if(arr.get(mid)==x)
{
ans=arr.get(mid);
break;
}
else if(arr.get(mid)<x)
{
ans=arr.get(mid);
low=mid+1;
}
else
high=mid-1;
}
return ans;
}
static int gcd(int a,int b)
{
return (b==0)?a:gcd(b,a%b);
}
static class UnionFind
{
private int size;
private int[] sz;
private int[] parent;
private int numComponents;
public UnionFind(int size,Pair dancers[])
{
if (size <= 0) throw new IllegalArgumentException("Size <= 0 is not allowed");
this.size = numComponents = size;
sz = new int[size];
parent = new int[size];
for (int i = 0; i < size; i++)
{
parent[i] = i; // Link to itself (self root)
sz[i] = 1; // Each component is originally of size one
}
}
public int find(int p)
{
int root = p;
while (root != parent[root])
root = parent[root];
while (p != root)
{
int next = parent[p];
parent[p] = root;
p = next;
}
return root;
}
public boolean isConnected(int p, int q)
{
return find(p) == find(q);
}
public int componentSize(int x)
{
return sz[find(x)];
}
public int size()
{
return size;
}
public int components()
{
return numComponents;
}
public void unify(int p, int q)
{
int root1 = find(p);
int root2 = find(q);
if(root1==root2)
{
return;
}
else if (sz[root1] < sz[root2])
{
parent[root1] = root2;
sz[root2] += sz[root1];
sz[root1] = 0;
}
else
{
parent[root2] = root1;
sz[root1] += sz[root2];
sz[root2] = 0;
}
numComponents--;
}
void calc()
{
for(int i=0;i<size;i++)
find(i);
}
}
static class Node
{
int vertex;
ArrayList<Node> adj;
boolean rec;
boolean vis;
int color;
Node(int v)
{
vertex=v;
adj=new ArrayList<Node>();
vis=false;
color=-1;
}
@Override
public String toString()
{
return vertex+" ";
}
}
static class Edge
{
Node a;
Node b;
Edge(Node m,Node n)
{
this.a=m;
this.b=n;
}
@Override
public String toString() {
return a.vertex+" "+b.vertex;
}
}
static long power(long x, long y)
{
long res = 1;
x = x % mod;
if (x == 0)
return 0;
while (y > 0)
{
if ((y & 1) != 0)
res = (res * x) % mod;
y = y >> 1; // y = y/2
x = (x * x) % mod;
}
return res;
}
static long binomialCoeff(long n, long k)
{
long res = 1;
if(k>n)
return 0;
// Since C(n, k) = C(n, n-k)
if (k > n - k)
k = n - k;
// Calculate value of
// [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1]
for (long i = 0; i < k; ++i) {
res *= (n - i);
res /= (i + 1);
}
return res;
}
static class FastReader
{
byte[] buf = new byte[2048];
int index, total;
InputStream in;
FastReader(InputStream is)
{
in = is;
}
int scan() throws IOException
{
if (index >= total) {
index = 0;
total = in.read(buf);
if (total <= 0) {
return -1;
}
}
return buf[index++];
}
String next() throws IOException
{
int c;
for (c = scan(); c <= 32; c = scan());
StringBuilder sb = new StringBuilder();
for (; c > 32; c = scan()) {
sb.append((char) c);
}
return sb.toString();
}
int nextInt() throws IOException
{
int c, val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
long nextLong() throws IOException
{
int c;
long val = 0;
for (c = scan(); c <= 32; c = scan());
boolean neg = c == '-';
if (c == '-' || c == '+') {
c = scan();
}
for (; c >= '0' && c <= '9'; c = scan()) {
val = (val << 3) + (val << 1) + (c & 15);
}
return neg ? -val : val;
}
}
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') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
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 void printarray(int arr[])
{
for (int i = 0; i < arr.length; i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}
}
| Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 11 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | c5aa33895ed813b60b7fdc66e0b4dbb6 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | /*
ID: abdelra29
LANG: JAVA
PROG: zerosum
*/
/*
TO LEARN
2-euler tour
*/
/*
TO SOLVE
*/
/*
bit manipulation shit
1-Computer Systems: A Programmer's Perspective
2-hacker's delight
*/
/*
TO WATCH
*/
import java.util.*;
import java.math.*;
import java.io.*;
import java.util.stream.Collectors;
public class A{
static FastScanner scan=new FastScanner();
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
static boolean isprime(int x)
{
if(x%2==0)
return false;
if(x==1)
return false;
if(x==2||x==3)
return true;
for(int i=3;i*i<=x;i+=2)
if(x%i==0)
return false;
return true;
}
static int hidden[]={0,181,21,53};
static Pair askand(int x)
{
System.out.println("and "+x+" "+(x-1));
//int fi=scan.nextInt();
int fi=hidden[x]&hidden[x-1];
System.out.println("and "+x+" "+(x-2));
int sec=hidden[x]&hidden[x-2];
//int sec=scan.nextInt();
return new Pair(fi,sec);
}
static Pair askor(int x)
{
System.out.println("or "+x+" "+(x-1));
//int fi=scan.nextInt();
int fi=hidden[x]|hidden[x-1];
System.out.println("or "+x+" "+(x-2));
int sec=hidden[x]|hidden[x-2];
//int sec=scan.nextInt();
return new Pair(fi,sec);
}
static int binaryToDecimal(String n)
{
String num = n;
int dec_value = 0;
// Initializing base value to 1,
// i.e 2^0
int base = 1;
int len = num.length();
for (int i = len - 1; i >= 0; i--) {
if (num.charAt(i) == '1')
dec_value += base;
base = base * 2;
}
return dec_value;
}
public static void main(String[] args) throws Exception
{
/*
very important tips
1-just fucking think backwards once in your shitty life
2-consider brute forcing and finding some patterns and observations
3-when you're in contest don't get out because you think there is no enough time
4-don't get stuck on one approach
*/
// File file=new File("D:\\input\\out.txt");
// scan=new FastScanner("D:\\input\\xs_and_os_input.txt");
// out = new PrintWriter(new File("D:\\input\\out.txt"));
/*
READING
3-Introduction to DP with Bitmasking codefoces
4-Bit Manipulation hackerearth
5-read more about mobious and inculsion-exclusion
*/
/*
1-
*/
/*for(int i=3;i<=30;i++)
{
int sh=(i%3==0)?i/3:i/3+1;
System.out.println(i*2+" "+(sh*4));
}*/
int tt =1;
//tt=scan.nextInt();
int T=1;
outer:while(tt-->0)
{
int n=scan.nextInt(),k=scan.nextInt();
int ans[]=new int[n+1];
System.out.println("and "+1+" "+2);
int and12=scan.nextInt();
//int and12=hidden[1]&hidden[2];
System.out.println("and "+1+" "+3);
int and13=scan.nextInt();
// int and13=hidden[1]&hidden[3];
System.out.println("and "+2+" "+3);
int and23=scan.nextInt();
//int and23=hidden[2]&hidden[3];
System.out.println("or "+1+" "+2);
int or12=scan.nextInt();
// int or12=hidden[1]|hidden[2];
System.out.println("or "+1+" "+3);
int or13=scan.nextInt();
// int or13=hidden[1]|hidden[3];
System.out.println("or "+2+" "+3);
int or23=scan.nextInt();
// int or23=hidden[2]|hidden[3];
StringBuilder first=new StringBuilder("");
StringBuilder second=new StringBuilder("");
StringBuilder third=new StringBuilder("");
for(int i=0;i<=29;i++)
{
first.append(" ");
second.append(" ");
third.append(" ");
}
for(int i=0;i<=29;i++)
{
//0 equals 29
//all zeros
{
//000
if((1&(or12>>i))==0&&(1&(or13>>i))==0){
first.setCharAt(29-i,'0');
second.setCharAt(29-i,'0');
third.setCharAt(29-i,'0');
continue;
}
}
//all ones
{
//111
if((1&(and12>>i))==1&&(1&(and13>>i))==1){
first.setCharAt(29-i,'1');
second.setCharAt(29-i,'1');
third.setCharAt(29-i,'1');
continue;
}
}
//2 zeros 1 ones
{
//001
//and12=0 and13=0 and23=0 or12=0 or13=1 or23=1
if((1&(and12>>i))==0&&(1&(and13>>i))==0&&(1&(and23>>i))==0&&(1&(or12>>i))==0&&(1&(or13>>i))==1&&(1&(or23>>i))==1)
{
first.setCharAt(29-i,'0');
second.setCharAt(29-i,'0');
third.setCharAt(29-i,'1');
continue;
}
//010
if((1&(and12>>i))==0&&(1&(and13>>i))==0&&(1&(and23>>i))==0&&(1&(or12>>i))==1&&(1&(or13>>i))==0&&(1&(or23>>i))==1)
{
first.setCharAt(29-i,'0');
second.setCharAt(29-i,'1');
third.setCharAt(29-i,'0');
continue;
}
//100
if((1&(and12>>i))==0&&(1&(and13>>i))==0&&(1&(and23>>i))==0&&(1&(or12>>i))==1&&(1&(or13>>i))==1&&(1&(or23>>i))==0)
{
first.setCharAt(29-i,'1');
second.setCharAt(29-i,'0');
third.setCharAt(29-i,'0');
continue;
}
}
//1 zeros 2 ones
{
//011
if((1&(and12>>i))==0&&(1&(and13>>i))==0&&(1&(and23>>i))==1&&(1&(or12>>i))==1&&(1&(or13>>i))==1&&(1&(or23>>i))==1)
{
first.setCharAt(29-i,'0');
second.setCharAt(29-i,'1');
third.setCharAt(29-i,'1');
continue;
}
//101
if((1&(and12>>i))==0&&(1&(and13>>i))==1&&(1&(and23>>i))==0&&(1&(or12>>i))==1&&(1&(or13>>i))==1&&(1&(or23>>i))==1)
{
first.setCharAt(29-i,'1');
second.setCharAt(29-i,'0');
third.setCharAt(29-i,'1');
continue;
}
//110
if((1&(and12>>i))==1&&(1&(and13>>i))==0&&(1&(and23>>i))==0&&(1&(or12>>i))==1&&(1&(or13>>i))==1&&(1&(or23>>i))==1)
{
first.setCharAt(29-i,'1');
second.setCharAt(29-i,'1');
third.setCharAt(29-i,'0');
continue;
}
}
// System.out.println("FUCK");
}
// out.println(second);
ans[1]=binaryToDecimal(first.toString());
ans[2]=binaryToDecimal(second.toString());
ans[3]=binaryToDecimal(third.toString());
// out.println(Arrays.toString(ans));
int my=ans[1];
for(int i=4;i<=n;i++)
{
System.out.println("and "+1+" "+i);
int and=scan.nextInt();
System.out.println("or "+1+" "+i);
int or=scan.nextInt();
StringBuilder now=new StringBuilder("");
for(int j=0;j<=29;j++)
now.append(" ");
for(int j=0;j<=29;j++)
{
if((1&(and>>j))==1)
{
now.setCharAt(29-j,'1');
}
else if((1&(or>>j))==0)
{
now.setCharAt(29-j,'0');
}
else {
if((1&(my>>j))==1)
now.setCharAt(29-j,'0');
else now.setCharAt(29-j,'1');
}
}
int ok=binaryToDecimal(now.toString());
ans[i]=ok;
}
ArrayList<Integer>res=new ArrayList<Integer>();
for(int i=1;i<=n;i++)
res.add(ans[i]);
Collections.sort(res);
System.out.println("finish "+res.get(k-1));
}
out.close();
}
static class special implements Comparable<special>{
int cnt,idx;
String s;
public special(int cnt,int idx,String s)
{
this.cnt=cnt;
this.idx=idx;
this.s=s;
}
@Override
public int hashCode() {
return (int)42;
}
@Override
public boolean equals(Object o){
// System.out.println("FUCK");
if (o == this) return true;
if (o.getClass() != getClass()) return false;
special t = (special)o;
return t.cnt == cnt && t.idx == idx;
}
public int compareTo(special o1)
{
if(o1.cnt==cnt)
{
return o1.idx-idx;
}
return o1.cnt-cnt;
}
}
static long binexp(long a,long n)
{
if(n==0)
return 1;
long res=binexp(a,n/2);
if(n%2==1)
return res*res*a;
else
return res*res;
}
static long powMod(long base, long exp, long mod) {
if (base == 0 || base == 1) return base;
if (exp == 0) return 1;
if (exp == 1) return (base % mod+mod)%mod;
long R = (powMod(base, exp/2, mod) % mod+mod)%mod;
R *= R;
R %= mod;
if ((exp & 1) == 1) {
return (base * R % mod+mod)%mod;
}
else return (R %mod+mod)%mod;
}
static double dis(double x1,double y1,double x2,double y2)
{
return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}
static long mod(long x,long y)
{
if(x<0)
x=x+(-x/y+1)*y;
return x%y;
}
public static long pow(long b, long e) {
long r = 1;
while (e > 0) {
if (e % 2 == 1) r = r * b ;
b = b * b;
e >>= 1;
}
return r;
}
private static void sort(int[] arr) {
List<Integer> list = new ArrayList<>();
for (int object : arr) list.add(object);
Collections.sort(list);
//Collections.reverse(list);
for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i);
}
private static void sort2(long[] arr) {
List<Long> list = new ArrayList<>();
for (Long object : arr) list.add(object);
Collections.sort(list);
Collections.reverse(list);
for (int i = 0; i < list.size(); ++i) arr[i] = list.get(i);
}
static class FastScanner
{
private int BS = 1 << 16;
private char NC = (char) 0;
private byte[] buf = new byte[BS];
private int bId = 0, size = 0;
private char c = NC;
private double cnt = 1;
private BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
} catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
private char getChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public int[] nextInts(int N) {
int[] res = new int[N];
for (int i = 0; i < N; i++) {
res[i] = (int) nextLong();
}
return res;
}
public long[] nextLongs(int N) {
long[] res = new long[N];
for (int i = 0; i < N; i++) {
res[i] = nextLong();
}
return res;
}
public long nextLong() {
cnt = 1;
boolean neg = false;
if (c == NC) c = getChar();
for (; (c < '0' || c > '9'); c = getChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = getChar()) {
res = (res << 3) + (res << 1) + c - '0';
cnt *= 10;
}
return neg ? -res : res;
}
public double nextDouble() {
double cur = nextLong();
return c != '.' ? cur : cur + nextLong() / cnt;
}
public double[] nextDoubles(int N) {
double[] res = new double[N];
for (int i = 0; i < N; i++) {
res[i] = nextDouble();
}
return res;
}
public String next() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c > 32) {
res.append(c);
c = getChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while (c <= 32) c = getChar();
while (c != '\n') {
res.append(c);
c = getChar();
}
return res.toString();
}
public boolean hasNext() {
if (c > 32) return true;
while (true) {
c = getChar();
if (c == NC) return false;
else if (c > 32) return true;
}
}
}
static class Pair implements Comparable<Pair>{
public long x, y,z;
public Pair(long x1, long y1,long z1) {
x=x1;
y=y1;
z=z1;
}
public Pair(long x1, long y1) {
x=x1;
y=y1;
}
@Override
public int hashCode() {
return (int)(x + 31 * y);
}
public String toString() {
return x + " " + y+" "+z;
}
@Override
public boolean equals(Object o){
if (o == this) return true;
if (o.getClass() != getClass()) return false;
Pair t = (Pair)o;
return t.x == x && t.y == y&&t.z==z;
}
public int compareTo(Pair o)
{
return (int)(x-o.x);
}
}
}
| Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 11 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | d53702d37585b20f3b5f99ed09467cac | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
import java.awt.geom.*;
import static java.lang.Math.*;
public class Solution implements Runnable {
long mod1 = (long) 1e9 + 7;
int mod2 = 998244353;
public void solve() throws Exception {
int n=sc.nextInt();
int k=sc.nextInt();
ArrayList<Integer> list = new ArrayList<>();
int firstOr = query(1,1,2);
int firstAnd = query(0,1,2);
int firstThirdOr = query(1,1,3);
int firstThirdAnd = query(0,1,3);
int secondThirdOr = query(1,2,3);
int secondThirdAnd = query(0,2,3);
int first=0, second=0;
for(int i=0;i<31;i++) {
if((firstOr&(1<<i)) == (firstAnd&(1<<i))) {
if((firstOr&(1<<i))!=0) {
first += (firstOr&(1<<i));
second += (firstOr&(1<<i));
} else {
}
}
else {
if((firstThirdOr&(1<<i)) != (secondThirdOr&(1<<i))) {
if((firstThirdOr&(1<<i))!=0) {
first += (firstThirdOr&(1<<i));
} else {
second += (secondThirdOr&(1<<i));
}
}
else {
if((firstThirdAnd&(1<<i))!=0) {
first += (firstThirdAnd&(1<<i));
} else {
second += (secondThirdAnd&(1<<i));
}
}
}
}
list.add(first);
list.add(second);
int third=0;
for(int i=0;i<31;i++) {
if((firstThirdAnd&(1<<i))!=0) {
third += (firstThirdAnd&(1<<i));
}
else {
if((firstThirdOr&(1<<i))!=0) {
if((first&(1<<i))==0) {
third += (firstThirdOr&(1<<i));
}
}
}
}
list.add(third);
for(int i=4;i<=n;i++) {
int num=0;
int q1 = query(0, 1, i);
int q2 = query(1, 1, i);
for(int j=0;j<31;j++) {
if((q1&(1<<j))!=0) {
num += (q1&(1<<j));
}
else {
if((q2&(1<<j))!=0) {
if((first&(1<<j))==0) {
num += (q2&(1<<j));
}
}
}
}
list.add(num);
}
Collections.sort(list);
System.out.println("finish "+list.get(k-1));
out.flush();
}
public int query(int type, int i, int j) throws Exception{
if(type == 0) {
System.out.println("and "+i+" "+j);
out.flush();
int x=sc.nextInt();
return x;
}
else {
System.out.println("or "+i+" "+j);
out.flush();
int x=sc.nextInt();
return x;
}
}
static long gcd(long a, long b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
static void sort(int[] a) {
ArrayList<Integer> l = new ArrayList<>();
for (int i : a)
l.add(i);
Collections.sort(l);
for (int i = 0; i < a.length; i++)
a[i] = l.get(i);
}
static long ncr(int n, int r, long p) {
if (r > n)
return 0l;
if (r > n - r)
r = n - r;
long C[] = new long[r + 1];
C[0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = Math.min(i, r); j > 0; j--)
C[j] = (C[j] + C[j - 1]) % p;
}
return C[r] % p;
}
void sieveOfEratosthenes(boolean prime[], int size) {
for (int i = 0; i < size; i++)
prime[i] = true;
for (int p = 2; p * p < size; p++) {
if (prime[p] == true) {
for (int i = p * p; i < size; i += p)
prime[i] = false;
}
}
}
static int LowerBound(int a[], int x) { // smallest index having value >= x; returns 0-based index
int l = -1, r = a.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (a[m] >= x)
r = m;
else
l = m;
}
return r;
}
static int UpperBound(int a[], int x) {// biggest index having value <= x; returns 1-based index
int l = -1, r = a.length;
while (l + 1 < r) {
int m = (l + r) >>> 1;
if (a[m] <= x)
l = m;
else
r = m;
}
return l + 1;
}
public long power(long x, long y, long p) {
long res = 1;
// out.println(x+" "+y);
x = x % p;
if (x == 0)
return 0;
while (y > 0) {
if ((y & 1) == 1)
res = (res * x) % p;
y = y >> 1;
x = (x * x) % p;
}
return res;
}
static Throwable uncaught;
BufferedReader in;
FastScanner sc;
PrintWriter out;
@Override
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
sc = new FastScanner(in);
solve();
} catch (Throwable uncaught) {
Solution.uncaught = uncaught;
} finally {
out.close();
}
}
public static void main(String[] args) throws Throwable {
Thread thread = new Thread(null, new Solution(), "", (1 << 26));
thread.start();
thread.join();
if (Solution.uncaught != null) {
throw Solution.uncaught;
}
}
}
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 int[] readArray(int n) throws Exception {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
public double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 11 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | d13350928a13a6d0a597c21c83752aab | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class _1556_D {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer line = new StringTokenizer(in.readLine());
int n = Integer.parseInt(line.nextToken());
int k = Integer.parseInt(line.nextToken());
int[][] a = new int[n][31];
for (int i = 0; i < n - 1; i++) {
int and = query("and", i + 1, i + 2, in);
int or = query("or", i + 1, i + 2, in);
for (int j = 30; j >= 0; j--) {
int ad = and % 2;
int od = or % 2;
if (ad == 1 && od == 1) {
a[i][j] = 1;
a[i + 1][j] = 1;
} else if (ad == 0 && od == 0) {
a[i][j] = 0;
a[i + 1][j] = 0;
} else {
if(i == 0) a[i][j] = 2;
a[i + 1][j] = 2;
}
and /= 2;
or /= 2;
}
}
if (n % 2 == 0) {
int and = query("and", 1, n - 1, in);
int or = query("or", 1, n - 1, in);
for (int j = 30; j >= 0; j--) {
int ad = and % 2;
int od = or % 2;
if (ad == 1 && od == 1) {
a[0][j] = 1;
a[n - 2][j] = 1;
} else if (ad == 0 && od == 0) {
a[0][j] = 0;
a[n - 2][j] = 0;
}
and /= 2;
or /= 2;
}
} else {
int and = query("and", 1, n, in);
int or = query("or", 1, n, in);
for (int j = 30; j >= 0; j--) {
int ad = and % 2;
int od = or % 2;
if (ad == 1 && od == 1) {
a[0][j] = 1;
a[n - 1][j] = 1;
} else if (ad == 0 && od == 0) {
a[0][j] = 0;
a[n - 1][j] = 0;
}
and /= 2;
or /= 2;
}
}
for (int i = 0; i < 31; i++) {
int prev = -1;
for (int j = 0; j < n; j++) {
if (a[j][i] == 2) {
if (prev > -1) {
a[j][i] = 1 - prev;
prev = a[j][i];
}
} else {
prev = a[j][i];
}
}
prev = -1;
for (int j = n - 1; j >= 0; j--) {
if (a[j][i] == 2) {
if (prev > -1) {
a[j][i] = 1 - prev;
prev = a[j][i];
}
} else {
prev = a[j][i];
}
}
}
int[] res = new int[n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < 31; j++) {
res[i] = res[i] * 2 + a[i][j];
}
}
Arrays.sort(res);
System.out.println("finish " + res[k - 1]);
System.out.flush();
in.close();
}
static int query(String type, int i, int j, BufferedReader in) throws IOException {
System.out.println(type + " " + i + " " + j);
System.out.flush();
return Integer.parseInt(in.readLine());
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 11 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 9b6d63ea7551888a0e8153951d9edd25 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class D {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
System.out.println("and 1 2");
long a_and_b = sc.nextLong(); if(a_and_b < 0) return;
System.out.println("and 1 3");
long a_and_c = sc.nextLong(); if(a_and_c < 0) return;
System.out.println("and 2 3");
long b_and_c = sc.nextLong(); if(b_and_c < 0) return;
System.out.println("or 1 2");
long a_or_b = sc.nextLong(); if(a_or_b < 0) return;
System.out.println("or 1 3");
long a_or_c = sc.nextLong(); if(a_or_c < 0) return;
System.out.println("or 2 3");
long b_or_c = sc.nextLong(); if(b_or_c < 0) return;
long[] arr = new long[n];
for(int bit = 0; bit < 31; bit++) {
if(!check(a_or_b, bit) && !check(a_or_c, bit)) {//0 0 0
}
else if(!check(a_or_b, bit) && check(a_or_c, bit)){//0 0 1
arr[2] += (1 << bit);
}
else if(!check(a_or_c, bit) && check(a_or_b, bit)){//0 1 0
arr[1] += (1 << bit);
}
else if(check(b_and_c, bit) && !check(a_and_b, bit)){//0 1 1
arr[1] += (1 << bit); arr[2] += (1 << bit);
}
else if(!check(b_or_c, bit) && check(a_or_b, bit)){//1 0 0
arr[0] += (1 << bit);
}
else if(check(a_and_c, bit) && !check(a_and_b, bit)){//1 0 1
arr[0] += (1 << bit); arr[2] += (1 << bit);
}
else if(check(a_and_b, bit) && !check(a_and_c, bit)) {//1 1 0
arr[0] += (1 << bit); arr[1] += (1 << bit);
}
else if(check(a_and_b, bit) && check(a_and_c, bit)) {// 1 1 1
arr[0] += (1 << bit); arr[1] += (1 << bit); arr[2] += (1 << bit);
}
}
for(int i = 3; i < n; i++) {
System.out.printf("and %d %d\n", 1, i+1);
long a = sc.nextLong(); if(a < 0) return;
System.out.printf("or %d %d\n", 1, i+1);
long b = sc.nextLong(); if(b < 0) return;
long c = a ^ b;
arr[i] = arr[0] ^ c;
}
sort(arr);
System.out.printf("finish %d\n",arr[k-1]);
}
static void sort(long[] arr) {
Random r = new Random();
for(int i = 0; i < arr.length; i++) {
int ind = r.nextInt(arr.length);
long aux = arr[ind]; arr[ind] = arr[i]; arr[i] = aux;
}
Arrays.sort(arr);
}
static boolean check(long x, int b) {
return (x & (1 << b)) > 0;
}
}
| Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 11 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 4216a392af3ce4aa7a1efcf69a79c74f | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
static int MOD = 1000000007;
// After writing solution, quick scan for:
// array out of bounds
// special cases e.g. n=1?
// npe, particularly in maps
//
// Big numbers arithmetic bugs:
// int overflow
// sorting, or taking max, after MOD
void solve() throws IOException {
int[] nk = ril(2);
int n = nk[0];
int k = nk[1];
pw.println("or 1 2"); pw.flush();
int or_ab = ri();
pw.println("and 1 2"); pw.flush();
int and_ab = ri();
pw.println("or 1 3"); pw.flush();
int or_ac = ri();
pw.println("and 1 3"); pw.flush();
int and_ac = ri();
pw.println("or 2 3"); pw.flush();
int or_bc = ri();
pw.println("and 2 3"); pw.flush();
int and_bc = ri();
int xor_ab = or_ab - and_ab;
int xor_ac = or_ac - and_ac;
int xor_bc = or_bc - and_bc;
int ab = xor_ab + 2 * and_ab;
int ac = xor_ac + 2 * and_ac;
int bc = xor_bc + 2 * and_bc;
int a = (ab + ac - bc) / 2;
int b = ab - a;
int c = ac - a;
List<Integer> nums = new ArrayList<>();
nums.add(a);
nums.add(b);
nums.add(c);
for (int i = 4; i <= n; i++) {
pw.println("or 1 " + i); pw.flush();
int or = ri();
pw.println("and 1 " + i); pw.flush();
int and = ri();
int xor = or - and;
int sum = xor + 2 * and;
nums.add(sum - a);
}
Collections.sort(nums);
pw.println("finish " + nums.get(k-1));
}
// IMPORTANT
// DID YOU CHECK THE COMMON MISTAKES ABOVE?
// Template code below
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
public static void main(String[] args) throws IOException {
Main m = new Main();
m.solve();
m.close();
}
void close() throws IOException {
pw.flush();
pw.close();
br.close();
}
int ri() throws IOException {
return Integer.parseInt(br.readLine().trim());
}
long rl() throws IOException {
return Long.parseLong(br.readLine().trim());
}
int[] ril(int n) throws IOException {
int[] nums = new int[n];
int c = 0;
for (int i = 0; i < n; i++) {
int sign = 1;
c = br.read();
int x = 0;
if (c == '-') {
sign = -1;
c = br.read();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = br.read();
}
nums[i] = x * sign;
}
while (c != '\n' && c != -1) c = br.read();
return nums;
}
long[] rll(int n) throws IOException {
long[] nums = new long[n];
int c = 0;
for (int i = 0; i < n; i++) {
int sign = 1;
c = br.read();
long x = 0;
if (c == '-') {
sign = -1;
c = br.read();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = br.read();
}
nums[i] = x * sign;
}
while (c != '\n' && c != -1) c = br.read();
return nums;
}
int[] rkil() throws IOException {
int sign = 1;
int c = br.read();
int x = 0;
if (c == '-') {
sign = -1;
c = br.read();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = br.read();
}
return ril(x);
}
long[] rkll() throws IOException {
int sign = 1;
int c = br.read();
int x = 0;
if (c == '-') {
sign = -1;
c = br.read();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = br.read();
}
return rll(x);
}
char[] rs() throws IOException {
return br.readLine().toCharArray();
}
void sort(int[] A) {
Random r = new Random();
for (int i = A.length-1; i > 0; i--) {
int j = r.nextInt(i+1);
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
Arrays.sort(A);
}
void printDouble(double d) {
pw.printf("%.16f", d);
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 11 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | c03ae28f16697d209388e89432e4e7c5 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class Solution {
public static void solve(InputReader ina, PrintWriter out) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
int[] A = new int[n];
for (int i = 1; i < n ; i++) {
System.out.println("and " + i + " " + (i + 1));
A[i] += in.nextInt();
System.out.println("or " + i + " " + (i + 1));
A[i] += in.nextInt();
}
System.out.println("and 1 3");
int c = in.nextInt();
System.out.println("or 1 3");
c += in.nextInt();
c = A[2] - c;
c += A[1];
c /= 2;
A[0] = A[1] - c;
for (int i = 1; i < n; i++) {
A[i] -= A[i - 1];
}
Arrays.sort(A);
System.out.println("finish " + A[k-1]);
System.out.flush();
}
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solve(in, out);
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 nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 11 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | 2f088f35865731befe5a2cd9b8e20caa | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.io.*;
import java.lang.*;
import java.util.*;
public class TakeAGuess {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int k = s.nextInt();
int nums[] = new int[n];
int o1, o2, o3, a1, a2, a3;
int s1, s2, s3;
System.out.println("and 1 2");
a3 = s.nextInt();
System.out.println("and 3 2");
a1 = s.nextInt();
System.out.println("and 3 1");
a2 = s.nextInt();
System.out.println("or 1 2");
o3 = s.nextInt();
System.out.println("or 3 2");
o1 = s.nextInt();
System.out.println("or 3 1");
o2 = s.nextInt();
s1 = o1 + a1;
s2 = o2 + a2;
s3 = o3 + a3;
nums[0] = (s2 + s3 + -s1) / 2;
nums[1] = (-s2 + s3 + s1) / 2;
nums[2] = (s2 + -s3 + s1) / 2;
int sum;
for (int i = 3; i < n; i++) {
sum = 0;
System.out.println("or 1 " + (i + 1));
sum += s.nextInt();
System.out.println("and 1 " + (i + 1));
sum += s.nextInt();
nums[i] = sum - nums[0];
}
Arrays.sort(nums);
System.out.println("finish " + nums[k - 1]);
}
}
| Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 11 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | fde2ee27c12f79124765a1e88c57479a | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 256 megabytes | import java.sql.SQLSyntaxErrorException;
import java.util.*;
import java.io.*;
import java.util.stream.StreamSupport;
public class Solution {
static int mod = 998244353;
public static void main(String str[]) throws IOException{
// Reader sc = new Reader();
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out));
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int[] arr = new int[n];
arr[0] = fun(1,2, sc, output);
arr[1] = fun(1,3, sc, output);
arr[2] = fun(2,3, sc, output);
int y = arr[2]-arr[1];
arr[0] = (arr[0]-y)/2;
arr[1] -=arr[0];
arr[2] -=arr[1];
for(int i=3;i<n;i++){
arr[i] = fun(1,i+1,sc,output) - arr[0];
}
Arrays.sort(arr);
output.write("finish "+arr[k-1]+"\n");
output.flush();
}
static int fun(int x, int y, Scanner sc, BufferedWriter output) throws IOException{
output.write("and "+x+" "+y+"\n");
output.flush();
int a = sc.nextInt();
output.write("or "+x+" "+y+"\n");
output.flush();
a+= sc.nextInt();
return a;
}
static class Pair {
int ind;
long weight;
Pair(int i, long w) {
ind = i;
weight = w;
}
}
static class Node{
int ind;
long total = -1;
int dis = 0;
Map<Integer, Long> map = new HashMap<>();
ArrayList<Pair> al = new ArrayList<>();
Node(int i){
ind =i;
}
}
static int maxHeight(List<Integer> wallPositions, List<Integer> wallHeights){
int ans = 0;
int n = wallHeights.size();
for(int i=1;i<n;i++){
int ind1 = wallPositions.get(i-1);
int ind2 = wallPositions.get(i);
if(ind2-ind1==1) continue;
int x = wallHeights.get(i-1);
int y = wallHeights.get(i);
int index = (y-x+ind1+ind2)/2;
if(index<=ind1){
index = ind1+1;
}
else if(index>=ind2){
index = ind2-1;
}
ans = Math.max(ans, Math.min(x+(index-ind1),y+(ind2-index)));
}
return ans;
}
// 3
// 2 1 1
// 2 3 1
// 3 4 1
// 4
// 2
public static ArrayList<Integer> primeFactors(int n)
{
// Print the number of 2s that divide n
ArrayList<Integer> al = new ArrayList<>();
while (n%2==0)
{
al.add(2);
n /= 2;
}
// n must be odd at this point. So we can
// skip one element (Note i = i +2)
for (int i = 3; i <= Math.sqrt(n); i+= 2)
{
// While i divides n, print i and divide n
while (n%i == 0)
{
al.add(i);
n /= i;
}
}
// This condition is to handle the case whien
// n is a prime number greater than 2
if (n > 2)
al.add(n);
return al;
}
static void bfs(Graph[] g, int ind, boolean vis[], ArrayList<Node> al, Set<Integer> set){
vis[ind] = true;
set.add(ind);
for(int i: g[ind].pq){
if(!vis[i]) bfs(g,i,vis,al,set);
}
g[ind].set = set;
}
// static class tempSort implements Comparator<Node> {
// // Used for sorting in ascending order of
// // roll number
// public int compare(Node a, Node b) {
// return a.size - b.size;
// }
// }
static long divide(long p, long q, long mod)
{
long expo = mod - 2;
while (expo != 0)
{
if ((expo & 1) == 1)
{
// long temp = p;
// System.out.println("zero--> "+temp+" "+q);
p = (p * q) % mod;
// if(p<0){
// System.out.println("one--> "+temp+" "+q);
// }
}
q = (q * q) % mod;
// if(q<0){
// System.out.println("two--> "+p+" "+q);
// }
expo >>= 1;
}
return p;
}
static class Graph{
int ind;
ArrayList<Integer> pq = new ArrayList<>();
Set<Integer> set;
boolean b = false;
public Graph(int a){
ind = a;
}
}
//
// static class Pair{
// int a=0;
// int b=0;
// int in = 0;
// int ac = 0;
// int ex = 0;
// }
long fun2(ArrayList<Integer> arr, int x){
ArrayList<ArrayList> al = new ArrayList<>();
ArrayList<Integer> curr = new ArrayList<>();
fun(arr, x, al, curr, 0);
if(al.size()==0) return 0;
int max = 0;
for(ArrayList<Integer> i: al){
if(i.size()>max) max = i.size();
}
for(int i=0;i<al.size();i++){
if(al.get(i).size()!=max){
al.remove(i);
i--;
}
}
for(ArrayList<Integer> i: al){
Collections.sort(al, Collections.reverseOrder());
}
long ans = 0;
for(ArrayList<Integer> i: al){
long temp = 0;
for(int j: i){
temp*=10;
temp+=j;
}
if(ans<temp) ans = temp;
}
return ans;
}
void fun(ArrayList<Integer> arr, int x, ArrayList<ArrayList> al, ArrayList<Integer> curr, int i){
if(x<0) return ;
if(x==0) {
al.add(curr);
return;
}
for(int j=i;j<arr.size();j++){
ArrayList<Integer> temp = new ArrayList<>(curr);
fun(arr, x-arr.get(j), al, temp, j);
}
}
// Returns n^(-1) mod p
static long modInverse(long n, long p)
{
return (long)power(n, p - 2, p);
}
// Returns nCr % p using Fermat's
// little theorem.
static long nCrModPFermat(int n, int r,
int p, long[] fac)
{
if (n<r)
return 0;
// Base case
if (r == 0)
return 1;
// Fill factorial array so that we
// can find all factorial of r, n
// and n-r
long x = modInverse(fac[r], p);
long y = modInverse(fac[n - r], p);
return (fac[n] * x
% p * y
% p)
% p;
}
static long[] sum(String[] str){
int n = str[0].length();
long ans[] = new long[n];
for(String s: str){
for(int i=0;i<n;i++) ans[i]+=s.charAt(i);
}
return ans;
}
// static class tSort implements Comparator<Pair>{
//
// public int compare(Pair s1, Pair s2) {
// if (s1.b < s2.b)
// return -1;
// else if (s1.b > s2.b)
// return 1;
// return 0;
// }
// }
// static boolean checkCycle(Tree[] arr, boolean[] visited, int curr, int node){
// if(curr==node && visited[curr]) return true;
// if(visited[curr]) return false;
// visited[curr] = true;
// for(int i: arr[curr].al){
// if(checkCycle(arr, visited, i, node)) return true;
// }
// return false;
// }
// static boolean allCombinations(int n){ //Global round 15
// int three2n = 1;
// for (int i = 1; i <= n; i++)
// three2n *= 3;
//
// for (int k = 1; k < three2n; k++) {
// int k_cp = k;
// int sum = 0;
// for (int i = 1; i <= n; i++) {
// int s = k_cp % 3;
// k_cp /= 3;
// if (s == 2) s = -1;
// sum += s * a[i];
// }
// if (sum == 0) {
// return true;
// }
// }
// return false;
// }
static ArrayList<String> fun( int curr, int n, char c){
int len = n-curr;
if(len==0) return null;
ArrayList<String> al = new ArrayList<>();
if(len==1){
al.add(c+"");
return al;
}
String ss = "";
for(int i=0;i<len/2;i++){
ss+=c;
}
ArrayList<String> one = fun(len/2+curr, n, (char)(c+1));
for(String str: one){
al.add(str+ss);
al.add(ss+str);
}
return al;
}
static ArrayList convert(int x, int k){
ArrayList<Integer> al = new ArrayList<>();
if(x>0) {
while (x > 0) {
al.add(x % k);
x /= k;
}
}
else al.add(0);
return al;
}
static int max(int x, int y, int z){
int ans = Math.max(x,y);
ans = Math.max(ans, z);
return ans;
}
static int min(int x, int y, int z){
int ans = Math.min(x,y);
ans = Math.min(ans, z);
return ans;
}
// static long treeTraversal(Tree arr[], int parent, int x){
// long tot = 0;
// for(int i: arr[x].al){
// if(i!=parent){
// tot+=treeTraversal(arr, x, i);
// }
// }
// arr[x].child = tot;
// if(arr[x].child==0) arr[x].child = 1;
// return tot+1;
// }
public static int primeFactors(int n, int k)
{
int ans = 0;
while (n%2==0)
{
ans++;
if(ans>=k) return k;
n /= 2;
}
for (int i = 3; i <= Math.sqrt(n); i+= 2)
{
while (n%i == 0)
{
ans++;
n /= i;
if(ans>=k) return k;
}
}
if (n > 2) ans++;
return ans;
}
static int binaryLow(ArrayList<Integer> arr, int x, int s, int e){
if(s>=e){
if(arr.get(s)>=x) return s;
else return s+1;
}
int m = (s+e)/2;
if(arr.get(m)==x) return m;
if(arr.get(m)>x) return binaryLow(arr,x,s,m);
if(arr.get(m)<x) return binaryLow(arr,x,m+1,e);
return 0;
}
static int binaryLow(int[] arr, int x, int s, int e){
if(s>=e){
if(arr[s]>=x) return s;
else return s+1;
}
int m = (s+e)/2;
if(arr[m]==x) return m;
if(arr[m]>x) return binaryLow(arr,x,s,m);
if(arr[m]<x) return binaryLow(arr,x,m+1,e);
return 0;
}
static int binaryHigh(int[] arr, int x, int s, int e){
if(s>=e){
if(arr[s]<=x) return s;
else return s-1;
}
int m = (s+e)/2;
if(arr[m]==x) return m;
if(arr[m]>x) return binaryHigh(arr,x,s,m-1);
if(arr[m]<x) return binaryHigh(arr,x,m+1,e);
return 0;
}
// static void arri(int arr[], int n, Reader sc) throws IOException{
// for(int i=0;i<n;i++){
// arr[i] = sc.nextInt();
// }
// }
// static void arrl(long arr[], int n, Reader sc) throws IOException{
// for(int i=0;i<n;i++){
// arr[i] = sc.nextLong();
// }
static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
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
if (x == 0)
return 0; // In case x is divisible by p;
while (y > 0)
{
// If y is odd, multiply x with result
if ((y & 1) != 0)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res%p;
}
// static boolean dfs(Tree node, boolean[] visited, int parent, ArrayList<Tree> tt){
// visited[node.a] = true;
// boolean b = false;
// for(int i: node.al){
// if(tt.get(i).a!=parent){
// if(visited[tt.get(i).a]) return true;
// b|= dfs(tt.get(i), visited, node.a, tt);
// }
// }
// return b;
// }
// static class SortbyI implements Comparator<Pair> {
// // Used for sorting in ascending order of
// // roll number
// public int compare(Pair a, Pair b)
// {
// if(a.a>=b.a) return 1;
// else return -1;
// }
// }
// static class SortbyD implements Comparator<Pair> {
// // Used for sorting in ascending order of
// // roll number
// public int compare(Pair a, Pair b)
// {
// if(a.a<b.a) return 1;
// else if(a.a==b.b && a.b>b.b) return 1;
// else return -1;
// }
// }
// static int binarySearch(ArrayList<Pair> a, int x, int s, int e){
// if(s>=e){
// if(x<=a.get(s).b) return s;
// else return s+1;
// }
// int mid = (e+s)/2;
// if(a.get(mid).b<x){
// return binarySearch(a, x, mid+1, e);
// }
// else return binarySearch(a,x,s, mid);
// }
// static class Edge{
// int a;
// int b;
// int c;
// int sec;
// Edge(int a, int b, int c, int sec){
// this.a = a;
// this.b = b;
// this.c = c;
// this.sec = sec;
// }
//
// }
static class Tree{
int a;
ArrayList<Tree> al = new ArrayList<>();
Tree(int a){
this.a = a;
}
}
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') {
if (cnt != 0) {
break;
}
else {
continue;
}
}
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();
}
}
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 ArrayList<Integer> sieveOfEratosthenes(int n)
{
ArrayList<Integer> al = new ArrayList<>();
// 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.
boolean prime[] = new boolean[n + 1];
for (int i = 0; i <= n; i++)
prime[i] = true;
for (int p = 2; p * p <= n; p++)
{
// If prime[p] is not changed, then it is a
// prime
if (prime[p] == true)
{
// Update all multiples of p
for (int i = p * p; i <= n; i += p)
prime[i] = false;
}
}
// Print all prime numbers
for (int i = 2; i <= n; i++)
{
if (prime[i] == true)
al.add(i);
}
return al;
}
} | Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 11 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output | |
PASSED | db6b3cac5203f0073c59d653a4f68d66 | train_107.jsonl | 1630247700 | This is an interactive taskWilliam has a certain sequence of integers $$$a_1, a_2, \dots, a_n$$$ in his mind, but due to security concerns, he does not want to reveal it to you completely. William is ready to respond to no more than $$$2 \cdot n$$$ of the following questions: What is the result of a bitwise AND of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) What is the result of a bitwise OR of two items with indices $$$i$$$ and $$$j$$$ ($$$i \neq j$$$) You can ask William these questions and you need to find the $$$k$$$-th smallest number of the sequence.Formally the $$$k$$$-th smallest number is equal to the number at the $$$k$$$-th place in a 1-indexed array sorted in non-decreasing order. For example in array $$$[5, 3, 3, 10, 1]$$$ $$$4$$$th smallest number is equal to $$$5$$$, and $$$2$$$nd and $$$3$$$rd are $$$3$$$. | 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.StringTokenizer;
public class taskd {
public static void main(String[] args) {
FastScanner in = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt(), k = in.nextInt();
int a[] = new int[n];
int a01 = askSum(0, 1, in, out);
int a12 = askSum(1, 2, in, out);
int a02 = askSum(0, 2, in, out);
a[0] = (a01 + a02 - a12) / 2;
a[1] = a01 - a[0];
a[2] = a02 - a[0];
for (int i = 3; i < n; i++) {
int x = askSum(i-1, i, in, out);
a[i] = x - a[i-1];
}
ArrayList<Integer> aa = new ArrayList<>();
for (int i = 0; i < n; i++) aa.add(a[i]);
Collections.sort(aa);
out.printf("finish %d\n", aa.get(k-1));
out.flush();
}
static int askSum(int i, int j, FastScanner in, PrintWriter out) {
out.printf("and %d %d\n", i+1, j+1);
out.flush();
int and = in.nextInt();
out.printf("or %d %d\n", i+1, j+1);
out.flush();
int or = in.nextInt();
return and + or;
}
static class FastScanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tok = new StringTokenizer("");
String next() {
while(!tok.hasMoreTokens()) {
try {
tok = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
}
return tok.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
float nextFloat() {
return Float.parseFloat(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
}
| Java | ["7 6\n\n2\n\n7"] | 2 seconds | ["and 2 5\n\nor 5 6\n\nfinish 5"] | NoteIn the example, the hidden sequence is $$$[1, 6, 4, 2, 3, 5, 4]$$$.Below is the interaction in the example.Query (contestant's program)Response (interactor)Notesand 2 52$$$a_2=6$$$, $$$a_5=3$$$. Interactor returns bitwise AND of the given numbers.or 5 67$$$a_5=3$$$, $$$a_6=5$$$. Interactor returns bitwise OR of the given numbers.finish 5$$$5$$$ is the correct answer. Note that you must find the value and not the index of the kth smallest number. | Java 11 | standard input | [
"bitmasks",
"constructive algorithms",
"interactive",
"math"
] | 7fb8b73fa2948b360644d40b7035ce4a | It is guaranteed that for each element in a sequence the condition $$$0 \le a_i \le 10^9$$$ is satisfied. | 1,800 | null | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.