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 | 69086bbc008abde895ce8e64f61a736e | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
private static final boolean OFFLINE_WITHOUT_FILES = false;
double[] sin;
double[] cos;
double Get(int n, double angle, double R, double alpha) {
double maxx = -1e9;
double maxy = -1e9;
double minx = 1e9;
double miny = 1e9;
double s = Math.sin(angle);
double c = Math.cos(angle);
for (int i = 0; i < n; i++) {
double x = (sin[i] * c + cos[i] * s) * R;
double y = (cos[i] * c - sin[i] * s) * R;
maxx = Math.max(x, maxx);
minx = Math.min(x, minx);
maxy = Math.max(y, maxy);
miny = Math.min(y, miny);
}
return Math.max(maxx - minx, maxy - miny);
}
void Solve() throws IOException {
int t = readInt();
while (t-- > 0) {
int n = readInt() * 2;
double left = 0;
double alpha = 2 * Math.PI / n;
double right = alpha;
double R = 0.5 / Math.sin(alpha / 2);
double mid1 = 0;
double mid2 = 0;
sin = new double[n];
cos = new double[n];
for (int i = 0; i < n; i++) {
sin[i] = Math.sin(i * alpha);
cos[i] = Math.cos(i * alpha);
}
out.print(Math.min(Get(n, alpha / 2, R, alpha), Get(n, alpha / 4, R, alpha)) + "\n");
}
}
public static void main(String[] args) {
new Main();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
Main() {
try {
long timeStart = System.currentTimeMillis();
if (ONLINE_JUDGE || OFFLINE_WITHOUT_FILES) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
tok = new StringTokenizer("");
Solve();
out.close();
long timeEnd = System.currentTimeMillis();
System.err.println("time = " + (timeEnd - timeStart) + " compiled");
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
String readLine() throws IOException {
return in.readLine();
}
String delimiter = " ";
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
String nextLine = readLine();
if (nextLine == null)
return null;
tok = new StringTokenizer(nextLine);
}
return tok.nextToken(delimiter);
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
} | Java | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | c9d239475747d46bfd4c67a40da77784 | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
private static final boolean OFFLINE_WITHOUT_FILES = false;
double[] sin;
double[] cos;
double Get(int n, double angle, double R, double alpha) {
double maxx = -1e9;
double maxy = -1e9;
double minx = 1e9;
double miny = 1e9;
double s = Math.sin(angle);
double c = Math.cos(angle);
for (int i = 0; i < n; i++) {
double x = (sin[i] * c + cos[i] * s) * R;
double y = (cos[i] * c - sin[i] * s) * R;
maxx = Math.max(x, maxx);
minx = Math.min(x, minx);
maxy = Math.max(y, maxy);
miny = Math.min(y, miny);
}
return Math.max(maxx - minx, maxy - miny);
}
void Solve() throws IOException {
int t = readInt();
while (t-- > 0) {
int n = readInt() * 2;
double left = 0;
double alpha = 2 * Math.PI / n;
double right = alpha;
double R = 0.5 / Math.sin(alpha / 2);
double mid1 = 0;
double mid2 = 0;
sin = new double[n];
cos = new double[n];
for (int i = 0; i < n; i++) {
sin[i] = Math.sin(i * alpha);
cos[i] = Math.cos(i * alpha);
}
out.print(Get(n, alpha / 2, R, alpha) + "\n");
}
}
public static void main(String[] args) {
new Main();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
Main() {
try {
long timeStart = System.currentTimeMillis();
if (ONLINE_JUDGE || OFFLINE_WITHOUT_FILES) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
tok = new StringTokenizer("");
Solve();
out.close();
long timeEnd = System.currentTimeMillis();
System.err.println("time = " + (timeEnd - timeStart) + " compiled");
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
String readLine() throws IOException {
return in.readLine();
}
String delimiter = " ";
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
String nextLine = readLine();
if (nextLine == null)
return null;
tok = new StringTokenizer(nextLine);
}
return tok.nextToken(delimiter);
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
} | Java | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | 9c91b37c054a336cb9d57895e30b51cc | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
private static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
private static final boolean OFFLINE_WITHOUT_FILES = false;
double[] sin;
double[] cos;
double Get(int n, double angle, double R, double alpha) {
double maxx = -1e9;
double maxy = -1e9;
double minx = 1e9;
double miny = 1e9;
double s = Math.sin(angle);
double c = Math.cos(angle);
for (int i = 0; i < n; i++) {
double x = (sin[i] * c + cos[i] * s) * R;
double y = (cos[i] * c - sin[i] * s) * R;
maxx = Math.max(x, maxx);
minx = Math.min(x, minx);
maxy = Math.max(y, maxy);
miny = Math.min(y, miny);
}
return Math.max(maxx - minx, maxy - miny);
}
void Solve() throws IOException {
int t = readInt();
while (t-- > 0) {
int n = readInt() * 2;
double left = 0;
double alpha = 2 * Math.PI / n;
double right = alpha;
double R = 0.5 / Math.sin(alpha / 2);
double mid1 = 0;
double mid2 = 0;
sin = new double[n];
cos = new double[n];
for (int i = 0; i < n; i++) {
sin[i] = Math.sin(i * alpha);
cos[i] = Math.cos(i * alpha);
}
for (int itr = 0; itr < 50; itr++) {
mid1 = left + (right - left) / 3;
mid2 = right - (right - left) / 3;
if (Get(n, mid1, R, alpha) < Get(n, mid2, R, alpha)) {
right = mid2;
} else {
left = mid1;
}
}
out.print(Get(n, (mid1 + mid2) / 2, R, alpha) + "\n");
}
}
public static void main(String[] args) {
new Main();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
Main() {
try {
long timeStart = System.currentTimeMillis();
if (ONLINE_JUDGE || OFFLINE_WITHOUT_FILES) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
tok = new StringTokenizer("");
Solve();
out.close();
long timeEnd = System.currentTimeMillis();
System.err.println("time = " + (timeEnd - timeStart) + " compiled");
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
String readLine() throws IOException {
return in.readLine();
}
String delimiter = " ";
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
String nextLine = readLine();
if (nextLine == null)
return null;
tok = new StringTokenizer(nextLine);
}
return tok.nextToken(delimiter);
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
} | Java | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | 6f198268ad35ab0af745398157b0d0d8 | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int T = sc.nextInt();
for(int t = 0; t<T; t++){
int n = sc.nextInt() * 2;
if(n == 4){
out.println(1); continue;
}
double angle = Math.toRadians((double)(180 * (n - 2)) / (n *2));
//out.println(angle);
double a = Math.tan(angle) * 0.5;
//out.println(a);
out.println(2 * a);
}
out.flush();
}
}
| Java | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | d4bd7991d308938214ed5f3d5b07c540 | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.awt.Point;
public class Main {
//static final long MOD = 998244353L;
//static final long INF = 1000000000000000007L;
static final long MOD = 1000000007L;
static final int INF = 1000000007;
public static void main(String[] args) {
FastScanner sc = new FastScanner();
PrintWriter pw = new PrintWriter(System.out);
int Q = sc.ni();
for (int q = 0; q < Q; q++) {
int N = 2*sc.ni();
double angle = Math.PI/N;
double side = 1/Math.tan(angle);
pw.println(side);
}
pw.close();
}
public static long dist(long[] p1, long[] p2) {
return (Math.abs(p2[0]-p1[0])+Math.abs(p2[1]-p1[1]));
}
//Find the GCD of two numbers
public static long gcd(long a, long b) {
if (a < b) return gcd(b,a);
if (b == 0)
return a;
else
return gcd(b,a%b);
}
//Fast exponentiation (x^y mod m)
public static long power(long x, long y, long m) {
if (y < 0) return 0L;
long ans = 1;
x %= m;
while (y > 0) {
if(y % 2 == 1)
ans = (ans * x) % m;
y /= 2;
x = (x * x) % m;
}
return ans;
}
public static int[] shuffle(int[] array) {
Random rgen = new Random();
for (int i = 0; i < array.length; i++) {
int randomPosition = rgen.nextInt(array.length);
int temp = array[i];
array[i] = array[randomPosition];
array[randomPosition] = temp;
}
return array;
}
public static long[] shuffle(long[] array) {
Random rgen = new Random();
for (int i = 0; i < array.length; i++) {
int randomPosition = rgen.nextInt(array.length);
long temp = array[i];
array[i] = array[randomPosition];
array[randomPosition] = temp;
}
return array;
}
public static int[][] shuffle(int[][] array) {
Random rgen = new Random();
for (int i = 0; i < array.length; i++) {
int randomPosition = rgen.nextInt(array.length);
int[] temp = array[i];
array[i] = array[randomPosition];
array[randomPosition] = temp;
}
return array;
}
public static int[][] sort(int[][] array) {
//Sort an array (immune to quicksort TLE)
Arrays.sort(array, new Comparator<int[]>() {
@Override
public int compare(int[] a, int[] b) {
return a[0]-b[0]; //ascending order
}
});
return array;
}
public static long[][] sort(long[][] array) {
//Sort an array (immune to quicksort TLE)
Random rgen = new Random();
for (int i = 0; i < array.length; i++) {
int randomPosition = rgen.nextInt(array.length);
long[] temp = array[i];
array[i] = array[randomPosition];
array[randomPosition] = temp;
}
Arrays.sort(array, new Comparator<long[]>() {
@Override
public int compare(long[] a, long[] b) {
if (a[0] < b[0])
return -1;
else
return 1;
}
});
return array;
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int 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 | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | 30f592ee8e4faae9cf7af89e83fe0cae | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 256 megabytes | import java.util.*;
import java.io.*;
import java.text.*;
/**
*
* @author alanl
*/
public class Main{
static BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
public static void main(String[] args) throws IOException{
int t = readInt();
while(t-->0){
int n = readInt();
System.out.println(1/(Math.tan(Math.PI/2.0/n)));
}
}
static String next () throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(input.readLine().trim());
return st.nextToken();
}
static long readLong () throws IOException {
return Long.parseLong(next());
}
static int readInt () throws IOException {
return Integer.parseInt(next());
}
static double readDouble () throws IOException {
return Double.parseDouble(next());
}
static char readChar () throws IOException {
return next().charAt(0);
}
static String readLine () throws IOException {
return input.readLine().trim();
}
}
| Java | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | bbadcd91ea476faa82c16cca3b775eb2 | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 256 megabytes | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.StringTokenizer;
public class Main {
public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
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[] nextSArray() {
String sr[] = null;
try {
sr = br.readLine().trim().split(" ");
} catch (IOException e) {
e.printStackTrace();
}
return sr;
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
//
int t1 = sc.nextInt();
for (int t = 0; t < t1; ++t) {
int n = sc.nextInt();
double side=1/(Math.tan(3.1415926535897/(2*n)));
out.println(side);
}
out.close();
}
}
// out.println(al.toString().replaceAll("[\\[|\\]|,]","")); | Java | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | f0aa9f7d88b172f3e5a6129bf3df76fa | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
static int MOD = 1000000007;
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());
}
long rl() throws IOException {
return Long.parseLong(br.readLine());
}
int[] ril() throws IOException {
String[] tokens = br.readLine().split(" ");
int[] A = new int[tokens.length];
for (int i = 0; i < A.length; i++)
A[i] = Integer.parseInt(tokens[i]);
return A;
}
long[] rll() throws IOException {
String[] tokens = br.readLine().split(" ");
long[] A = new long[tokens.length];
for (int i = 0; i < A.length; i++)
A[i] = Long.parseLong(tokens[i]);
return A;
}
void solve() throws IOException {
int t = ri();
for (int ti = 0; ti < t; ti++) {
int n = ri();
n *= 2;
double angle = Math.PI - Math.PI * (n - 2) / n;
double len = 0;
for (double a = angle; a < Math.PI / 2; a += angle) {
len += Math.cos(a);
}
len = len * 2 + 1;
pw.println(len);
}
}
} | Java | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | 5326a9b2d7f74d29aed7d4993ee9832f | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class c87 implements Runnable{
public static void main(String[] args) {
try{
new Thread(null, new c87(), "process", 1<<26).start();
}
catch(Exception e){
System.out.println(e);
}
}
public void run() {
FastReader scan = new FastReader();
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
//PrintWriter out = new PrintWriter("file.out");
Task solver = new Task();
int t = scan.nextInt();
//int t = 1;
for(int i = 1; i <= t; i++) solver.solve(i, scan, out);
out.close();
}
static class Task {
static final int inf = Integer.MAX_VALUE;
public void solve(int testNumber, FastReader sc, PrintWriter out) {
int N = sc.nextInt();
if(N % 2 == 0) {
double a = 1 / Math.tan(Math.PI / (N*2));
out.println(a);
} else {
double r = 1 / Math.sin(Math.PI / (N*2));
out.println(r);
}
}
}
static long binpow(long a, long b, long m) {
a %= m;
long res = 1;
while (b > 0) {
if ((b & 1) == 1)
res = res * a % m;
a = a * a % m;
b >>= 1;
}
return res;
}
static void sort(int[] x){
shuffle(x);
Arrays.sort(x);
}
static void sort(long[] x){
shuffle(x);
Arrays.sort(x);
}
static class tup implements Comparable<tup>, Comparator<tup>{
int a, b;
tup(int a,int b){
this.a=a;
this.b=b;
}
public tup() {
}
@Override
public int compareTo(tup o){
return Integer.compare(o.b,b);
}
@Override
public int compare(tup o1, tup o2) {
return Integer.compare(o1.b, o2.b);
}
@Override
public int hashCode() {
return Objects.hash(a, b);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
tup other = (tup) obj;
return a==other.a && b==other.b;
}
@Override
public String toString() {
return a + " " + b;
}
}
static void shuffle(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
static void shuffle(long[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
long temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File(s)));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | ec4628e63022eda33b3ad12e78f994bd | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 256 megabytes | import java.util.Scanner;
import java.lang.Math;
public class simple_polygon_embedding{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
double n,ans,theta;
int t;
t=sc.nextInt();
while(t>0){
t--;
n=sc.nextInt();
theta=90/n;
ans=1/Math.tan(Math.toRadians(theta));
System.out.println(ans);
}
}
} | Java | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | 8e34d43726004f99df08bc7af35ee491 | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class Main {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static FastReader s = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
private static int[] rai(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = s.nextInt();
}
return arr;
}
private static long[] ral(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = s.nextLong();
}
return arr;
}
private static int ri() {
return s.nextInt();
}
private static long rl() {
return s.nextLong();
}
private static String rs() {
return s.next();
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
static int bsearch(List<Long> list,long num)
{
int l=0,r=list.size()-1;
while(l<=r)
{
int mid=(l+r)/2;
if(list.get(mid)<=num)
{
if(mid==list.size()-1)
{
return mid;
}
if(list.get(mid+1)>num)
{
return mid;
}
else
{
l=mid+1;
}
}
else
{
r=mid-1;
}
}
return -1;
}
public static void main(String[] args) {
int t=ri();
StringBuilder ans=new StringBuilder();
while(t-->0)
{
int n=ri();
double res=1/Math.tan(Math.PI/((double)2*n));
ans.append(res).append("\n");
}
out.print(ans.toString());
out.flush();
}
}
| Java | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | 320b3df8cb7e46a2e25faba0d811c326 | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 256 megabytes | import javax.swing.text.html.StyleSheet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import java.util.StringTokenizer;
public class Codeforces {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
static FastReader s = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
private static int[] rai(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = s.nextInt();
}
return arr;
}
private static long[] ral(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = s.nextLong();
}
return arr;
}
private static int ri() {
return s.nextInt();
}
private static long rl() {
return s.nextLong();
}
private static String rs() {
return s.next();
}
static int search(List<Integer> array,int target,int flag)
{
int left=0,right=array.size()-1;
while(left<=right)
{
int mid=(left+right)/2;
if(array.get(mid)>=target)
{
if((mid==0 && flag==0)||(mid==array.size()-1 && flag==1))
{
return mid;
}
else if((flag==0 && array.get(mid-1)<target ) || (flag==1 && array.get(mid+1)!=target ))
{
return mid;
}
else
{
if(flag==0)
{right=mid-1;
}
else
{
left=mid+1;
}
}
}
else
{
if(array.get(mid)>target)
{
right=mid-1;
}
else
{
left=mid+1;
}
}
}
return -1;
}
public static void main(String[] args) {
int t=ri();
StringBuilder ans=new StringBuilder();
while(t-->0)
{
double n=ri();
double res=1D/(2*Math.tan((Math.PI)/(2*n)));
ans.append(res*2).append("\n");
}
out.print(ans.toString());
out.flush();
}
}
class MinHeap {
List<Integer> heap = new ArrayList<Integer>();
public MinHeap(List<Integer> array) {
heap = buildHeap(array);
}
public List<Integer> buildHeap(List<Integer> array) {
// Write your code here.
int lastParent=(array.size()-2)/2;
for(int i=lastParent;i>=0;i--)
{
siftDown(i,array.size()-1,array);
}
return array;
}
public void siftDown(int currentIdx, int endIdx, List<Integer> heap) {
// Write your code here.
int left=currentIdx*2+1;
while(left<=endIdx)
{
int right=-1;
if(currentIdx*2+2<=endIdx)
{
right=currentIdx*2+2;
}
int idx=left;
if(right!=-1 && heap.get(right)<heap.get(left))
{
idx=right;
}
if(heap.get(idx)<heap.get(currentIdx))
{
int temp=heap.get(idx);
heap.set(idx,heap.get(currentIdx));
heap.set(currentIdx,temp);
currentIdx=idx;
left=currentIdx*2+1;
}
else
{
break;
}
}
}
public void siftUp(int currentIdx, List<Integer> heap) {
// Write your code here.
int parentIdx=(currentIdx-1)/2;
while(currentIdx>0)
{
if(heap.get(parentIdx)>heap.get(currentIdx))
{
int temp=heap.get(parentIdx);
heap.set(parentIdx,heap.get(currentIdx));
heap.set(currentIdx,temp);
currentIdx=parentIdx;
parentIdx=(currentIdx-1)/2;
}
else
{
break;
}
}
}
public int peek() {
// Write your code here.
// if(this.heap.size()==0)
// {
// return -1;
// }
return heap.get(0);
}
public int remove() {
// Write your code here.
int temp=heap.get(0);
heap.set(0,heap.get(heap.size()-1));
heap.set(heap.size()-1,temp);
int val=heap.get(heap.size()-1);
heap.remove(heap.size()-1);
siftDown(0,heap.size()-1,heap);
return val;
}
public void remove(int ind) {
// Write your code here.
int temp=heap.get(ind);
heap.set(ind,heap.get(heap.size()-1));
heap.set(heap.size()-1,temp);
int val=heap.get(heap.size()-1);
heap.remove(heap.size()-1);
siftDown(ind,heap.size()-1,heap);
// return val;
}
public void insert(int value) {
// Write your code here.
heap.add(value);
int index=heap.size()-1;
siftUp(index,heap);
}
} | Java | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | 5f65a3cd11814ba4acaeb6cf6cf959ab | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 256 megabytes | import java.util.*;
import java.io.*;
public class solution {
public static void main(String[] args) {
FastReader in = new FastReader();
int t = in.nextInt();
while(t-- > 0) {
int n = in.nextInt();
double ans = 1 / (Math.tan(Math.PI/(2*n)));
System.out.println(ans);
}
}
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 | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | 88eece4e4e067d36523d50a7ede6b491 | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class CF1354C {
public static void main(String[] args) {
FastReader input = new FastReader();
int t = input.nextInt();
while (t > 0){
int n = input.nextInt();
double sides = n * 2;
double angle = 360.0/sides;
angle = angle * (Math.PI / 180.0);
double halfAngle = angle / 2;
double x = 0.5 / (Math.tan(halfAngle));
System.out.printf("%.9f\n",x * 2);
t--;
}
}
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 | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | 5902ac735b9b18ea121e0970fe90ac5a | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 256 megabytes | import java.util.Scanner;
public class polygonembed {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int T = in.nextInt();
for (int i = 0; i < T; i++) {
int n = in.nextInt();
double extAng = Math.PI/n;
double sum = 0;
for (int s = 1; s < n/2; s++) {
sum += Math.sin(extAng * s);
}
System.out.println(sum*2+1);
}
in.close();
}
}
| Java | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | e4ca546ee2bacd1ef60b54afa3da195f | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 256 megabytes | import java.util.*;
import java.io.*;
public class C1_1354 {
public static double f(double a, double n) {
return (float) (2 * a * Math.sin((((n - 2) * 90) / (2 * n)) * 3.14159 / 180));
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int t = sc.nextInt();
while(t-->0) {
int n = sc.nextInt();
double ans = 1.0 / (Math.tan((180.0 / (2 * n)) * Math.PI / 180.0));
pw.println(ans);
}
pw.flush();
}
public 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[] nextIntArray(int n) throws IOException {
int[] array = new int[n];
for (int i = 0; i < n; i++)
array[i] = nextInt();
return array;
}
public Integer[] nextIntegerArray(int n) throws IOException {
Integer[] array = new Integer[n];
for (int i = 0; i < n; i++)
array[i] = new Integer(nextInt());
return array;
}
public long[] nextLongArray(int n) throws IOException {
long[] array = new long[n];
for (int i = 0; i < n; i++)
array[i] = nextLong();
return array;
}
public double[] nextDoubleArray(int n) throws IOException {
double[] array = new double[n];
for (int i = 0; i < n; i++)
array[i] = nextDouble();
return array;
}
public static void shuffle(int[] a) {
int n = a.length;
Random rand = new Random();
for (int i = 0; i < n; i++) {
int tmpIdx = rand.nextInt(n);
int tmp = a[i];
a[i] = a[tmpIdx];
a[tmpIdx] = tmp;
}
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
}
| Java | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | 4ecf309a8897ea835fd48bc2c115ea28 | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
//BigInteger A;
//A= BigInteger.valueOf(54);
//ArrayList<Integer> a=new ArrayList<>();
//TreeSet<Integer> ts=new TreeSet<>();
//HashMap<Integer,Integer> hm=new HashMap<>();
//PriorityQueue<Integer> pq=new PriorityQueue<>();
public final class CF
{
public static void main(String[]args)throws IOException
{
int K=(int)Math.pow(10,9)+7;
FastReader ob=new FastReader();
StringBuffer sb=new StringBuffer();
int t=ob.nextInt();
while(t-->0)
{
double n=ob.nextDouble();
double ans=1/(Math.tan(Math.toRadians(180/(2*n))));
sb.append(ans+"\n");
}
System.out.println(sb);
}
}
class Pair
{
int x,y;
Pair(int x,int y)
{
this.x=x;
this.y=y;
}
}
class PairComparator implements Comparator<Pair>
{
public int compare(Pair a,Pair b)
{
return a.y-b.y;
}
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public String nextLine()
{
String s="";
try {
s=br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
} | Java | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | 476c302e2d42a93b21f4c57406cc62cb | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 256 megabytes | /**
* Author: Nirav Talaviya
*/
import java.io.*;
import java.util.*;
public class C1354 {
static BufferedReader br;
static PrintWriter out;
static double degreetoradian(double degree){
return (Math.PI*degree)/(double)180;
}
static void solve() throws IOException {
int t = readInt();
while(t-->0){
int n = readInt();
double in = (double)360 / (double)(2*n);
in = 180 - in;
in = in / 2;
System.out.println(Math.tan(degreetoradian(in)));
}
}
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
static int readInt() throws IOException {
return Integer.parseInt(br.readLine());
}
static long readLong() throws IOException {
return Long.parseLong(br.readLine());
}
static int[] readintarr() throws IOException {
String[] ___str___ = br.readLine().split(" ");
int[] ___arr___ = new int[___str___.length];
for (int i = 0; i < ___str___.length; i++) {
___arr___[i] = Integer.parseInt(___str___[i]);
}
return ___arr___;
}
static long[] readlongarr() throws IOException {
String[] ___str___ = br.readLine().split(" ");
long[] ___arr___ = new long[___str___.length];
for (int i = 0; i < ___str___.length; i++) {
___arr___[i] = Long.parseLong(___str___[i]);
}
return ___arr___;
}
}
| Java | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | e7dddf6dc5b28b2483b1001ff293d0c3 | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 256 megabytes | import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int cases = scanner.nextInt();
for(int i = 0 ; i<cases;i++) {
int n = 2*scanner.nextInt();
System.out.println(1.0/Math.tan(Math.PI/n));
}
scanner.close();
}
}
| Java | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | b7ea0ba5918daf8c9f89c6254dd44e01 | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 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;
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 = 1000000007L;
void solve() {
int T = ni();
while (T-- > 0) {
int n = ni() * 2;
out.println(1 / Math.tan(Math.PI / n));
}
}
private int query(int[] a, int[] b, int n) {
int cnt = 0;
for (int i : a)
cnt += i <= n ? 1 : 0;
for (int i : b) {
if (i > 0)
cnt += i <= n ? 1 : 0;
else {
if (-i <= cnt)
cnt--;
}
}
return cnt;
}
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 boolean vis[];
private int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != '
// ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n) {
if (!(isSpaceChar(b)))
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private List<Integer> na2(int n) {
List<Integer> a = new ArrayList<Integer>();
for (int i = 0; i < n; i++)
a.add(ni());
return a;
}
private int[][] na(int n, int m) {
int[][] a = new int[n][];
for (int i = 0; i < n; i++)
a[i] = na(m);
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long[] nl(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nl();
return a;
}
private long[][] nl(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));
}
public class Pair<K, V> {
/**
* Key of this <code>Pair</code>.
*/
private K key;
/**
* Gets the key for this pair.
*
* @return key for this pair
*/
public K getKey() {
return key;
}
/**
* Value of this this <code>Pair</code>.
*/
private V value;
/**
* Gets the value for this pair.
*
* @return value for this pair
*/
public V getValue() {
return value;
}
/**
* Creates a new pair
*
* @param key The key for this pair
* @param value The value to use for this pair
*/
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
/**
* <p>
* <code>String</code> representation of this <code>Pair</code>.
* </p>
*
* <p>
* The default name/value delimiter '=' is always used.
* </p>
*
* @return <code>String</code> representation of this <code>Pair</code>
*/
@Override
public String toString() {
return key + "=" + value;
}
/**
* <p>
* Generate a hash code for this <code>Pair</code>.
* </p>
*
* <p>
* The hash code is calculated using both the name and the value of the
* <code>Pair</code>.
* </p>
*
* @return hash code for this <code>Pair</code>
*/
@Override
public int hashCode() {
// name's hashCode is multiplied by an arbitrary prime number (13)
// in order to make sure there is a difference in the hashCode between
// these two parameters:
// name: a value: aa
// name: aa value: a
return key.hashCode() * 13 + (value == null ? 0 : value.hashCode());
}
/**
* <p>
* Test this <code>Pair</code> for equality with another <code>Object</code>.
* </p>
*
* <p>
* If the <code>Object</code> to be tested is not a <code>Pair</code> or is
* <code>null</code>, then this method returns <code>false</code>.
* </p>
*
* <p>
* Two <code>Pair</code>s are considered equal if and only if both the names and
* values are equal.
* </p>
*
* @param o the <code>Object</code> to test for equality with this
* <code>Pair</code>
* @return <code>true</code> if the given <code>Object</code> is equal to this
* <code>Pair</code> else <code>false</code>
*/
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o instanceof Pair) {
Pair pair = (Pair) o;
if (key != null ? !key.equals(pair.key) : pair.key != null)
return false;
if (value != null ? !value.equals(pair.value) : pair.value != null)
return false;
return true;
}
return false;
}
}
} | Java | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | 4c6ed74e52355f2851b51423a717089b | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 256 megabytes | import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt(), n;
while(t-- > 0) {
n = in.nextInt() * 2;
System.out.println(Math.tan(Math.PI * (n - 2) / n / 2));
}
}
}
| Java | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | a8949ff6315ced6c59a1f7d9fc101273 | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 256 megabytes | import java.io.*;
import java.util.*;
public class Space3{
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int tst = Integer.parseInt(br.readLine());
while(--tst>=0){
int n = Integer.parseInt(br.readLine());
double angle = Math.PI/(2*n);
double ans = Math.tan(angle);
System.out.println(1/ans);
}
}
}
| Java | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | ebea4391b67d2fec72672bb1c1df2b5d | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 256 megabytes | import java.io.*;
import java.text.*;
import java.util.*;
import java.math.*;
public class template {
public static void main(String[] args) throws Exception {
new template().run();
}
public void run() throws Exception {
FastScanner f = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int asdf = f.nextInt();
while(asdf-->0) {
int n = f.nextInt();
out.println(1/Math.tan(Math.PI/n/2));
}
out.flush();
}
static class FastScanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastScanner() {
reader = new BufferedReader(new InputStreamReader(System.in), 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());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
} | Java | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | 7b98c9fbf07554e5e3d111e8ad1a09ae | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 256 megabytes | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class C {
private static class Solver {
private void solve() throws Exception {
int n = in.nextInt();
while (n-- > 0) {
out.println(1 / Math.tan(3.141592653589793 / in.nextInt() / 2));
}
}
}
//--------------------------------------------------------
private static final MyScanner in = new MyScanner(System.in);
private static final PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
public static void main(String[] args) throws Exception {
Solver solver = new Solver();
solver.solve();
out.close();
}
public static class MyScanner {
private final BufferedReader br;
private StringTokenizer st;
public MyScanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
String next() throws IOException {
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
String nextLine() throws IOException {
return br.readLine();
}
}
} | Java | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | a557666532bc9ef3327c18e4de0470e6 | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task11 solver = new Task11();
solver.solve(1, in, out);
out.close();
}
static class Task11 {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int t = in.nextInt();
while (t-- > 0) {
int n = in.nextInt();
double ans = (double) 1 / Math.tan(Math.PI / (2 * n));
out.println(ans);
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | b3afd7f5cea743fc7cedaf4fdd8ffa20 | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 256 megabytes | import java.util.Scanner;
public class C1_1354 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
while (t-- > 0) {
System.out.println((1.0 / Math.tan(Math.PI / (2 * in.nextInt()))) + "");
}
}
}
| Java | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | 71bb1143e54a9bd78df9f7792a258df4 | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 256 megabytes | import java.io.*;
import java.util.*;
import java.lang.Math.*;
public class main{
static Scanner in;
private static void solve(){
double n = in.nextDouble();
n *=2;
double ang = 360/(n*2);
ang = 180-(90+ang);
ang = Math.toRadians(ang);
double ans = Math.tan(ang);
System.out.println(String.format("%.9f",ans));
}
public static void main(String args[]){
in = new Scanner(System.in);
int t = in.nextInt();
while (t-->0)
solve();
}
private static class Read{
BufferedReader br;
StringTokenizer st;
public Read(){
br = new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while (st==null || !st.hasMoreElements()){
try { st = new StringTokenizer(br.readLine()); }
catch (IOException e) { e.printStackTrace(); }
}
return st.nextToken();
}
String line(){
String ans = "";
try { ans = br.readLine(); }
catch (IOException e) { e.printStackTrace(); }
return ans;
}
int nextInt(){return Integer.parseInt(next());}
double nextDouble(){return Double.parseDouble(next());}
long nextLong(){return Long.parseLong(next());}
}
} | Java | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | 1706ecbceaf79168166361cdb9bc7fe8 | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class PolygonEmbedding {
public static void main(String[] args) {
FastReader input=new FastReader();
int t=input.nextInt();
while(t-->0)
{
int n=input.nextInt();
double angle=3.141592653589793238/(2*n);
System.out.println(String.format("%.9f",1/(Math.tan(angle))));
}
}
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 | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | c347bb6b62e024af456d17dc68902992 | train_004.jsonl | 1589707200 | The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, $$$n$$$ is always even, and in C2, $$$n$$$ is always odd.You are given a regular polygon with $$$2 \cdot n$$$ vertices (it's convex and has equal sides and equal angles) and all its sides have length $$$1$$$. Let's name it as $$$2n$$$-gon.Your task is to find the square of the minimum size such that you can embed $$$2n$$$-gon in the square. Embedding $$$2n$$$-gon in the square means that you need to place $$$2n$$$-gon in the square in such way that each point which lies inside or on a border of $$$2n$$$-gon should also lie inside or on a border of the square.You can rotate $$$2n$$$-gon and/or the square. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author out_of_the_box
*/
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);
C1SimplePolygonEmbedding solver = new C1SimplePolygonEmbedding();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class C1SimplePolygonEmbedding {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt();
n <<= 1;
double ang = (Math.PI) * ((double) (n - 2)) / ((double) n);
double theta = ang / 2.0;
double val = Math.tan(theta);
out.println(val);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c)) {
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return nextString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["3\n2\n4\n200"] | 2 seconds | ["1.000000000\n2.414213562\n127.321336469"] | null | Java 8 | standard input | [
"binary search",
"geometry",
"ternary search",
"math"
] | 0c7a476716445c535a61f4e81edc7f75 | The first line contains a single integer $$$T$$$ ($$$1 \le T \le 200$$$) — the number of test cases. Next $$$T$$$ lines contain descriptions of test cases — one per line. Each line contains single even integer $$$n$$$ ($$$2 \le n \le 200$$$). Don't forget you need to embed $$$2n$$$-gon, not an $$$n$$$-gon. | 1,400 | Print $$$T$$$ real numbers — one per test case. For each test case, print the minimum length of a side of the square $$$2n$$$-gon can be embedded in. Your answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. | standard output | |
PASSED | b7e3f39e3c9395e6e6dee74b079f46a0 | train_004.jsonl | 1593354900 | You are given three integers $$$x, y$$$ and $$$n$$$. Your task is to find the maximum integer $$$k$$$ such that $$$0 \le k \le n$$$ that $$$k \bmod x = y$$$, where $$$\bmod$$$ is modulo operation. Many programming languages use percent operator % to implement it.In other words, with given $$$x, y$$$ and $$$n$$$ you need to find the maximum possible integer from $$$0$$$ to $$$n$$$ that has the remainder $$$y$$$ modulo $$$x$$$.You have to answer $$$t$$$ independent test cases. It is guaranteed that such $$$k$$$ exists for each test case. | 256 megabytes | /* 盗图小能手
⣿⣿⣿⣿⣿⣿⡷⣯⢿⣿⣷⣻⢯⣿⡽⣻⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣇⠸⣿⣿⣆⠹⣿⣿⢾⣟⣯⣿⣿⣿⣿⣿⣿⣽⣻⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣻⣽⡿⣿⣎⠙⣿⣞⣷⡌⢻⣟⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣿⣿⣿⣿⣿⣿⡄⠹⣿⣿⡆⠻⣿⣟⣯⡿⣽⡿⣿⣿⣿⣿⣽⡷⣯⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣟⣷⣿⣿⣿⡀⠹⣟⣾⣟⣆⠹⣯⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⢠⡘⣿⣿⡄⠉⢿⣿⣽⡷⣿⣻⣿⣿⣿⣿⡝⣷⣯⢿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣯⢿⣾⢿⣿⡄⢄⠘⢿⣞⡿⣧⡈⢷⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⢸⣧⠘⣿⣷⠈⣦⠙⢿⣽⣷⣻⣽⣿⣿⣿⣿⣌⢿⣯⢿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣟⣯⣿⢿⣿⡆⢸⡷⡈⢻⡽⣷⡷⡄⠻⣽⣿⣿⡿⣿⣿⣿⣿⣿⣿⣷⣿⣿⣿⣿⣏⢰⣯⢷⠈⣿⡆⢹⢷⡌⠻⡾⢋⣱⣯⣿⣿⣿⣿⡆⢻⡿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⡎⣿⢾⡿⣿⡆⢸⣽⢻⣄⠹⣷⣟⣿⣄⠹⣟⣿⣿⣟⣿⣿⣿⣿⣿⣿⣽⣿⣿⣿⡇⢸⣯⣟⣧⠘⣷⠈⡯⠛⢀⡐⢾⣟⣷⣻⣿⣿⣿⡿⡌⢿⣻⣿⣿
⣿⣿⣿⣿⣿⣿⣧⢸⡿⣟⣿⡇⢸⣯⣟⣮⢧⡈⢿⣞⡿⣦⠘⠏⣹⣿⣽⢿⣿⣿⣿⣿⣯⣿⣿⣿⡇⢸⣿⣿⣾⡆⠹⢀⣠⣾⣟⣷⡈⢿⣞⣯⢿⣿⣿⣿⢷⠘⣯⣿⣿
⣿⣿⣿⣿⣿⣿⣿⡈⣿⢿⣽⡇⠘⠛⠛⠛⠓⠓⠈⠛⠛⠟⠇⢀⢿⣻⣿⣯⢿⣿⣿⣿⣷⢿⣿⣿⠁⣾⣿⣿⣿⣧⡄⠇⣹⣿⣾⣯⣿⡄⠻⣽⣯⢿⣻⣿⣿⡇⢹⣾⣿
⣿⣿⣿⣿⣿⣿⣿⡇⢹⣿⡽⡇⢸⣿⣿⣿⣿⣿⣞⣆⠰⣶⣶⡄⢀⢻⡿⣯⣿⡽⣿⣿⣿⢯⣟⡿⢀⣿⣿⣿⣿⣿⣧⠐⣸⣿⣿⣷⣿⣿⣆⠹⣯⣿⣻⣿⣿⣿⢀⣿⢿
⣿⣿⣿⣿⣿⣿⣿⣿⠘⣯⡿⡇⢸⣿⣿⣿⣿⣿⣿⣿⣧⡈⢿⣳⠘⡄⠻⣿⢾⣽⣟⡿⣿⢯⣿⡇⢸⣿⣿⣿⣿⣿⣿⡀⢾⣿⣿⣿⣿⣿⣿⣆⠹⣾⣷⣻⣿⡿⡇⢸⣿
⣿⣿⣿⣿⣿⣿⣿⣿⡇⢹⣿⠇⢸⣿⣿⣿⣿⣿⣿⣿⣿⣷⣄⠻⡇⢹⣆⠹⣟⣾⣽⣻⣟⣿⣽⠁⣾⣿⣿⣿⣿⣿⣿⣇⣿⣿⠿⠛⠛⠉⠙⠋⢀⠁⢘⣯⣿⣿⣧⠘⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⡈⣿⡃⢼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⡙⠌⣿⣆⠘⣿⣞⡿⣞⡿⡞⢠⣿⣿⣿⣿⣿⡿⠛⠉⠁⢀⣀⣠⣤⣤⣶⣶⣶⡆⢻⣽⣞⡿⣷⠈⣿
⣿⣿⣿⣿⣿⣿⣿⣿⡿⠃⠘⠁⠉⠉⠉⠉⠉⠉⠉⠉⠉⠙⠛⠛⢿⣄⢻⣿⣧⠘⢯⣟⡿⣽⠁⣾⣿⣿⣿⣿⣿⡃⢀⢀⠘⠛⠿⢿⣻⣟⣯⣽⣻⣵⡀⢿⣯⣟⣿⢀⣿
⣿⣿⣿⣟⣿⣿⣿⣿⣶⣶⡆⢀⣿⣾⣿⣾⣷⣿⣶⠿⠚⠉⢀⢀⣤⣿⣷⣿⣿⣷⡈⢿⣻⢃⣼⣿⣿⣿⣿⣻⣿⣿⣿⡶⣦⣤⣄⣀⡀⠉⠛⠛⠷⣯⣳⠈⣾⡽⣾⢀⣿
⣿⢿⣿⣿⣻⣿⣿⣿⣿⣿⡿⠐⣿⣿⣿⣿⠿⠋⠁⢀⢀⣤⣾⣿⣿⣿⣿⣿⣿⣿⣿⣌⣥⣾⡿⣿⣿⣷⣿⣿⢿⣷⣿⣿⣟⣾⣽⣳⢯⣟⣶⣦⣤⡾⣟⣦⠘⣿⢾⡁⢺
⣿⣻⣿⣿⡷⣿⣿⣿⣿⣿⡗⣦⠸⡿⠋⠁⢀⢀⣠⣴⢿⣿⣽⣻⢽⣾⣟⣷⣿⣟⣿⣿⣿⣳⠿⣵⣧⣼⣿⣿⣿⣿⣿⣾⣿⣿⣿⣿⣿⣽⣳⣯⣿⣿⣿⣽⢀⢷⣻⠄⠘
⣿⢷⣻⣿⣿⣷⣻⣿⣿⣿⡷⠛⣁⢀⣀⣤⣶⣿⣛⡿⣿⣮⣽⡻⣿⣮⣽⣻⢯⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣯⢀⢸⣿⢀⡆
⠸⣟⣯⣿⣿⣷⢿⣽⣿⣿⣷⣿⣷⣆⠹⣿⣶⣯⠿⣿⣶⣟⣻⢿⣷⣽⣻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢀⣯⣟⢀⡇
⣇⠹⣟⣾⣻⣿⣿⢾⡽⣿⣿⣿⣿⣿⣆⢹⣶⣿⣻⣷⣯⣟⣿⣿⣽⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⢀⡿⡇⢸⡇
⣿⣆⠹⣷⡻⣽⣿⣯⢿⣽⣻⣿⣿⣿⣿⣆⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠛⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⢸⣿⠇⣼⡇
⡙⠾⣆⠹⣿⣦⠛⣿⢯⣷⢿⡽⣿⣿⣿⣿⣆⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠃⠎⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠏⢀⣿⣾⣣⡿⡇
⣿⣷⡌⢦⠙⣿⣿⣌⠻⣽⢯⣿⣽⣻⣿⣿⣿⣧⠩⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡏⢰⢣⠘⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠃⢀⢀⢿⣞⣷⢿⡇
⣿⣽⣆⠹⣧⠘⣿⣿⡷⣌⠙⢷⣯⡷⣟⣿⣿⣿⣷⡀⡹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣈⠃⣸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⢀⣴⡧⢀⠸⣿⡽⣿⢀
⢻⣽⣿⡄⢻⣷⡈⢿⣿⣿⢧⢀⠙⢿⣻⡾⣽⣻⣿⣿⣄⠌⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠛⢁⣰⣾⣟⡿⢀⡄⢿⣟⣿⢀
⡄⢿⣿⣷⢀⠹⣟⣆⠻⣿⣿⣆⢀⣀⠉⠻⣿⡽⣯⣿⣿⣷⣈⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⢀⣠⠘⣯⣷⣿⡟⢀⢆⠸⣿⡟⢸
⣷⡈⢿⣿⣇⢱⡘⢿⣷⣬⣙⠿⣧⠘⣆⢀⠈⠻⣷⣟⣾⢿⣿⣆⠹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⣠⡞⢡⣿⢀⣿⣿⣿⠇⡄⢸⡄⢻⡇⣼
⣿⣷⡈⢿⣿⡆⢣⡀⠙⢾⣟⣿⣿⣷⡈⠂⠘⣦⡈⠿⣯⣿⢾⣿⣆⠙⠻⠿⠿⠿⠿⡿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠛⢋⣠⣾⡟⢠⣿⣿⢀⣿⣿⡟⢠⣿⢈⣧⠘⢠⣿
⣿⣿⣿⣄⠻⣿⡄⢳⡄⢆⡙⠾⣽⣿⣿⣆⡀⢹⡷⣄⠙⢿⣿⡾⣿⣆⢀⡀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⣀⣠⣴⡿⣯⠏⣠⣿⣿⡏⢸⣿⡿⢁⣿⣿⢀⣿⠆⢸⣿
⣿⣿⣿⣿⣦⡙⣿⣆⢻⡌⢿⣶⢤⣉⣙⣿⣷⡀⠙⠽⠷⠄⠹⣿⣟⣿⣆⢙⣋⣤⣤⣤⣄⣀⢀⢀⢀⢀⣾⣿⣟⡷⣯⡿⢃⣼⣿⣿⣿⠇⣼⡟⣡⣿⣿⣿⢀⡿⢠⠈⣿
⣿⣿⣿⣿⣿⣷⣮⣿⣿⣿⡌⠁⢤⣤⣤⣤⣬⣭⣴⣶⣶⣶⣆⠈⢻⣿⣿⣆⢻⣿⣿⣿⣿⣿⣿⣷⣶⣤⣌⣉⡘⠛⠻⠶⣿⣿⣿⣿⡟⣰⣫⣴⣿⣿⣿⣿⠄⣷⣿⣿⣿
*/
import java.io.*;
import java.net.URL;
import java.util.*;
public class A {
/**
* TODO 提交的时候一定要设置为 true
*/
boolean submitFlag = false;
private void solve(int x, int y, int n) {
int ans = (n / x) * x + y;
if (ans > n) {
ans -= x;
}
System.out.println(ans);
}
private void run() throws IOException {
//TODO 从这里开始读入题目输入
int numberOfTestcases = nextInt();
for (int t = 0; t < numberOfTestcases; t++) {
int x = nextInt();
int y = nextInt();
int n = nextInt();
solve(x, y, n);
}
}
// main以及输入输出========================================================================
public static void main(String[] args) throws IOException {
A solution = new A();
solution.setReader();
solution.run();
solution.reader.close();
}
/**
* 注意不同题目这里路径要设一下
*
* @throws IOException
*/
private void setReader() throws IOException {
URL resource = this.getClass().getResource("");
submitFlag = resource == null;
if (submitFlag) {
reader = new BufferedReader(new InputStreamReader(System.in));
} else {
String path = this.getClass().getResource("").getPath();
File file = new File(path);
while (!file.getName().equals("target")) {
file = file.getParentFile();
}
String moduleName = file.getParentFile().getName();
String projectPath = System.getProperty("user.dir");
String modulePath = projectPath + "/" + moduleName + "/src/main/java/";
String className = this.getClass().getName().replace(".", "\\");
reader = new BufferedReader(new FileReader(modulePath + className + "input.txt"));
}
}
BufferedReader reader;
StringTokenizer tokenizer;
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String next() throws IOException {
return nextToken();
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
| Java | ["7\n7 5 12345\n5 0 4\n10 5 15\n17 8 54321\n499999993 9 1000000000\n10 5 187\n2 0 999999999"] | 1 second | ["12339\n0\n15\n54306\n999999995\n185\n999999998"] | NoteIn the first test case of the example, the answer is $$$12339 = 7 \cdot 1762 + 5$$$ (thus, $$$12339 \bmod 7 = 5$$$). It is obvious that there is no greater integer not exceeding $$$12345$$$ which has the remainder $$$5$$$ modulo $$$7$$$. | Java 8 | standard input | [
"math"
] | 2589e832f22089fac9ccd3456c0abcec | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. The next $$$t$$$ lines contain test cases. The only line of the test case contains three integers $$$x, y$$$ and $$$n$$$ ($$$2 \le x \le 10^9;~ 0 \le y < x;~ y \le n \le 10^9$$$). It can be shown that such $$$k$$$ always exists under the given constraints. | 800 | For each test case, print the answer — maximum non-negative integer $$$k$$$ such that $$$0 \le k \le n$$$ and $$$k \bmod x = y$$$. It is guaranteed that the answer always exists. | standard output | |
PASSED | e9ea359fc034ffeae5f90f1eb7028ddc | train_004.jsonl | 1593354900 | You are given three integers $$$x, y$$$ and $$$n$$$. Your task is to find the maximum integer $$$k$$$ such that $$$0 \le k \le n$$$ that $$$k \bmod x = y$$$, where $$$\bmod$$$ is modulo operation. Many programming languages use percent operator % to implement it.In other words, with given $$$x, y$$$ and $$$n$$$ you need to find the maximum possible integer from $$$0$$$ to $$$n$$$ that has the remainder $$$y$$$ modulo $$$x$$$.You have to answer $$$t$$$ independent test cases. It is guaranteed that such $$$k$$$ exists for each test case. | 256 megabytes |
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
Scanner scan = new Scanner(System.in);
int iter = scan.nextInt();
ArrayList<Integer> arr = new ArrayList<Integer>();
for (int i = 0; i < iter; i++) {
int x = scan.nextInt();
int y = scan.nextInt();
int n = scan.nextInt();
int k = n;
int rem = k % x;
if( rem == y){
arr.add(k);
// System.out.println(k);
}
else if (rem >y ) {
arr.add(( k / x ) * x + y);
}
else{ k-= y;
arr.add(( k / x ) * x + y); }
}
for ( int i : arr) {
System.out.println(i); }
}
}
| Java | ["7\n7 5 12345\n5 0 4\n10 5 15\n17 8 54321\n499999993 9 1000000000\n10 5 187\n2 0 999999999"] | 1 second | ["12339\n0\n15\n54306\n999999995\n185\n999999998"] | NoteIn the first test case of the example, the answer is $$$12339 = 7 \cdot 1762 + 5$$$ (thus, $$$12339 \bmod 7 = 5$$$). It is obvious that there is no greater integer not exceeding $$$12345$$$ which has the remainder $$$5$$$ modulo $$$7$$$. | Java 8 | standard input | [
"math"
] | 2589e832f22089fac9ccd3456c0abcec | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. The next $$$t$$$ lines contain test cases. The only line of the test case contains three integers $$$x, y$$$ and $$$n$$$ ($$$2 \le x \le 10^9;~ 0 \le y < x;~ y \le n \le 10^9$$$). It can be shown that such $$$k$$$ always exists under the given constraints. | 800 | For each test case, print the answer — maximum non-negative integer $$$k$$$ such that $$$0 \le k \le n$$$ and $$$k \bmod x = y$$$. It is guaranteed that the answer always exists. | standard output | |
PASSED | c4c4e5f193443516ff1d14a9b54a79b3 | train_004.jsonl | 1593354900 | You are given three integers $$$x, y$$$ and $$$n$$$. Your task is to find the maximum integer $$$k$$$ such that $$$0 \le k \le n$$$ that $$$k \bmod x = y$$$, where $$$\bmod$$$ is modulo operation. Many programming languages use percent operator % to implement it.In other words, with given $$$x, y$$$ and $$$n$$$ you need to find the maximum possible integer from $$$0$$$ to $$$n$$$ that has the remainder $$$y$$$ modulo $$$x$$$.You have to answer $$$t$$$ independent test cases. It is guaranteed that such $$$k$$$ exists for each test case. | 256 megabytes | import java.util.Scanner;
public class RequiredRemainder {
static long findMax(long x, long y , long n){
long q = n/x;
if(q * x+ y <= n){
return q * x + y;
}
else{
return (q-1) * x + y;
}
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- >0){
long x = sc.nextLong();
long y = sc.nextLong();
long n = sc.nextLong();
System.out.println(findMax(x, y, n));
}
}
}
| Java | ["7\n7 5 12345\n5 0 4\n10 5 15\n17 8 54321\n499999993 9 1000000000\n10 5 187\n2 0 999999999"] | 1 second | ["12339\n0\n15\n54306\n999999995\n185\n999999998"] | NoteIn the first test case of the example, the answer is $$$12339 = 7 \cdot 1762 + 5$$$ (thus, $$$12339 \bmod 7 = 5$$$). It is obvious that there is no greater integer not exceeding $$$12345$$$ which has the remainder $$$5$$$ modulo $$$7$$$. | Java 8 | standard input | [
"math"
] | 2589e832f22089fac9ccd3456c0abcec | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. The next $$$t$$$ lines contain test cases. The only line of the test case contains three integers $$$x, y$$$ and $$$n$$$ ($$$2 \le x \le 10^9;~ 0 \le y < x;~ y \le n \le 10^9$$$). It can be shown that such $$$k$$$ always exists under the given constraints. | 800 | For each test case, print the answer — maximum non-negative integer $$$k$$$ such that $$$0 \le k \le n$$$ and $$$k \bmod x = y$$$. It is guaranteed that the answer always exists. | standard output | |
PASSED | db8201edd58117001eb26b9baed0fb20 | train_004.jsonl | 1593354900 | You are given three integers $$$x, y$$$ and $$$n$$$. Your task is to find the maximum integer $$$k$$$ such that $$$0 \le k \le n$$$ that $$$k \bmod x = y$$$, where $$$\bmod$$$ is modulo operation. Many programming languages use percent operator % to implement it.In other words, with given $$$x, y$$$ and $$$n$$$ you need to find the maximum possible integer from $$$0$$$ to $$$n$$$ that has the remainder $$$y$$$ modulo $$$x$$$.You have to answer $$$t$$$ independent test cases. It is guaranteed that such $$$k$$$ exists for each test case. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
while (t-- > 0) {
int x = in.nextInt();
int y = in.nextInt();
int n = in.nextInt();
int rem = n % x;
if (rem < y) {
System.out.println(n - (rem+(x-y)));
}
else if (rem > y) {
System.out.println(n - (rem-y));
}
else {
System.out.println(n);
}
}
}
} | Java | ["7\n7 5 12345\n5 0 4\n10 5 15\n17 8 54321\n499999993 9 1000000000\n10 5 187\n2 0 999999999"] | 1 second | ["12339\n0\n15\n54306\n999999995\n185\n999999998"] | NoteIn the first test case of the example, the answer is $$$12339 = 7 \cdot 1762 + 5$$$ (thus, $$$12339 \bmod 7 = 5$$$). It is obvious that there is no greater integer not exceeding $$$12345$$$ which has the remainder $$$5$$$ modulo $$$7$$$. | Java 8 | standard input | [
"math"
] | 2589e832f22089fac9ccd3456c0abcec | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. The next $$$t$$$ lines contain test cases. The only line of the test case contains three integers $$$x, y$$$ and $$$n$$$ ($$$2 \le x \le 10^9;~ 0 \le y < x;~ y \le n \le 10^9$$$). It can be shown that such $$$k$$$ always exists under the given constraints. | 800 | For each test case, print the answer — maximum non-negative integer $$$k$$$ such that $$$0 \le k \le n$$$ and $$$k \bmod x = y$$$. It is guaranteed that the answer always exists. | standard output | |
PASSED | cc5ad4d236e85bebb5f6ea31d4a4b6ee | train_004.jsonl | 1593354900 | You are given three integers $$$x, y$$$ and $$$n$$$. Your task is to find the maximum integer $$$k$$$ such that $$$0 \le k \le n$$$ that $$$k \bmod x = y$$$, where $$$\bmod$$$ is modulo operation. Many programming languages use percent operator % to implement it.In other words, with given $$$x, y$$$ and $$$n$$$ you need to find the maximum possible integer from $$$0$$$ to $$$n$$$ that has the remainder $$$y$$$ modulo $$$x$$$.You have to answer $$$t$$$ independent test cases. It is guaranteed that such $$$k$$$ exists for each test case. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
while (t-- > 0) {
int x = in.nextInt();
int y = in.nextInt();
int n = in.nextInt();
int rem = n % x;
if (rem < y) {
System.out.println(n - (x-y+rem));
}
else if (rem > y){
System.out.println(n - (rem - y));
}
else {
System.out.println(n);
}
}
}
} | Java | ["7\n7 5 12345\n5 0 4\n10 5 15\n17 8 54321\n499999993 9 1000000000\n10 5 187\n2 0 999999999"] | 1 second | ["12339\n0\n15\n54306\n999999995\n185\n999999998"] | NoteIn the first test case of the example, the answer is $$$12339 = 7 \cdot 1762 + 5$$$ (thus, $$$12339 \bmod 7 = 5$$$). It is obvious that there is no greater integer not exceeding $$$12345$$$ which has the remainder $$$5$$$ modulo $$$7$$$. | Java 8 | standard input | [
"math"
] | 2589e832f22089fac9ccd3456c0abcec | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. The next $$$t$$$ lines contain test cases. The only line of the test case contains three integers $$$x, y$$$ and $$$n$$$ ($$$2 \le x \le 10^9;~ 0 \le y < x;~ y \le n \le 10^9$$$). It can be shown that such $$$k$$$ always exists under the given constraints. | 800 | For each test case, print the answer — maximum non-negative integer $$$k$$$ such that $$$0 \le k \le n$$$ and $$$k \bmod x = y$$$. It is guaranteed that the answer always exists. | standard output | |
PASSED | 470299af3171c1243458556b65ac7ddf | train_004.jsonl | 1593354900 | You are given three integers $$$x, y$$$ and $$$n$$$. Your task is to find the maximum integer $$$k$$$ such that $$$0 \le k \le n$$$ that $$$k \bmod x = y$$$, where $$$\bmod$$$ is modulo operation. Many programming languages use percent operator % to implement it.In other words, with given $$$x, y$$$ and $$$n$$$ you need to find the maximum possible integer from $$$0$$$ to $$$n$$$ that has the remainder $$$y$$$ modulo $$$x$$$.You have to answer $$$t$$$ independent test cases. It is guaranteed that such $$$k$$$ exists for each test case. | 256 megabytes |
import java.util.Scanner;
public class Cf1374A {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
long t=sc.nextLong();
while(t>0)
{
long x=sc.nextInt();
long y=sc.nextInt();
long n=sc.nextInt();
System.out.println(n-(n-y)%x);
t--;
}
}
}
| Java | ["7\n7 5 12345\n5 0 4\n10 5 15\n17 8 54321\n499999993 9 1000000000\n10 5 187\n2 0 999999999"] | 1 second | ["12339\n0\n15\n54306\n999999995\n185\n999999998"] | NoteIn the first test case of the example, the answer is $$$12339 = 7 \cdot 1762 + 5$$$ (thus, $$$12339 \bmod 7 = 5$$$). It is obvious that there is no greater integer not exceeding $$$12345$$$ which has the remainder $$$5$$$ modulo $$$7$$$. | Java 8 | standard input | [
"math"
] | 2589e832f22089fac9ccd3456c0abcec | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. The next $$$t$$$ lines contain test cases. The only line of the test case contains three integers $$$x, y$$$ and $$$n$$$ ($$$2 \le x \le 10^9;~ 0 \le y < x;~ y \le n \le 10^9$$$). It can be shown that such $$$k$$$ always exists under the given constraints. | 800 | For each test case, print the answer — maximum non-negative integer $$$k$$$ such that $$$0 \le k \le n$$$ and $$$k \bmod x = y$$$. It is guaranteed that the answer always exists. | standard output | |
PASSED | 9e93b715cd867aa4adef8ceacea59ff3 | train_004.jsonl | 1593354900 | You are given three integers $$$x, y$$$ and $$$n$$$. Your task is to find the maximum integer $$$k$$$ such that $$$0 \le k \le n$$$ that $$$k \bmod x = y$$$, where $$$\bmod$$$ is modulo operation. Many programming languages use percent operator % to implement it.In other words, with given $$$x, y$$$ and $$$n$$$ you need to find the maximum possible integer from $$$0$$$ to $$$n$$$ that has the remainder $$$y$$$ modulo $$$x$$$.You have to answer $$$t$$$ independent test cases. It is guaranteed that such $$$k$$$ exists for each test case. | 256 megabytes | import java.io.*;
import java.util.*;
public class Mohammad {
//------------------------------|بسم الله الرحمن الرحيم|------------------------------//
public static void Mohammad_AboHasan() throws IOException{
FastReader fr = new FastReader();
int t = fr.nextInt();
while(t-->0){
int x = fr.nextInt();
int y = fr.nextInt();
int n = fr.nextInt();
int c = 0;
long p =(n-y)/x;
boolean rrrrrrrrr = true;
System.out.println(p*x+y);
}
}
//-----------------------------------|الحمدلله|-----------------------------------//
public static void main(String[] args) throws IOException{
Mohammad_AboHasan();
}
//-------------------------------------FAST I/O-------------------------------------//
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() throws IOException{
while (st == null || !st.hasMoreElements()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException{
return Integer.parseInt(next());
}
long nextLong() throws IOException{
return Long.parseLong(next());
}
double nextDouble() throws IOException{
return Double.parseDouble(next());
}
String nextLine() throws IOException{
String s = br.readLine();
return s;
}
}
} | Java | ["7\n7 5 12345\n5 0 4\n10 5 15\n17 8 54321\n499999993 9 1000000000\n10 5 187\n2 0 999999999"] | 1 second | ["12339\n0\n15\n54306\n999999995\n185\n999999998"] | NoteIn the first test case of the example, the answer is $$$12339 = 7 \cdot 1762 + 5$$$ (thus, $$$12339 \bmod 7 = 5$$$). It is obvious that there is no greater integer not exceeding $$$12345$$$ which has the remainder $$$5$$$ modulo $$$7$$$. | Java 8 | standard input | [
"math"
] | 2589e832f22089fac9ccd3456c0abcec | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. The next $$$t$$$ lines contain test cases. The only line of the test case contains three integers $$$x, y$$$ and $$$n$$$ ($$$2 \le x \le 10^9;~ 0 \le y < x;~ y \le n \le 10^9$$$). It can be shown that such $$$k$$$ always exists under the given constraints. | 800 | For each test case, print the answer — maximum non-negative integer $$$k$$$ such that $$$0 \le k \le n$$$ and $$$k \bmod x = y$$$. It is guaranteed that the answer always exists. | standard output | |
PASSED | 9aceb068292f02ebe47008d1cfb15384 | train_004.jsonl | 1593354900 | You are given three integers $$$x, y$$$ and $$$n$$$. Your task is to find the maximum integer $$$k$$$ such that $$$0 \le k \le n$$$ that $$$k \bmod x = y$$$, where $$$\bmod$$$ is modulo operation. Many programming languages use percent operator % to implement it.In other words, with given $$$x, y$$$ and $$$n$$$ you need to find the maximum possible integer from $$$0$$$ to $$$n$$$ that has the remainder $$$y$$$ modulo $$$x$$$.You have to answer $$$t$$$ independent test cases. It is guaranteed that such $$$k$$$ exists for each test case. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
public class ProblemA {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int totalLines = Integer.parseInt(br.readLine());
for (int i = 0; i < totalLines; i++) {
String[] lineItems = br.readLine().split(" ");
int x = Integer.parseInt(lineItems[0]);
int y = Integer.parseInt(lineItems[1]);
int n = Integer.parseInt(lineItems[2]);
// n % x == y
double calc = n - ((n - y) % x);
System.out.println(new BigDecimal(calc).toBigInteger());
}
}
} | Java | ["7\n7 5 12345\n5 0 4\n10 5 15\n17 8 54321\n499999993 9 1000000000\n10 5 187\n2 0 999999999"] | 1 second | ["12339\n0\n15\n54306\n999999995\n185\n999999998"] | NoteIn the first test case of the example, the answer is $$$12339 = 7 \cdot 1762 + 5$$$ (thus, $$$12339 \bmod 7 = 5$$$). It is obvious that there is no greater integer not exceeding $$$12345$$$ which has the remainder $$$5$$$ modulo $$$7$$$. | Java 8 | standard input | [
"math"
] | 2589e832f22089fac9ccd3456c0abcec | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. The next $$$t$$$ lines contain test cases. The only line of the test case contains three integers $$$x, y$$$ and $$$n$$$ ($$$2 \le x \le 10^9;~ 0 \le y < x;~ y \le n \le 10^9$$$). It can be shown that such $$$k$$$ always exists under the given constraints. | 800 | For each test case, print the answer — maximum non-negative integer $$$k$$$ such that $$$0 \le k \le n$$$ and $$$k \bmod x = y$$$. It is guaranteed that the answer always exists. | standard output | |
PASSED | 036e962d06884a1d51921e33c4f7685a | train_004.jsonl | 1593354900 | You are given three integers $$$x, y$$$ and $$$n$$$. Your task is to find the maximum integer $$$k$$$ such that $$$0 \le k \le n$$$ that $$$k \bmod x = y$$$, where $$$\bmod$$$ is modulo operation. Many programming languages use percent operator % to implement it.In other words, with given $$$x, y$$$ and $$$n$$$ you need to find the maximum possible integer from $$$0$$$ to $$$n$$$ that has the remainder $$$y$$$ modulo $$$x$$$.You have to answer $$$t$$$ independent test cases. It is guaranteed that such $$$k$$$ exists for each test case. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
public class ProblemA {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int totalLines = Integer.parseInt(br.readLine());
for (int i = 0; i < totalLines; i++) {
String[] lineItems = br.readLine().split(" ");
int x = Integer.parseInt(lineItems[0]);
int y = Integer.parseInt(lineItems[1]);
int n = Integer.parseInt(lineItems[2]);
// n % x == y
double calc = n - ((n - y) % x);
System.out.println(new BigDecimal(calc).toBigInteger());
}
}
}
| Java | ["7\n7 5 12345\n5 0 4\n10 5 15\n17 8 54321\n499999993 9 1000000000\n10 5 187\n2 0 999999999"] | 1 second | ["12339\n0\n15\n54306\n999999995\n185\n999999998"] | NoteIn the first test case of the example, the answer is $$$12339 = 7 \cdot 1762 + 5$$$ (thus, $$$12339 \bmod 7 = 5$$$). It is obvious that there is no greater integer not exceeding $$$12345$$$ which has the remainder $$$5$$$ modulo $$$7$$$. | Java 8 | standard input | [
"math"
] | 2589e832f22089fac9ccd3456c0abcec | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. The next $$$t$$$ lines contain test cases. The only line of the test case contains three integers $$$x, y$$$ and $$$n$$$ ($$$2 \le x \le 10^9;~ 0 \le y < x;~ y \le n \le 10^9$$$). It can be shown that such $$$k$$$ always exists under the given constraints. | 800 | For each test case, print the answer — maximum non-negative integer $$$k$$$ such that $$$0 \le k \le n$$$ and $$$k \bmod x = y$$$. It is guaranteed that the answer always exists. | standard output | |
PASSED | 2c81a8339df4213ad9ad201f71d02198 | train_004.jsonl | 1593354900 | You are given three integers $$$x, y$$$ and $$$n$$$. Your task is to find the maximum integer $$$k$$$ such that $$$0 \le k \le n$$$ that $$$k \bmod x = y$$$, where $$$\bmod$$$ is modulo operation. Many programming languages use percent operator % to implement it.In other words, with given $$$x, y$$$ and $$$n$$$ you need to find the maximum possible integer from $$$0$$$ to $$$n$$$ that has the remainder $$$y$$$ modulo $$$x$$$.You have to answer $$$t$$$ independent test cases. It is guaranteed that such $$$k$$$ exists for each test case. | 256 megabytes | import java.io.*;
import java.util.*;
public class RequiredRemainder {
private final FastReader fr = new FastReader();
public static void main(String[] args) {
new RequiredRemainder().solve();
}
private void solve() {
int t = fr.nextInt();
while (t-- > 0) {
int x = fr.nextInt(), y = fr.nextInt(), n = fr.nextInt();
System.out.println(solve(x, y, n));
}
}
private int solve(int x, int y, int n) {
int z = n / x;
int k = x * z + y;
if (k <= n) return k;
else return k - x;
}
class FastReader {
private final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private StringTokenizer st;
public String nextLine() {
try {
return br.readLine();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(nextLine());
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
} | Java | ["7\n7 5 12345\n5 0 4\n10 5 15\n17 8 54321\n499999993 9 1000000000\n10 5 187\n2 0 999999999"] | 1 second | ["12339\n0\n15\n54306\n999999995\n185\n999999998"] | NoteIn the first test case of the example, the answer is $$$12339 = 7 \cdot 1762 + 5$$$ (thus, $$$12339 \bmod 7 = 5$$$). It is obvious that there is no greater integer not exceeding $$$12345$$$ which has the remainder $$$5$$$ modulo $$$7$$$. | Java 8 | standard input | [
"math"
] | 2589e832f22089fac9ccd3456c0abcec | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. The next $$$t$$$ lines contain test cases. The only line of the test case contains three integers $$$x, y$$$ and $$$n$$$ ($$$2 \le x \le 10^9;~ 0 \le y < x;~ y \le n \le 10^9$$$). It can be shown that such $$$k$$$ always exists under the given constraints. | 800 | For each test case, print the answer — maximum non-negative integer $$$k$$$ such that $$$0 \le k \le n$$$ and $$$k \bmod x = y$$$. It is guaranteed that the answer always exists. | standard output | |
PASSED | 820062e3ed581423da81e5932872b05c | train_004.jsonl | 1593354900 | You are given three integers $$$x, y$$$ and $$$n$$$. Your task is to find the maximum integer $$$k$$$ such that $$$0 \le k \le n$$$ that $$$k \bmod x = y$$$, where $$$\bmod$$$ is modulo operation. Many programming languages use percent operator % to implement it.In other words, with given $$$x, y$$$ and $$$n$$$ you need to find the maximum possible integer from $$$0$$$ to $$$n$$$ that has the remainder $$$y$$$ modulo $$$x$$$.You have to answer $$$t$$$ independent test cases. It is guaranteed that such $$$k$$$ exists for each test case. | 256 megabytes | import java.util.*;
public class P1374A {
public static void main(String [] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for (int i = 0; i < t; i++) {
long x = in.nextLong();
long y = in.nextLong();
long n = in.nextLong();
long result = x * (n / x) + y;
if (result <= n) System.out.println(result);
else System.out.println(result - x);
}
}
} | Java | ["7\n7 5 12345\n5 0 4\n10 5 15\n17 8 54321\n499999993 9 1000000000\n10 5 187\n2 0 999999999"] | 1 second | ["12339\n0\n15\n54306\n999999995\n185\n999999998"] | NoteIn the first test case of the example, the answer is $$$12339 = 7 \cdot 1762 + 5$$$ (thus, $$$12339 \bmod 7 = 5$$$). It is obvious that there is no greater integer not exceeding $$$12345$$$ which has the remainder $$$5$$$ modulo $$$7$$$. | Java 8 | standard input | [
"math"
] | 2589e832f22089fac9ccd3456c0abcec | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. The next $$$t$$$ lines contain test cases. The only line of the test case contains three integers $$$x, y$$$ and $$$n$$$ ($$$2 \le x \le 10^9;~ 0 \le y < x;~ y \le n \le 10^9$$$). It can be shown that such $$$k$$$ always exists under the given constraints. | 800 | For each test case, print the answer — maximum non-negative integer $$$k$$$ such that $$$0 \le k \le n$$$ and $$$k \bmod x = y$$$. It is guaranteed that the answer always exists. | standard output | |
PASSED | e7d18e2ce46b05259987ec8615ab32d3 | train_004.jsonl | 1593354900 | You are given three integers $$$x, y$$$ and $$$n$$$. Your task is to find the maximum integer $$$k$$$ such that $$$0 \le k \le n$$$ that $$$k \bmod x = y$$$, where $$$\bmod$$$ is modulo operation. Many programming languages use percent operator % to implement it.In other words, with given $$$x, y$$$ and $$$n$$$ you need to find the maximum possible integer from $$$0$$$ to $$$n$$$ that has the remainder $$$y$$$ modulo $$$x$$$.You have to answer $$$t$$$ independent test cases. It is guaranteed that such $$$k$$$ exists for each test case. | 256 megabytes | import java.util.*;
import java.math.*;
public class solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0) {
int x = sc.nextInt();
int y = sc.nextInt();
int n = sc.nextInt();
int temp = (n-y)/x;
System.out.println((temp*x) + y);
}
}
} | Java | ["7\n7 5 12345\n5 0 4\n10 5 15\n17 8 54321\n499999993 9 1000000000\n10 5 187\n2 0 999999999"] | 1 second | ["12339\n0\n15\n54306\n999999995\n185\n999999998"] | NoteIn the first test case of the example, the answer is $$$12339 = 7 \cdot 1762 + 5$$$ (thus, $$$12339 \bmod 7 = 5$$$). It is obvious that there is no greater integer not exceeding $$$12345$$$ which has the remainder $$$5$$$ modulo $$$7$$$. | Java 8 | standard input | [
"math"
] | 2589e832f22089fac9ccd3456c0abcec | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. The next $$$t$$$ lines contain test cases. The only line of the test case contains three integers $$$x, y$$$ and $$$n$$$ ($$$2 \le x \le 10^9;~ 0 \le y < x;~ y \le n \le 10^9$$$). It can be shown that such $$$k$$$ always exists under the given constraints. | 800 | For each test case, print the answer — maximum non-negative integer $$$k$$$ such that $$$0 \le k \le n$$$ and $$$k \bmod x = y$$$. It is guaranteed that the answer always exists. | standard output | |
PASSED | 799a36713c1c8addc254a520378ea7c6 | train_004.jsonl | 1593354900 | You are given three integers $$$x, y$$$ and $$$n$$$. Your task is to find the maximum integer $$$k$$$ such that $$$0 \le k \le n$$$ that $$$k \bmod x = y$$$, where $$$\bmod$$$ is modulo operation. Many programming languages use percent operator % to implement it.In other words, with given $$$x, y$$$ and $$$n$$$ you need to find the maximum possible integer from $$$0$$$ to $$$n$$$ that has the remainder $$$y$$$ modulo $$$x$$$.You have to answer $$$t$$$ independent test cases. It is guaranteed that such $$$k$$$ exists for each test case. | 256 megabytes | // package Round653;
import java.io.*;
import java.util.*;
import java.lang.*;
public class A implements Runnable {
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception {
new Thread(null, new A(), "Main", 1 << 27).start();
}
public void run() {
InputReader in = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int t = in.nextInt();
while (t-- != 0){
int x = in.nextInt();
int y = in.nextInt();
int n = in.nextInt();
int ans = n;
if (n % x >= y){
ans = n - (n%x - y);
}
else{
ans = n - n%x - x + y;
}
w.println(ans);
}
w.flush();
w.close();
}
public static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
} | Java | ["7\n7 5 12345\n5 0 4\n10 5 15\n17 8 54321\n499999993 9 1000000000\n10 5 187\n2 0 999999999"] | 1 second | ["12339\n0\n15\n54306\n999999995\n185\n999999998"] | NoteIn the first test case of the example, the answer is $$$12339 = 7 \cdot 1762 + 5$$$ (thus, $$$12339 \bmod 7 = 5$$$). It is obvious that there is no greater integer not exceeding $$$12345$$$ which has the remainder $$$5$$$ modulo $$$7$$$. | Java 8 | standard input | [
"math"
] | 2589e832f22089fac9ccd3456c0abcec | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. The next $$$t$$$ lines contain test cases. The only line of the test case contains three integers $$$x, y$$$ and $$$n$$$ ($$$2 \le x \le 10^9;~ 0 \le y < x;~ y \le n \le 10^9$$$). It can be shown that such $$$k$$$ always exists under the given constraints. | 800 | For each test case, print the answer — maximum non-negative integer $$$k$$$ such that $$$0 \le k \le n$$$ and $$$k \bmod x = y$$$. It is guaranteed that the answer always exists. | standard output | |
PASSED | 5763f6e97aeb83f83e6da991332ccf82 | train_004.jsonl | 1593354900 | You are given three integers $$$x, y$$$ and $$$n$$$. Your task is to find the maximum integer $$$k$$$ such that $$$0 \le k \le n$$$ that $$$k \bmod x = y$$$, where $$$\bmod$$$ is modulo operation. Many programming languages use percent operator % to implement it.In other words, with given $$$x, y$$$ and $$$n$$$ you need to find the maximum possible integer from $$$0$$$ to $$$n$$$ that has the remainder $$$y$$$ modulo $$$x$$$.You have to answer $$$t$$$ independent test cases. It is guaranteed that such $$$k$$$ exists for each test case. | 256 megabytes | import java.util.*;
public class Main{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for(int i=0;i<t;i++){
int x = sc.nextInt();
int y = sc.nextInt();
int n = sc.nextInt();
if(n-n%x+y <= n){
System.out.println(n-n%x+y);
}
else{
System.out.println(n-n%x+y-x);
}
}
}
} | Java | ["7\n7 5 12345\n5 0 4\n10 5 15\n17 8 54321\n499999993 9 1000000000\n10 5 187\n2 0 999999999"] | 1 second | ["12339\n0\n15\n54306\n999999995\n185\n999999998"] | NoteIn the first test case of the example, the answer is $$$12339 = 7 \cdot 1762 + 5$$$ (thus, $$$12339 \bmod 7 = 5$$$). It is obvious that there is no greater integer not exceeding $$$12345$$$ which has the remainder $$$5$$$ modulo $$$7$$$. | Java 8 | standard input | [
"math"
] | 2589e832f22089fac9ccd3456c0abcec | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. The next $$$t$$$ lines contain test cases. The only line of the test case contains three integers $$$x, y$$$ and $$$n$$$ ($$$2 \le x \le 10^9;~ 0 \le y < x;~ y \le n \le 10^9$$$). It can be shown that such $$$k$$$ always exists under the given constraints. | 800 | For each test case, print the answer — maximum non-negative integer $$$k$$$ such that $$$0 \le k \le n$$$ and $$$k \bmod x = y$$$. It is guaranteed that the answer always exists. | standard output | |
PASSED | 48073c01383879a5668c72841edc23fd | train_004.jsonl | 1593354900 | You are given three integers $$$x, y$$$ and $$$n$$$. Your task is to find the maximum integer $$$k$$$ such that $$$0 \le k \le n$$$ that $$$k \bmod x = y$$$, where $$$\bmod$$$ is modulo operation. Many programming languages use percent operator % to implement it.In other words, with given $$$x, y$$$ and $$$n$$$ you need to find the maximum possible integer from $$$0$$$ to $$$n$$$ that has the remainder $$$y$$$ modulo $$$x$$$.You have to answer $$$t$$$ independent test cases. It is guaranteed that such $$$k$$$ exists for each test case. | 256 megabytes | //package com.code.codeforces;
import java.io.IOException;
import java.util.Scanner;
public class RequiredReminder {
public static void main(String[] args) throws IOException {
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
while(n-- >0) {
int x = reader.nextInt();
int y = reader.nextInt();
int limit = reader.nextInt();
System.out.println(((limit-y)/x)*x+y);
}
}
}
| Java | ["7\n7 5 12345\n5 0 4\n10 5 15\n17 8 54321\n499999993 9 1000000000\n10 5 187\n2 0 999999999"] | 1 second | ["12339\n0\n15\n54306\n999999995\n185\n999999998"] | NoteIn the first test case of the example, the answer is $$$12339 = 7 \cdot 1762 + 5$$$ (thus, $$$12339 \bmod 7 = 5$$$). It is obvious that there is no greater integer not exceeding $$$12345$$$ which has the remainder $$$5$$$ modulo $$$7$$$. | Java 8 | standard input | [
"math"
] | 2589e832f22089fac9ccd3456c0abcec | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. The next $$$t$$$ lines contain test cases. The only line of the test case contains three integers $$$x, y$$$ and $$$n$$$ ($$$2 \le x \le 10^9;~ 0 \le y < x;~ y \le n \le 10^9$$$). It can be shown that such $$$k$$$ always exists under the given constraints. | 800 | For each test case, print the answer — maximum non-negative integer $$$k$$$ such that $$$0 \le k \le n$$$ and $$$k \bmod x = y$$$. It is guaranteed that the answer always exists. | standard output | |
PASSED | 6b691a7ae91387b995edd4c9bd8aa1df | train_004.jsonl | 1593354900 | You are given three integers $$$x, y$$$ and $$$n$$$. Your task is to find the maximum integer $$$k$$$ such that $$$0 \le k \le n$$$ that $$$k \bmod x = y$$$, where $$$\bmod$$$ is modulo operation. Many programming languages use percent operator % to implement it.In other words, with given $$$x, y$$$ and $$$n$$$ you need to find the maximum possible integer from $$$0$$$ to $$$n$$$ that has the remainder $$$y$$$ modulo $$$x$$$.You have to answer $$$t$$$ independent test cases. It is guaranteed that such $$$k$$$ exists for each test case. | 256 megabytes | import java.util.Scanner;
public class Cdf
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while( t-- != 0)
{
int x = sc.nextInt();
int y = sc.nextInt();
int n = sc.nextInt();
int k = n;
if(n/x*x+y > n)
{
System.out.println(n/x*x+y-x);
continue;
}
System.out.println(n/x*x+y);
}
}
} | Java | ["7\n7 5 12345\n5 0 4\n10 5 15\n17 8 54321\n499999993 9 1000000000\n10 5 187\n2 0 999999999"] | 1 second | ["12339\n0\n15\n54306\n999999995\n185\n999999998"] | NoteIn the first test case of the example, the answer is $$$12339 = 7 \cdot 1762 + 5$$$ (thus, $$$12339 \bmod 7 = 5$$$). It is obvious that there is no greater integer not exceeding $$$12345$$$ which has the remainder $$$5$$$ modulo $$$7$$$. | Java 8 | standard input | [
"math"
] | 2589e832f22089fac9ccd3456c0abcec | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. The next $$$t$$$ lines contain test cases. The only line of the test case contains three integers $$$x, y$$$ and $$$n$$$ ($$$2 \le x \le 10^9;~ 0 \le y < x;~ y \le n \le 10^9$$$). It can be shown that such $$$k$$$ always exists under the given constraints. | 800 | For each test case, print the answer — maximum non-negative integer $$$k$$$ such that $$$0 \le k \le n$$$ and $$$k \bmod x = y$$$. It is guaranteed that the answer always exists. | standard output | |
PASSED | 0ab1f12d16e21e7d68b43427458fc6e1 | train_004.jsonl | 1593354900 | You are given three integers $$$x, y$$$ and $$$n$$$. Your task is to find the maximum integer $$$k$$$ such that $$$0 \le k \le n$$$ that $$$k \bmod x = y$$$, where $$$\bmod$$$ is modulo operation. Many programming languages use percent operator % to implement it.In other words, with given $$$x, y$$$ and $$$n$$$ you need to find the maximum possible integer from $$$0$$$ to $$$n$$$ that has the remainder $$$y$$$ modulo $$$x$$$.You have to answer $$$t$$$ independent test cases. It is guaranteed that such $$$k$$$ exists for each test case. | 256 megabytes | import java.io.*;
public class reqRem{
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
while (T-->0){
String s = br.readLine();
String[] token = s.split(" ");
long x = Long.parseLong(token[0]);
long y = Long.parseLong(token[1]);
long n = Long.parseLong(token[2]);
long z = (n/x)*x + y;
if(z<=n)
System.out.println(z);
else{
z = ((n/x)-1)*x + y;
System.out.println(z);
}
}
}
} | Java | ["7\n7 5 12345\n5 0 4\n10 5 15\n17 8 54321\n499999993 9 1000000000\n10 5 187\n2 0 999999999"] | 1 second | ["12339\n0\n15\n54306\n999999995\n185\n999999998"] | NoteIn the first test case of the example, the answer is $$$12339 = 7 \cdot 1762 + 5$$$ (thus, $$$12339 \bmod 7 = 5$$$). It is obvious that there is no greater integer not exceeding $$$12345$$$ which has the remainder $$$5$$$ modulo $$$7$$$. | Java 8 | standard input | [
"math"
] | 2589e832f22089fac9ccd3456c0abcec | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. The next $$$t$$$ lines contain test cases. The only line of the test case contains three integers $$$x, y$$$ and $$$n$$$ ($$$2 \le x \le 10^9;~ 0 \le y < x;~ y \le n \le 10^9$$$). It can be shown that such $$$k$$$ always exists under the given constraints. | 800 | For each test case, print the answer — maximum non-negative integer $$$k$$$ such that $$$0 \le k \le n$$$ and $$$k \bmod x = y$$$. It is guaranteed that the answer always exists. | standard output | |
PASSED | bda191a143fd89f7a9e8dee8b77dce08 | train_004.jsonl | 1593354900 | You are given three integers $$$x, y$$$ and $$$n$$$. Your task is to find the maximum integer $$$k$$$ such that $$$0 \le k \le n$$$ that $$$k \bmod x = y$$$, where $$$\bmod$$$ is modulo operation. Many programming languages use percent operator % to implement it.In other words, with given $$$x, y$$$ and $$$n$$$ you need to find the maximum possible integer from $$$0$$$ to $$$n$$$ that has the remainder $$$y$$$ modulo $$$x$$$.You have to answer $$$t$$$ independent test cases. It is guaranteed that such $$$k$$$ exists for each test case. | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
public static void main (String[] args) throws IOException
{
// your code goes here
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
// long ans = 0;
while(t-- >0){
String[] s = br.readLine().split(" ");
int x = Integer.parseInt(s[0]);
int y = Integer.parseInt(s[1]);
int n = Integer.parseInt(s[2]);
int ans = (n/x)*x + y;
if(ans>n)
ans = ans - x;
System.out.println(ans);
}
}
} | Java | ["7\n7 5 12345\n5 0 4\n10 5 15\n17 8 54321\n499999993 9 1000000000\n10 5 187\n2 0 999999999"] | 1 second | ["12339\n0\n15\n54306\n999999995\n185\n999999998"] | NoteIn the first test case of the example, the answer is $$$12339 = 7 \cdot 1762 + 5$$$ (thus, $$$12339 \bmod 7 = 5$$$). It is obvious that there is no greater integer not exceeding $$$12345$$$ which has the remainder $$$5$$$ modulo $$$7$$$. | Java 8 | standard input | [
"math"
] | 2589e832f22089fac9ccd3456c0abcec | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. The next $$$t$$$ lines contain test cases. The only line of the test case contains three integers $$$x, y$$$ and $$$n$$$ ($$$2 \le x \le 10^9;~ 0 \le y < x;~ y \le n \le 10^9$$$). It can be shown that such $$$k$$$ always exists under the given constraints. | 800 | For each test case, print the answer — maximum non-negative integer $$$k$$$ such that $$$0 \le k \le n$$$ and $$$k \bmod x = y$$$. It is guaranteed that the answer always exists. | standard output | |
PASSED | 956fa3640fe995bbfa09058862b3ef7b | train_004.jsonl | 1593354900 | You are given three integers $$$x, y$$$ and $$$n$$$. Your task is to find the maximum integer $$$k$$$ such that $$$0 \le k \le n$$$ that $$$k \bmod x = y$$$, where $$$\bmod$$$ is modulo operation. Many programming languages use percent operator % to implement it.In other words, with given $$$x, y$$$ and $$$n$$$ you need to find the maximum possible integer from $$$0$$$ to $$$n$$$ that has the remainder $$$y$$$ modulo $$$x$$$.You have to answer $$$t$$$ independent test cases. It is guaranteed that such $$$k$$$ exists for each test case. | 256 megabytes | import java.util.Scanner;
public class RequiredRemainder {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int test = sc.nextInt();
for (int i = 0; i < test; i++) {
int divisor = sc.nextInt();
int remainder = sc.nextInt();
int max_number = sc.nextInt();
int quotient=max_number/divisor;
while (quotient>=0){
int dividend=divisor*quotient+remainder;
if(dividend>max_number){
quotient--;
}
else {
System.out.println(dividend);
break;
}
}
}
}
}
| Java | ["7\n7 5 12345\n5 0 4\n10 5 15\n17 8 54321\n499999993 9 1000000000\n10 5 187\n2 0 999999999"] | 1 second | ["12339\n0\n15\n54306\n999999995\n185\n999999998"] | NoteIn the first test case of the example, the answer is $$$12339 = 7 \cdot 1762 + 5$$$ (thus, $$$12339 \bmod 7 = 5$$$). It is obvious that there is no greater integer not exceeding $$$12345$$$ which has the remainder $$$5$$$ modulo $$$7$$$. | Java 8 | standard input | [
"math"
] | 2589e832f22089fac9ccd3456c0abcec | The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 5 \cdot 10^4$$$) — the number of test cases. The next $$$t$$$ lines contain test cases. The only line of the test case contains three integers $$$x, y$$$ and $$$n$$$ ($$$2 \le x \le 10^9;~ 0 \le y < x;~ y \le n \le 10^9$$$). It can be shown that such $$$k$$$ always exists under the given constraints. | 800 | For each test case, print the answer — maximum non-negative integer $$$k$$$ such that $$$0 \le k \le n$$$ and $$$k \bmod x = y$$$. It is guaranteed that the answer always exists. | standard output | |
PASSED | 77e433b51c6d8e7b043151f64ed96e81 | train_004.jsonl | 1486042500 | Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.A subtree of some vertex is a subgraph containing that vertex and all its descendants.Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. | 256 megabytes | //package cdr;
import java.util.*;
import java.math.*;
import java.io.*;
public class Luck{
public static InputReader sc;
public static PrintWriter out;
public static final int MOD = (int) (1e9 + 7);
static TreeSet<Integer>[] adj;
static int[] colors;
static int[] v;
static int ans=-1;
public static void main(String[] args){
sc=new InputReader(System.in);
out=new PrintWriter(System.out);
int n=sc.nextInt();
adj=new TreeSet[n+1];
colors=new int[n+1];
v=new int[n+1];
for(int i=1;i<=n;i++){
adj[i]=new TreeSet<Integer>();
}
for(int i=0;i<n-1;i++){
int u=sc.nextInt();
int v=sc.nextInt();
adj[u].add(v);
adj[v].add(u);
}
for(int i=1;i<=n;i++){
colors[i]=sc.nextInt();
}
dfs(1,1);
dfs2(1,1);
if(ans==-1){
out.println("NO");
}
else{
out.println("YES");
out.println(ans);
}
out.close();
}
static void dfs2(int u,int p){
int storeU=v[u];
int storeP=v[p];
if(u!=p){
if(v[u]>0){
v[p]--;
}
if(v[p]>0 || colors[u]!=colors[p]){
v[u]++;
}
}
boolean ok=true;
for(int nei:adj[u]){
if(nei!=p){
dfs2(nei,u);
}
if(v[nei]>0){
ok=false;
break;
}
}
if(ok==true){
ans=u;
}
v[u]=storeU;
v[p]=storeP;
}
static void dfs(int u,int p){
v[u]=0;
for(int nei:adj[u]){
if(nei!=p){
dfs(nei,u);
if(v[nei]>0 || colors[nei]!=colors[u]){
v[u]++;
}
}
}
}
static int gcd(int a,int b){
if(b==0){
return a;
}
return gcd(b,a%b);
}
static int lcm(int a,int b){
int g;
if(a<b){
g=gcd(b,a);
}
else{
g=gcd(a,b);
}
return (a*b)/g;
}
static boolean isPrime(int n){
if (n == 2)
return true;
for (long i = 2; i * i <= n; i++) {
if (n % i == 0)
return false;
}
return true;
}
static void shuffle(int[] A){
for(int i=A.length-1;i>0;i--){
int j=(int)(Math.random()*(i+1));
int temp=A[j];
A[j]=A[i];
A[i]=temp;
}
}
public static class Node implements Comparator<Node>{
int v;
int u;
public Node(){
;
}
public Node (int u, int v) {
this.u = u;
this.v = v;
}
public void print() {
out.println(v + " " + u + " ");
}
public int compare(Node n1,Node n2) {
return n1.u-n2.u;
}
}
public static BigInteger pow(BigInteger base, BigInteger exp) {
if(exp.equals(new BigInteger(String.valueOf(0)))){
return new BigInteger(String.valueOf(1));
}
if(exp.equals(new BigInteger(String.valueOf(1))))
return base;
BigInteger temp=exp.divide(new BigInteger(String.valueOf(2)));
BigInteger val = pow(base, temp);
BigInteger result = val.multiply(val);
result=result.remainder(new BigInteger(String.valueOf(MOD)));
BigInteger AND=exp.and(new BigInteger(String.valueOf(1)));
if(AND.equals(new BigInteger(String.valueOf(1)))){
result = result.multiply(base);
result=result.remainder(new BigInteger(String.valueOf(MOD)));
}
return result;
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["4\n1 2\n2 3\n3 4\n1 2 1 1", "3\n1 2\n2 3\n1 2 3", "4\n1 2\n2 3\n3 4\n1 2 1 2"] | 2 seconds | ["YES\n2", "YES\n2", "NO"] | null | Java 8 | standard input | [
"dp",
"graphs",
"dsu",
"implementation",
"dfs and similar",
"trees"
] | aaca5d07795a42ecab210327c1cf6be9 | The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices. | 1,600 | Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. | standard output | |
PASSED | a67760f4443c4fddf4c732230ff431fb | train_004.jsonl | 1486042500 | Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.A subtree of some vertex is a subgraph containing that vertex and all its descendants.Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. | 256 megabytes | //package cdr;
import java.util.*;
import java.math.*;
import java.io.*;
public class Luck{
public static InputReader sc;
public static PrintWriter out;
public static final int MOD = (int) (1e9 + 7);
public static void main(String[] args){
sc=new InputReader(System.in);
out=new PrintWriter(System.out);
int n=sc.nextInt();
int[] u=new int[n];
int[] v=new int[n];
int[] colors=new int[n+1];
for(int i=0;i<n-1;i++){
u[i]=sc.nextInt();
v[i]=sc.nextInt();
}
for(int i=1;i<=n;i++){
colors[i]=sc.nextInt();
}
int sum=0;
int flag=0;
int[] count=new int[n+1];
for(int i=0;i<n;i++){
if(colors[u[i]]!=colors[v[i]]){
count[u[i]]+=1;
count[v[i]]+=1;
sum+=1;
}
}
for(int i=1;i<=n;i++){
if(count[i]==sum){
out.println("YES");
out.println(i);
flag=1;
break;
}
}
if(flag==0){
out.println("NO");
}
out.close();
}
static int gcd(int a,int b){
if(b==0){
return a;
}
return gcd(b,a%b);
}
static int lcm(int a,int b){
int g;
if(a<b){
g=gcd(b,a);
}
else{
g=gcd(a,b);
}
return (a*b)/g;
}
static boolean isPrime(int n){
if (n == 2)
return true;
for (long i = 2; i * i <= n; i++) {
if (n % i == 0)
return false;
}
return true;
}
static void shuffle(int[] A){
for(int i=A.length-1;i>0;i--){
int j=(int)(Math.random()*(i+1));
int temp=A[j];
A[j]=A[i];
A[i]=temp;
}
}
public static class Node implements Comparator<Node>{
int v;
int u;
public Node(){
;
}
public Node (int u, int v) {
this.u = u;
this.v = v;
}
public void print() {
out.println(v + " " + u + " ");
}
public int compare(Node n1,Node n2) {
return n1.u-n2.u;
}
}
public static BigInteger pow(BigInteger base, BigInteger exp) {
if(exp.equals(new BigInteger(String.valueOf(0)))){
return new BigInteger(String.valueOf(1));
}
if(exp.equals(new BigInteger(String.valueOf(1))))
return base;
BigInteger temp=exp.divide(new BigInteger(String.valueOf(2)));
BigInteger val = pow(base, temp);
BigInteger result = val.multiply(val);
result=result.remainder(new BigInteger(String.valueOf(MOD)));
BigInteger AND=exp.and(new BigInteger(String.valueOf(1)));
if(AND.equals(new BigInteger(String.valueOf(1)))){
result = result.multiply(base);
result=result.remainder(new BigInteger(String.valueOf(MOD)));
}
return result;
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["4\n1 2\n2 3\n3 4\n1 2 1 1", "3\n1 2\n2 3\n1 2 3", "4\n1 2\n2 3\n3 4\n1 2 1 2"] | 2 seconds | ["YES\n2", "YES\n2", "NO"] | null | Java 8 | standard input | [
"dp",
"graphs",
"dsu",
"implementation",
"dfs and similar",
"trees"
] | aaca5d07795a42ecab210327c1cf6be9 | The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices. | 1,600 | Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. | standard output | |
PASSED | de9849847d1d1c99583151f7b084d017 | train_004.jsonl | 1486042500 | Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.A subtree of some vertex is a subgraph containing that vertex and all its descendants.Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. | 256 megabytes | /******************************************************************************
Online Java Compiler.
Code, Compile, Run and Debug java program online.
Write your code in this editor and press "Run" button to execute it.
*******************************************************************************/
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
int[] color=new int[n];
int[] diff=new int[n];
int[][] edge=new int[n-1][2];
for(int i=0;i<n-1;i++) {
edge[i][0]=scan.nextInt()-1;
edge[i][1]=scan.nextInt()-1;
}
int count=0;
for(int i=0;i<n;i++)
color[i]=scan.nextInt();
for(int i=0;i<n-1;i++) {
if(color[edge[i][0]]!=color[edge[i][1]]) {
diff[edge[i][0]]++;
diff[edge[i][1]]++;
count++;
}
}
boolean mila=false;
for(int i=0;i<n;i++){
if(diff[i]==count){
System.out.println("YES");
System.out.println(i+1);
mila=true;
break;
}
}
if(!mila)
System.out.println("NO");
}
}
| Java | ["4\n1 2\n2 3\n3 4\n1 2 1 1", "3\n1 2\n2 3\n1 2 3", "4\n1 2\n2 3\n3 4\n1 2 1 2"] | 2 seconds | ["YES\n2", "YES\n2", "NO"] | null | Java 8 | standard input | [
"dp",
"graphs",
"dsu",
"implementation",
"dfs and similar",
"trees"
] | aaca5d07795a42ecab210327c1cf6be9 | The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices. | 1,600 | Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. | standard output | |
PASSED | e187b839815b3af968ef6fe60c0eb640 | train_004.jsonl | 1486042500 | Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.A subtree of some vertex is a subgraph containing that vertex and all its descendants.Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int v1[] = new int[n-1], v2[] = new int[n-1], color[] = new int[n+1];
for(int i=0 ;i<n-1;i++){
v1[i] = sc.nextInt();
v2[i] = sc.nextInt();
}
for(int i=1 ;i<=n;i++){
color[i] = sc.nextInt();
}
boolean ans=true;
int ansv=1;
for(int i=0 ;i<n-1;i++){
if(color[v1[i]]!=color[v2[i]]){
ansv = v1[i];
for(int j=0 ;j<n-1;j++){
int color1 = color[v1[j]], color2 = color[v2[j]];
if(v1[j]==v1[i] || v2[j] ==v1[i])
continue;
if(color1!=color2){
ans = false;
break;
}
}
if(ans)
break;
ans = true;
ansv = v2[i];
for(int j=0 ;j<n-1;j++){
int color1 = color[v1[j]], color2 = color[v2[j]];
if(v1[j]==v2[i] || v2[j] ==v2[i])
continue;
if(color1!=color2){
ans = false;
break;
}
}
if(ans)
break;
}
}
System.out.print(ans?"YES\r\n"+ansv :"NO");
}
} | Java | ["4\n1 2\n2 3\n3 4\n1 2 1 1", "3\n1 2\n2 3\n1 2 3", "4\n1 2\n2 3\n3 4\n1 2 1 2"] | 2 seconds | ["YES\n2", "YES\n2", "NO"] | null | Java 8 | standard input | [
"dp",
"graphs",
"dsu",
"implementation",
"dfs and similar",
"trees"
] | aaca5d07795a42ecab210327c1cf6be9 | The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices. | 1,600 | Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. | standard output | |
PASSED | 20f45c917c4df814bfd0fef0cc7a287b | train_004.jsonl | 1486042500 | Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.A subtree of some vertex is a subgraph containing that vertex and all its descendants.Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{ static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args)
{
FastReader sc=new FastReader();
int n= sc.nextInt();
Pair p[]= new Pair[n-1];
for(int i=0;i<n-1;i++)
{
p[i]= new Pair(sc.nextInt()-1,sc.nextInt()-1);
}
int a[]= new int[n];
for(int i=0;i<n;i++)
a[i]= sc.nextInt();
int count[]=new int[n];
int c=0;
for(int i=0;i<n-1;i++)
{
int x= p[i].x;
int y= p[i].y;
if(a[x]!=a[y])
{
count[x]++;
count[y]++;
c++;
}
}
int flag=0;
for(int i=0;i<n;i++)
{
if(c==count[i])
{
System.out.println("YES");
System.out.println(i+1);
flag=1;
break;
}
}
if(flag==0)
System.out.println("NO");
}
static class Pair
{
int x;
int y;
public Pair(int a, int b)
{
x=a;
y=b;
}
}
}
| Java | ["4\n1 2\n2 3\n3 4\n1 2 1 1", "3\n1 2\n2 3\n1 2 3", "4\n1 2\n2 3\n3 4\n1 2 1 2"] | 2 seconds | ["YES\n2", "YES\n2", "NO"] | null | Java 8 | standard input | [
"dp",
"graphs",
"dsu",
"implementation",
"dfs and similar",
"trees"
] | aaca5d07795a42ecab210327c1cf6be9 | The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices. | 1,600 | Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. | standard output | |
PASSED | 8ae68f7235efd49d91e48b26c6173fb5 | train_004.jsonl | 1486042500 | Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can.Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex.A subtree of some vertex is a subgraph containing that vertex and all its descendants.Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. | 256 megabytes |
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Scanner;
public class TimeofeyAndATree {
private static class ColoredTree {
private static class ColoredTreeNode {
private static final int MIXED_COLORS = -1;
private final int id;
private int color;
private final List<ColoredTreeNode> connections;
private final Map<ColoredTreeNode, Integer> colorConnections;
/**
* Used in the population algorithm to reduce time complexity.
*/
private final Map<Integer, Integer> colorFrequency;
public ColoredTreeNode(int id) {
this.id = id;
connections = new ArrayList<>();
colorConnections = new HashMap<>();
colorFrequency = new HashMap<>();
}
public void setColor(int color) {
this.color = color;
}
public void connectWith(ColoredTreeNode o) {
connections.add(o);
o.connections.add(this);
}
/**
* Mutates the node and its connected nodes. Unspecified behavior if already
* called.
*/
public Optional<Integer> findRemovableVertex() {
populateChildrenRelations(null);
populateParentRelations(null);
ColoredTreeNode n = findRemovableVertex(null);
if (n != null) {
return Optional.of(n.id);
}
return Optional.empty();
}
/**
* Should be O(n) as we explore all nodes and should only consider each edge at
* most twice.
*/
private ColoredTreeNode findRemovableVertex(ColoredTreeNode parent) {
// This node is removable if all its connections are uniform in color.
boolean isRemovableVertex = colorConnections.values().stream().allMatch(i -> i != MIXED_COLORS);
if (isRemovableVertex) {
return this;
}
for (ColoredTreeNode child : connections) {
if (child != parent) {
// Filter out parent nodes we already visited.
ColoredTreeNode n = child.findRemovableVertex(this);
if (n != null) {
return n;
}
}
}
return null;
}
/**
* Should be O(n) as we explore all nodes and should only consider each edge at
* most twice.
*/
private void populateChildrenRelations(ColoredTreeNode parent) {
for (ColoredTreeNode child : connections) {
if (child != parent) {
// Filter out parent nodes we already visited.
child.populateChildrenRelations(this);
// Set this node's color connection to this child.
int childConnection = child.colorConnections.entrySet().stream().map(Entry::getValue)
.reduce(child.color, this::reduceColorConnections);
recordColorConnection(child, childConnection);
}
}
}
/**
* Should be O(n) as we explore all nodes once.
*/
private void populateParentRelations(ColoredTreeNode parent) {
if (parent != null) {
// Set this node's color connection to its parent.
int colorConnection = MIXED_COLORS;
if (parent.connections.size() == 1) {
colorConnection = parent.color;
} else if (parent.colorFrequency.size() == 1) {
// If our parent only had one color among is children, that is this node's color
// connection to the parent unless the parent itself is a different color.
colorConnection = parent.colorFrequency.keySet().iterator().next();
} else if (parent.colorFrequency.size() == 2) {
int toThisColor = parent.colorConnections.get(this);
if (parent.colorFrequency.get(toThisColor) == 1) {
// We know every other node was uniform in color. Use that for our connection to
// the parent unless the parent itself is a different color.
colorConnection = parent.colorFrequency.entrySet().stream()
.filter(e -> e.getKey() != toThisColor).findFirst().get().getKey();
}
}
if (parent.color != colorConnection) {
colorConnection = MIXED_COLORS;
}
recordColorConnection(parent, colorConnection);
}
for (ColoredTreeNode child : connections) {
if (child != parent) {
// Filter out parent nodes we already visited.
child.populateParentRelations(this);
}
}
}
private void recordColorConnection(ColoredTreeNode node, int colorConnection) {
colorConnections.put(node, colorConnection);
colorFrequency.put(colorConnection, colorFrequency.getOrDefault(colorConnection, 0) + 1);
}
private int reduceColorConnections(int n1, int n2) {
return n1 == n2 ? n1 : MIXED_COLORS;
}
}
private static class Builder {
/**
* Table to find existing nodes in constant time.
*/
private final Map<Integer, ColoredTreeNode> nodeLookup = new HashMap<>();
public void addConnection(int n1, int n2) {
ColoredTreeNode node1 = nodeLookup.getOrDefault(n1, new ColoredTreeNode(n1));
ColoredTreeNode node2 = nodeLookup.getOrDefault(n2, new ColoredTreeNode(n2));
node1.connectWith(node2);
// Add the nodes to our table. They may already be in there but this simplifies
// handling.
nodeLookup.put(n1, node1);
nodeLookup.put(n2, node2);
}
public void setColorFor(int nodeId, int color) {
nodeLookup.get(nodeId).setColor(color);
}
public ColoredTree build() {
// Any node can be a root node in a tree.
return new ColoredTree(nodeLookup.values().iterator().next());
}
}
/**
* If we already calculated this previously, just reuse the answer. The tree is
* immutable.
*/
private Optional<Integer> removableVertex;
private final ColoredTreeNode rootNode;
public ColoredTree(ColoredTreeNode rootNode) {
this.rootNode = rootNode;
}
public Optional<Integer> getRemovableVertex() {
if (removableVertex == null) {
removableVertex = rootNode.findRemovableVertex();
}
return removableVertex;
}
public static Builder builder() {
return new Builder();
}
}
public static void main(String[] args) {
try (Scanner s = new Scanner(System.in)) {
ColoredTree.Builder treeBuilder = ColoredTree.builder();
int numNodes = s.nextInt();
for (int i = 0; i < numNodes - 1; i++) {
treeBuilder.addConnection(s.nextInt(), s.nextInt());
}
for (int i = 0; i < numNodes; i++) {
treeBuilder.setColorFor(i + 1, s.nextInt());
}
Optional<Integer> removalVertex = treeBuilder.build().getRemovableVertex();
System.out.println(removalVertex.map(i -> String.format("YES\n%d", i)).orElse("NO"));
}
}
}
| Java | ["4\n1 2\n2 3\n3 4\n1 2 1 1", "3\n1 2\n2 3\n1 2 3", "4\n1 2\n2 3\n3 4\n1 2 1 2"] | 2 seconds | ["YES\n2", "YES\n2", "NO"] | null | Java 8 | standard input | [
"dp",
"graphs",
"dsu",
"implementation",
"dfs and similar",
"trees"
] | aaca5d07795a42ecab210327c1cf6be9 | The first line contains single integer n (2 ≤ n ≤ 105) — the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 105), denoting the colors of the vertices. | 1,600 | Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. | standard output | |
PASSED | 2d6b0890d0660d535ac58db4c2207f7d | train_004.jsonl | 1411054200 | The new ITone 6 has been released recently and George got really keen to buy it. Unfortunately, he didn't have enough money, so George was going to work as a programmer. Now he faced the following problem at the work.Given a sequence of n integers p1, p2, ..., pn. You are to choose k pairs of integers: [l1, r1], [l2, r2], ..., [lk, rk] (1 ≤ l1 ≤ r1 < l2 ≤ r2 < ... < lk ≤ rk ≤ n; ri - li + 1 = m), in such a way that the value of sum is maximal possible. Help George to cope with the task. | 256 megabytes | import java.io.*;
import java.util.*;
public class lastProblem {
/**
* @param args
* @throws IOException
* @throws NumberFormatException
*/
public static long[]sum = new long[5003];
public static long[]num = new long[5003];
public static long[][]dp ;
public static int n , m , K;
public static long solve(int index , int pairs){
if (pairs == 0) {
return 0;
}
if (index >= n) {
return -10000000;
}
if (dp[index][pairs] != -1) {
return dp[index][pairs];
}
long first = solve(index+1, pairs);
long second = 0;
if (m+index-1 < n ) {
second = solve(m+index, pairs-1)+sum[m+index-1]-sum[index]+num[index];
}
return dp[index][pairs] = Math.max(first,second);
}
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO Auto-generated method stub
BufferedReader k = new BufferedReader(new InputStreamReader(System.in));
//BufferedReader k = new BufferedReader(new FileReader("cubes.in"));
StringTokenizer str = new StringTokenizer(k.readLine());
n = Integer.parseInt(str.nextToken());// len
m = Integer.parseInt(str.nextToken());// diff
K = Integer.parseInt(str.nextToken());// pairs
str = new StringTokenizer(k.readLine());
for (int i = 0; i < n; i++) {
num[i] = Integer.parseInt(str.nextToken());
sum[i]+= num[i]+ (i == 0? 0 : sum[i-1]);
}
dp = new long[n+1][K+1];
for (int i = 0; i < n+1; i++) {
Arrays.fill(dp[i], -1);
}
System.out.println(solve(0, K));
}
}
| Java | ["5 2 1\n1 2 3 4 5", "7 1 3\n2 10 7 18 5 33 0"] | 1 second | ["9", "61"] | null | Java 8 | standard input | [
"dp",
"implementation"
] | ee3c228cc817536bf6c10ea4508d786f | The first line contains three integers n, m and k (1 ≤ (m × k) ≤ n ≤ 5000). The second line contains n integers p1, p2, ..., pn (0 ≤ pi ≤ 109). | 1,700 | Print an integer in a single line — the maximum possible value of sum. | standard output | |
PASSED | 2288ab62af769e7947f24df5886d51b2 | train_004.jsonl | 1411054200 | The new ITone 6 has been released recently and George got really keen to buy it. Unfortunately, he didn't have enough money, so George was going to work as a programmer. Now he faced the following problem at the work.Given a sequence of n integers p1, p2, ..., pn. You are to choose k pairs of integers: [l1, r1], [l2, r2], ..., [lk, rk] (1 ≤ l1 ≤ r1 < l2 ≤ r2 < ... < lk ≤ rk ≤ n; ri - li + 1 = m), in such a way that the value of sum is maximal possible. Help George to cope with the task. | 256 megabytes | import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(1, in, out);
out.close();
}
}
class Task {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
long[] s = new long[n+1];
long temp;
for(int i = 1; i <= n; ++i){
temp = in.nextLong();
s[i] = s[i-1] + temp;
}
long[][] dp = new long[2][n+1];
int index = 0;
for(int i = 1; i <= k; ++i) {
index = 1 - index;
for (int j = i * m; j <= n; ++j) {
dp[index][j] = Math.max(dp[index][j - 1], dp[1 - index][j - m] + s[j] - s[j - m]);
}
}
out.println(dp[index][n]);
}
}
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 2 1\n1 2 3 4 5", "7 1 3\n2 10 7 18 5 33 0"] | 1 second | ["9", "61"] | null | Java 6 | standard input | [
"dp",
"implementation"
] | ee3c228cc817536bf6c10ea4508d786f | The first line contains three integers n, m and k (1 ≤ (m × k) ≤ n ≤ 5000). The second line contains n integers p1, p2, ..., pn (0 ≤ pi ≤ 109). | 1,700 | Print an integer in a single line — the maximum possible value of sum. | standard output | |
PASSED | b52869c9dad1dd7ed9144cab857d460b | train_004.jsonl | 1411054200 | The new ITone 6 has been released recently and George got really keen to buy it. Unfortunately, he didn't have enough money, so George was going to work as a programmer. Now he faced the following problem at the work.Given a sequence of n integers p1, p2, ..., pn. You are to choose k pairs of integers: [l1, r1], [l2, r2], ..., [lk, rk] (1 ≤ l1 ≤ r1 < l2 ≤ r2 < ... < lk ≤ rk ≤ n; ri - li + 1 = m), in such a way that the value of sum is maximal possible. Help George to cope with the task. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class TC {
public void solve(int n, int m, int k, int[] p) {
long[] sum = new long[n + 1];
for (int i = 1; i <= n; i ++) {
sum[i] = sum[i - 1] + p[i - 1];
}
long [][] dp = new long[n + 2][2];
int a = 0, b = 0;
for (int i = 0; i < k; i ++) {
a = i % 2;
b = 1 ^ a;
for (int j = 1; j <= n - m + 1; j ++)
dp[j][a] = Math.max(dp[j][a], sum[j + m - 1] - sum[j - 1] + dp[j + m][b]);
for (int j = n; j > 1; j --)
dp[j - 1][a] = Math.max(dp[j][a], dp[j - 1][a]);
}
System.out.println(dp[1][a]);
}
public static void main(String[] args) {
FastScanner in = new FastScanner();
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int[] p = new int[n];
for (int i = 0; i < n; i ++) p[i] = in.nextInt();
new TC().solve(n, m, k, p);
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(String s) {
try {
br = new BufferedReader(new FileReader(s));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String nextToken() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
| Java | ["5 2 1\n1 2 3 4 5", "7 1 3\n2 10 7 18 5 33 0"] | 1 second | ["9", "61"] | null | Java 6 | standard input | [
"dp",
"implementation"
] | ee3c228cc817536bf6c10ea4508d786f | The first line contains three integers n, m and k (1 ≤ (m × k) ≤ n ≤ 5000). The second line contains n integers p1, p2, ..., pn (0 ≤ pi ≤ 109). | 1,700 | Print an integer in a single line — the maximum possible value of sum. | standard output | |
PASSED | 0380174a0115a30c5bfbfd2ae6e910d2 | train_004.jsonl | 1411054200 | The new ITone 6 has been released recently and George got really keen to buy it. Unfortunately, he didn't have enough money, so George was going to work as a programmer. Now he faced the following problem at the work.Given a sequence of n integers p1, p2, ..., pn. You are to choose k pairs of integers: [l1, r1], [l2, r2], ..., [lk, rk] (1 ≤ l1 ≤ r1 < l2 ≤ r2 < ... < lk ≤ rk ≤ n; ri - li + 1 = m), in such a way that the value of sum is maximal possible. Help George to cope with the task. | 256 megabytes | import java.util.Arrays;
//################################################################################################################
import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.InputStream;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
//################################################################################################################
public class Main {
class InputReader1 {
//private final boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader1(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1)
return -1;
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0)
return -1;
}
return buf[curChar];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int length = readInt();
if (length < 0)
return null;
byte[] bytes = new byte[length];
for (int i = 0; i < length; i++)
bytes[i] = (byte) read();
try {
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
return new String(bytes);
}
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuffer buf = new StringBuffer();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r')
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines)
return readLine();
else
return readLine0();
}
public BigInteger readBigInteger() {
try {
return new BigInteger(readString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public double readDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted() {
int value;
while (isSpaceChar(value = peek()) && value != -1)
read();
return value == -1;
}
public String next() {
return readString();
}
public boolean readBoolean() {
return readInt() == 1;
}
public void close(){
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream stream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void println(String s) {
writer.println(s);
}
public void println(int x) {
writer.println(x);
}
public void print(int x) {
writer.print(x);
}
public void println(long x) {
writer.println(x);
}
public void printSpace() {
writer.print(" ");
}
public void close() {
writer.close();
}
}
public static void main(String[] args) {
Main main = new Main();
InputReader1 reader = main.new InputReader1(System.in);
OutputWriter writer = main.new OutputWriter(System.out);
//put your code here
int n = reader.readInt();
int m = reader.readInt();
int k = reader.readInt();
if (m == 1) {
int[] p = new int[n];
for (int i = 0; i < p.length; i++) {
p[i] = reader.readInt();
}
Arrays.sort(p);
long sum = 0;
for (int i = 0; i < k; i++) {
sum += p[p.length - 1 - i];
}
writer.println(sum);
} else {
long[][] dp = new long[n][k];
long[] cs = new long[n + 1];
cs[0] = 0;
for (int i = 1; i <= dp.length; i++) {
cs[i] = reader.readInt();
cs[i] += cs[i - 1];
}
for (int i = 0; i < m - 1; i++) {
for (int j = 0; j < k; j++) {
dp[i][j] = 0;
}
}
dp[m - 1][0] = cs[m];
for (int j = 1; j < k; j++) {
dp[m - 1][j] = 0;
}
for (int i = m; i < n; i++) {
dp[i][0] = Math.max(dp[i - 1][0], cs[i + 1] - cs[i - m + 1]);
for (int j = 1; j < k; j++) {
dp[i][j] = Math.max(dp[i - 1][j], dp[i - m][j - 1] + cs[i + 1] - cs[i - m + 1]);
}
}
writer.println(dp[n - 1][k - 1]);
}
reader.close();
writer.close();
}
}
| Java | ["5 2 1\n1 2 3 4 5", "7 1 3\n2 10 7 18 5 33 0"] | 1 second | ["9", "61"] | null | Java 6 | standard input | [
"dp",
"implementation"
] | ee3c228cc817536bf6c10ea4508d786f | The first line contains three integers n, m and k (1 ≤ (m × k) ≤ n ≤ 5000). The second line contains n integers p1, p2, ..., pn (0 ≤ pi ≤ 109). | 1,700 | Print an integer in a single line — the maximum possible value of sum. | standard output | |
PASSED | 421ba43835bc5592f7a9a6f4787a5de8 | train_004.jsonl | 1411054200 | The new ITone 6 has been released recently and George got really keen to buy it. Unfortunately, he didn't have enough money, so George was going to work as a programmer. Now he faced the following problem at the work.Given a sequence of n integers p1, p2, ..., pn. You are to choose k pairs of integers: [l1, r1], [l2, r2], ..., [lk, rk] (1 ≤ l1 ≤ r1 < l2 ≤ r2 < ... < lk ≤ rk ≤ n; ri - li + 1 = m), in such a way that the value of sum is maximal possible. Help George to cope with the task. | 256 megabytes | import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
/*
br = new BufferedReader(new FileReader("input.txt"));
pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
*/
public class Main {
private static BufferedReader br;
private static StringTokenizer st;
private static PrintWriter pw;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
//int qq = 1;
int qq = Integer.MAX_VALUE;
//int qq = readInt();
for(int casenum = 1; casenum <= qq; casenum++) {
int n = readInt();
int size = readInt();
int num = readInt();
long[] prefix = new long[n+1];
for(int i = 1; i <= n; i++) {
prefix[i] = prefix[i-1] + readInt();
}
long[] dp = new long[n+1];
while(num-- > 0) {
long[] next = new long[n+1];
long big = 0;
for(int i = 0; i < dp.length-size; i++) {
big = Math.max(big, dp[i]);
next[i + size] = big + prefix[i+size] - prefix[i];
}
dp = next;
}
long ret = 0;
for(long out: dp) {
ret = Math.max(ret, out);
}
pw.println(ret);
}
exitImmediately();
}
private static void exitImmediately() {
pw.close();
System.exit(0);
}
private static long readLong() throws IOException {
return Long.parseLong(nextToken());
}
private static double readDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private static int readInt() throws IOException {
return Integer.parseInt(nextToken());
}
private static String nextLine() throws IOException {
if(!br.ready()) {
exitImmediately();
}
st = null;
return br.readLine();
}
private static String nextToken() throws IOException {
while(st == null || !st.hasMoreTokens()) {
if(!br.ready()) {
exitImmediately();
}
st = new StringTokenizer(br.readLine().trim());
}
return st.nextToken();
}
}
| Java | ["5 2 1\n1 2 3 4 5", "7 1 3\n2 10 7 18 5 33 0"] | 1 second | ["9", "61"] | null | Java 6 | standard input | [
"dp",
"implementation"
] | ee3c228cc817536bf6c10ea4508d786f | The first line contains three integers n, m and k (1 ≤ (m × k) ≤ n ≤ 5000). The second line contains n integers p1, p2, ..., pn (0 ≤ pi ≤ 109). | 1,700 | Print an integer in a single line — the maximum possible value of sum. | standard output | |
PASSED | 547f109d7b525f2537dd7aa8c11de354 | train_004.jsonl | 1411054200 | The new ITone 6 has been released recently and George got really keen to buy it. Unfortunately, he didn't have enough money, so George was going to work as a programmer. Now he faced the following problem at the work.Given a sequence of n integers p1, p2, ..., pn. You are to choose k pairs of integers: [l1, r1], [l2, r2], ..., [lk, rk] (1 ≤ l1 ≤ r1 < l2 ≤ r2 < ... < lk ≤ rk ≤ n; ri - li + 1 = m), in such a way that the value of sum is maximal possible. Help George to cope with the task. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader scn = new InputReader(inputStream);
PrintWriter prn = new PrintWriter(outputStream);
II__ASC__II Mechanism = new II__ASC__II();
Mechanism.Process(scn, prn);
prn.close();
}
}
class II__ASC__II {
public void Process(InputReader scn, PrintWriter prn) throws IOException {
int n = scn.nextInt(), m = scn.nextInt(), k = scn.nextInt();
long[][] f = new long[m + 1][];
long inf = (long) -1e17;
f[0] = new long[k + 1];
Arrays.fill(f[0], inf);
f[0][0] = 0;
long sum[] = new long[n + 1];
for (int i = 1; i <= n; ++i) {
int p = scn.nextInt();
sum[i] = sum[i - 1] + p;
int ii = i % (m + 1);
f[ii] = new long[k + 1];
for (int j = 0; j <= k; ++j) {
f[ii][j] = f[(i - 1) % (m + 1)][j];
if (j > 0 && i >= m)
f[ii][j] = Math.max(f[ii][j], f[(i - m) % (m + 1)][j - 1]
+ sum[i] - sum[i - m]);
}
}
prn.println(f[n % (m + 1)][k]);
}
}
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 String nextLine() throws IOException {
return reader.readLine();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public Integer toInt(String s) {
return Integer.parseInt(s.trim());
}
public Long toLong(String s) {
return Long.parseLong(s.trim());
}
public Double toDouble(String s) {
return Double.parseDouble(s.trim());
}
public int[] getIntArray(String line) {
String s[] = line.split(" ");
int a[] = new int[s.length];
for (int i = 0; i < s.length; ++i) {
a[i] = Integer.parseInt(s[i]);
}
return a;
}
public Integer[] getIntegerArray(String line) {
String s[] = line.split(" ");
Integer a[] = new Integer[s.length];
for (int i = 0; i < s.length; ++i) {
a[i] = Integer.parseInt(s[i]);
}
return a;
}
public Double[] getDoubleArray(String line) {
String s[] = line.split(" ");
Double a[] = new Double[s.length];
for (int i = 0; i < s.length; ++i) {
a[i] = Double.parseDouble(s[i]);
}
return a;
}
public Long[] getLongArray(String line) {
String s[] = line.split(" ");
Long a[] = new Long[s.length];
for (int i = 0; i < s.length; ++i) {
a[i] = Long.parseLong(s[i]);
}
return a;
}
public Long getMaxFromLongArray(Long a[]) {
Long max = Long.MIN_VALUE;
for (int i = 0; i < a.length; ++i) {
if (max < a[i]) {
max = a[i];
}
}
return max;
}
public Long getMinFromLongArray(Long a[]) {
Long min = Long.MAX_VALUE;
for (int i = 0; i < a.length; ++i) {
if (min > a[i]) {
min = a[i];
}
}
return min;
}
public Integer getMaxFromIntegerArray(Integer a[]) {
Integer max = Integer.MIN_VALUE;
for (int i = 0; i < a.length; ++i) {
if (max < a[i]) {
max = a[i];
}
}
return max;
}
public Integer getMinFromIntegerArray(Integer a[]) {
Integer min = Integer.MAX_VALUE;
for (int i = 0; i < a.length; ++i) {
if (min > a[i]) {
min = a[i];
}
}
return min;
}
long modPow(long a, long x, long p) {
long res = 1;
while (x > 0) {
if (x % 2 != 0) {
res = (res % p * a % p) % p;
}
a = (a % p * a % p) % p;
x /= 2;
}
return res;
}
long modInverse(long a, long p) {
return modPow(a, p - 2, p);
}
long modBinomial(long n, long k, long p) {
long numerator = 1; // n * (n-1) * ... * (n-k+1)
for (long i = 0; i < k; i++) {
numerator = (numerator % p * (n - i) % p) % p;
}
long denominator = 1; // k!
for (long i = 1; i <= k; i++) {
denominator = (denominator % p * i % p) % p;
}
return (numerator % p * modInverse(denominator, p) % p) % p;
}
public long calculate(long k, long n) {
return (modBinomial(n, k, 1000000007));
}
} | Java | ["5 2 1\n1 2 3 4 5", "7 1 3\n2 10 7 18 5 33 0"] | 1 second | ["9", "61"] | null | Java 6 | standard input | [
"dp",
"implementation"
] | ee3c228cc817536bf6c10ea4508d786f | The first line contains three integers n, m and k (1 ≤ (m × k) ≤ n ≤ 5000). The second line contains n integers p1, p2, ..., pn (0 ≤ pi ≤ 109). | 1,700 | Print an integer in a single line — the maximum possible value of sum. | standard output | |
PASSED | 1ada6731bfd665f022ace7367a4851ea | train_004.jsonl | 1411054200 | The new ITone 6 has been released recently and George got really keen to buy it. Unfortunately, he didn't have enough money, so George was going to work as a programmer. Now he faced the following problem at the work.Given a sequence of n integers p1, p2, ..., pn. You are to choose k pairs of integers: [l1, r1], [l2, r2], ..., [lk, rk] (1 ≤ l1 ≤ r1 < l2 ≤ r2 < ... < lk ≤ rk ≤ n; ri - li + 1 = m), in such a way that the value of sum is maximal possible. Help George to cope with the task. | 256 megabytes | import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
}
class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int k = in.nextInt();
int[] a = new int[n];
long[] sum = new long[n + 1];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
sum[i + 1] = a[i] + sum[i];
}
long res = 0;
long[] tmp = new long[n - m + 1];
for (int i = 0; i <= n - m; i++) {
tmp[i] = sum[i + m] - sum[i];
}
if (m == 1) {
Arrays.sort(a);
int i = n - 1;
while (k > 0) {
res += a[i];
i--;
k--;
}
out.println(res);
} else {
long[][] dp = new long[k + 1][tmp.length+1];
for (int i = 1; i <= k; i++) {
for (int j = 1; j <= tmp.length; j++) {
dp[i][j] = Math.max(dp[i][j - 1], ((j - m >= 0) ? (dp[i - 1][j - m]) : (0)) + tmp[j-1]);
}
}
out.println(dp[k][tmp.length]);
}
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
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 2 1\n1 2 3 4 5", "7 1 3\n2 10 7 18 5 33 0"] | 1 second | ["9", "61"] | null | Java 6 | standard input | [
"dp",
"implementation"
] | ee3c228cc817536bf6c10ea4508d786f | The first line contains three integers n, m and k (1 ≤ (m × k) ≤ n ≤ 5000). The second line contains n integers p1, p2, ..., pn (0 ≤ pi ≤ 109). | 1,700 | Print an integer in a single line — the maximum possible value of sum. | standard output | |
PASSED | fb8aff893ff132623d82b28b777e09df | train_004.jsonl | 1411054200 | The new ITone 6 has been released recently and George got really keen to buy it. Unfortunately, he didn't have enough money, so George was going to work as a programmer. Now he faced the following problem at the work.Given a sequence of n integers p1, p2, ..., pn. You are to choose k pairs of integers: [l1, r1], [l2, r2], ..., [lk, rk] (1 ≤ l1 ≤ r1 < l2 ≤ r2 < ... < lk ≤ rk ≤ n; ri - li + 1 = m), in such a way that the value of sum is maximal possible. Help George to cope with the task. | 256 megabytes | import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int m=s.nextInt();
int k=s.nextInt();
int[] a=new int[n];
for(int i=0;i<n;i++)
{
a[i]=s.nextInt();
}
long s1=0;
for(int i=0;i<m;i++)
{
s1=s1+a[i];
}
long[] sum=new long[n-m+1];
sum[0]=s1;
for(int i=1;i<=n-m;i++)
{
sum[i] = sum[i-1] - a[i-1] + a[m+i-1];
}
long[][] ans=new long[n+1][2];
for(int j=0;j<=k;j++)
{
for(int i=0;i<=n;i++)
{
ans[i][j%2]=0;
if(i>=1)
{
ans[i][j%2]=ans[i-1][j%2];
}
if(i>=m && j>=1 && ans[i-m][(j-1)%2] + sum[i-m]>ans[i][j%2])
{
ans[i][j%2]=ans[i-m][(j-1)%2] + sum[i-m];
}
}
}
System.out.println(ans[n][k%2]);
}
}
| Java | ["5 2 1\n1 2 3 4 5", "7 1 3\n2 10 7 18 5 33 0"] | 1 second | ["9", "61"] | null | Java 6 | standard input | [
"dp",
"implementation"
] | ee3c228cc817536bf6c10ea4508d786f | The first line contains three integers n, m and k (1 ≤ (m × k) ≤ n ≤ 5000). The second line contains n integers p1, p2, ..., pn (0 ≤ pi ≤ 109). | 1,700 | Print an integer in a single line — the maximum possible value of sum. | standard output | |
PASSED | fa497612c178a7d9a53ec6ee3078de8b | train_004.jsonl | 1411054200 | The new ITone 6 has been released recently and George got really keen to buy it. Unfortunately, he didn't have enough money, so George was going to work as a programmer. Now he faced the following problem at the work.Given a sequence of n integers p1, p2, ..., pn. You are to choose k pairs of integers: [l1, r1], [l2, r2], ..., [lk, rk] (1 ≤ l1 ≤ r1 < l2 ≤ r2 < ... < lk ≤ rk ≤ n; ri - li + 1 = m), in such a way that the value of sum is maximal possible. Help George to cope with the task. | 256 megabytes | import java.util.*;
public class Main {
private static long solve(int n, int m, int k, int[] p) {
if (m == 1) {
Arrays.sort(p);
long res = 0;
for (int i = 0; i < k; i++) res += p[n-1-i];
return res;
}
long[] s = new long[n+1];
for (int i = 1; i <= n; i++) s[i] = s[i-1]+p[i-1];
long[][] d = new long[n+1][k+1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= k; j++) {
d[i][j] = d[i-1][j];
if (i-m >= 0) d[i][j] = Math.max(
d[i][j], d[i-m][j-1]+s[i]-s[i-m]);
}
}
return d[n][k];
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt(), m = in.nextInt(), k = in.nextInt();
int[] p = new int[n];
for (int i = 0; i < n; i++) p[i] = in.nextInt();
System.out.println(solve(n, m, k, p));
}
} | Java | ["5 2 1\n1 2 3 4 5", "7 1 3\n2 10 7 18 5 33 0"] | 1 second | ["9", "61"] | null | Java 6 | standard input | [
"dp",
"implementation"
] | ee3c228cc817536bf6c10ea4508d786f | The first line contains three integers n, m and k (1 ≤ (m × k) ≤ n ≤ 5000). The second line contains n integers p1, p2, ..., pn (0 ≤ pi ≤ 109). | 1,700 | Print an integer in a single line — the maximum possible value of sum. | standard output | |
PASSED | f852ab7fbe165ddcd3ed427d72c57604 | train_004.jsonl | 1411054200 | The new ITone 6 has been released recently and George got really keen to buy it. Unfortunately, he didn't have enough money, so George was going to work as a programmer. Now he faced the following problem at the work.Given a sequence of n integers p1, p2, ..., pn. You are to choose k pairs of integers: [l1, r1], [l2, r2], ..., [lk, rk] (1 ≤ l1 ≤ r1 < l2 ≤ r2 < ... < lk ≤ rk ≤ n; ri - li + 1 = m), in such a way that the value of sum is maximal possible. Help George to cope with the task. | 256 megabytes | /**
* Created by ckboss on 14-9-19.
*/
import java.util.*;
public class GeorgeandJob {
static int n,m,k;
static long[] a = new long[5050];
static long[] sum = new long[5050];
static long[][] dp = new long[5050][3];
public static void main(String[] args){
Scanner in = new Scanner(System.in);
n=in.nextInt(); m=in.nextInt(); k=in.nextInt();
for(int i=1;i<=n;i++){
a[i]=in.nextInt();
sum[i]=sum[i-1]+a[i];
}
///init...
for(int i=m;i<=n;i++){
dp[i][1]=Math.max(dp[i-1][1],sum[i]-sum[i-m]);
}
for(int j=2;j<=k;j++){
for(int i=j*m;i<=n;i++){
dp[i][j%2]=Math.max(dp[i-m][(j-1)%2]+sum[i]-sum[i-m],dp[i-1][j%2]);
}
}
long ans=0;
for(int i=k*m;i<=n;i++){
ans=Math.max(ans,dp[i][k%2]);
}
System.out.println(ans);
}
}
| Java | ["5 2 1\n1 2 3 4 5", "7 1 3\n2 10 7 18 5 33 0"] | 1 second | ["9", "61"] | null | Java 6 | standard input | [
"dp",
"implementation"
] | ee3c228cc817536bf6c10ea4508d786f | The first line contains three integers n, m and k (1 ≤ (m × k) ≤ n ≤ 5000). The second line contains n integers p1, p2, ..., pn (0 ≤ pi ≤ 109). | 1,700 | Print an integer in a single line — the maximum possible value of sum. | standard output | |
PASSED | 9f2cc821a36ab9409b2157e651452811 | train_004.jsonl | 1471698300 | Recently in school Alina has learned what are the persistent data structures: they are data structures that always preserves the previous version of itself and access to it when it is modified.After reaching home Alina decided to invent her own persistent data structure. Inventing didn't take long: there is a bookcase right behind her bed. Alina thinks that the bookcase is a good choice for a persistent data structure. Initially the bookcase is empty, thus there is no book at any position at any shelf.The bookcase consists of n shelves, and each shelf has exactly m positions for books at it. Alina enumerates shelves by integers from 1 to n and positions at shelves — from 1 to m. Initially the bookcase is empty, thus there is no book at any position at any shelf in it.Alina wrote down q operations, which will be consecutively applied to the bookcase. Each of the operations has one of four types: 1 i j — Place a book at position j at shelf i if there is no book at it. 2 i j — Remove the book from position j at shelf i if there is a book at it. 3 i — Invert book placing at shelf i. This means that from every position at shelf i which has a book at it, the book should be removed, and at every position at shelf i which has not book at it, a book should be placed. 4 k — Return the books in the bookcase in a state they were after applying k-th operation. In particular, k = 0 means that the bookcase should be in initial state, thus every book in the bookcase should be removed from its position.After applying each of operation Alina is interested in the number of books in the bookcase. Alina got 'A' in the school and had no problem finding this values. Will you do so? | 512 megabytes | import java.util.*;
import java.io.*;
/**
* @author Azuz
*
*/
public class Main {
int n, m , q;
Query[] queries;
int[] ans;
List<Integer>[] g;
BitSet[] books;
void solve(Scanner in, PrintWriter out) {
n = in.nextInt();
m = in.nextInt();
q = in.nextInt();
books = new BitSet[n];
for (int i = 0; i < n; ++i) {
books[i] = new BitSet(m);
}
ans = new int[q + 1];
queries = new Query[q + 1];
g = new List[q + 1];
for (int i = 0; i <= q; ++i) {
g[i] = new ArrayList<>();
}
for (int i = 1; i <= q; ++i) {
int type = in.nextInt();
if (type <= 2) {
g[i - 1].add(i);
queries[i] = new Query(type, in.nextInt() - 1, in.nextInt() - 1, 0);
} else if (type == 3) {
g[i - 1].add(i);
queries[i] = new Query(type, in.nextInt() - 1, 0, 0);
} else {
queries[i] = new Query(type, 0, 0, in.nextInt());
g[queries[i].k].add(i);
}
}
dfs(0, 0);
for (int i = 1; i <= q; ++i) {
out.println(ans[i]);
}
}
private void dfs(int u, int count) {
ans[u] = count;
for (int v : g[u]) {
Query qq = queries[v];
int i = qq.i;
int j = qq.j;
int k = qq.k;
if (qq.type == 1) {
boolean current = books[i].get(j);
books[i].set(j, true);
dfs(v, count + (current ? 0 : 1));
books[i].set(j, current);
} else if (qq.type == 2) {
boolean current = books[i].get(j);
books[i].set(j, false);
dfs(v, count - (current ? 1 : 0));
books[i].set(j, current);
} else if (qq.type == 3) {
int current = books[i].cardinality();
books[i].flip(0, m);
dfs(v, count - current + (m - current));
books[i].flip(0, m);
} else {
dfs(v, count);
}
}
}
public static void main(String[] args) {
try(Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out)) {
new Main().solve(in, out);
}
}
private static class Query {
int type, i, j, k;
public Query(int type, int i, int j, int k) {
this.type = type;
this.i = i;
this.j = j;
this.k = k;
}
}
}
| Java | ["2 3 3\n1 1 1\n3 2\n4 0", "4 2 6\n3 2\n2 2 2\n3 3\n3 2\n2 2 2\n3 2", "2 2 2\n3 2\n2 2 1"] | 2 seconds | ["1\n4\n0", "2\n1\n3\n3\n2\n4", "2\n1"] | NoteThis image illustrates the second sample case. | Java 11 | standard input | [
"data structures",
"implementation",
"bitmasks",
"dfs and similar"
] | 2b78f6626fce6b5b4f9628fb15666dc4 | The first line of the input contains three integers n, m and q (1 ≤ n, m ≤ 103, 1 ≤ q ≤ 105) — the bookcase dimensions and the number of operations respectively. The next q lines describes operations in chronological order — i-th of them describes i-th operation in one of the four formats described in the statement. It is guaranteed that shelf indices and position indices are correct, and in each of fourth-type operation the number k corresponds to some operation before it or equals to 0. | 2,200 | For each operation, print the number of books in the bookcase after applying it in a separate line. The answers should be printed in chronological order. | standard output | |
PASSED | 8457775cdaf838ad80f8107dcd45e4e8 | train_004.jsonl | 1471698300 | Recently in school Alina has learned what are the persistent data structures: they are data structures that always preserves the previous version of itself and access to it when it is modified.After reaching home Alina decided to invent her own persistent data structure. Inventing didn't take long: there is a bookcase right behind her bed. Alina thinks that the bookcase is a good choice for a persistent data structure. Initially the bookcase is empty, thus there is no book at any position at any shelf.The bookcase consists of n shelves, and each shelf has exactly m positions for books at it. Alina enumerates shelves by integers from 1 to n and positions at shelves — from 1 to m. Initially the bookcase is empty, thus there is no book at any position at any shelf in it.Alina wrote down q operations, which will be consecutively applied to the bookcase. Each of the operations has one of four types: 1 i j — Place a book at position j at shelf i if there is no book at it. 2 i j — Remove the book from position j at shelf i if there is a book at it. 3 i — Invert book placing at shelf i. This means that from every position at shelf i which has a book at it, the book should be removed, and at every position at shelf i which has not book at it, a book should be placed. 4 k — Return the books in the bookcase in a state they were after applying k-th operation. In particular, k = 0 means that the bookcase should be in initial state, thus every book in the bookcase should be removed from its position.After applying each of operation Alina is interested in the number of books in the bookcase. Alina got 'A' in the school and had no problem finding this values. Will you do so? | 512 megabytes | import java.io.*;
import java.math.BigDecimal;
import java.net.Inet4Address;
import java.util.*;
import java.util.Map.Entry;
public class Contest1 {
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////// /////////
//////// /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMMMM MMMMMM OOO OOO SSSS SSS EEEEEEEEEEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMM MMM MMMM OOO OOO SSSS SSS EEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMMMM MMMM OOO OOO SSSS EEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSSSSS EEEEE /////////
//////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSS EEEEEEEEEEE /////////
//////// HHHHHHHHHHHHHHHH EEEEEEEEEEE MMMM MMMM OOO OOO SSSSSSS EEEEEEEEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSSS EEEEE /////////
//////// HHHH HHHH EEEEE MMMM MMMM OOO OOO SSS SSSS EEEEE /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOO OOO SSS SSSS EEEEEEEEEEEEE /////////
//////// HHHH HHHH EEEEEEEEEEEEE MMMM MMMM OOOOOO SSSSSSS EEEEEEEEEEEEE /////////
//////// /////////
//////// /////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void go(int idx) {
for (ArrayList<Query>a1:typo[idx]) {
boolean[]operated= new boolean[a1.size()];
int id=0;
for (Query a : a1) {
int pre=curans;
if (a.type < 3) {
update(a.vals[0]-1, a.vals[1]-1, a.type);
operated[id++]=pre!=curans;
} else {
rev(a.vals[0]-1);
operated[id++]=true;
}
sol[a.idx] = curans;
go(a.idx);
}
for (int i = a1.size()-1;i>=0;i--){
Query a= a1.get(i);
if (!operated[i])continue;
if (a.type < 3) {
update(a.vals[0]-1, a.vals[1]-1, a.type-1);
} else {
rev(a.vals[0]-1);
}
}
}
}
static ArrayList<ArrayList<Query>>[]typo;
static class Query{
int type,idx,vals[];
Query(int t,int[]a,int i){
type=t;
idx=i;
vals=a;
}
}
static int[][]books;
static int[]here,state,sol;
static int n,m,curans;
static void update(int i,int j,int t){
if (t==1){
if (state[i]==1){
if (books[i][j]==1){
books[i][j]=0;
here[i]--;
curans++;
}
}
else {
if (books[i][j]!=1){
books[i][j]=1;
here[i]++;
curans++;
}
}
}
else {
if (state[i]==1){
if (books[i][j]==0){
books[i][j]=1;
here[i]++;
curans--;
}
}
else {
if (books[i][j]==1){
books[i][j]=0;
here[i]--;
curans--;
}
}
}
}
static void rev(int i){
state[i]^=1;
if (state[i]==0){
curans-=(m-here[i]);
curans+=here[i];
}
else {
curans-=here[i];
curans+=(m-here[i]);
}
}
public static void main(String[] args) throws IOException, InterruptedException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
n = sc.nextInt();
m = sc.nextInt();
int q = sc.nextInt();
books= new int[n][m];
state= new int[n];
here= new int[n];
ArrayList<Query>all = new ArrayList<>();
ArrayList<Query>type4=new ArrayList<>();
int tt=0;
typo=new ArrayList[q+1];
int[]move= new int[q+1];
Arrays.fill(move,-1);
move[0]=0;
for (int i =0;i<=q;i++)typo[i]=new ArrayList<>();
for (int i =0;i<q;i++){
int t = sc.nextInt();
int[]a;
if (t>2){
a= new int[1];
a[0]=sc.nextInt();
}
else {
a= new int[2];
a[0]=sc.nextInt();
a[1]=sc.nextInt();
}
Query qq= new Query(t,a,i+1);
if (t==4) {
typo[tt].add(all);
all=new ArrayList<>();
type4.add(qq);
if (move[qq.vals[0]]==-1) {
tt = qq.vals[0];
move[i+1]=qq.vals[0];
}
else {
move[i+1]=move[qq.vals[0]];
tt=move[i+1];
}
}
else{
all.add(qq);
}
}
typo[tt].add(all);
sol= new int[q+1];
curans=0;
go(0);
for (Query a:type4){
sol[a.idx]=sol[a.vals[0]];
}
for (int i =1;i<=q;i++)
pw.println(sol[i]);
pw.flush();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
} | Java | ["2 3 3\n1 1 1\n3 2\n4 0", "4 2 6\n3 2\n2 2 2\n3 3\n3 2\n2 2 2\n3 2", "2 2 2\n3 2\n2 2 1"] | 2 seconds | ["1\n4\n0", "2\n1\n3\n3\n2\n4", "2\n1"] | NoteThis image illustrates the second sample case. | Java 11 | standard input | [
"data structures",
"implementation",
"bitmasks",
"dfs and similar"
] | 2b78f6626fce6b5b4f9628fb15666dc4 | The first line of the input contains three integers n, m and q (1 ≤ n, m ≤ 103, 1 ≤ q ≤ 105) — the bookcase dimensions and the number of operations respectively. The next q lines describes operations in chronological order — i-th of them describes i-th operation in one of the four formats described in the statement. It is guaranteed that shelf indices and position indices are correct, and in each of fourth-type operation the number k corresponds to some operation before it or equals to 0. | 2,200 | For each operation, print the number of books in the bookcase after applying it in a separate line. The answers should be printed in chronological order. | standard output | |
PASSED | 41d5d09d7e9a08e78a740c11915ba5c2 | train_004.jsonl | 1471698300 | Recently in school Alina has learned what are the persistent data structures: they are data structures that always preserves the previous version of itself and access to it when it is modified.After reaching home Alina decided to invent her own persistent data structure. Inventing didn't take long: there is a bookcase right behind her bed. Alina thinks that the bookcase is a good choice for a persistent data structure. Initially the bookcase is empty, thus there is no book at any position at any shelf.The bookcase consists of n shelves, and each shelf has exactly m positions for books at it. Alina enumerates shelves by integers from 1 to n and positions at shelves — from 1 to m. Initially the bookcase is empty, thus there is no book at any position at any shelf in it.Alina wrote down q operations, which will be consecutively applied to the bookcase. Each of the operations has one of four types: 1 i j — Place a book at position j at shelf i if there is no book at it. 2 i j — Remove the book from position j at shelf i if there is a book at it. 3 i — Invert book placing at shelf i. This means that from every position at shelf i which has a book at it, the book should be removed, and at every position at shelf i which has not book at it, a book should be placed. 4 k — Return the books in the bookcase in a state they were after applying k-th operation. In particular, k = 0 means that the bookcase should be in initial state, thus every book in the bookcase should be removed from its position.After applying each of operation Alina is interested in the number of books in the bookcase. Alina got 'A' in the school and had no problem finding this values. Will you do so? | 512 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf707d_4 {
public static void main(String[] args) throws IOException {
int n = rni(), m = ni(), q = ni(), ans[] = new int[q];
bitset[] b = new bitset[n];
for (int i = 0; i < n; ++i) {
b[i] = new bitset();
}
List<List<int[]>> g = new ArrayList<>();
for (int i = 0; i <= q; ++i) {
g.add(new ArrayList<>());
}
for (int qq = 1; qq <= q; ++qq) {
int t = rni();
if (t == 1) {
int i = ni() - 1, j = ni() - 1;
g.get(qq - 1).add(new int[] {qq, 1, i, j});
} else if (t == 2) {
int i = ni() - 1, j = ni() - 1;
g.get(qq - 1).add(new int[] {qq, 2, i, j});
} else if (t == 3) {
int i = ni() - 1;
g.get(qq - 1).add(new int[] {qq, 3, i});
} else {
int k = ni();
g.get(k).add(new int[] {qq, 4});
}
}
dfs(g, 0,b, m, ans, 0);
for (int i = 0; i < q; ++i) {
prln(ans[i]);
}
close();
}
static void dfs(List<List<int[]>> g, int i, bitset[] b, int m, int ans[], int cnt) {
if (i > 0) {
ans[i - 1] = cnt;
}
for (int[] e : g.get(i)) {
if (e[1] == 1) {
int old = b[e[2]].get(e[3]);
b[e[2]].set(e[3]);
cnt += 1 - old;
dfs(g, e[0], b, m, ans, cnt);
if (old == 0) {
b[e[2]].rem(e[3]);
--cnt;
}
} else if (e[1] == 2) {
int old = b[e[2]].get(e[3]);
b[e[2]].rem(e[3]);
cnt -= old;
dfs(g, e[0], b, m, ans, cnt);
if (old == 1) {
b[e[2]].set(e[3]);
++cnt;
}
} else if (e[1] == 3) {
int oldcnt = b[e[2]].cnt(m);
b[e[2]].not();
cnt += m - oldcnt - oldcnt;
dfs(g, e[0], b, m, ans, cnt);
b[e[2]].not();
cnt -= m - oldcnt - oldcnt;
} else {
dfs(g, e[0], b, m, ans, cnt);
}
}
}
static class bitset {
int[] b = new int[50];
int cnt(int n) {
int ans = 0;
for (int i = 0; i < 50; ++i) {
ans += Integer.bitCount(b[i] & ((1 << min(20, max(0, n - i * 20))) - 1));
}
return ans;
}
int get(int i) {
return (b[i / 20] & (1 << (i % 20))) > 0 ? 1 : 0;
}
void set(int i) {
b[i / 20] |= 1 << (i % 20);
}
void rem(int i) {
b[i / 20] &= ~0 - (1 << (i % 20));
}
void not() {
for (int i = 0; i < 50; ++i) {
b[i] = ~b[i];
}
}
}
static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));
static StringTokenizer input;
static Random __rand = new Random();
// references
// IBIG = 1e9 + 7
// IMAX ~= 2e9
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IMAX = 2147483647;
static final int IMIN = -2147483648;
static final long LMAX = 9223372036854775807L;
static final long LMIN = -9223372036854775808L;
// math util
static int minof(int a, int b, int c) {return min(a, min(b, c));}
static int minof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); int min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}
static long minof(long a, long b, long c) {return min(a, min(b, c));}
static long minof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return min(x[0], x[1]); if (x.length == 3) return min(x[0], min(x[1], x[2])); long min = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] < min) min = x[i]; return min;}
static int maxof(int a, int b, int c) {return max(a, max(b, c));}
static int maxof(int... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); int max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}
static long maxof(long a, long b, long c) {return max(a, max(b, c));}
static long maxof(long... x) {if (x.length == 1) return x[0]; if (x.length == 2) return max(x[0], x[1]); if (x.length == 3) return max(x[0], max(x[1], x[2])); long max = x[0]; for (int i = 1; i < x.length; ++i) if (x[i] > max) max = x[i]; return max;}
static int powi(int a, int b) {if (a == 0) return 0; int ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static long powl(long a, int b) {if (a == 0) return 0; long ans = 1; while (b > 0) {if ((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static int fli(double d) {return (int) d;}
static int cei(double d) {return (int) ceil(d);}
static long fll(double d) {return (long) d;}
static long cel(double d) {return (long) ceil(d);}
static int gcf(int a, int b) {return b == 0 ? a : gcf(b, a % b);}
static long gcf(long a, long b) {return b == 0 ? a : gcf(b, a % b);}
static int lcm(int a, int b) {return a * b / gcf(a, b);}
static long lcm(long a, long b) {return a * b / gcf(a, b);}
static int randInt(int min, int max) {return __rand.nextInt(max - min + 1) + min;}
static long mix(long x) {x += 0x9e3779b97f4a7c15L; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9L; x = (x ^ (x >> 27)) * 0x94d049bb133111ebL; return x ^ (x >> 31);}
// array util
static void reverse(int[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {int swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(long[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {long swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(double[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {double swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void reverse(char[] a) {for (int i = 0, n = a.length, half = n / 2; i < half; ++i) {char swap = a[i]; a[i] = a[n - i - 1]; a[n - i - 1] = swap;}}
static void shuffle(int[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(long[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(double[] a) {int n = a.length - 1; for (int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void rsort(int[] a) {shuffle(a); sort(a);}
static void rsort(long[] a) {shuffle(a); sort(a);}
static void rsort(double[] a) {shuffle(a); sort(a);}
static int[] copy(int[] a) {int[] ans = new int[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static long[] copy(long[] a) {long[] ans = new long[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static double[] copy(double[] a) {double[] ans = new double[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
static char[] copy(char[] a) {char[] ans = new char[a.length]; for (int i = 0; i < a.length; ++i) ans[i] = a[i]; return ans;}
// input
static void r() throws IOException {input = new StringTokenizer(rline());}
static int ri() throws IOException {return Integer.parseInt(rline());}
static long rl() throws IOException {return Long.parseLong(rline());}
static double rd() throws IOException {return Double.parseDouble(rline());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni(); return a;}
static int[] riam1(int n) throws IOException {int[] a = new int[n]; r(); for (int i = 0; i < n; ++i) a[i] = ni() - 1; return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; r(); for (int i = 0; i < n; ++i) a[i] = nl(); return a;}
static double[] rda(int n) throws IOException {double[] a = new double[n]; r(); for (int i = 0; i < n; ++i) a[i] = nd(); return a;}
static char[] rcha() throws IOException {return rline().toCharArray();}
static String rline() throws IOException {return __in.readLine();}
static String n() {return input.nextToken();}
static int rni() throws IOException {r(); return ni();}
static int ni() {return Integer.parseInt(n());}
static long rnl() throws IOException {r(); return nl();}
static long nl() {return Long.parseLong(n());}
static double rnd() throws IOException {r(); return nd();}
static double nd() {return Double.parseDouble(n());}
// output
static void pr(int i) {__out.print(i);}
static void prln(int i) {__out.println(i);}
static void pr(long l) {__out.print(l);}
static void prln(long l) {__out.println(l);}
static void pr(double d) {__out.print(d);}
static void prln(double d) {__out.println(d);}
static void pr(char c) {__out.print(c);}
static void prln(char c) {__out.println(c);}
static void pr(char[] s) {__out.print(new String(s));}
static void prln(char[] s) {__out.println(new String(s));}
static void pr(String s) {__out.print(s);}
static void prln(String s) {__out.println(s);}
static void pr(Object o) {__out.print(o);}
static void prln(Object o) {__out.println(o);}
static void prln() {__out.println();}
static void pryes() {prln("yes");}
static void pry() {prln("Yes");}
static void prY() {prln("YES");}
static void prno() {prln("no");}
static void prn() {prln("No");}
static void prN() {prln("NO");}
static boolean pryesno(boolean b) {prln(b ? "yes" : "no"); return b;};
static boolean pryn(boolean b) {prln(b ? "Yes" : "No"); return b;}
static boolean prYN(boolean b) {prln(b ? "YES" : "NO"); return b;}
static void prln(int... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static void prln(long... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static void prln(double... a) {for (int i = 0, len = a.length - 1; i < len; pr(a[i]), pr(' '), ++i); if (a.length > 0) prln(a[a.length - 1]); else prln();}
static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for (int i = 0; i < n; pr(iter.next()), pr(' '), ++i); if (n >= 0) prln(iter.next()); else prln();}
static void h() {prln("hlfd"); flush();}
static void flush() {__out.flush();}
static void close() {__out.close();}
} | Java | ["2 3 3\n1 1 1\n3 2\n4 0", "4 2 6\n3 2\n2 2 2\n3 3\n3 2\n2 2 2\n3 2", "2 2 2\n3 2\n2 2 1"] | 2 seconds | ["1\n4\n0", "2\n1\n3\n3\n2\n4", "2\n1"] | NoteThis image illustrates the second sample case. | Java 11 | standard input | [
"data structures",
"implementation",
"bitmasks",
"dfs and similar"
] | 2b78f6626fce6b5b4f9628fb15666dc4 | The first line of the input contains three integers n, m and q (1 ≤ n, m ≤ 103, 1 ≤ q ≤ 105) — the bookcase dimensions and the number of operations respectively. The next q lines describes operations in chronological order — i-th of them describes i-th operation in one of the four formats described in the statement. It is guaranteed that shelf indices and position indices are correct, and in each of fourth-type operation the number k corresponds to some operation before it or equals to 0. | 2,200 | For each operation, print the number of books in the bookcase after applying it in a separate line. The answers should be printed in chronological order. | standard output | |
PASSED | 410b47445a72b07462752e2180e6804b | train_004.jsonl | 1471698300 | Recently in school Alina has learned what are the persistent data structures: they are data structures that always preserves the previous version of itself and access to it when it is modified.After reaching home Alina decided to invent her own persistent data structure. Inventing didn't take long: there is a bookcase right behind her bed. Alina thinks that the bookcase is a good choice for a persistent data structure. Initially the bookcase is empty, thus there is no book at any position at any shelf.The bookcase consists of n shelves, and each shelf has exactly m positions for books at it. Alina enumerates shelves by integers from 1 to n and positions at shelves — from 1 to m. Initially the bookcase is empty, thus there is no book at any position at any shelf in it.Alina wrote down q operations, which will be consecutively applied to the bookcase. Each of the operations has one of four types: 1 i j — Place a book at position j at shelf i if there is no book at it. 2 i j — Remove the book from position j at shelf i if there is a book at it. 3 i — Invert book placing at shelf i. This means that from every position at shelf i which has a book at it, the book should be removed, and at every position at shelf i which has not book at it, a book should be placed. 4 k — Return the books in the bookcase in a state they were after applying k-th operation. In particular, k = 0 means that the bookcase should be in initial state, thus every book in the bookcase should be removed from its position.After applying each of operation Alina is interested in the number of books in the bookcase. Alina got 'A' in the school and had no problem finding this values. Will you do so? | 512 megabytes | import java.io.*;
import java.util.*;
import java.lang.*;
public class Rextester{
static boolean[][] bookShelf;
static boolean[] inv;
static int[] shelfState;
static int n,m;
static class TreeNode{
ArrayList<TreeNode> list = new ArrayList<TreeNode>();
int t,i,j,k,b;
public TreeNode(int t,int i,int j,int k){
this.t = t;
this.i = i;
this.j = j;
this.k = k;
}
public void dfs(int lastBook){
boolean updated = false;
if(t==1){
if((!inv[i]&&!bookShelf[i][j])||(inv[i]&&bookShelf[i][j])){
lastBook++;
updated = true;
bookShelf[i][j]=!bookShelf[i][j];
shelfState[i]++;
}
}
else if(t==2){
if((!inv[i]&&bookShelf[i][j])||(inv[i]&&!bookShelf[i][j])){
lastBook --;
updated = true;
bookShelf[i][j]=!bookShelf[i][j];
shelfState[i]--;
}
}
else if(t==3){
inv[i]=!inv[i];
lastBook -= shelfState[i];
lastBook += m - shelfState[i];
shelfState[i] = m - shelfState[i];
updated = true;
}
this.b = lastBook;
for(TreeNode w:list){
w.dfs(b);
}
if(!updated){
return;
}
if(t==1){
lastBook--;
bookShelf[i][j]=!bookShelf[i][j];
shelfState[i]--;
}
else if(t==2){
lastBook++;
bookShelf[i][j]=!bookShelf[i][j];
shelfState[i]++;
}
else if(t==3){
lastBook-=shelfState[i];
lastBook+=m-shelfState[i];
shelfState[i]=m-shelfState[i];
inv[i]=!inv[i];
}
}
}
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
int q = Integer.parseInt(st.nextToken());
TreeNode[] t = new TreeNode[q+1];
t[0]=new TreeNode(0,0,0,0);
for(int i=1;i<=q;i++){
StringTokenizer st1 = new StringTokenizer(br.readLine());
int z = Integer.parseInt(st1.nextToken());
int childOf = i-1;
if(z==1){
int r = Integer.parseInt(st1.nextToken())-1;
int c = Integer.parseInt(st1.nextToken())-1;
t[i]= new TreeNode(z,r,c,0);
}
else if(z==2){
int r = Integer.parseInt(st1.nextToken())-1;
int c = Integer.parseInt(st1.nextToken())-1;
t[i]=new TreeNode(z,r,c,0);
}
else if(z==3){
int r = Integer.parseInt(st1.nextToken())-1;
t[i]=new TreeNode(z,r,0,0);
}
else if(z==4){
int k = Integer.parseInt(st1.nextToken());
t[i]=new TreeNode(z,0,0,k);
childOf = k;
}
t[childOf].list.add(t[i]);
}
br.close();
bookShelf = new boolean[n][m];
inv = new boolean[n];
shelfState = new int[n];
t[0].dfs(0);
StringBuffer sb = new StringBuffer();
for(int i=1;i<=q;i++){
sb.append(t[i].b).append("\n");
}
System.out.println(sb);
}
}
| Java | ["2 3 3\n1 1 1\n3 2\n4 0", "4 2 6\n3 2\n2 2 2\n3 3\n3 2\n2 2 2\n3 2", "2 2 2\n3 2\n2 2 1"] | 2 seconds | ["1\n4\n0", "2\n1\n3\n3\n2\n4", "2\n1"] | NoteThis image illustrates the second sample case. | Java 11 | standard input | [
"data structures",
"implementation",
"bitmasks",
"dfs and similar"
] | 2b78f6626fce6b5b4f9628fb15666dc4 | The first line of the input contains three integers n, m and q (1 ≤ n, m ≤ 103, 1 ≤ q ≤ 105) — the bookcase dimensions and the number of operations respectively. The next q lines describes operations in chronological order — i-th of them describes i-th operation in one of the four formats described in the statement. It is guaranteed that shelf indices and position indices are correct, and in each of fourth-type operation the number k corresponds to some operation before it or equals to 0. | 2,200 | For each operation, print the number of books in the bookcase after applying it in a separate line. The answers should be printed in chronological order. | standard output | |
PASSED | 353c811fb56680d38f715741851b70d7 | train_004.jsonl | 1343662200 | Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.Each digit is allowed to occur in the number the same number of times it occurs in the set. | 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 main(String args[]) throws IOException {
Scan input=new Scan();
int n=input.scanInt();
int freq[]=new int[10];
for(int i=0;i<n;i++) {
freq[input.scanInt()]++;
}
System.out.println(solve(n,freq));
}
public static StringBuilder solve(int n,int freq[]) {
if(freq[0]==0) {
return new StringBuilder("-1");
}
int sum=0;
for(int i=0;i<freq.length;i++) {
sum+=(i*freq[i]);
}
if(sum%3==1) {
if(freq[1]>0) {
sum-=1;
freq[1]--;
}
else if(freq[4]>0) {
sum-=4;
freq[4]--;
}
else if(freq[7]>0) {
sum-=7;
freq[7]--;
}
}
else if(sum%3==2) {
if(freq[2]>0) {
sum-=2;
freq[2]--;
}
else if(freq[5]>0) {
sum-=5;
freq[5]--;
}
else if(freq[8]>0) {
sum-=8;
freq[8]--;
}
else if(freq[1]>1) {
sum-=2;
freq[1]-=2;
}
else if(freq[4]>1) {
sum-=8;
freq[4]-=2;
}
else if(freq[7]>1) {
sum-=14;
freq[7]-=2;
}
}
while(sum%3!=0) {
boolean sub=false;
for(int i=1;i<freq.length;i++) {
if(i%3==0) {
continue;
}
if(freq[i]>0) {
sum-=i;
freq[i]--;
sub=true;
break;
}
}
if(!sub) {
break;
}
}
if(sum%3!=0) {
return new StringBuilder("-1");
}
StringBuilder ans=new StringBuilder("");
for(int i=freq.length-1;i>=0;i--) {
for(int j=0;j<freq[i];j++) {
ans.append(i);
}
}
if(ans.charAt(0)=='0') {
ans=new StringBuilder("0");
}
return ans;
}
}
| Java | ["1\n0", "11\n3 4 5 4 5 3 5 3 4 4 0", "8\n3 2 5 1 5 2 2 3"] | 2 seconds | ["0", "5554443330", "-1"] | NoteIn the first sample there is only one number you can make — 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"math",
"brute force"
] | b263917e47e1c84340bcb1c77999fd7e | A single line contains a single integer n (1 ≤ n ≤ 100000) — the number of digits in the set. The second line contains n digits, the digits are separated by a single space. | 1,600 | On a single line print the answer to the problem. If such number does not exist, then you should print -1. | standard output | |
PASSED | 525997bc9063eb0ceb41b942294a3985 | train_004.jsonl | 1343662200 | Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.Each digit is allowed to occur in the number the same number of times it occurs in the set. | 256 megabytes | import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Random;
public class Solution {
public static void main(String[] args) {
try (PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out))) {
_Scanner sc = new _Scanner(System.in);
int n = sc.nextInt();
int[] freq = new int[10];
int sum = 0;
for (int i = 0; i < n; i++) {
int v = sc.nextInt();
freq[v]++;
sum += v;
}
int rest;
outer:
while ((rest = sum % 3) != 0) {
for (int i = 0; i < freq.length; i++) {
if (freq[i] > 0 && i % 3 == rest) {
freq[i]--;
sum -= i;
break outer;
}
}
for (int i = 0; i < freq.length && sum % 3 != 0; i++) {
while (freq[i] > 0 && i % 3 != 0 && sum % 3 != 0) {
freq[i]--;
sum -= i;
}
}
}
if (freq[0] == 0 || sum % 3 != 0) {
out.println(-1);
} else if (sum > 0) {
for (int i = freq.length - 1; i >= 0; i--) {
while (freq[i]-- > 0) out.print(i);
}
out.println();
} else {
out.println(0);
}
}
}
private static void reverse(int[] vs) {
for (int i = 0; i < vs.length / 2; i++) {
swap(vs, i, vs.length - 1 - i);
}
}
static class _Scanner {
InputStream is;
_Scanner(InputStream is) {
this.is = is;
}
byte[] bb = new byte[1 << 15];
int k, l;
byte getc() {
try {
if (k >= l) {
k = 0;
l = is.read(bb);
if (l < 0) return -1;
}
return bb[k++];
} catch (IOException e) {
throw new RuntimeException(e);
}
}
byte skip() {
byte b;
while ((b = getc()) <= 32)
;
return b;
}
int nextInt() {
int n = 0;
int sig = 1;
for (byte b = skip(); b > 32; b = getc()) {
if (b == '-') {
sig = -1;
} else {
n = n * 10 + b - '0';
}
}
return sig * n;
}
long nextLong() {
long n = 0;
long sig = 1;
for (byte b = skip(); b > 32; b = getc()) {
if (b == '-') {
sig = -1;
} else {
n = n * 10 + b - '0';
}
}
return sig * n;
}
public String next() {
StringBuilder sb = new StringBuilder();
for (int b = skip(); b > 32; b = getc()) {
sb.append(((char) b));
}
return sb.toString();
}
}
private static void shuffle(int[] ar) {
Random rnd = new Random();
for (int i = 0; i < ar.length; i++) {
int j = i + rnd.nextInt(ar.length - i);
swap(ar, i, j);
}
}
private static void shuffle(Object[] ar) {
Random rnd = new Random();
for (int i = 0; i < ar.length; i++) {
int j = i + rnd.nextInt(ar.length - i);
swap(ar, i, j);
}
}
private static void swap(int[] ar, int i, int j) {
int t = ar[i];
ar[i] = ar[j];
ar[j] = t;
}
private static void swap(Object[] ar, int i, int j) {
Object t = ar[i];
ar[i] = ar[j];
ar[j] = t;
}
}
| Java | ["1\n0", "11\n3 4 5 4 5 3 5 3 4 4 0", "8\n3 2 5 1 5 2 2 3"] | 2 seconds | ["0", "5554443330", "-1"] | NoteIn the first sample there is only one number you can make — 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"math",
"brute force"
] | b263917e47e1c84340bcb1c77999fd7e | A single line contains a single integer n (1 ≤ n ≤ 100000) — the number of digits in the set. The second line contains n digits, the digits are separated by a single space. | 1,600 | On a single line print the answer to the problem. If such number does not exist, then you should print -1. | standard output | |
PASSED | 75b17baaa9063bfd91806d95806eb5b5 | train_004.jsonl | 1343662200 | Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.Each digit is allowed to occur in the number the same number of times it occurs in the set. | 256 megabytes |
import java.io.*;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Locale;
public class B214 implements Runnable {
public InputReader in;
public PrintWriter out;
public void solve() throws Exception {
// solution goes here
int n = in.nextInt();
int[] digits = in.nextInts(n);
if (n == 1 && digits[0] == 0) {
out.println(0);
return;
}
int[] count = new int[10];
int sum = 0;
for (int i = 0; i < n; i++) {
count[digits[i]]++;
sum += digits[i];
}
if (count[0] == 0) {
out.println(-1);
} else {
while (sum % 3 != 0) {
boolean found = false;
int min = -1;
for (int i = 1; i < 10; i++) {
if (count[i] > 0 && min == -1 && i % 3 != 0) {
min = i;
}
if (count[i] > 0 && (sum-i) % 3 == 0) {
count[i]--;
n--;
found = true;
break;
}
}
if (found) {
break;
} else {
count[min]--;
n--;
sum -= min;
}
}
if (n == count[0]) {
out.println(0);
return;
}
for (int i = 9; i >= 0; i--) {
for (int j = 0; j < count[i]; j++) {
out.print(i);
}
}
out.println();
}
}
public void run() {
try {
in = new InputReader(System.in);
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
Locale.setDefault(Locale.US);
int tests = 1;
while (tests-- > 0) {
solve();
}
out.close();
} catch (Throwable e) {
e.printStackTrace();
System.exit(7);
}
}
static int abs(int x) {
return x < 0 ? -x : x;
}
static int max(int a, int b) {
return a > b ? a : b;
}
static int min(int a, int b) {
return a < b ? a : b;
}
static long abs(long x) {
return x < 0 ? -x : x;
}
static long max(long a, long b) {
return a > b ? a : b;
}
static long min(long a, long b) {
return a < b ? a : b;
}
public static void main(String[] args) {
new Thread(null, new B214(), "tt.Main", 1 << 28).start();
}
static boolean OJ = System.getProperty("ONLINE_JUDGE") != null;
public void console(Object... objects) {
if (!OJ) {
out.println(Arrays.deepToString(objects));
out.flush();
}
}
@SuppressWarnings({"Duplicates", "unused"})
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[2048];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader() {
this.stream = System.in;
}
public InputReader(InputStream stream) {
this.stream = stream;
}
public InputReader(SpaceCharFilter filter) {
this.stream = System.in;
this.filter = filter;
}
public InputReader(InputStream stream, SpaceCharFilter filter) {
this.stream = stream;
this.filter = filter;
}
public int read() {
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 char nextChar() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public int nextDigit() {
int c = read();
while (isSpaceChar(c))
c = read();
return c - '0';
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
boolean negative = false;
if (c == '-') {
negative = true;
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 negative ? -res : res;
}
public int[] nextInts(int N) {
int[] nums = new int[N];
for (int i = 0; i < N; i++)
nums[i] = nextInt();
return nums;
}
public long[] nextLongs(int N) {
long[] nums = new long[N];
for (int i = 0; i < N; i++)
nums[i] = nextLong();
return nums;
}
public int nextUnsignedInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res;
}
public final long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
boolean negative = false;
if (c == '-') {
negative = true;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return negative ? -res : res;
}
public final long nextUnsignedLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res;
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
long sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!(c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1 || c == '.'));
if (c != '.') {
return res * sgn;
}
c = read();
long aft = 0;
int len = 1;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
aft *= 10;
len *= 10;
aft += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn + aft / (1.0 * len);
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndChar(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 boolean isEndChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public char[] nextChars() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
char[] chars = new char[res.length()];
res.getChars(0, chars.length, chars, 0);
return chars;
}
public int[][] nextIntMatrix(int rows, int cols) {
int[][] matrix = new int[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix[i][j] = nextInt();
return matrix;
}
public long[][] nextLongMatrix(int rows, int cols) {
long[][] matrix = new long[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix[i][j] = nextLong();
return matrix;
}
public char[][] nextCharMap(int rows, int cols) {
char[][] matrix = new char[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix[i][j] = nextChar();
return matrix;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["1\n0", "11\n3 4 5 4 5 3 5 3 4 4 0", "8\n3 2 5 1 5 2 2 3"] | 2 seconds | ["0", "5554443330", "-1"] | NoteIn the first sample there is only one number you can make — 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"math",
"brute force"
] | b263917e47e1c84340bcb1c77999fd7e | A single line contains a single integer n (1 ≤ n ≤ 100000) — the number of digits in the set. The second line contains n digits, the digits are separated by a single space. | 1,600 | On a single line print the answer to the problem. If such number does not exist, then you should print -1. | standard output | |
PASSED | c44d83084ce0056bfdaee15edf79945b | train_004.jsonl | 1343662200 | Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.Each digit is allowed to occur in the number the same number of times it occurs in the set. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class cf214b {
public static void main(String[] args) throws IOException {
int n = ri(), a[] = ria(n), cnt[] = new int[10], sum = 0;
boolean zero_only = true;
for(int i = 0; i < n; ++i) {
++cnt[a[i]];
sum += a[i];
if(a[i] != 0) {
zero_only = false;
}
}
if(cnt[0] == 0) {
prln(-1);
} else {
if(sum % 3 == 0) {
if(zero_only) {
prln(0);
} else {
for(int i = 9; i >= 0; --i) {
for(int j = 0; j < cnt[i]; ++j) {
pr(i);
}
}
prln();
}
} else if(sum % 3 == 1) {
boolean solved = false;
for(int i = 1; i <= 7; i += 3) {
if(cnt[i] > 0) {
--cnt[i];
solved = true;
break;
}
}
if(!solved) {
int x = 0;
for(int i = 2; i <= 8; i += 3) {
x += cnt[i];
}
if(x >= 2) {
solved = true;
int need = 2;
out: for(int i = 2; i <= 8; i += 3) {
while(cnt[i] > 0 && need > 0) {
--cnt[i];
if(--need == 0) {
break out;
}
}
}
}
}
if(solved) {
zero_only = true;
for(int i = 1; i <= 9; ++i) {
if(cnt[i] > 0) {
zero_only = false;
}
}
if(zero_only) {
prln(0);
} else {
for(int i = 9; i >= 0; --i) {
for(int j = 0; j < cnt[i]; ++j) {
pr(i);
}
}
prln();
}
} else {
prln(-1);
}
} else {
boolean solved = false;
for(int i = 2; i <= 8; i += 3) {
if(cnt[i] > 0) {
--cnt[i];
solved = true;
break;
}
}
if(!solved) {
int x = 0;
for(int i = 1; i <= 7; i += 3) {
x += cnt[i];
}
if(x >= 2) {
solved = true;
int need = 2;
out: for(int i = 1; i <= 7; i += 3) {
while(cnt[i] > 0 && need > 0) {
--cnt[i];
if(--need == 0) {
break out;
}
}
}
}
}
if(solved) {
zero_only = true;
for(int i = 1; i <= 9; ++i) {
if(cnt[i] > 0) {
zero_only = false;
}
}
if(zero_only) {
prln(0);
} else {
for(int i = 9; i >= 0; --i) {
for(int j = 0; j < cnt[i]; ++j) {
pr(i);
}
}
prln();
}
} else {
prln(-1);
}
}
}
close();
}
static BufferedReader __in = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter __out = new PrintWriter(new OutputStreamWriter(System.out));
static StringTokenizer input;
static Random rand = new Random();
// references
// IBIG = 1e9 + 7
// IRAND ~= 3e8
// IMAX ~= 2e10
// LMAX ~= 9e18
// constants
static final int IBIG = 1000000007;
static final int IRAND = 327859546;
static final int IMAX = 2147483647;
static final int IMIN = -2147483648;
static final long LMAX = 9223372036854775807L;
static final long LMIN = -9223372036854775808L;
// util
static int minof(int a, int b, int c) {return min(a, min(b, c));}
static int minof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));}
static int minstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));}
static long minof(long a, long b, long c) {return min(a, min(b, c));}
static long minof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? min(x[0], x[1]) : min(x[0], minstarting(1, x));}
static long minstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? min(x[offset], x[offset + 1]) : min(x[offset], minstarting(offset + 1, x));}
static int maxof(int a, int b, int c) {return max(a, max(b, c));}
static int maxof(int... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));}
static int maxstarting(int offset, int... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));}
static long maxof(long a, long b, long c) {return max(a, max(b, c));}
static long maxof(long... x) {return x.length == 1 ? x[0] : x.length == 2 ? max(x[0], x[1]) : max(x[0], maxstarting(1, x));}
static long maxstarting(int offset, long... x) {assert x.length > 2; return offset == x.length - 2 ? max(x[offset], x[offset + 1]) : max(x[offset], maxstarting(offset + 1, x));}
static int powi(int a, int b) {if(a == 0) return 0; int ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static long powl(long a, int b) {if(a == 0) return 0; long ans = 1; while(b > 0) {if((b & 1) > 0) ans *= a; a *= a; b >>= 1;} return ans;}
static int floori(double d) {return (int)d;}
static int ceili(double d) {return (int)ceil(d);}
static long floorl(double d) {return (long)d;}
static long ceill(double d) {return (long)ceil(d);}
static void shuffle(int[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); int swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(long[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); long swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void shuffle(double[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); double swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static <T> void shuffle(T[] a) {int n = a.length - 1; for(int i = 0; i < n; ++i) {int ind = randInt(i, n); T swap = a[i]; a[i] = a[ind]; a[ind] = swap;}}
static void sort(int[] a) {shuffle(a); Arrays.sort(a);}
static void sort(long[] a) {shuffle(a); Arrays.sort(a);}
static void sort(double[] a) {shuffle(a); Arrays.sort(a);}
static void qsort(int[] a) {Arrays.sort(a);}
static void qsort(long[] a) {Arrays.sort(a);}
static void qsort(double[] a) {Arrays.sort(a);}
static int randInt(int min, int max) {return rand.nextInt(max - min + 1) + min;}
// input
static void r() throws IOException {input = new StringTokenizer(__in.readLine());}
static int ri() throws IOException {return Integer.parseInt(__in.readLine());}
static long rl() throws IOException {return Long.parseLong(__in.readLine());}
static int[] ria(int n) throws IOException {int[] a = new int[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Integer.parseInt(input.nextToken()); return a;}
static long[] rla(int n) throws IOException {long[] a = new long[n]; input = new StringTokenizer(__in.readLine()); for(int i = 0; i < n; ++i) a[i] = Long.parseLong(input.nextToken()); return a;}
static char[] rcha() throws IOException {return __in.readLine().toCharArray();}
static String rline() throws IOException {return __in.readLine();}
static int rni() throws IOException {input = new StringTokenizer(__in.readLine()); return Integer.parseInt(input.nextToken());}
static int ni() {return Integer.parseInt(input.nextToken());}
static long rnl() throws IOException {input = new StringTokenizer(__in.readLine()); return Long.parseLong(input.nextToken());}
static long nl() {return Long.parseLong(input.nextToken());}
// output
static void pr(int i) {__out.print(i);}
static void prln(int i) {__out.println(i);}
static void pr(long l) {__out.print(l);}
static void prln(long l) {__out.println(l);}
static void pr(double d) {__out.print(d);}
static void prln(double d) {__out.println(d);}
static void pr(char c) {__out.print(c);}
static void prln(char c) {__out.println(c);}
static void pr(char[] s) {__out.print(new String(s));}
static void prln(char[] s) {__out.println(new String(s));}
static void pr(String s) {__out.print(s);}
static void prln(String s) {__out.println(s);}
static void pr(Object o) {__out.print(o);}
static void prln(Object o) {__out.println(o);}
static void prln() {__out.println();}
static void pryes() {__out.println("yes");}
static void pry() {__out.println("Yes");}
static void prY() {__out.println("YES");}
static void prno() {__out.println("no");}
static void prn() {__out.println("No");}
static void prN() {__out.println("NO");}
static void pryesno(boolean b) {__out.println(b ? "yes" : "no");};
static void pryn(boolean b) {__out.println(b ? "Yes" : "No");}
static void prYN(boolean b) {__out.println(b ? "YES" : "NO");}
static void prln(int... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static void prln(long... a) {for(int i = 0, len = a.length - 1; i < len; __out.print(a[i]), __out.print(' '), ++i); __out.println(a[a.length - 1]);}
static <T> void prln(Collection<T> c) {int n = c.size() - 1; Iterator<T> iter = c.iterator(); for(int i = 0; i < n; __out.print(iter.next()), __out.print(' '), ++i); if(n >= 0) __out.println(iter.next());}
static void h() {__out.println("hlfd");}
static void flush() {__out.flush();}
static void close() {__out.close();}
} | Java | ["1\n0", "11\n3 4 5 4 5 3 5 3 4 4 0", "8\n3 2 5 1 5 2 2 3"] | 2 seconds | ["0", "5554443330", "-1"] | NoteIn the first sample there is only one number you can make — 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"math",
"brute force"
] | b263917e47e1c84340bcb1c77999fd7e | A single line contains a single integer n (1 ≤ n ≤ 100000) — the number of digits in the set. The second line contains n digits, the digits are separated by a single space. | 1,600 | On a single line print the answer to the problem. If such number does not exist, then you should print -1. | standard output | |
PASSED | 62eb093516c21942d7ccd45ce1811b7d | train_004.jsonl | 1343662200 | Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.Each digit is allowed to occur in the number the same number of times it occurs in the set. | 256 megabytes | import java.io.*;
import java.util.*;
public class Q2 {
public static void main(String[] args)throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String[] ss=br.readLine().split(" ");
int n=Integer.parseInt(ss[0]);
ss=br.readLine().split(" ");
int[] a=new int[n];
int sum=0;int z=0;
for(int i=0;i<n;i++)
{ a[i]=Integer.parseInt(ss[i]);
sum+=a[i];
if(a[i]==0)
z=1;
}
if(z==0)
System.out.println(-1);
else
{
Arrays.sort(a);
int mod=sum%3;
String ans="";
if(mod==0)
{
for(int i=n-1;i>=0;i--)
ans=ans+a[i];
}
else if(mod==1)
{
int index=-1;
int i=0;int l1=-1;int l2=-1;
while(i<n)
{
if(a[i]%3==1)
{
index=i;
break;
}
else
i++;
}
if(index==-1)
{ i=0;
while(i<n)
{
if(a[i]%3==2)
{
if(l1==-1)
{ l1=i;
i++;}
else
{ l2=i;
break;
}
}
else
i++;
}
}
if(index!=-1)
{ for(int j=n-1;j>=0;j--)
{
if(j!=index)
ans=ans+a[j];
}
}
else if(l1!=-1&&l2!=-1)
{
for(int j=n-1;j>=0;j--)
{
if(j!=l1&&j!=l2)
ans=ans+a[j];
}
}
else
ans=ans+"-1";
}
else if(mod==2)
{
int index=-1;
int i=0;int l1=-1;int l2=-1;
while(i<n)
{
if(a[i]%3==2)
{
index=i;
break;
}
else
i++;
}
if(index==-1)
{ i=0;
while(i<n)
{
if(a[i]%3==1)
{
if(l1==-1)
{ l1=i;
i++;
}
else
{ l2=i;
break;
}
}
else
i++;
}
}
if(index!=-1)
{ for(int j=n-1;j>=0;j--)
{
if(j!=index)
ans=ans+a[j];
}
}
else if(l1!=-1&&l2!=-1)
{
for(int j=n-1;j>=0;j--)
{
if(j!=l1&&j!=l2)
ans=ans+a[j];
}
}
else
ans=ans+"-1";
}
if(ans.charAt(0)=='0')
System.out.println("0");
else
System.out.println(ans);
}
}
} | Java | ["1\n0", "11\n3 4 5 4 5 3 5 3 4 4 0", "8\n3 2 5 1 5 2 2 3"] | 2 seconds | ["0", "5554443330", "-1"] | NoteIn the first sample there is only one number you can make — 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"math",
"brute force"
] | b263917e47e1c84340bcb1c77999fd7e | A single line contains a single integer n (1 ≤ n ≤ 100000) — the number of digits in the set. The second line contains n digits, the digits are separated by a single space. | 1,600 | On a single line print the answer to the problem. If such number does not exist, then you should print -1. | standard output | |
PASSED | d091fe4a457a59a5a949c8324cfedc38 | train_004.jsonl | 1343662200 | Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.Each digit is allowed to occur in the number the same number of times it occurs in the set. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
public static void process(int test_number)throws IOException
{
int n = ni(), arr[] = new int[n], sum = 0, freq[] = new int[10], tot = n;
boolean take[] = new boolean[n];
Arrays.fill(take, true);
for(int i = 0; i < n; i++){
arr[i] = ni();
sum += arr[i];
freq[arr[i]]++;
}
Arrays.sort(arr);
if(arr[0] != 0){
pn(-1);
return ;
}
if(arr[n-1] == 0){
pn(0);
return ;
}
if(sum % 3 == 1){
boolean flag = true;
for(int i = 0; i < n; i++)
if(arr[i] % 3 == 1){
tot = n - 1;
take[i] = false;
flag = false;
break;
}
if(flag){
int cnt = 0;
tot = n - 2;
for(int i = 0; i < n && cnt != 2; i++){
if(arr[i] % 3 == 2){
cnt++;
take[i] = false;
}
}
}
}
else if(sum % 3 == 2){
boolean flag = true;
for(int i = 0; i < n; i++)
if(arr[i] % 3 == 2){
take[i] = false;
flag = false;
tot = n - 1;
break;
}
if(flag){
int cnt = 0;
for(int i = 0; i < n && cnt != 2; i++){
if(arr[i] % 3 == 1){
cnt++;
take[i] = false;
}
}
tot = n - 2;
}
}
if(freq[0] == tot){
p("0\n");
}
else{
for(int i = n - 1; i >= 0; i--){
if(take[i])
p(arr[i]);
}
p('\n');
}
}
static final long mod = (long)1e9+7l;
static FastReader sc;
static PrintWriter out;
public static void main(String[]args)throws IOException
{
out = new PrintWriter(System.out);
sc = new FastReader();
long s = System.currentTimeMillis();
int t = 1;
//t = ni();
for(int i = 1; i <= t; i++)
process(i);
out.flush();
System.err.println(System.currentTimeMillis()-s+"ms");
}
static void trace(Object... o){ System.err.println(Arrays.deepToString(o)); };
static void pn(Object o){ out.println(o); }
static void p(Object o){ out.print(o); }
static int ni()throws IOException{ return Integer.parseInt(sc.next()); }
static long nl()throws IOException{ return Long.parseLong(sc.next()); }
static double nd()throws IOException{ return Double.parseDouble(sc.next()); }
static String nln()throws IOException{ return sc.nextLine(); }
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 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();
}
String nextLine(){
String str = "";
try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); }
return str;
}
}
}
| Java | ["1\n0", "11\n3 4 5 4 5 3 5 3 4 4 0", "8\n3 2 5 1 5 2 2 3"] | 2 seconds | ["0", "5554443330", "-1"] | NoteIn the first sample there is only one number you can make — 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"math",
"brute force"
] | b263917e47e1c84340bcb1c77999fd7e | A single line contains a single integer n (1 ≤ n ≤ 100000) — the number of digits in the set. The second line contains n digits, the digits are separated by a single space. | 1,600 | On a single line print the answer to the problem. If such number does not exist, then you should print -1. | standard output | |
PASSED | 6bd1a36b473eb553febe829cb6dad214 | train_004.jsonl | 1343662200 | Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.Each digit is allowed to occur in the number the same number of times it occurs in the set. | 256 megabytes | //package random_practiceQuestions;
import java.util.Arrays;
import java.util.Scanner;
public class B214 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
int a = s.nextInt();
s.nextLine();
String[] l=s.nextLine().split(" ");
int[] list=new int[l.length];
int sum=0;
for (int i=0;i<list.length;i++){
list[i]=Integer.parseInt(l[i]);
sum=sum+list[i];
}
Arrays.sort(list);
if (list[0]!=0){
System.out.println(-1);
}
else if (list[list.length-1]==0){
System.out.println(0);
}
else{
if (sum%3==0){
for (int i=list.length-1;i>=0;i--){
System.out.print(list[i]);
}
}
else{
boolean check=false;
int max1=-1;
for (int i=0;i<list.length;i++){
if (list[i]%3==sum%3){
max1=i;
check=true;
break;
}
}
int max2=-1;
int ind1=0;
int count=0;
for (int i=0;i<list.length;i++){
if (list[i]%3!=sum%3 && list[i]%3!=0){
count++;
if (count==1){
ind1=i;
}
}
if (count==2){
max2=i;
check=true;
break;
}
}
if (!check){
System.out.println(-1);
}
else{
String str="";
if (max1!=-1){
for (int i=list.length-1;i>=0;i--){
if (i!=max1){
str=str+list[i];
}
}
}
else {
for (int i=list.length-1;i>=0;i--){
if (i!=max2 && i!=ind1){
str=str+list[i];
}
}
}
if (str.charAt(0)=='0'){
System.out.println(0);
}
else{
System.out.println(str);
}
}
}
}
}
}
| Java | ["1\n0", "11\n3 4 5 4 5 3 5 3 4 4 0", "8\n3 2 5 1 5 2 2 3"] | 2 seconds | ["0", "5554443330", "-1"] | NoteIn the first sample there is only one number you can make — 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"math",
"brute force"
] | b263917e47e1c84340bcb1c77999fd7e | A single line contains a single integer n (1 ≤ n ≤ 100000) — the number of digits in the set. The second line contains n digits, the digits are separated by a single space. | 1,600 | On a single line print the answer to the problem. If such number does not exist, then you should print -1. | standard output | |
PASSED | b0368835bbc26ce9196078edcecc0f8e | train_004.jsonl | 1343662200 | Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.Each digit is allowed to occur in the number the same number of times it occurs in the set. | 256 megabytes | import java.util.*;
import java.io.*;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Sum of digits must be divisible by 3.
// Get total, and then determine what digits we
// can remove to get to desired result.
int n = sc.nextInt();
int[] nums = new int[n];
long total = 0;
for (int i = 0; i < n; i++) {
nums[i] = sc.nextInt();
total += nums[i];
}
Arrays.sort(nums);
if (nums[0] != 0) {
System.out.println(-1);
return;
}
// Only consists of zeroes.
if (total == 0 || nums[n-1] == 0) {
System.out.println(0);
return;
}
StringBuilder sb = new StringBuilder();
if (total % 3 == 0) {
for (int i = n-1; i >= 0; i--) {
sb.append(nums[i]);
}
if (sb.charAt(0) == '0') {
System.out.println(0);
return;
}
System.out.println(sb.toString());
return;
}
if (total % 3 == 1) {
// Remove 1 digit which is 1 mod 3,
// or remove 2 digits which are 2 mod 3.
List<Integer> ones = new ArrayList<>();
List<Integer> twos = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (nums[i] % 3 == 1) {
ones.add(i);
nums[i] = -1;
break;
}
else if (nums[i] % 3 == 2) {
twos.add(i);
}
}
if (ones.size() > 0) {
for (int i = n-1; i >= 0; i--) {
if (nums[i] >= 0) {
sb.append(nums[i]);
}
}
if (sb.charAt(0) == '0') {
System.out.println(0);
return;
}
System.out.println(sb.toString());
}
else if (twos.size() >= 2) {
nums[twos.get(0)] = -1;
nums[twos.get(1)] = -1;
for (int i = n-1; i >= 0; i--) {
if (nums[i] >= 0) {
sb.append(nums[i]);
}
}
if (sb.charAt(0) == '0') {
System.out.println(0);
return;
}
System.out.println(sb.toString());
}
else {
System.out.println(-1);
return;
}
}
else {
List<Integer> ones = new ArrayList<>();
List<Integer> twos = new ArrayList<>();
for (int i = 0; i < n; i++) {
if (nums[i] % 3 == 2) {
ones.add(i);
nums[i] = -1;
break;
}
else if (nums[i] % 3 == 1) {
twos.add(i);
}
}
if (ones.size() > 0) {
for (int i = n-1; i >= 0; i--) {
if (nums[i] >= 0) {
sb.append(nums[i]);
}
}
if (sb.charAt(0) == '0') {
System.out.println(0);
return;
}
System.out.println(sb.toString());
}
else if (twos.size() >= 2) {
nums[twos.get(0)] = -1;
nums[twos.get(1)] = -1;
for (int i = n-1; i >= 0; i--) {
if (nums[i] >= 0) {
sb.append(nums[i]);
}
}
if (sb.charAt(0) == '0') {
System.out.println(0);
return;
}
System.out.println(sb.toString());
}
else {
System.out.println(-1);
return;
}
}
}
} | Java | ["1\n0", "11\n3 4 5 4 5 3 5 3 4 4 0", "8\n3 2 5 1 5 2 2 3"] | 2 seconds | ["0", "5554443330", "-1"] | NoteIn the first sample there is only one number you can make — 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"math",
"brute force"
] | b263917e47e1c84340bcb1c77999fd7e | A single line contains a single integer n (1 ≤ n ≤ 100000) — the number of digits in the set. The second line contains n digits, the digits are separated by a single space. | 1,600 | On a single line print the answer to the problem. If such number does not exist, then you should print -1. | standard output | |
PASSED | 209beb28f081c1c3f07dd8f515ec4d15 | train_004.jsonl | 1343662200 | Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.Each digit is allowed to occur in the number the same number of times it occurs in the set. | 256 megabytes | import java.util.*;import java.io.*;import java.math.*;
public class Main
{
public static void process()throws IOException
{
int n=ni();
int[]dig=new int[10];
int sum=0;
for(int i=0;i<n;i++)
{
int x=ni();
sum+=x;
dig[x]++;
}
if(dig[0]==0)
{pn(-1);return;}
if(sum%3==1)
{
if(dig[1]>0)
dig[1]--;
else if(dig[4]>0)
dig[4]--;
else if(dig[7]>0)
dig[7]--;
else
{
int temp=2;
int l=2;
while(temp>0)
{
if(dig[l]==0)
l+=3;
else
{
dig[l]--;
temp--;
}
if(l>=10)
{pn(-1);return;}
}
}
}
if(sum%3==2)
{
if(dig[2]>0)
dig[2]--;
else if(dig[5]>0)
dig[5]--;
else if(dig[8]>0)
dig[8]--;
else
{
int temp=2;
int l=1;
while(temp>0)
{
if(dig[l]==0)
l+=3;
else
{
dig[l]--;
temp--;
}
if(l>=10)
{pn(-1);return;}
}
}
}
int flag=0;
for(int i=9;i>=0;i--)
{
if(flag==0 && i==0)
dig[i]=1;
while(dig[i]>0)
{
flag=1;
dig[i]--;
p(i);
}
}
pn("");
}
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 | ["1\n0", "11\n3 4 5 4 5 3 5 3 4 4 0", "8\n3 2 5 1 5 2 2 3"] | 2 seconds | ["0", "5554443330", "-1"] | NoteIn the first sample there is only one number you can make — 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"math",
"brute force"
] | b263917e47e1c84340bcb1c77999fd7e | A single line contains a single integer n (1 ≤ n ≤ 100000) — the number of digits in the set. The second line contains n digits, the digits are separated by a single space. | 1,600 | On a single line print the answer to the problem. If such number does not exist, then you should print -1. | standard output | |
PASSED | 58adce388df96cc431f8b470acb850b0 | train_004.jsonl | 1343662200 | Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?You are given a set of digits, your task is to find the maximum integer that you can make from these digits. The made number must be divisible by 2, 3, 5 without a residue. It is permitted to use not all digits from the set, it is forbidden to use leading zeroes.Each digit is allowed to occur in the number the same number of times it occurs in the set. | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Main
{
public static void main (String[] args) throws java.lang.Exception
{
try{
//long a=Long.parseLong(next());
// int a=sc.nextInt();
Reader sc=new Reader();
PrintWriter out=new PrintWriter(System.out);
int n=sc.nextInt();
int a[]=new int[n];
int x=0;
long sum=0,z=0;
for(int i=0;i<n;i++)
{
x=sc.nextInt();
a[i]=x;
if(x==0)
z++;
sum+=x;
}
if(z==0)
out.println("-1");
else
{
Arrays.sort(a);
int temp[]=new int[n];
for(int i=n-1;i>=0;i--)
temp[n-1-i]=a[i];
StringBuilder sb=new StringBuilder("");
if(sum%3==0)
{
for(int i=0;i<n;i++)
sb.append(temp[i]);
}
else if(sum%3==1)
{
boolean ar[]=new boolean[n];
boolean flag=false;
for(int i=n-1;i>=0;i--)
{
if(temp[i]%3==1)
{
ar[i]=true;
flag=true;
break;
}
}
if(flag)
{ for(int i=0;i<n;i++)
{
if(!ar[i])
sb.append(temp[i]);
}
}
else
{
int co=0;
for(int i=n-1;i>=0;i--)
{
if(temp[i]%3==2)
{
ar[i]=true;
co++;
}
if(co==2)
break;
}
if(co==2)
{for(int i=0;i<n;i++)
{
if(!ar[i])
sb.append(temp[i]);
}
}
else
sb.append("0");
}
}
else if(sum%3==2)
{
boolean ar[]=new boolean[n];
boolean flag=false;
for(int i=n-1;i>=0;i--)
{
if(temp[i]%3==2)
{
ar[i]=true;
flag=true;
break;
}
}
if(flag)
{
for(int i=0;i<n;i++)
{
if(!ar[i])
sb.append(temp[i]);
}
}
else
{
int co=0;
for(int i=n-1;i>=0;i--)
{
if(temp[i]%3==1)
{
ar[i]=true;
co++;
}
if(co==2)
break;
}
if(co==2)
{for(int i=0;i<n;i++)
{
if(!ar[i])
sb.append(temp[i]);
}
}
else
sb.append("0");
}
}
String s=sb.toString();
if(s.charAt(0)=='0')
out.println("0");
else
out.println(s);
}
out.flush();
out.close();
}
catch(Exception e)
{}
}
//Template
// static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// static PrintWriter pw = new PrintWriter(System.out);
// static StringTokenizer st;
// static String next()
// {
// while(st==null || !st.hasMoreElements())
// {
// try
// {
// st = new StringTokenizer(br.readLine());
// }
// catch(IOException e)
// {
// e.printStackTrace();
// }
// }
// return st.nextToken();
// }
// static int gcd(int a,int b)
// {
// if(b==0)
// return a;
// else
// return gcd(b,a%b);
// }
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
}
| Java | ["1\n0", "11\n3 4 5 4 5 3 5 3 4 4 0", "8\n3 2 5 1 5 2 2 3"] | 2 seconds | ["0", "5554443330", "-1"] | NoteIn the first sample there is only one number you can make — 0. In the second sample the sought number is 5554443330. In the third sample it is impossible to make the required number. | Java 11 | standard input | [
"constructive algorithms",
"greedy",
"math",
"brute force"
] | b263917e47e1c84340bcb1c77999fd7e | A single line contains a single integer n (1 ≤ n ≤ 100000) — the number of digits in the set. The second line contains n digits, the digits are separated by a single space. | 1,600 | On a single line print the answer to the problem. If such number does not exist, then you should print -1. | standard output | |
PASSED | c32701edacd07c371a33d9accadcb224 | train_004.jsonl | 1427387400 | After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
/** Class: VitaliyAndPie.java
* @author Yury Park
* @version 1.0 <p>
* Course:
* Written / Updated: Mar 27, 2015
*
* This Class -
* After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.
The potato pie is located in the n-th room and Vitaly needs to go there.
Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key.
In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.
Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.
Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.
Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number.
Input
The first line of the input contains a positive integer n (2 ≤ n ≤ 10^5) — the number of rooms in the house.
The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one.
The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2.
The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1.
Output
Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n.
Sample test(s)
input
3
aAbB
output
0
input
4
aBaCaB
output
3
input
5
xYyXzZaZ
output
2
* Purpose -
*/
public class VitaliyAndPie {
static class reader{
static BufferedReader bReader=new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer token=new StringTokenizer("");
static String readNextLine() throws Exception{
return bReader.readLine();
}
static String next() throws Exception{
while (token.hasMoreTokens()==false){
token=new StringTokenizer(bReader.readLine());
}
return token.nextToken();
}
static char nextChar() throws IOException {
return (char)bReader.read();
}
static int nextDigit() throws IOException {
return Integer.parseInt("" + (char)bReader.read());
}
static int nextInt()throws Exception{
while (token.hasMoreTokens()==false){
token=new StringTokenizer(bReader.readLine());
}
return Integer.parseInt(token.nextToken());
}
static long nextLong()throws Exception{
while (token.hasMoreTokens()==false){
token=new StringTokenizer(bReader.readLine());
}
return Long.parseLong(token.nextToken());
}
static double nextDouble()throws Exception{
while (token.hasMoreTokens()==false){
token=new StringTokenizer(bReader.readLine());
}
return Double.parseDouble(token.nextToken());
}
}
public static void main(String[] args) throws Exception {
long n = reader.nextLong();
// char[] s = reader.next().toCharArray();
int keysHave[] = new int[256];
long countKeysBought = 0;
for(int i = 0; i < 2 * n - 2 - 1; i += 2) {
char firstChar = Character.toUpperCase(reader.nextChar());
char secondChar = reader.nextChar();
if(firstChar == secondChar) {}
else
//if(keysHave.contains(secondChar)) {
if(keysHave[secondChar]>0){
keysHave[secondChar]--;
keysHave[firstChar]++;
// keysHave.add(firstChar);
}
else {
keysHave[firstChar]++;
countKeysBought++;
}
}
System.out.println(countKeysBought);
}
}
| Java | ["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"] | 2 seconds | ["0", "3", "2"] | null | Java 8 | standard input | [
"hashing",
"greedy",
"strings"
] | 80fdb95372c1e8d558b8c8f31c9d0479 | The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1. | 1,100 | Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n. | standard output | |
PASSED | e6b911368fafd806fb1a33857d86a86c | train_004.jsonl | 1427387400 | After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number. | 256 megabytes | import java.util.*;
public class Vitaliy {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();String str=sc.next();
int[] keys = new int[26];int ans=0;
for(int i=0;i<2*(n-1); i+=2)
{
keys[str.charAt(i)-'a']++;
if(keys[str.charAt(i+1)-'A']!=0)
keys[str.charAt(i+1)-'A']--;
else
ans++;
}
System.out.print(ans);
}
}
| Java | ["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"] | 2 seconds | ["0", "3", "2"] | null | Java 8 | standard input | [
"hashing",
"greedy",
"strings"
] | 80fdb95372c1e8d558b8c8f31c9d0479 | The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1. | 1,100 | Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n. | standard output | |
PASSED | 9b4f218b48cf4e51f9fe2196b6b09f58 | train_004.jsonl | 1427387400 | After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number. | 256 megabytes |
import java.util.*;
import java.util.Scanner;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Dell
*/
public class NewMain53 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner s = new Scanner(System.in);
int k = s.nextInt();
HashMap<Character, Integer> hmap = new HashMap<>();
String str = s.next();
int ans = 0;
for (char c : str.toCharArray()) {
if (Character.isUpperCase(c)) {
if (hmap.containsKey(Character.toLowerCase(c)) && hmap.get(Character.toLowerCase(c)) > 0) {
hmap.put(Character.toLowerCase(c), hmap.get(Character.toLowerCase(c)) - 1);
} else {
ans++;
}
} else {
hmap.put(c, hmap.getOrDefault(c, 0) + 1);
}
}
System.out.println(ans);
}
}
| Java | ["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"] | 2 seconds | ["0", "3", "2"] | null | Java 8 | standard input | [
"hashing",
"greedy",
"strings"
] | 80fdb95372c1e8d558b8c8f31c9d0479 | The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1. | 1,100 | Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n. | standard output | |
PASSED | 07f22194ea528affa8b7d409952e23d7 | train_004.jsonl | 1427387400 | After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number. | 256 megabytes | import java.util.Scanner;
public class A525 {
void solve(){
Scanner sc=new Scanner(System.in);
int n= sc.nextInt();
char[] str =sc.next().toCharArray();
int len=str.length;
int[] lower=new int[27];
for(int i=0;i<27;i++){
lower[i]=0;
}
int result=0;
for(int i=0;i<len;i++){
if(str[i]>='a' && str[i]<='z'){
// System.out.println(str[i]);
// System.out.println(str[i]-'a');
int temp=str[i]-'a';
lower[temp]=lower[temp]+1;
}else if(str[i]>='A' && str[i]<='Z'){
int temp=str[i]-'A';
if(lower[temp]>0){
lower[temp]=lower[temp]-1;
}else if(lower[temp]==0){
result=result+1;
}
}
}
System.out.println(result);
}
public static void main(String [] args){
new A525().solve();
}
}
| Java | ["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"] | 2 seconds | ["0", "3", "2"] | null | Java 8 | standard input | [
"hashing",
"greedy",
"strings"
] | 80fdb95372c1e8d558b8c8f31c9d0479 | The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1. | 1,100 | Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n. | standard output | |
PASSED | d504264d92dbb9af22a7923fc497b0f7 | train_004.jsonl | 1427387400 | After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number. | 256 megabytes |
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scan= new Scanner(System.in);
int counter=0;
String roomtypesandkeys;
scan.nextInt();
roomtypesandkeys=scan.next();
int[] arr = new int[30];
for(int i=0;i<roomtypesandkeys.length();i+=2)
{
arr[(roomtypesandkeys.charAt(i)- 'a')]++;
if(arr[roomtypesandkeys.charAt(i+1) - 'A'] > 0)
arr[roomtypesandkeys.charAt(i+1) - 'A']--;
else
counter++;
}
System.out.print(counter);
}
}
| Java | ["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"] | 2 seconds | ["0", "3", "2"] | null | Java 8 | standard input | [
"hashing",
"greedy",
"strings"
] | 80fdb95372c1e8d558b8c8f31c9d0479 | The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1. | 1,100 | Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n. | standard output | |
PASSED | 113dacad8f1fddbcbd1917bfc91a81f6 | train_004.jsonl | 1427387400 | After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number. | 256 megabytes |
import java.io.*;
import java.util.*;
public class Main {
static final int INF = Integer.MAX_VALUE;
static void mergeSort(int[] a, int[] b, int[] c, int p, int r) {
if (p < r) {
int q = (p + r) / 2;
mergeSort(a, b, c, p, q);
mergeSort(a, b, c, q + 1, r);
merge(a, b, c, p, q, r);
}
}
static void merge(int[] a, int[] b, int[] c, int p, int q, int r) {
int n1 = q - p + 1;
int n2 = r - q;
int[] L = new int[n1 + 1], R = new int[n2 + 1];
int[] L1 = new int[n1 + 1], R1 = new int[n2 + 1];
int[] L2 = new int[n1 + 1], R2 = new int[n2 + 1];
for (int i = 0; i < n1; i++) {
L[i] = a[p + i];
L1[i] = b[p + i];
L2[i] = c[p + i];
}
for (int i = 0; i < n2; i++) {
R[i] = a[q + 1 + i];
R1[i] = b[q + 1 + i];
R2[i] = c[q + 1 + i];
}
L[n1] = R[n2] = INF;
L1[n1] = R1[n2] = INF;
L2[n1] = R2[n2] = INF;
for (int k = p, i = 0, j = 0; k <= r; k++) {
if (L[i] <= R[j]) {
a[k] = L[i];
b[k] = L1[i];
c[k] = L2[i++];
} else {
a[k] = R[j];
b[k] = R1[j];
c[k] = R2[j++];
}
}
}
public static int[] sieve(int n) {
int a[] = new int[n + 1];
for (int i = 2; i <= n; i++) {
a[i] = 1;
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if (a[i] == 1) {
for (int k = 2; i * k <= n; k++) {
a[i * k] = 0;
}
}
}
return a;
}
public static long sum(int a) {
long su = 0;
while (a > 0) {
su += a % 10;
a /= 10;
}
return su;
}
public static int divi(int b) {
int n = 0;
for (int i = 2; i <= Math.sqrt(b); i++) {
if (b % i == 0) {
n = i;
break;
}
}
if (n == 0) {
return b;
}
return n;
}
public static boolean prime(int n) {
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static String reve(int a, int b, String s) {
String q = "";
for (int i = b; i >= a; i--) {
q += s.charAt(i);
}
return q;
}
public static boolean isvowel(char c) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'y') {
return true;
} else {
return false;
}
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
public static int hole(int n) {
int y = 0;
if (n == 1) {
return 0;
}
if (prime(n)) {
return 1;
}
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
if (prime(i)) {
y++;
}
if (prime(n / i) && i != (n / i)) {
y++;
}
}
}
return y;
}
static StringBuilder getnine(StringBuilder s) {
StringBuilder c = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
c.append('9');
}
return c;
}
static boolean contain(int[] a) {
for (int i = 1; i < a.length; i++) {
if (a[i] == 0) {
return true;
}
}
return false;
}
static void decrease(int[] a) {
for (int i = 1; i < a.length; i++) {
a[i]--;
}
}
static long power(StringBuilder s) {
long c = 1, sum = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'C') {
c *= 2;
} else {
sum += c;
}
}
return sum;
}
public static void main(String[] args) throws IOException {
InputReader in = new InputReader(System.in);
OutputWriter or = new OutputWriter(System.out);
int n = in.nextInt(),ans=0;
StringBuilder s= new StringBuilder(in.readString());
int [] a= new int[26];
for (int i = 0; i < s.length(); i++) {
if (i%2==0) {
a[s.charAt(i)-'a']++;
}
else{
if (a[s.charAt(i)-'A']==0) {
ans++;
}
else a[s.charAt(i)-'A']--;
}
}
or.print(ans);
or.flush();
}
}
//System.out.println(s);
class Pair implements Comparable<Pair> {
int a;
int b;
int c;
public Pair(int n, int p, int C) {
a = n;
b = p;
c = C;
}
@Override
public int compareTo(Pair o) {
return b - o.b;
}
}
class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (snumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
| Java | ["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"] | 2 seconds | ["0", "3", "2"] | null | Java 8 | standard input | [
"hashing",
"greedy",
"strings"
] | 80fdb95372c1e8d558b8c8f31c9d0479 | The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1. | 1,100 | Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n. | standard output | |
PASSED | 0d36f22bc1d663a0e6c131af2e3c8a41 | train_004.jsonl | 1427387400 | After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number. | 256 megabytes | import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Pie {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Map<Character, Integer> map = new HashMap<>();
String input = sc.next();
int count = 0;
for (int i = 0; i < input.length(); i = i + 2) {
char key = input.charAt(i);
char door = input.charAt(i+1);
map.merge(key, 1, Integer::sum);
char doorKeyNeeded = Character.toLowerCase(door);
if (map.get(doorKeyNeeded) == null || map.get(doorKeyNeeded) == 0) {
count++;
} else {
map.put(doorKeyNeeded, map.get(doorKeyNeeded) - 1);
continue;
}
}
System.out.println(count);
}
}
| Java | ["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"] | 2 seconds | ["0", "3", "2"] | null | Java 8 | standard input | [
"hashing",
"greedy",
"strings"
] | 80fdb95372c1e8d558b8c8f31c9d0479 | The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1. | 1,100 | Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n. | standard output | |
PASSED | 83542ee191b9f886ebe3069b4d10a67d | train_004.jsonl | 1427387400 | After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
public class VitaliyandPie {
public static void main(String[] args) throws IOException {
BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
sc.readLine();
String str = sc.readLine();
int[]keys = new int[26];
int count = 0;
for(int i = 0; i < str.length(); i++){
if(i % 2 == 0){
char key = str.charAt(i);
keys[key - 'a'] +=1;
}else{
String door = str.charAt(i) + "";
if(keys[door.toLowerCase().charAt(0) - 'a'] > 0){
keys[door.toLowerCase().charAt(0) - 'a'] -=1;
}else{
count++;
}
}
}
System.out.println(count);
}
} | Java | ["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"] | 2 seconds | ["0", "3", "2"] | null | Java 8 | standard input | [
"hashing",
"greedy",
"strings"
] | 80fdb95372c1e8d558b8c8f31c9d0479 | The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1. | 1,100 | Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n. | standard output | |
PASSED | e8f58f496b4e030dd7a5e923d3d78e32 | train_004.jsonl | 1427387400 | After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number. | 256 megabytes | import java.util.*;
import java.io.*;
public class c{
public static void main( String [] args) throws IOException{
FastScanner sc=new FastScanner();
int n=sc.nextInt();
char [] ch=sc.next().toCharArray();
int [] key=new int[26];
int need=0;
for(int i=0;i<ch.length;i+=2){
int k=ch[i]-'a';
int room=ch[i+1]-'A';
key[k]++;
if(key[room]>0){
--key[room];
}
else{
need++;
}
}
System.out.println(need);
}
}
class FastScanner{
private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public FastScanner() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public FastScanner( 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];
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public String next() throws IOException{
byte c = read();
while(Character.isWhitespace(c)){
c = read();
}
StringBuilder builder = new StringBuilder();
builder.append((char)c);
c = read();
while(!Character.isWhitespace(c)){
builder.append((char)c);
c = read();
}
return builder.toString();
}
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 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 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 long[] nextLongArray( int n) throws IOException {
long arr[] = new long[n];
for(int i = 0; i < n; i++){
arr[i] = nextLong();
}
return arr;
}
public char nextChar() throws IOException{
byte c = read();
while(Character.isWhitespace(c)){
c = read();
}
return (char) c;
}
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;
}
public double[] nextDoubleArray( int n) throws IOException {
double arr[] = new double[n];
for(int i = 0; i < n; i++){
arr[i] = nextDouble();
}
return arr;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
| Java | ["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"] | 2 seconds | ["0", "3", "2"] | null | Java 8 | standard input | [
"hashing",
"greedy",
"strings"
] | 80fdb95372c1e8d558b8c8f31c9d0479 | The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1. | 1,100 | Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n. | standard output | |
PASSED | b107ed7ec22cdcf9bc0279f11dcebd68 | train_004.jsonl | 1427387400 | After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number. | 256 megabytes |
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String s = in.next();
int c = 0;
int[] a = new int[123];
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) >= 65 && s.charAt(i) < 97) {
if (a[Character.toLowerCase(s.charAt(i))] > 0) {
a[Character.toLowerCase(s.charAt(i))]--;
} else {
c++;
}
} else {
a[s.charAt(i)]++;
}
}
System.out.println(c);
}
}
| Java | ["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"] | 2 seconds | ["0", "3", "2"] | null | Java 8 | standard input | [
"hashing",
"greedy",
"strings"
] | 80fdb95372c1e8d558b8c8f31c9d0479 | The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1. | 1,100 | Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n. | standard output | |
PASSED | 8b121494a62ae153b8ef81a81e35b2ce | train_004.jsonl | 1427387400 | After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number. | 256 megabytes | //package contest_298;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class A_VitalyAndPie {
private static BufferedReader in;
private static StringTokenizer st;
public static void main(String[] args) throws NumberFormatException, IOException {
InputStreamReader isr = new InputStreamReader(System.in);
in = new BufferedReader(isr);
st = new StringTokenizer("");
int n = nextInt();
String s = next();
List<String> list = new LinkedList<String>();
TreeMap<String, Integer> tm = new TreeMap<String, Integer>();
int cnt = 0;
for (int i =2; i<=2*n-2; i+=2) {
String key = s.substring(i-2,i-1);
String door = s.substring(i-1,i).toLowerCase();
if(key.equals(door))
continue;
else{
if(tm.get(key)!=null)
tm.put(key, tm.get(key)+1);
else
tm.put(key, 1);
if(tm.get(door)!=null && tm.get(door)!=0){
tm.put(door, tm.get(door)-1);
continue;
} else{
cnt++;
}
// list.add(key);
// boolean ok = false;
// for (String st : list) {
// if(st.equals(door)){
// ok = true;
// list.remove(st);
// break;
// }
// }
// if(ok){
// continue;
// }
// else
// cnt++;
}
}
System.out.println(cnt);
}
// private static double nextDouble() throws NumberFormatException, IOException {
// return Double.parseDouble(next());
// }
//
// private static long nextLong() throws NumberFormatException, IOException {
// return Long.parseLong(next());
// }
//
private static int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(next());
}
private static String next() throws IOException {
while(!st.hasMoreElements()){
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
}
| Java | ["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"] | 2 seconds | ["0", "3", "2"] | null | Java 8 | standard input | [
"hashing",
"greedy",
"strings"
] | 80fdb95372c1e8d558b8c8f31c9d0479 | The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1. | 1,100 | Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n. | standard output | |
PASSED | d25309ac0da8f10e7df3fe1a13827d48 | train_004.jsonl | 1427387400 | After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number. | 256 megabytes | public class Problem {
public static final int LTA = -97;
public static final int UTA = -65;
public static final int UTL = 32;
public static void main(String[] args) {
java.util.Scanner input = new java.util.Scanner(System.in);
int n = input.nextInt();
char[] s = input.next().toCharArray();
int[] lower = new int[26];
int keys = 0;
for ( int i = 0 , j = 1 ; i < s.length && j < s.length ; i+=2 , j+=2 ){
if(s[j]+UTL == s[i])
continue;
else if (lower[s[j]+UTA] > 0){
lower[s[j]+UTA]--;
lower[s[i]+LTA]++;
continue;
}else{
keys++;
lower[s[i]+LTA]++;
}
}
System.out.println(keys);
}
}
| Java | ["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"] | 2 seconds | ["0", "3", "2"] | null | Java 8 | standard input | [
"hashing",
"greedy",
"strings"
] | 80fdb95372c1e8d558b8c8f31c9d0479 | The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1. | 1,100 | Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n. | standard output | |
PASSED | a84a0649b745b04b26173d89507e58fd | train_004.jsonl | 1427387400 | After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
public class c297a {
static class TaskA
{
public void solve(int testNumber, InputReader in, PrintWriter out)
{
int n=in.nextInt();
int count=0;
String s=in.next();
Map<Integer,Integer> hs=new HashMap<Integer, Integer>();
for(int i=0;i<s.length();i++)
{
if((int)s.charAt(i)>96&(int)s.charAt(i)<123)
{
hs.put((int)s.charAt(i),hs.get((int)s.charAt(i))!=null?hs.get((int)s.charAt(i))+1:1);
}
else if(hs.containsKey(s.charAt(i)+32))
{
if(hs.get(s.charAt(i)+32)>0)
hs.put(s.charAt(i)+32,hs.get(s.charAt(i)+32)-1);
else
count++;
}
else
{
count++;
}
// out.println(hs);
// out.println(count);
}
out.println(count);
}
}
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
/* java.util.Arrays.sort(array_name,new java.util.Comparator<int[]>(){
public int compare(int[] a, int[] b) {
return Integer.compare(a[0], b[0]);
}}); */
static void radixSort(int[] xs){
int[] cnt = new int[(1<<16)+1];
int[] ys = new int[xs.length];
for(int j = 0; j <= 16; j += 16)
{ Arrays.fill(cnt, 0);
for(int x : xs) { cnt[(x>>j&0xFFFF)+1]++; }
for(int i = 1; i < cnt.length; i++) { cnt[i] += cnt[i-1]; }
for(int x : xs) { ys[cnt[x>>j&0xFFFF]++] = x; }
{ final int[] t = xs; xs = ys; ys = t; } }
if(xs[0] < 0 || xs[xs.length - 1] >= 0)
return;
int i, j, c;
for(i = xs.length - 1, c = 0; xs[i] < 0; i--, c++) { ys[c] = xs[i]; }
for(j = xs.length - 1; i >= 0; i--, j--) { xs[j] = xs[i]; }
for(i = c - 1; i >= 0; i--) { xs[i] = ys[c-1-i]; }
}
static long min(long x,long y){return x<y?x:y;}
static long min(long x,long y,long z){return x<y?(x<z?x:z):(y<z?y:z);}
static long min(long n1,long n2,long n3,long n4){
return n1<n2?(n1<n3?(n1<n4?n1:n4):(n3<n4?n3:n4)):(n2<n3?(n2<n4?n2:n4):(n3<n4?n3:n4));}
static long max(long x,long y){return x>y?x:y;}
static long max(long x,long y,long z){return x>y?(x>z?x:z):(y>z?y:z);}
static long max(long n1,long n2,long n3,long n4){
return n1>n2?(n1>n3?(n1>n4?n1:n4):(n3>n4?n3:n4)):(n2>n3?(n2>n4?n2:n4):(n3>n4?n3:n4));}
static int min(int x,int y){return x<y?x:y;}
static int min(int x,int y,int z){return x<y?(x<z?x:z):(y<z?y:z);}
static long min(int n1,int n2,int n3,int n4){
return n1<n2?(n1<n3?(n1<n4?n1:n4):(n3<n4?n3:n4)):(n2<n3?(n2<n4?n2:n4):(n3<n4?n3:n4));}
static int max(int x,int y){return x>y?x:y;}
static int max(int x,int y,int z){return x>y?(x>z?x:z):(y>z?y:z);}
static long max(int n1,int n2,int n3,int n4){
return n1>n2?(n1>n3?(n1>n4?n1:n4):(n3>n4?n3:n4)):(n2>n3?(n2>n4?n2:n4):(n3>n4?n3:n4));}
static long sumarr(int arr[],int n1,int n2){
long sum=0; for(int i=n1-1;i<n2;i++) sum=sum+arr[i]; return sum; }
//**************************************Reader Class*********************************************//
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 String nextLine() {
String fullLine=null;
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
fullLine=reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return fullLine;
}
return fullLine;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"] | 2 seconds | ["0", "3", "2"] | null | Java 8 | standard input | [
"hashing",
"greedy",
"strings"
] | 80fdb95372c1e8d558b8c8f31c9d0479 | The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1. | 1,100 | Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n. | standard output | |
PASSED | 7362b9c4ca98d80768f85128cf614f82 | train_004.jsonl | 1427387400 | After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number. | 256 megabytes | //package codeForcesTry;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class A525_VitalityPie implements Closeable {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(System.out);
StringTokenizer stringTokenizer;
String next() throws IOException {
while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
stringTokenizer = new StringTokenizer(reader.readLine());
}
return stringTokenizer.nextToken();
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
public void solve()throws IOException {
int n=nextInt();
int cnt[]=new int[130];
String x=next();
int ans=0;
for(int i=0;i<x.length();i++){
if(i%2==0)
cnt[x.charAt(i)]++;
else{
char y=(char)(x.charAt(i)+32);
if(cnt[y]>0)
cnt[y]--;
else
ans++;
}
}
writer.println(ans);
/* for(int i=1;i<2*(n-1);i=i+2)
door+=x.charAt(i);
for(int i=0,j=0;i<2*(n-1)-1;i=i+2,j++){
if(door.substring(j).contains(Character.toString((char) (x.charAt(i)-32)))&&Character.isLowerCase(x.charAt(i))){
temp+=x.charAt(i);
}
}
writer.println(door.length()-temp.length());*/
}
public static void main(String args[]) throws IOException{
try(A525_VitalityPie c=new A525_VitalityPie()){
c.solve();
}
}
public void close() throws IOException {
reader.close();
writer.close();
}
}
| Java | ["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"] | 2 seconds | ["0", "3", "2"] | null | Java 8 | standard input | [
"hashing",
"greedy",
"strings"
] | 80fdb95372c1e8d558b8c8f31c9d0479 | The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1. | 1,100 | Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n. | standard output | |
PASSED | 9f71f3a426e060658fbc79dee13d0aff | train_004.jsonl | 1427387400 | After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number. | 256 megabytes | import java.util.Map;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.util.HashMap;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.NoSuchElementException;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Morgrey
*/
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);
cf525A solver = new cf525A();
solver.solve(1, in, out);
out.close();
}
}
class cf525A {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
String str = in.readLine();
Character[][] mas = new Character[(2*n-2) / 2][2];
Map<Character, Integer> Inventory = new HashMap<>();
int answer = 0;
int index = 0;
for(int i = 0; i < (2*n-2) / 2; i++){
mas[i][0] = str.charAt(index++);
mas[i][1] = Character.toLowerCase(str.charAt(index++));
}
Boolean add;
for(int i = 0; i < (2*n-2) / 2; i++) {
add = false;
try{
Inventory.replace(mas[i][0], Inventory.get(mas[i][0])+1);
}
catch (NullPointerException e){
Inventory.put(mas[i][0], 1);
}
try{
if(Inventory.get(mas[i][1]) <= 0)
add = true;
else
Inventory.replace(mas[i][1], Inventory.get(mas[i][1]) - 1);
}
catch (NullPointerException e){
add = true;
}
if(add)
answer++;
}
out.printLine(answer);
}
}
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 readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r')
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public void close() {
writer.close();
}
public void printLine(int i) {
writer.println(i);
}
}
| Java | ["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"] | 2 seconds | ["0", "3", "2"] | null | Java 8 | standard input | [
"hashing",
"greedy",
"strings"
] | 80fdb95372c1e8d558b8c8f31c9d0479 | The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1. | 1,100 | Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n. | standard output | |
PASSED | bf51afe8e9b6b4c96b27428dc503fd7d | train_004.jsonl | 1427387400 | After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number. | 256 megabytes | import java.util.*;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sol = 0;
sc.nextLine();
String roomsAndKeys = sc.nextLine();
Map<Character, Integer> keys = new HashMap<Character, Integer>();
for (int i = 0; i < roomsAndKeys.length(); i++) {
Character ch = roomsAndKeys.charAt(i);
if (i%2 == 0) {
int keysCount = keys.get(ch) == null ? 0 : keys.get(ch);
keys.put(
ch,
keysCount + 1);
// System.out.println(ch + ": " + keys.get(ch));
}
else {
ch = Character.toLowerCase(ch);
if (keys.get(ch) == null)
sol++;
else if (keys.get(ch) > 0) {
keys.put(ch, keys.get(ch)-1);
}
else
sol++;
}
}
System.out.println(sol);
}
}
| Java | ["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"] | 2 seconds | ["0", "3", "2"] | null | Java 8 | standard input | [
"hashing",
"greedy",
"strings"
] | 80fdb95372c1e8d558b8c8f31c9d0479 | The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1. | 1,100 | Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n. | standard output | |
PASSED | 89d42e824c4a9c0a25a36fa59ba0a1a4 | train_004.jsonl | 1427387400 | After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number. | 256 megabytes | import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = Integer.parseInt(scanner.nextLine());
String string = scanner.nextLine();
scanner.close();
string = string.toLowerCase();
char[] array = string.toCharArray();
HashMap<Character, Integer> pocket = new HashMap<>();
int buy = 0;
for (int i = 0; i < n * 2 - 2; i += 2) {
char key = array[i];
char door = array[i + 1];
/*
If you have the key in the pocket just increase the value.
Else, initalize the value to 1.
*/
if (pocket.containsKey(key)){
pocket.put(key, pocket.get(key)+1);
}
else{
pocket.put(key, 1);
}
/*
Check if it is a first time you get that door.
If YES, then buy a key for the door.
If NO, then:
if the value is not zero, decrease the number of keys for that door in the pocket;
if the value is zero, buy a key for the door.
*/
if (pocket.containsKey(door)){
if (pocket.get(door) != 0){
pocket.put(door, pocket.get(door)-1);
}
else
buy++;
}
else
buy++;
}
System.out.println(buy);
}
}
| Java | ["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"] | 2 seconds | ["0", "3", "2"] | null | Java 8 | standard input | [
"hashing",
"greedy",
"strings"
] | 80fdb95372c1e8d558b8c8f31c9d0479 | The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1. | 1,100 | Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n. | standard output | |
PASSED | 76f91c02a8341d0cb3f31a4d124c9d8f | train_004.jsonl | 1427387400 | After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number. | 256 megabytes | import java.util.HashMap;
import java.util.Scanner;
public class VitaliiIPirosok {
public static int[] getArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = sr.nextInt();
}
return array;
}
public static int[][] getMatrix(int sizeI, int sizeJ) {
int[][] array = new int[sizeI][sizeJ];
for (int i = 0; i < sizeI; i++) {
for (int j = 0; j < sizeJ; j++) {
array[i][j] = sr.nextInt();
}
}
return array;
}
public static boolean isSimpleNumber(int val) {
for (int i = 2; i <= Math.sqrt(val); i++) {
if (val % i == 0)
return false;
}
return true;
}
public static int NOD(int a, int b) {
while (a != 0 && b != 0) {
if (a > b) {
a = a % b;
} else {
b = b % a;
}
}
return a + b;
}
public static int NOK(int a, int b) {
return a * b / NOD(a, b);
}
public static long factorial(int i) {
long res = 1;
for (int j = 2; j <= i; j++) {
res *= j;
}
return res;
}
static char letters[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
static Scanner sr = new Scanner(System.in);
public static void main(String[] args) {
int n = sr.nextInt();
String input = sr.next();
int money = 0;
HashMap<Character, Integer> keys = new HashMap<>();
for (int i = 0; i < n - 1; i++) {
char key = Character.toUpperCase(input.charAt(2 * i));
char door = input.charAt(2 * i + 1);
Integer value = keys.get(key);
keys.put(key, value == null ? 1 : ++value);
Integer val = keys.get(door);
if (val == null) {
money++;
} else if (val == 1) {
keys.remove(door);
} else {
keys.put(door, --val);
}
}
System.out.println(money);
}
} | Java | ["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"] | 2 seconds | ["0", "3", "2"] | null | Java 8 | standard input | [
"hashing",
"greedy",
"strings"
] | 80fdb95372c1e8d558b8c8f31c9d0479 | The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1. | 1,100 | Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n. | standard output | |
PASSED | 5a607fbf1a74a0e404036106bd1fb4f3 | train_004.jsonl | 1427387400 | After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number. | 256 megabytes | /*
* Code Author: Jayesh Udhani
* Dhirubhai Ambani Institute of Information and Communication Technology (DA-IICT ,Gandhinagar)
* 2nd Year ICT BTECH student
*/
import java.io.*;
import java.util.*;
public class Main
{
static class Pair<F,S>
{
private int first;
private int second;
public Pair(int i, int j)
{
this.first = i;
this.second = j;
}
public int getFirst() { return first; }
public int getSecond() { return second ;}
}
public static void main(String args[])
{
InputReader in = new InputReader(System.in);
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
//----------My Code Starts Here----------
int n=in.nextInt(),cnt=0,i=0;
String s=in.next();
HashMap<Character, Integer> hm=new HashMap<>(); // Lower case n it's count
for(;i<s.length();i++)
{
if(i%2==0)
{
if(hm.containsKey(s.charAt(i)))
hm.put(s.charAt(i), hm.get(s.charAt(i))+1);
else
hm.put(s.charAt(i), 1);
}
else
{
char character = s.charAt(i);
int ascii = (int) character;
ascii+=32;
if(hm.containsKey((char) ascii) && hm.get((char)ascii)>0)
{
hm.put((char) ascii, hm.get((char)ascii)-1);
}
else
cnt++;
}
}
System.out.println(cnt);
out.close();
//---------------The End———————————————————
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream inputstream) {
reader = new BufferedReader(new InputStreamReader(inputstream));
tokenizer = null;
}
public String nextLine(){
String fullLine=null;
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
fullLine=reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return fullLine;
}
return fullLine;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
}
} | Java | ["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"] | 2 seconds | ["0", "3", "2"] | null | Java 8 | standard input | [
"hashing",
"greedy",
"strings"
] | 80fdb95372c1e8d558b8c8f31c9d0479 | The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1. | 1,100 | Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n. | standard output | |
PASSED | a297c30d7e1af1a965715cb0de6f4988 | train_004.jsonl | 1427387400 | After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number. | 256 megabytes | import java.util.HashMap;
import java.util.Scanner;
public class CR126B {
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt()*2,cnt=0;
String s=sc.next().toLowerCase();
n-=2;
HashMap<Character,Integer> keys=new HashMap<>();
for (char i = 'a'; i <= 'z'; i++)
keys.put(i,0);
for (int i = 0; i < s.length(); i+=2) {
if (s.charAt(i)==s.charAt(i+1))continue;
else {
if (keys.get(s.charAt(i+1))>0){
int t=keys.get(s.charAt(i+1));
keys.remove(s.charAt(i+1));
keys.put(s.charAt(i+1),t-1);
t=keys.get(s.charAt(i));
keys.remove(s.charAt(i));
keys.put(s.charAt(i),t+1);
}
else {
cnt++;
int t=keys.get(s.charAt(i));
keys.remove(s.charAt(i));
keys.put(s.charAt(i),t+1);
}
}
}
System.out.println(cnt);
}
}
| Java | ["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"] | 2 seconds | ["0", "3", "2"] | null | Java 8 | standard input | [
"hashing",
"greedy",
"strings"
] | 80fdb95372c1e8d558b8c8f31c9d0479 | The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1. | 1,100 | Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n. | standard output | |
PASSED | a361a9f016d4ed35fb0bf62e128fc802 | train_004.jsonl | 1427387400 | After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class p1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String str = sc.next();
int[] k = new int[26];
int res = 0;
for (int i = 0; i < 2 * n - 3; i += 2) {
int idx1 = (int)(str.charAt(i) - 'a');
int idx2 = (int)(str.charAt(i + 1) - 'A');
if (idx1 != idx2) {
k[idx1]++;
if (k[idx2] > 0) {
k[idx2]--;
} else {
res++;
}
}
}
System.out.println(res);
}
} | Java | ["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"] | 2 seconds | ["0", "3", "2"] | null | Java 8 | standard input | [
"hashing",
"greedy",
"strings"
] | 80fdb95372c1e8d558b8c8f31c9d0479 | The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1. | 1,100 | Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n. | standard output | |
PASSED | f57fbf6594ace3b805e13b7ecbbf5249 | train_004.jsonl | 1427387400 | After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (n - 1)-th room to the n-th room. Thus, you can go to room x only from room x - 1.The potato pie is located in the n-th room and Vitaly needs to go there. Each pair of consecutive rooms has a door between them. In order to go to room x from room x - 1, you need to open the door between the rooms with the corresponding key. In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type t can open the door of type T if and only if t and T are the same letter, written in different cases. For example, key f can open door F.Each of the first n - 1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room n.Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room n, which has a delicious potato pie. Write a program that will help Vitaly find out this number. | 256 megabytes | import java.util.*;
import java.io.*;
import java.awt.Point;
import java.math.BigDecimal;
import java.math.BigInteger;
import static java.lang.Math.*;
// Solution is at the bottom of code
public class A implements Runnable{
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
OutputWriter out;
StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args){
new Thread(null, new A(), "", 128 * (1L << 20)).start();
}
/////////////////////////////////////////////////////////////////////
void init() throws FileNotFoundException{
Locale.setDefault(Locale.US);
if (ONLINE_JUDGE){
in = new BufferedReader(new InputStreamReader(System.in));
out = new OutputWriter(System.out);
}else{
in = new BufferedReader(new FileReader("input.txt"));
out = new OutputWriter("output.txt");
}
}
////////////////////////////////////////////////////////////////
long timeBegin, timeEnd;
void time(){
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
void debug(Object... objects){
if (ONLINE_JUDGE){
for (Object o: objects){
System.err.println(o.toString());
}
}
}
/////////////////////////////////////////////////////////////////////
public void run(){
try{
timeBegin = System.currentTimeMillis();
Locale.setDefault(Locale.US);
init();
solve();
out.close();
time();
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
/////////////////////////////////////////////////////////////////////
String delim = " ";
String readString() throws IOException{
while(!tok.hasMoreTokens()){
try{
tok = new StringTokenizer(in.readLine());
}catch (Exception e){
return null;
}
}
return tok.nextToken(delim);
}
String readLine() throws IOException{
return in.readLine();
}
/////////////////////////////////////////////////////////////////
final char NOT_A_SYMBOL = '\0';
char readChar() throws IOException{
int intValue = in.read();
if (intValue == -1){
return NOT_A_SYMBOL;
}
return (char) intValue;
}
char[] readCharArray() throws IOException{
return readLine().toCharArray();
}
/////////////////////////////////////////////////////////////////
int readInt() throws IOException {
return Integer.parseInt(readString());
}
int[] readIntArray(int size) throws IOException {
int[] array = new int[size];
for (int index = 0; index < size; ++index){
array[index] = readInt();
}
return array;
}
int[] readSortedIntArray(int size) throws IOException {
Integer[] array = new Integer[size];
for (int index = 0; index < size; ++index) {
array[index] = readInt();
}
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) {
sortedArray[index] = array[index];
}
return sortedArray;
}
int[] readIntArrayWithDecrease(int size) throws IOException {
int[] array = readIntArray(size);
for (int i = 0; i < size; ++i) {
array[i]--;
}
return array;
}
///////////////////////////////////////////////////////////////////
int[][] readIntMatrix(int rowsCount, int columnsCount) throws IOException {
int[][] matrix = new int[rowsCount][];
for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
matrix[rowIndex] = readIntArray(columnsCount);
}
return matrix;
}
int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) throws IOException {
int[][] matrix = new int[rowsCount][];
for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
matrix[rowIndex] = readIntArrayWithDecrease(columnsCount);
}
return matrix;
}
///////////////////////////////////////////////////////////////////
long readLong() throws IOException{
return Long.parseLong(readString());
}
long[] readLongArray(int size) throws IOException{
long[] array = new long[size];
for (int index = 0; index < size; ++index){
array[index] = readLong();
}
return array;
}
////////////////////////////////////////////////////////////////////
double readDouble() throws IOException{
return Double.parseDouble(readString());
}
double[] readDoubleArray(int size) throws IOException{
double[] array = new double[size];
for (int index = 0; index < size; ++index){
array[index] = readDouble();
}
return array;
}
////////////////////////////////////////////////////////////////////
BigInteger readBigInteger() throws IOException {
return new BigInteger(readString());
}
BigDecimal readBigDecimal() throws IOException {
return new BigDecimal(readString());
}
/////////////////////////////////////////////////////////////////////
Point readPoint() throws IOException{
int x = readInt();
int y = readInt();
return new Point(x, y);
}
Point[] readPointArray(int size) throws IOException{
Point[] array = new Point[size];
for (int index = 0; index < size; ++index){
array[index] = readPoint();
}
return array;
}
/////////////////////////////////////////////////////////////////////
List<Integer>[] readGraph(int vertexNumber, int edgeNumber)
throws IOException{
@SuppressWarnings("unchecked")
List<Integer>[] graph = new List[vertexNumber];
for (int index = 0; index < vertexNumber; ++index){
graph[index] = new ArrayList<Integer>();
}
while (edgeNumber-- > 0){
int from = readInt() - 1;
int to = readInt() - 1;
graph[from].add(to);
graph[to].add(from);
}
return graph;
}
/////////////////////////////////////////////////////////////////////
static class IntIndexPair {
static Comparator<IntIndexPair> increaseComparator = new Comparator<IntIndexPair>() {
@Override
public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) {
int value1 = indexPair1.value;
int value2 = indexPair2.value;
if (value1 != value2) return value1 - value2;
int index1 = indexPair1.index;
int index2 = indexPair2.index;
return index1 - index2;
}
};
static Comparator<IntIndexPair> decreaseComparator = new Comparator<IntIndexPair>() {
@Override
public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) {
int value1 = indexPair1.value;
int value2 = indexPair2.value;
if (value1 != value2) return -(value1 - value2);
int index1 = indexPair1.index;
int index2 = indexPair2.index;
return index1 - index2;
}
};
int value, index;
public IntIndexPair(int value, int index) {
super();
this.value = value;
this.index = index;
}
public int getRealIndex() {
return index + 1;
}
}
IntIndexPair[] readIntIndexArray(int size) throws IOException {
IntIndexPair[] array = new IntIndexPair[size];
for (int index = 0; index < size; ++index) {
array[index] = new IntIndexPair(readInt(), index);
}
return array;
}
/////////////////////////////////////////////////////////////////////
static class OutputWriter extends PrintWriter {
final int DEFAULT_PRECISION = 12;
protected int precision;
protected String format, formatWithSpace;
{
precision = DEFAULT_PRECISION;
format = createFormat(precision);
formatWithSpace = format + " ";
}
public OutputWriter(OutputStream out) {
super(out);
}
public OutputWriter(String fileName) throws FileNotFoundException {
super(fileName);
}
public int getPrecision() {
return precision;
}
public void setPrecision(int precision) {
precision = max(0, precision);
this.precision = precision;
format = createFormat(precision);
formatWithSpace = format + " ";
}
private String createFormat(int precision){
return "%." + precision + "f";
}
@Override
public void print(double d){
printf(format, d);
}
public void printWithSpace(double d){
printf(formatWithSpace, d);
}
public void printAll(double...d){
for (int i = 0; i < d.length - 1; ++i){
printWithSpace(d[i]);
}
print(d[d.length - 1]);
}
@Override
public void println(double d){
printlnAll(d);
}
public void printlnAll(double... d){
printAll(d);
println();
}
}
/////////////////////////////////////////////////////////////////////
static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
static final int[][] steps8 = {
{-1, 0}, {1, 0}, {0, -1}, {0, 1},
{-1, -1}, {1, 1}, {1, -1}, {-1, 1}
};
static final boolean check(int index, int lim){
return (0 <= index && index < lim);
}
/////////////////////////////////////////////////////////////////////
static final boolean checkBit(int mask, int bit){
return (mask & (1 << bit)) != 0;
}
/////////////////////////////////////////////////////////////////////
static final long getSum(int[] array) {
long sum = 0;
for (int value: array) {
sum += value;
}
return sum;
}
static final Point getMinMax(int[] array) {
int min = array[0];
int max = array[0];
for (int index = 0, size = array.length; index < size; ++index, ++index) {
int value = array[index];
if (index == size - 1) {
min = min(min, value);
max = max(max, value);
} else {
int otherValue = array[index + 1];
if (value <= otherValue) {
min = min(min, value);
max = max(max, otherValue);
} else {
min = min(min, otherValue);
max = max(max, value);
}
}
}
return new Point(min, max);
}
/////////////////////////////////////////////////////////////////////
void solve() throws IOException {
int n = readInt();
char[] keysAndDoors = readCharArray();
int answer = 0;
int[] keysCounts = new int[26];
for (char keyOrDoor : keysAndDoors) {
if ('a' <= keyOrDoor && keyOrDoor <= 'z') {
keysCounts[keyOrDoor-'a']++;
} else {
int needKey = keyOrDoor - 'A';
if (keysCounts[needKey] == 0) {
++answer;
} else {
keysCounts[needKey]--;
}
}
}
out.println(answer);
}
}
| Java | ["3\naAbB", "4\naBaCaB", "5\nxYyXzZaZ"] | 2 seconds | ["0", "3", "2"] | null | Java 8 | standard input | [
"hashing",
"greedy",
"strings"
] | 80fdb95372c1e8d558b8c8f31c9d0479 | The first line of the input contains a positive integer n (2 ≤ n ≤ 105) — the number of rooms in the house. The second line of the input contains string s of length 2·n - 2. Let's number the elements of the string from left to right, starting from one. The odd positions in the given string s contain lowercase Latin letters — the types of the keys that lie in the corresponding rooms. Thus, each odd position i of the given string s contains a lowercase Latin letter — the type of the key that lies in room number (i + 1) / 2. The even positions in the given string contain uppercase Latin letters — the types of doors between the rooms. Thus, each even position i of the given string s contains an uppercase letter — the type of the door that leads from room i / 2 to room i / 2 + 1. | 1,100 | Print the only integer — the minimum number of keys that Vitaly needs to buy to surely get from room one to room n. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.