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 | 9b295ad778c5b00f8cb8cc561db808ba | train_001.jsonl | 1353857400 | One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.Karlsson's gaze immediately fell on n wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds t, in which he is able to bring all the cupboard doors in the required position.Your task is to write a program that will determine the required number of seconds t. | 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.sql.Time;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.Vector;
public class Codeforces {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
// ---------------------------------------------------
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
// -------- Write Task Code ----------
int n = in.nextInt();
int leftCount = 0;
int rightCount = 0;
for (int i = 0; i < n; i++) {
int inLeft = in.nextInt();
int inRight = in.nextInt();
if (inLeft == 1) {
leftCount++;
}
if (inRight == 0) {
rightCount++;
}
}
if(leftCount > n/2){
leftCount = n - leftCount ;
}
if(rightCount > n/2){
rightCount = n - rightCount ;
}
System.out.println(leftCount + rightCount);
// ------- finish Task Code ---------
}
public static ArrayList<String> SplitString(String num) {
ArrayList<String> numbers = new ArrayList<>();
String[] j = num.split("");
for (int f = 0; f < num.length(); f++) {
numbers.add(j[f]);
}
return numbers;
}
public static ArrayList<Integer> SplitInteger(int num) {
ArrayList<Integer> numbers = new ArrayList<>();
String number = String.valueOf(num);
for (int f = 0; f < number.length(); f++) {
int j = Character.digit(number.charAt(f), 10);
numbers.add(j);
}
return numbers;
}
public static ArrayList<Long> SplitLong(long num) {
ArrayList<Long> numbers = new ArrayList<>();
String number = String.valueOf(num);
for (int f = 0; f < number.length(); f++) {
int j = Character.digit(number.charAt(f), 10);
numbers.add((long) j);
}
return numbers;
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
}
} | Java | ["5\n0 1\n1 0\n0 1\n1 1\n0 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"implementation"
] | 2052b0b4abdcf7d613b56842b1267f60 | The first input line contains a single integer n β the number of cupboards in the kitchen (2ββ€βnββ€β104). Then follow n lines, each containing two integers li and ri (0ββ€βli,βriββ€β1). Number li equals one, if the left door of the i-th cupboard is opened, otherwise number li equals zero. Similarly, number ri equals one, if the right door of the i-th cupboard is opened, otherwise number ri equals zero. The numbers in the lines are separated by single spaces. | 800 | In the only output line print a single integer t β the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs. | standard output | |
PASSED | 198b80e0aeed7dcffa569cff4f2a7cce | train_001.jsonl | 1353857400 | One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.Karlsson's gaze immediately fell on n wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds t, in which he is able to bring all the cupboard doors in the required position.Your task is to write a program that will determine the required number of seconds t. | 256 megabytes | import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int l0 = 0, l1 = 0, r0 = 0, r1 = 0;
int[][] cabz = new int[n][2];
for (int i = 0; i < n; i++) {
for (int k = 0; k < 2; k++) {
cabz[i][k] = sc.nextInt();
}
if (cabz[i][0] == 0) {
l0++;
} else {
l1++;
}
if (cabz[i][1] == 0) {
r0++;
} else {
r1++;
}
}
System.out.println(Math.min(l0, l1) + Math.min(r0, r1));
}
} | Java | ["5\n0 1\n1 0\n0 1\n1 1\n0 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"implementation"
] | 2052b0b4abdcf7d613b56842b1267f60 | The first input line contains a single integer n β the number of cupboards in the kitchen (2ββ€βnββ€β104). Then follow n lines, each containing two integers li and ri (0ββ€βli,βriββ€β1). Number li equals one, if the left door of the i-th cupboard is opened, otherwise number li equals zero. Similarly, number ri equals one, if the right door of the i-th cupboard is opened, otherwise number ri equals zero. The numbers in the lines are separated by single spaces. | 800 | In the only output line print a single integer t β the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs. | standard output | |
PASSED | 14280a0384e134b2d460883a10dc92a2 | train_001.jsonl | 1353857400 | One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.Karlsson's gaze immediately fell on n wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds t, in which he is able to bring all the cupboard doors in the required position.Your task is to write a program that will determine the required number of seconds t. | 256 megabytes | import java.util.Scanner;
public class Cupboards {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int left = 0, right = 0;
for (int i = 0 ; i < n ; i++) {
int a = scan.nextInt(), b = scan.nextInt();
if (a == 1)
left++;
if (b == 1)
right++;
}
int min1 = Math.min(left + (n - right), (n - left) + right);
int min2 = Math.min(left + right, (n - left) + (n - right));
System.out.println(Math.min(min1, min2));
}
}
| Java | ["5\n0 1\n1 0\n0 1\n1 1\n0 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"implementation"
] | 2052b0b4abdcf7d613b56842b1267f60 | The first input line contains a single integer n β the number of cupboards in the kitchen (2ββ€βnββ€β104). Then follow n lines, each containing two integers li and ri (0ββ€βli,βriββ€β1). Number li equals one, if the left door of the i-th cupboard is opened, otherwise number li equals zero. Similarly, number ri equals one, if the right door of the i-th cupboard is opened, otherwise number ri equals zero. The numbers in the lines are separated by single spaces. | 800 | In the only output line print a single integer t β the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs. | standard output | |
PASSED | becac88c69451dba05fecab393424583 | train_001.jsonl | 1353857400 | One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.Karlsson's gaze immediately fell on n wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds t, in which he is able to bring all the cupboard doors in the required position.Your task is to write a program that will determine the required number of seconds t. | 256 megabytes | /*package whatever //do not write package name here */
import java.util.*;
import java.lang.*;
import java.io.*;
public class GFG {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int counta0=0;
int counta1=0;
int countb0=0;
int countb1=0;
while(n-->0) {
int a=s.nextInt();
int b=s.nextInt();
if(a==0) {
counta0++;
}
if(a==1) {
counta1++;
}
if(b==0) {
countb0++;
}
if(b==1) {
countb1++;
}
}
int ans=0;
if(counta0>counta1) {
ans+=counta1;
}
else if(counta0<counta1){
ans+=counta0;
}
else {
ans+=counta0;
}
if(countb0>countb1) {
ans+=countb1;
}
else if(countb0<countb1){
ans+=countb0;
}
else {
ans+=countb0;
}
System.out.println(ans);
}
} | Java | ["5\n0 1\n1 0\n0 1\n1 1\n0 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"implementation"
] | 2052b0b4abdcf7d613b56842b1267f60 | The first input line contains a single integer n β the number of cupboards in the kitchen (2ββ€βnββ€β104). Then follow n lines, each containing two integers li and ri (0ββ€βli,βriββ€β1). Number li equals one, if the left door of the i-th cupboard is opened, otherwise number li equals zero. Similarly, number ri equals one, if the right door of the i-th cupboard is opened, otherwise number ri equals zero. The numbers in the lines are separated by single spaces. | 800 | In the only output line print a single integer t β the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs. | standard output | |
PASSED | 563bbc948d2987480618db94e9019384 | train_001.jsonl | 1353857400 | One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.Karlsson's gaze immediately fell on n wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds t, in which he is able to bring all the cupboard doors in the required position.Your task is to write a program that will determine the required number of seconds t. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), l = 0, r = 0;
for (int i = 0; i < n; i++) {
l += sc.nextInt();
r += sc.nextInt();
}
System.out.println(Math.min(l, n-l) + Math.min(r, n-r));
}
} | Java | ["5\n0 1\n1 0\n0 1\n1 1\n0 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"implementation"
] | 2052b0b4abdcf7d613b56842b1267f60 | The first input line contains a single integer n β the number of cupboards in the kitchen (2ββ€βnββ€β104). Then follow n lines, each containing two integers li and ri (0ββ€βli,βriββ€β1). Number li equals one, if the left door of the i-th cupboard is opened, otherwise number li equals zero. Similarly, number ri equals one, if the right door of the i-th cupboard is opened, otherwise number ri equals zero. The numbers in the lines are separated by single spaces. | 800 | In the only output line print a single integer t β the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs. | standard output | |
PASSED | f0062f5aa5dcb3956fec72b57041bc19 | train_001.jsonl | 1353857400 | One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.Karlsson's gaze immediately fell on n wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds t, in which he is able to bring all the cupboard doors in the required position.Your task is to write a program that will determine the required number of seconds t. | 256 megabytes |
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
int r = 0, l = 0;
for (int i = 0; i < t; i++) {
String[] a = br.readLine().split(" ");
r += Integer.parseInt(a[0]);
l += Integer.parseInt(a[1]);
}
int ans = Math.min(r, t - r) + Math.min(l, t - l);
System.out.println(ans);
}
}
| Java | ["5\n0 1\n1 0\n0 1\n1 1\n0 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"implementation"
] | 2052b0b4abdcf7d613b56842b1267f60 | The first input line contains a single integer n β the number of cupboards in the kitchen (2ββ€βnββ€β104). Then follow n lines, each containing two integers li and ri (0ββ€βli,βriββ€β1). Number li equals one, if the left door of the i-th cupboard is opened, otherwise number li equals zero. Similarly, number ri equals one, if the right door of the i-th cupboard is opened, otherwise number ri equals zero. The numbers in the lines are separated by single spaces. | 800 | In the only output line print a single integer t β the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs. | standard output | |
PASSED | 412fdc40e57e2ea1f996b1ccd5bf5c1f | train_001.jsonl | 1353857400 | One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.Karlsson's gaze immediately fell on n wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds t, in which he is able to bring all the cupboard doors in the required position.Your task is to write a program that will determine the required number of seconds t. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Amine
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInput in = new FastInput(inputStream);
FastOutput out = new FastOutput(outputStream);
Cupboards solver = new Cupboards();
solver.solve(1, in, out);
out.close();
}
static class Cupboards {
public void solve(int testNumber, FastInput in, FastOutput out) {
int n = in.nextInt();
int l[] = new int[n];
int r[] = new int[n];
int ls = 0, rs = 0;
for (int i = 0; i < n; i++) {
l[i] = in.nextInt();
ls += l[i];
r[i] = in.nextInt();
rs += r[i];
}
int min1 = Math.min(n - rs, rs);
int min2 = Math.min(n - ls, ls);
out.println(min1 + min2);
}
}
static class FastOutput {
private final PrintWriter writer;
public FastOutput(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public FastOutput(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(int i) {
writer.println(i);
}
}
static class FastInput {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private FastInput.SpaceCharFilter filter;
public FastInput(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["5\n0 1\n1 0\n0 1\n1 1\n0 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"implementation"
] | 2052b0b4abdcf7d613b56842b1267f60 | The first input line contains a single integer n β the number of cupboards in the kitchen (2ββ€βnββ€β104). Then follow n lines, each containing two integers li and ri (0ββ€βli,βriββ€β1). Number li equals one, if the left door of the i-th cupboard is opened, otherwise number li equals zero. Similarly, number ri equals one, if the right door of the i-th cupboard is opened, otherwise number ri equals zero. The numbers in the lines are separated by single spaces. | 800 | In the only output line print a single integer t β the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs. | standard output | |
PASSED | f9138781c7d4cee55216bfa47d90770d | train_001.jsonl | 1353857400 | One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.Karlsson's gaze immediately fell on n wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds t, in which he is able to bring all the cupboard doors in the required position.Your task is to write a program that will determine the required number of seconds t. | 256 megabytes | import java.util.*;
public class Cupboards
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int lopen = 0;
int lclosed = 0;
int ropen = 0;
int rclosed = 0;
for(int i=0;i<n;i++)
{
int l = sc.nextInt();
int r = sc.nextInt();
if(l==1)
lclosed++;
else if(l==0)
lopen++;
if(r==1)
rclosed++;
else if(r==0)
ropen++;
}
int c1 = lopen + rclosed;
int c2 = lclosed + ropen;
int c3 = lopen + ropen;
int c4 = lclosed + rclosed;
int ans = Math.min(c1,Math.min(c2,Math.min(c3,c4)));
System.out.println(ans);
}
} | Java | ["5\n0 1\n1 0\n0 1\n1 1\n0 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"implementation"
] | 2052b0b4abdcf7d613b56842b1267f60 | The first input line contains a single integer n β the number of cupboards in the kitchen (2ββ€βnββ€β104). Then follow n lines, each containing two integers li and ri (0ββ€βli,βriββ€β1). Number li equals one, if the left door of the i-th cupboard is opened, otherwise number li equals zero. Similarly, number ri equals one, if the right door of the i-th cupboard is opened, otherwise number ri equals zero. The numbers in the lines are separated by single spaces. | 800 | In the only output line print a single integer t β the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs. | standard output | |
PASSED | 9f5e416ecd846983e1277a2cab8d47a2 | train_001.jsonl | 1353857400 | One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.Karlsson's gaze immediately fell on n wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds t, in which he is able to bring all the cupboard doors in the required position.Your task is to write a program that will determine the required number of seconds t. | 256 megabytes |
import java.util.Scanner;
/**
*
* @author farah
*/
public class AhmadAli {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
int sum=0;
int l1=0 , l0=0 , r1=0 , r0=0;
for(int i=0 ; i<n ; i++){
if(sc.nextInt()==1)
l1++;
else
l0++;
if(sc.nextInt()==1)
r1++;
else
r0++;
}
sum+=Math.min(l1, l0);
sum+=Math.min(r1, r0);
System.out.println(sum);
}
}
| Java | ["5\n0 1\n1 0\n0 1\n1 1\n0 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"implementation"
] | 2052b0b4abdcf7d613b56842b1267f60 | The first input line contains a single integer n β the number of cupboards in the kitchen (2ββ€βnββ€β104). Then follow n lines, each containing two integers li and ri (0ββ€βli,βriββ€β1). Number li equals one, if the left door of the i-th cupboard is opened, otherwise number li equals zero. Similarly, number ri equals one, if the right door of the i-th cupboard is opened, otherwise number ri equals zero. The numbers in the lines are separated by single spaces. | 800 | In the only output line print a single integer t β the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs. | standard output | |
PASSED | 9c9bfd8ac33ffe0409f64a47c4a31d2b | train_001.jsonl | 1353857400 | One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.Karlsson's gaze immediately fell on n wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds t, in which he is able to bring all the cupboard doors in the required position.Your task is to write a program that will determine the required number of seconds t. | 256 megabytes | import java.util.Scanner;
/**
* Created: 2/16/2018
*
* @author phil
*/
public class A248_Cupboards {
public static void main(String[] arg) {
Scanner sc = new Scanner(System.in);
int numCupboards = sc.nextInt();
int leftDoorsOpen = 0;
int rightDoorsOpen = 0;
int time = 0;
for (int i=0; i<numCupboards; i++) {
if (sc.nextInt() == 1) {
leftDoorsOpen++;
}
if (sc.nextInt() == 1) {
rightDoorsOpen++;
}
}
if (leftDoorsOpen > numCupboards/2) {
time += numCupboards-leftDoorsOpen;
} else {
time += leftDoorsOpen;
}
if (rightDoorsOpen > numCupboards/2) {
time += numCupboards - rightDoorsOpen;
} else {
time += rightDoorsOpen;
}
System.out.println(time);
}
}
| Java | ["5\n0 1\n1 0\n0 1\n1 1\n0 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"implementation"
] | 2052b0b4abdcf7d613b56842b1267f60 | The first input line contains a single integer n β the number of cupboards in the kitchen (2ββ€βnββ€β104). Then follow n lines, each containing two integers li and ri (0ββ€βli,βriββ€β1). Number li equals one, if the left door of the i-th cupboard is opened, otherwise number li equals zero. Similarly, number ri equals one, if the right door of the i-th cupboard is opened, otherwise number ri equals zero. The numbers in the lines are separated by single spaces. | 800 | In the only output line print a single integer t β the minimum number of seconds Karlsson needs to change the doors of all cupboards to the position he needs. | standard output | |
PASSED | d9e221da988139629a9e15bb92cd1472 | train_001.jsonl | 1584018300 | The next lecture in a high school requires two topics to be discussed. The $$$i$$$-th topic is interesting by $$$a_i$$$ units for the teacher and by $$$b_i$$$ units for the students.The pair of topics $$$i$$$ and $$$j$$$ ($$$i < j$$$) is called good if $$$a_i + a_j > b_i + b_j$$$ (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics. | 256 megabytes | import java.util.*;
import java.io.*;
public class Solution{
public static class pair{
int x;
int y;
}
public static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
public String next() {
while (st == null || !st.hasMoreElements())
try {
st=new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) {
a[i]=nextInt();
}
return a;
}public double nextDouble() {
return Double.parseDouble(next());
}
}
public static void printarr(int[] arr){
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+" ");
}
System.out.println();
}
static HashMap<Long,Integer> map;
public static void main(String[] args) throws IOException{
FastScanner fs=new FastScanner();
int t=1; //fs.nextInt();
PrintWriter out=new PrintWriter(System.out);
while(t-->0){
int n=fs.nextInt();
int[] a=fs.readArray(n);
Integer[] arr1=new Integer[n];
for(int i=0;i<n;i++){
arr1[i]=a[i]-fs.nextInt();
}
Arrays.sort(arr1);
long ans=0;
for(int i=0;i<n;i++){
int val=-arr1[i];
int l=0;
int r=n;
while(l<r){
int mid=(l+r)/2;
if(arr1[mid]<=val){
l=mid+1;
}else{
r=mid;
}
}
if(l==n){
continue;
}
l=Math.max(i+1,l);
ans+=(n-l);
// System.out.println(r+" "+i);
}
out.println(ans);
}
out.close();
}
static long maxSubArraySum(int a[])
{
int size = a.length;
long max_so_far = Long.MIN_VALUE, max_ending_here = 0;
int max=Integer.MIN_VALUE;
for (int i = 0; i < size; i++)
{
max_ending_here = max_ending_here + a[i];
if (max_so_far < max_ending_here)
max_so_far = max_ending_here;
if (max_ending_here < 0)
max_ending_here = 0;
max=Math.max(max,a[i]);
}
if(max<0){
return (long)0;
}
return max_so_far;
}
public static class Comp implements Comparator<pair>{
public int compare(pair a,pair b){
if(a.x!=b.x){
return b.x-a.x;
}else{
return a.y-b.y;
}
}
}
public static long gcd(long a,long b){
if (b == 0)
return a;
return gcd(b, a % b);
}
public static int lcm(int a,int b){
int x=Math.max(a,b);
int y=Math.min(a,b);
long ans=x;
while(ans%y!=0){
ans+=x;
}
if(ans>Integer.MAX_VALUE){
return -1;
}
return (int)ans;
}
public static long fact(int n){
long ans=1;
for(int i=1;i<=n;i++){
ans*=i;
}
return ans;
}
} | Java | ["5\n4 8 2 6 2\n4 5 4 1 3", "4\n1 3 2 4\n1 3 2 4"] | 2 seconds | ["7", "0"] | null | Java 8 | standard input | [
"data structures",
"two pointers",
"binary search",
"sortings"
] | e25b247975660c5005bd4da7afd38a56 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) β the number of topics. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the interestingness of the $$$i$$$-th topic for the teacher. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$), where $$$b_i$$$ is the interestingness of the $$$i$$$-th topic for the students. | 1,400 | Print one integer β the number of good pairs of topic. | standard output | |
PASSED | 18f9799a00b5f8a04e1df4a0b65d9a36 | train_001.jsonl | 1584018300 | The next lecture in a high school requires two topics to be discussed. The $$$i$$$-th topic is interesting by $$$a_i$$$ units for the teacher and by $$$b_i$$$ units for the students.The pair of topics $$$i$$$ and $$$j$$$ ($$$i < j$$$) is called good if $$$a_i + a_j > b_i + b_j$$$ (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.StringTokenizer;
public class q4 {
public static void main(String[] args) {
FastReader s = new FastReader();
int n = s.nextInt();
ArrayList<Integer> arr = new ArrayList<>();
for(int i=0;i<n;++i)
arr.add(s.nextInt());
for(int i=0;i<n;++i)
arr.set(i,arr.get(i) - s.nextInt());
Collections.sort(arr);
long ans = 0;
int start = 0;
int end = n-1;
while(start<end)
{
if(arr.get(start) + arr.get(end)> 0)
{
ans += end - start;
end--;
}
else start++;
}
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 | ["5\n4 8 2 6 2\n4 5 4 1 3", "4\n1 3 2 4\n1 3 2 4"] | 2 seconds | ["7", "0"] | null | Java 8 | standard input | [
"data structures",
"two pointers",
"binary search",
"sortings"
] | e25b247975660c5005bd4da7afd38a56 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) β the number of topics. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the interestingness of the $$$i$$$-th topic for the teacher. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$), where $$$b_i$$$ is the interestingness of the $$$i$$$-th topic for the students. | 1,400 | Print one integer β the number of good pairs of topic. | standard output | |
PASSED | 4866cecd8f30dbc85287c8bf1680f8b3 | train_001.jsonl | 1584018300 | The next lecture in a high school requires two topics to be discussed. The $$$i$$$-th topic is interesting by $$$a_i$$$ units for the teacher and by $$$b_i$$$ units for the students.The pair of topics $$$i$$$ and $$$j$$$ ($$$i < j$$$) is called good if $$$a_i + a_j > b_i + b_j$$$ (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Stack;
import java.util.StringTokenizer;
public class q4 {
public static void main(String[] args) {
FastReader s = new FastReader();
int n = s.nextInt();
ArrayList<Integer> arr = new ArrayList<>();
for(int i=0;i<n;++i)
arr.add(s.nextInt());
for(int i=0;i<n;++i)
arr.set(i,arr.get(i) - s.nextInt());
Collections.sort(arr);
Stack<Integer> st = new Stack<>();
long ans = 0;
for(int i=arr.size()-1; i >= 0 ; --i )
{
if(arr.get(i) > 0)
{
if(!st.isEmpty())
ans += st.size();
st.push(i);
}
else
{
while(!st.isEmpty() && Math.abs(arr.get(i)) >= arr.get(st.peek()) )
st.pop();
ans += st.size();
}
}
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 | ["5\n4 8 2 6 2\n4 5 4 1 3", "4\n1 3 2 4\n1 3 2 4"] | 2 seconds | ["7", "0"] | null | Java 8 | standard input | [
"data structures",
"two pointers",
"binary search",
"sortings"
] | e25b247975660c5005bd4da7afd38a56 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) β the number of topics. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the interestingness of the $$$i$$$-th topic for the teacher. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$), where $$$b_i$$$ is the interestingness of the $$$i$$$-th topic for the students. | 1,400 | Print one integer β the number of good pairs of topic. | standard output | |
PASSED | 8030a2a9ad17dea7965b0ae8e2ed8ab8 | train_001.jsonl | 1584018300 | The next lecture in a high school requires two topics to be discussed. The $$$i$$$-th topic is interesting by $$$a_i$$$ units for the teacher and by $$$b_i$$$ units for the students.The pair of topics $$$i$$$ and $$$j$$$ ($$$i < j$$$) is called good if $$$a_i + a_j > b_i + b_j$$$ (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics. | 256 megabytes | import java.util.*;
import java.io.*;
public class Pair_of_Topics
{
public static void main (String[] args) throws java.lang.Exception
{
solve();
}
static void solve()throws java.lang.Exception
{ // 2 pointer approach
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine()),a[]=new int[n],b[]=new int[n];
StringTokenizer st=new StringTokenizer(br.readLine());
StringTokenizer s=new StringTokenizer(br.readLine());
int c[]=new int[n];
for(int i=0; i<n; i++) {
a[i]=Integer.parseInt(st.nextToken());
b[i]=Integer.parseInt(s.nextToken());
c[i]=a[i]-b[i];
}
sort(c);
int l=0,r=n-1;
long ans=0;
while(l<r) {
if(c[l]+c[r]>0) {
ans+=(r-l);
--r;
}else ++l;
}
System.out.println(ans);
}
static void sort(int a[]) {
PriorityQueue<Integer> q=new PriorityQueue<>();
for(int i=0; i<a.length; i++) q.add(a[i]);
for(int i=0; i<a.length; i++) a[i]=q.poll();
}
}
| Java | ["5\n4 8 2 6 2\n4 5 4 1 3", "4\n1 3 2 4\n1 3 2 4"] | 2 seconds | ["7", "0"] | null | Java 8 | standard input | [
"data structures",
"two pointers",
"binary search",
"sortings"
] | e25b247975660c5005bd4da7afd38a56 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) β the number of topics. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the interestingness of the $$$i$$$-th topic for the teacher. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$), where $$$b_i$$$ is the interestingness of the $$$i$$$-th topic for the students. | 1,400 | Print one integer β the number of good pairs of topic. | standard output | |
PASSED | d138f4b0c1bbb495740511b69d139496 | train_001.jsonl | 1584018300 | The next lecture in a high school requires two topics to be discussed. The $$$i$$$-th topic is interesting by $$$a_i$$$ units for the teacher and by $$$b_i$$$ units for the students.The pair of topics $$$i$$$ and $$$j$$$ ($$$i < j$$$) is called good if $$$a_i + a_j > b_i + b_j$$$ (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Pair_of_Topics {
public static void main(String[] args) throws java.lang.Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine()),a[]=new int[n],b[]=new int[n];
StringTokenizer st=new StringTokenizer(br.readLine());
StringTokenizer s=new StringTokenizer(br.readLine());
int c[]=new int[n];
for(int i=0; i<n; i++) {
a[i]=Integer.parseInt(st.nextToken());
b[i]=Integer.parseInt(s.nextToken());
c[i]=a[i]-b[i];
}
/*
INEQUALITY:
a[i]+a[j]>b[i]+b[j]
or (a[i]-b[i])+(a[j]-b[j])>0
or c[i]+c[j]>0
or c[i]+c[j]>=1
or c[j]>=(1-c[i])
i.e. we have to find number of such j for which c[j]>=(1-c[i])
i.e. we have to calculate leftmost position j
or minimal j for which c[j]>=x {here x=(1-c[i])}
i.e. we have to calculate lower bound of(1-c[i]).
Then add the value iβj to the answer and consider the next element.
total time complexity O(N*log(N))
*/
sort(c);
long ans=0;
for(int i=0; i<n; i++) {
if(c[i]<=0) continue;
// Because our sum (c[i]+c[j]) must be greater than 0,
// then at least one of these summands will be positive. So, if c[i]β€0, just skip it.
long lb=lower_bound(c,1-c[i]);
ans+=(i-lb);
}
System.out.println(ans);
}
static void sort(int a[]) {
PriorityQueue<Integer> q=new PriorityQueue<>();
for(int i=0; i<a.length; i++) q.add(a[i]);
for(int i=0; i<a.length; i++) a[i]=q.poll();
}
static int lower_bound(int a[], int x) {//O(log(N))
int l=-1, r=a.length;
while(l+1<r) {
int m=(l+r)>>1;
if(a[m]>=x) r=m;
else l=m;
}
return r;
}
} | Java | ["5\n4 8 2 6 2\n4 5 4 1 3", "4\n1 3 2 4\n1 3 2 4"] | 2 seconds | ["7", "0"] | null | Java 8 | standard input | [
"data structures",
"two pointers",
"binary search",
"sortings"
] | e25b247975660c5005bd4da7afd38a56 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) β the number of topics. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the interestingness of the $$$i$$$-th topic for the teacher. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$), where $$$b_i$$$ is the interestingness of the $$$i$$$-th topic for the students. | 1,400 | Print one integer β the number of good pairs of topic. | standard output | |
PASSED | 9087e3c6d64e6d0f2f025d3ddda7060f | train_001.jsonl | 1584018300 | The next lecture in a high school requires two topics to be discussed. The $$$i$$$-th topic is interesting by $$$a_i$$$ units for the teacher and by $$$b_i$$$ units for the students.The pair of topics $$$i$$$ and $$$j$$$ ($$$i < j$$$) is called good if $$$a_i + a_j > b_i + b_j$$$ (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.Random;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author L_aka_ryuga
*/
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);
DPairOfTopics solver = new DPairOfTopics();
solver.solve(1, in, out);
out.close();
}
static class DPairOfTopics {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.ni();
int[] arra = in.nia(n), arrb = in.nia(n);
int[] diff = new int[n + 1];
for (int i = 0; i < n; ++i) {
diff[i] = arra[i] - arrb[i];
}
diff[n] = Integer.MAX_VALUE;
_Ez_Int_Sort.sort(diff);
long ans = 0;
for (int i = 0; i < n; i++) {
int index = diff[i] <= 0 ? getIndexOfEleGreaterThan(Math.abs(diff[i]) + 1, diff) : i + 1;
/*out.println("index = "+index);*/
ans += n - index;
}
out.println(ans);
}
private int getIndexOfEleGreaterThan(int i, int[] diff) {
int low = 0, high = diff.length - 1, mid = 0, req = 0;
while (low <= high) {
mid = (low + high) / 2;
/*if(diff[mid] == i) break;*/
if (diff[mid] >= i) {
req = mid;
high = mid - 1;
} else if (diff[mid] < i) low = mid + 1;
}
return req;
}
}
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 ni() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int[] nia(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = ni();
return array;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static final class _Ez_Int_Sort {
private static final double HEAPSORT_DEPTH_COEFFICIENT = 2.0;
private static final Random rnd = new Random();
private _Ez_Int_Sort() {
}
private static int maxQuickSortDepth(int length) {
if (length <= 1) {
return 0;
}
int log = Integer.numberOfTrailingZeros(Integer.highestOneBit(length - 1)) + 1;
return (int) (HEAPSORT_DEPTH_COEFFICIENT * log);
}
public static void sort(/*C*/int/*C*/[] a) {
quickSort(a, 0, a.length, 0, maxQuickSortDepth(a.length));
}
private static void quickSort(/*C*/int/*C*/[] a, int left, int right, int depth, int maxDepth) {
if (right - left <= 1) {
return;
}
if (depth > maxDepth) {
heapSort(a, left, right - left);
return;
}
final /*C*/ int/*C*/ pivot = a[left + rnd.nextInt(right - left)];
int i = left;
int j = right - 1;
do {
while (a[i] < pivot) i++;
while (pivot < a[j]) j--;
if (i <= j) {
/*C*/
int/*C*/ tmp = a[i];
a[i++] = a[j];
a[j--] = tmp;
}
} while (i <= j);
quickSort(a, left, j + 1, depth + 1, maxDepth);
quickSort(a, i, right, depth + 1, maxDepth);
}
private static void heapSort(/*C*/int/*C*/[] a, int offset, int size) {
// If size <= 1, nothing is executed
for (int i = (size >>> 1) - 1; i >= 0; i--) {
down(a, i, offset, size);
}
for (int i = size - 1; i > 0; i--) {
/*C*/
int/*C*/ tmp = a[offset];
a[offset] = a[offset + i];
a[offset + i] = tmp;
down(a, 0, offset, i);
}
}
private static void down(/*C*/int/*C*/[] a, int index, int offset, int size) {
final /*C*/ int/*C*/ element = a[offset + index];
final int firstLeaf = (size >>> 1);
while (index < firstLeaf) {
int largestChild = (index << 1) + 1;
if (largestChild + 1 < size && a[offset + largestChild + 1] > a[offset + largestChild]) {
largestChild++;
}
if (a[offset + largestChild] <= element) {
break;
}
a[offset + index] = a[offset + largestChild];
index = largestChild;
}
a[offset + index] = element;
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(long i) {
writer.println(i);
}
}
}
| Java | ["5\n4 8 2 6 2\n4 5 4 1 3", "4\n1 3 2 4\n1 3 2 4"] | 2 seconds | ["7", "0"] | null | Java 8 | standard input | [
"data structures",
"two pointers",
"binary search",
"sortings"
] | e25b247975660c5005bd4da7afd38a56 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) β the number of topics. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the interestingness of the $$$i$$$-th topic for the teacher. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$), where $$$b_i$$$ is the interestingness of the $$$i$$$-th topic for the students. | 1,400 | Print one integer β the number of good pairs of topic. | standard output | |
PASSED | 25fb00d74c8f08e06e895069537cfc16 | train_001.jsonl | 1584018300 | The next lecture in a high school requires two topics to be discussed. The $$$i$$$-th topic is interesting by $$$a_i$$$ units for the teacher and by $$$b_i$$$ units for the students.The pair of topics $$$i$$$ and $$$j$$$ ($$$i < j$$$) is called good if $$$a_i + a_j > b_i + b_j$$$ (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics. | 256 megabytes | import java.io.*;
import java.util.*;
public class R627D {
public static void main(String[] args) {
JS scan = new JS();
//ai+aj > bi+bj
//aj has to be at least (bi-ai)+1 greater than bj
int n = scan.nextInt();
Integer[] prefix = new Integer[n];
int[] a = new int[n];
int[] b= new int[n];
long ans =0;
for(int i =0;i<n;i++) {
a[i] = scan.nextInt();
}
for(int i =0;i<n;i++) {
b[i] = scan.nextInt();
}
for(int i =0;i<n;i++) {
prefix[i] = a[i]-b[i];
}
Arrays.sort(prefix);
for(int i = 0;i<n;i++) {
//we need something that is greater than Math.abs(prefix[i])
if(prefix[i]>0) {
ans+=n-(i+1);
continue;
}
int need = Math.abs(prefix[i])+1;
int lo = 0;
int hi = n-1;
int min = n;
while(lo<=hi) {
int m = lo + (hi - lo) / 2;
if(prefix[m]>=need) {
//lets try lower bound
min = m;
hi = m-1;
}else {
lo = m+1;
}
}
ans+=n-min;
}
System.out.println(ans);
}
/*
3
1 5 6
1 2 3
*/
static class JS{
public int BS = 1<<16;
public char NC = (char)0;
byte[] buf = new byte[BS];
int bId = 0, size = 0;
char c = NC;
double num = 1;
BufferedInputStream in;
public JS() {
in = new BufferedInputStream(System.in, BS);
}
public JS(String s) throws FileNotFoundException {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
public char nextChar(){
while(bId==size) {
try {
size = in.read(buf);
}catch(Exception e) {
return NC;
}
if(size==-1)return NC;
bId=0;
}
return (char)buf[bId++];
}
public int nextInt() {
return (int)nextLong();
}
public long nextLong() {
num=1;
boolean neg = false;
if(c==NC)c=nextChar();
for(;(c<'0' || c>'9'); c = nextChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=nextChar()) {
res = (res<<3)+(res<<1)+c-'0';
num*=10;
}
return neg?-res:res;
}
public double nextDouble() {
double cur = nextLong();
return c!='.' ? cur:cur+nextLong()/num;
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c>32) {
res.append(c);
c=nextChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c!='\n') {
res.append(c);
c=nextChar();
}
return res.toString();
}
public boolean hasNext() {
if(c>32)return true;
while(true) {
c=nextChar();
if(c==NC)return false;
else if(c>32)return true;
}
}
}
}
| Java | ["5\n4 8 2 6 2\n4 5 4 1 3", "4\n1 3 2 4\n1 3 2 4"] | 2 seconds | ["7", "0"] | null | Java 8 | standard input | [
"data structures",
"two pointers",
"binary search",
"sortings"
] | e25b247975660c5005bd4da7afd38a56 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) β the number of topics. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the interestingness of the $$$i$$$-th topic for the teacher. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$), where $$$b_i$$$ is the interestingness of the $$$i$$$-th topic for the students. | 1,400 | Print one integer β the number of good pairs of topic. | standard output | |
PASSED | 7eaa1b94d67b616fe334a908e4bf6397 | train_001.jsonl | 1584018300 | The next lecture in a high school requires two topics to be discussed. The $$$i$$$-th topic is interesting by $$$a_i$$$ units for the teacher and by $$$b_i$$$ units for the students.The pair of topics $$$i$$$ and $$$j$$$ ($$$i < j$$$) is called good if $$$a_i + a_j > b_i + b_j$$$ (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class PairTopics {
static int[] sums;
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
sums = new int[n];
for(int i = 0; i < n; i++) sums[i] = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
for(int i = 0; i < n; i++) sums[i] -= Integer.parseInt(st.nextToken());
//Arrays.sort(sums);
mergeSort(sums);
System.out.println(solve(sums));
}
static long solve(int[] a){
long pairs = 0;
if(upperBound(a, 0) == a.length) return 0;
for(int i = 0; i < a.length-1; i++){
if(a[i] <= 0){
int target = -(a[i]);
int index = upperBound(a, target);
pairs += (a.length - index);
}
else {
pairs += (a.length - i) - 1;
}
}
return pairs;
}
public static int upperBound(int[] array, int value) {
int low = 0;
int high = array.length;
while (low < high) {
final int mid = (low + high) / 2;
if (value >= array[mid]) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
static void mergeSort(int[] A){ // low to hi sort, single array only
int n = A.length;
if (n < 2) return;
int[] l = new int[n/2];
int[] r = new int[n - n/2];
for (int i = 0; i < n/2; i++){
l[i] = A[i];
}
for (int j = n/2; j < n; j++){
r[j-n/2] = A[j];
}
mergeSort(l);
mergeSort(r);
merge(l, r, A);
}
static void merge(int[] l, int[] r, int[] a){
int i = 0, j = 0, k = 0;
while (i < l.length && j < r.length && k < a.length){
if (l[i] < r[j]){
a[k] = l[i];
i++;
}
else{
a[k] = r[j];
j++;
}
k++;
}
while (i < l.length){
a[k] = l[i];
i++;
k++;
}
while (j < r.length){
a[k] = r[j];
j++;
k++;
}
}
} | Java | ["5\n4 8 2 6 2\n4 5 4 1 3", "4\n1 3 2 4\n1 3 2 4"] | 2 seconds | ["7", "0"] | null | Java 8 | standard input | [
"data structures",
"two pointers",
"binary search",
"sortings"
] | e25b247975660c5005bd4da7afd38a56 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) β the number of topics. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the interestingness of the $$$i$$$-th topic for the teacher. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$), where $$$b_i$$$ is the interestingness of the $$$i$$$-th topic for the students. | 1,400 | Print one integer β the number of good pairs of topic. | standard output | |
PASSED | a18e5db8fee06f427fbc9b7f207e9ef3 | train_001.jsonl | 1584018300 | The next lecture in a high school requires two topics to be discussed. The $$$i$$$-th topic is interesting by $$$a_i$$$ units for the teacher and by $$$b_i$$$ units for the students.The pair of topics $$$i$$$ and $$$j$$$ ($$$i < j$$$) is called good if $$$a_i + a_j > b_i + b_j$$$ (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics. | 256 megabytes | import java.util.*;
public class codeforc {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
Integer[] a = new Integer[n];
Integer[] b = new Integer[n];
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
}
for (int i = 0; i < n; i++) {
b[i] = a[i] - s.nextInt();
}
Arrays.sort(b);
long ans = 0;
for (int i = 0; i < n; i++) {
if (b[i] <= 0) {
continue;
}
int low = 0;
int high = i - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (b[mid] + b[i] > 0) {
high = mid - 1;
} else {
low = mid + 1;
}
}
ans += i - low;
}
System.out.println(ans);
}
}
| Java | ["5\n4 8 2 6 2\n4 5 4 1 3", "4\n1 3 2 4\n1 3 2 4"] | 2 seconds | ["7", "0"] | null | Java 8 | standard input | [
"data structures",
"two pointers",
"binary search",
"sortings"
] | e25b247975660c5005bd4da7afd38a56 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) β the number of topics. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the interestingness of the $$$i$$$-th topic for the teacher. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$), where $$$b_i$$$ is the interestingness of the $$$i$$$-th topic for the students. | 1,400 | Print one integer β the number of good pairs of topic. | standard output | |
PASSED | 0e59322f9357adab509c89a318ef1de7 | train_001.jsonl | 1584018300 | The next lecture in a high school requires two topics to be discussed. The $$$i$$$-th topic is interesting by $$$a_i$$$ units for the teacher and by $$$b_i$$$ units for the students.The pair of topics $$$i$$$ and $$$j$$$ ($$$i < j$$$) is called good if $$$a_i + a_j > b_i + b_j$$$ (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
Scanner sc=new Scanner(System.in);
int m=sc.nextInt();
arr=new long[m];
arr2=new long[m];
arr3=new long[m];
for (int i = 0; i < m; i++) {
arr[i]=sc.nextInt();
}
PriorityQueue<Long> pq =new PriorityQueue<>(Collections.reverseOrder());
for (int i = 0; i < m; i++) {
arr2[i]=sc.nextInt();
}
for (int i = 0; i < m; i++) {
pq.add(arr[i]-arr2[i]);
}
// System.out.println(pq);
for (int i = 0; i < m; i++) {
arr3[i]=pq.poll();
}
// System.out.println(Arrays.toString(arr));
c=0;
for (int i = 0; i < m; i++) {
if(arr3[i]<=0) break;
res(arr3[i],i);
}
pw.println(c);
pw.close();
}
static PrintWriter pw=new PrintWriter(System.out);
static long[] arr,arr2,arr3;
static long c;
static int p;
static void res(long x,int i) {
if (c==0) p=arr.length-1;
int start=i,end=p;
long ans=-1;
while(start<=end) {
int mid=(start+end)/2;
if (x+arr3[mid]>0) {
ans=mid;
start = mid + 1;
}else {
end = mid - 1;
}
}
p=(int)ans;
c+=ans-i;
}
static int gcd(int x,int y) {
while (x!=y) {
if (x>y) x-=y;
else if (x<y) y-=x;
}
return x;
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public boolean hasNext() {
// TODO Auto-generated method stub
return false;
}
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 | ["5\n4 8 2 6 2\n4 5 4 1 3", "4\n1 3 2 4\n1 3 2 4"] | 2 seconds | ["7", "0"] | null | Java 8 | standard input | [
"data structures",
"two pointers",
"binary search",
"sortings"
] | e25b247975660c5005bd4da7afd38a56 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) β the number of topics. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the interestingness of the $$$i$$$-th topic for the teacher. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$), where $$$b_i$$$ is the interestingness of the $$$i$$$-th topic for the students. | 1,400 | Print one integer β the number of good pairs of topic. | standard output | |
PASSED | dd17763e36323cc35d8d65467c154d45 | train_001.jsonl | 1584018300 | The next lecture in a high school requires two topics to be discussed. The $$$i$$$-th topic is interesting by $$$a_i$$$ units for the teacher and by $$$b_i$$$ units for the students.The pair of topics $$$i$$$ and $$$j$$$ ($$$i < j$$$) is called good if $$$a_i + a_j > b_i + b_j$$$ (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics. | 256 megabytes | import java.util.*;
public class pair {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Integer n = sc.nextInt();
Integer a[] = new Integer[n], b[] = new Integer[n], d[] = new Integer[n];
for (int i = 0; i < n; i++)
a[i] = sc.nextInt();
for (int i = 0; i < n; i++)
b[i] = sc.nextInt();
for (int i = 0; i < n; i++)
{
d[i] = a[i] - b[i];
}
Arrays.sort(d);
long ans = 0;
int l = 0, r = n - 1;
while (l < r)
if (d[l] + d[r] > 0) {
ans = ans + r - l;
r--;
} else
l++;
System.out.println(ans);
}
} | Java | ["5\n4 8 2 6 2\n4 5 4 1 3", "4\n1 3 2 4\n1 3 2 4"] | 2 seconds | ["7", "0"] | null | Java 8 | standard input | [
"data structures",
"two pointers",
"binary search",
"sortings"
] | e25b247975660c5005bd4da7afd38a56 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) β the number of topics. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the interestingness of the $$$i$$$-th topic for the teacher. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$), where $$$b_i$$$ is the interestingness of the $$$i$$$-th topic for the students. | 1,400 | Print one integer β the number of good pairs of topic. | standard output | |
PASSED | 085fa443145704aca0f84fb408d8d2c5 | train_001.jsonl | 1584018300 | The next lecture in a high school requires two topics to be discussed. The $$$i$$$-th topic is interesting by $$$a_i$$$ units for the teacher and by $$$b_i$$$ units for the students.The pair of topics $$$i$$$ and $$$j$$$ ($$$i < j$$$) is called good if $$$a_i + a_j > b_i + b_j$$$ (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics. | 256 megabytes |
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
Integer[] arr1 = new Integer[t];
for (int i = 0; i < t; i++) {
arr1[i] = sc.nextInt();
}
Integer[] arr2 = new Integer[t];
Integer[] core = new Integer[t];
for (int j = 0; j < t; j++) {
arr2[j] = sc.nextInt();
core[j] = arr1[j] - arr2[j];
}
Arrays.sort(core);
int left = 0;
int right = t - 1;
long count = 0;
while (left < right) {
if (core[left] + core[right] > 0) {
count += right - left;
right--;
} else {
left++;
}
}
System.out.println(count);
}
} | Java | ["5\n4 8 2 6 2\n4 5 4 1 3", "4\n1 3 2 4\n1 3 2 4"] | 2 seconds | ["7", "0"] | null | Java 8 | standard input | [
"data structures",
"two pointers",
"binary search",
"sortings"
] | e25b247975660c5005bd4da7afd38a56 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) β the number of topics. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the interestingness of the $$$i$$$-th topic for the teacher. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$), where $$$b_i$$$ is the interestingness of the $$$i$$$-th topic for the students. | 1,400 | Print one integer β the number of good pairs of topic. | standard output | |
PASSED | ab471aaf0e3931d66bdab9ed86c5f124 | train_001.jsonl | 1584018300 | The next lecture in a high school requires two topics to be discussed. The $$$i$$$-th topic is interesting by $$$a_i$$$ units for the teacher and by $$$b_i$$$ units for the students.The pair of topics $$$i$$$ and $$$j$$$ ($$$i < j$$$) is called good if $$$a_i + a_j > b_i + b_j$$$ (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.*;
public class Main
{
public static long ans(int a[],int b[],int n){
ArrayList<Integer> c=new ArrayList<>();
for(int i=0;i<n;i++){
c.add(a[i]-b[i]);
}
Collections.sort(c);
long ans=0;
int start=0;
int end=n-1;
while(start<end){
if(c.get(start)+c.get(end)>0){
ans=ans+(end-start);
end--;
}else{
start++;
}
}
return ans;
}
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
StringTokenizer as = new StringTokenizer(br.readLine());
int a[]=new int[n];
for(int i=0;i<n;i++){
a[i]=Integer.parseInt(as.nextToken());
}
StringTokenizer bs = new StringTokenizer(br.readLine());
int b[]=new int[n];
for(int i=0;i<n;i++){
b[i]=Integer.parseInt(bs.nextToken());
}
System.out.println(ans(a,b,n));
}
}
| Java | ["5\n4 8 2 6 2\n4 5 4 1 3", "4\n1 3 2 4\n1 3 2 4"] | 2 seconds | ["7", "0"] | null | Java 8 | standard input | [
"data structures",
"two pointers",
"binary search",
"sortings"
] | e25b247975660c5005bd4da7afd38a56 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) β the number of topics. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the interestingness of the $$$i$$$-th topic for the teacher. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$), where $$$b_i$$$ is the interestingness of the $$$i$$$-th topic for the students. | 1,400 | Print one integer β the number of good pairs of topic. | standard output | |
PASSED | 63b5fe653749387362436b89ec2a098e | train_001.jsonl | 1584018300 | The next lecture in a high school requires two topics to be discussed. The $$$i$$$-th topic is interesting by $$$a_i$$$ units for the teacher and by $$$b_i$$$ units for the students.The pair of topics $$$i$$$ and $$$j$$$ ($$$i < j$$$) is called good if $$$a_i + a_j > b_i + b_j$$$ (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics. | 256 megabytes | //ARNAV KUMAR MANDAL//
//XYPHER//
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.io.*;
public class Solution{
static class sort implements Comparator<pair>
{
public int compare(pair m1, pair m2)
{
return -((m1.x - m1.y) - (m2.x - m2.y)); // ascending order
}
}
static class pair{
int x;
int y;
pair(int x, int y){
this.x = x;
this.y = y;
}
}
//--------------------------MAIN---------------------------------------------------------------------//
public static void main(String[] args) throws IOException {
Reader a= new Reader(System.in);
OutputWriter out = new OutputWriter(System.out);
//Scanner a = new Scanner(System.in);
int n = a.nextInt();
pair A[] = new pair[n];
for(int i=0;i<n;i++) {
A[i] = new pair(a.nextInt(), 0);
}
for(int i=0;i<n;i++) {
A[i].y = a.nextInt();
}
Arrays.sort(A, new sort());
int i=0,j=n-1;
long count = 0;
while(i<j) {
if(A[i].x + A[j].x > A[i].y + A[j].y) {
count+=j-i;
i++;
}
else j--;
// out.println(count);
}
out.println(count);;
}
//--------------------------FAST IO------------------------------------------------------------------//
private static class Reader {
private InputStream stream;
private byte[] buf = new byte[4*1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public Reader(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 {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
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 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 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 nextString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
private 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 println(Object... objects) {
print(objects);
writer.println();
writer.flush();
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
writer.flush();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
} | Java | ["5\n4 8 2 6 2\n4 5 4 1 3", "4\n1 3 2 4\n1 3 2 4"] | 2 seconds | ["7", "0"] | null | Java 8 | standard input | [
"data structures",
"two pointers",
"binary search",
"sortings"
] | e25b247975660c5005bd4da7afd38a56 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) β the number of topics. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the interestingness of the $$$i$$$-th topic for the teacher. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$), where $$$b_i$$$ is the interestingness of the $$$i$$$-th topic for the students. | 1,400 | Print one integer β the number of good pairs of topic. | standard output | |
PASSED | 0cdbfd735b9b9a66a938461ebbc9d8ca | train_001.jsonl | 1584018300 | The next lecture in a high school requires two topics to be discussed. The $$$i$$$-th topic is interesting by $$$a_i$$$ units for the teacher and by $$$b_i$$$ units for the students.The pair of topics $$$i$$$ and $$$j$$$ ($$$i < j$$$) is called good if $$$a_i + a_j > b_i + b_j$$$ (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics. | 256 megabytes | import java.util.*;
import java.io.*;
public class D1324 {
static int[] array;
public static boolean check(int a, int b) {
return a + b > 0;
}
public static int search(int start, int end, int x) {
while(start < end) {
int mid = (start + end) / 2;
if(check(x, array[mid])) {
end = mid;
} else {
start = mid + 1;
}
}
if(check(x, array[start]))
return start;
else
return -1;
}
public static void main(String[] args) throws IOException {
//Scanner sc = new Scanner(System.in);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
StringTokenizer st;
int n = Integer.parseInt(br.readLine());
StringTokenizer a = new StringTokenizer(br.readLine()), b = new StringTokenizer(br.readLine());
Integer[] temp = new Integer[n];
for(int i = 0; i < n; i++) {
temp[i] = Integer.parseInt(a.nextToken()) - Integer.parseInt(b.nextToken());
}
Arrays.sort(temp);
array = new int[n];
for(int i = 0; i < n; i++) {
array[i] = temp[i].intValue();
}
long c = 0;
for(int i = n - 1; i > 0; i--) {
int j = search(0, i - 1, array[i]);
if(j == -1)
break;
c += i - j;
}
pw.println(c);
pw.flush();
}
}
| Java | ["5\n4 8 2 6 2\n4 5 4 1 3", "4\n1 3 2 4\n1 3 2 4"] | 2 seconds | ["7", "0"] | null | Java 8 | standard input | [
"data structures",
"two pointers",
"binary search",
"sortings"
] | e25b247975660c5005bd4da7afd38a56 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) β the number of topics. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the interestingness of the $$$i$$$-th topic for the teacher. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$), where $$$b_i$$$ is the interestingness of the $$$i$$$-th topic for the students. | 1,400 | Print one integer β the number of good pairs of topic. | standard output | |
PASSED | 3b28d63eea32b624126655ac94b4c0e7 | train_001.jsonl | 1584018300 | The next lecture in a high school requires two topics to be discussed. The $$$i$$$-th topic is interesting by $$$a_i$$$ units for the teacher and by $$$b_i$$$ units for the students.The pair of topics $$$i$$$ and $$$j$$$ ($$$i < j$$$) is called good if $$$a_i + a_j > b_i + b_j$$$ (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.InputMismatchException;
public class four {
class inputreader{
private InputStream stream;
private int curchar;
private int numchars;
private byte[]arr=new byte[2048];
public inputreader() {
stream=System.in;
}
private boolean isSpace(int c)
{
return c==' '||c=='\n'||c=='\r'||c=='\t'||c==-1;
}
private int read()
{
if(numchars==-1)
throw new InputMismatchException();
if(curchar>=numchars)
{
curchar=0;
try {
numchars=stream.read(arr);
}
catch(IOException e)
{
throw new InputMismatchException();
}
if(numchars<=0)
return -1;
}
return arr[curchar++];
}
public int nextInt()
{
int c=read();
while(isSpace(c))c=read();
int res=0,sign=1;
if(c=='-')
{
sign=-1;
c=read();
}
do {
if(c>'9'||c<'0')
throw new InputMismatchException();
res*=10;
res+=c-'0';
c=read();
}while(!isSpace(c));
return sign*res;
}
public long nextLong()
{
int c=read();
while(isSpace(c))c=read();
long res=0,sign=1;
if(c=='-')
{
sign=-1;
c=read();
}
do {
if(c>'9'||c<'0')
throw new InputMismatchException();
res*=10;
res+=c-'0';
c=read();
}while(!isSpace(c));
return sign*res;
}
public String next()
{
StringBuilder sb=new StringBuilder("");
int c=read();
while(isSpace(c))c=read();
do {
sb.appendCodePoint(c);
c=read();
}while(!isSpace(c));
return sb.toString();
}
}
public void solve()
{
inputreader in=new inputreader();
// int t=in.nextInt();
// while(t-->0) {
int n=in.nextInt();
int[]arr=new int[n];
int[]barr=new int[n];
for(int i=0;i<n;i++) {
arr[i]=in.nextInt();
}
for(int i=0;i<n;i++) {
barr[i]=in.nextInt();
}
Integer[]diff=new Integer[n];
for(int i=0;i<n;i++) {
diff[i]=arr[i]-barr[i];
}
Arrays.sort(diff);
//take care
long res=0l;
int l=0,r=n-1;
while(l<r) {
if(diff[l]+diff[r]>0) {
res+=r-l;
r--;
}else {
l++;
}
}
System.out.println(res);
//}
}
public static void main(String[] args) {
new four().solve();
}
} | Java | ["5\n4 8 2 6 2\n4 5 4 1 3", "4\n1 3 2 4\n1 3 2 4"] | 2 seconds | ["7", "0"] | null | Java 8 | standard input | [
"data structures",
"two pointers",
"binary search",
"sortings"
] | e25b247975660c5005bd4da7afd38a56 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) β the number of topics. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the interestingness of the $$$i$$$-th topic for the teacher. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$), where $$$b_i$$$ is the interestingness of the $$$i$$$-th topic for the students. | 1,400 | Print one integer β the number of good pairs of topic. | standard output | |
PASSED | 8ea5d5dde618d137a7d18416b027e4ea | train_001.jsonl | 1584018300 | The next lecture in a high school requires two topics to be discussed. The $$$i$$$-th topic is interesting by $$$a_i$$$ units for the teacher and by $$$b_i$$$ units for the students.The pair of topics $$$i$$$ and $$$j$$$ ($$$i < j$$$) is called good if $$$a_i + a_j > b_i + b_j$$$ (i.e. it is more interesting for the teacher).Your task is to find the number of good pairs of topics. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
Integer[] a = new Integer[n];
Integer[] b = new Integer[n];
for (int i = 0; i < n; i ++)
a[i] = scan.nextInt();
for (int i = 0; i < n; i ++)
b[i] = scan.nextInt();
Integer[] c = new Integer[n];
for (int i = 0; i < n; i ++)
c[i] = a[i] - b[i];
long ans = 0;
Arrays.sort(c);
int low = 0, high = n - 1;
while (low < high){
if (c[low] + c[high] > 0){
ans += high - low;
high --;
}else
low ++;
}
System.out.println(ans);
}
}
| Java | ["5\n4 8 2 6 2\n4 5 4 1 3", "4\n1 3 2 4\n1 3 2 4"] | 2 seconds | ["7", "0"] | null | Java 8 | standard input | [
"data structures",
"two pointers",
"binary search",
"sortings"
] | e25b247975660c5005bd4da7afd38a56 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) β the number of topics. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the interestingness of the $$$i$$$-th topic for the teacher. The third line of the input contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$1 \le b_i \le 10^9$$$), where $$$b_i$$$ is the interestingness of the $$$i$$$-th topic for the students. | 1,400 | Print one integer β the number of good pairs of topic. | standard output | |
PASSED | 8a8d1439d16fa735217649755a897b7e | train_001.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 Graphs;
import javafx.util.Pair;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
public class TimofeyAndTree {
public static void main(String[] args)throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
HashMap<Pair<Integer,Integer>,Integer> edges=new HashMap();
for(int i=1;i<n;i++){
String line[]=br.readLine().split(" ");
int x=Integer.parseInt(line[0]);
int y=Integer.parseInt(line[1]);
edges.put(new Pair<>(x,y),1);
}
int a[]=new int[n+1];
String line[]=br.readLine().split(" ");
for(int i=1;i<=n;i++){
a[i]=Integer.parseInt(line[i-1]);
}
int op1=0,op2=0;
for(Pair<Integer,Integer> edge:edges.keySet()){
int x=edge.getKey();
int y=edge.getValue();
if(a[x]==a[y]){
continue;
}
if(op1==0&&op2==0){
op1=x;op2=y;
}
else if(op1!=0){
if(op1==x||op2==x){
op1=0;op2=x;
}
else if(op1==y||op2==y){
op1=0;op2=y;
}
else{
op2=-1;
break;
}
}
else{
if(op2==x||op2==y){
continue;
}
else{
op2=-1;
break;
}
}
}
if(op2!=-1){
System.out.println("YES");
if(op2==0){
System.out.println(1);
}
else{
System.out.println(op2);
}
}
else{
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 | 0a730536a4ec55a7a7d5fc9ffab8b348 | train_001.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.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);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] ev = new int[n - 1];
int[] eu = new int[n - 1];
int[] col = new int[n];
for (int i = 0; i < n - 1; i++) {
ev[i] = in.nextInt() - 1;
eu[i] = in.nextInt() - 1;
}
for (int i = 0; i < n; i++) {
col[i] = in.nextInt();
}
int[] diffCol = new int[n];
for (int i = 0; i < n - 1; i++) {
if (col[ev[i]] != col[eu[i]]) {
diffCol[ev[i]]++;
diffCol[eu[i]]++;
}
}
int maxi = 0;
int cnt = 0;
int total = 0;
for (int i = 0; i < n; i++) {
if (diffCol[i] > 0)
total++;
if (diffCol[i] > 1)
cnt++;
if (diffCol[maxi] < diffCol[i])
maxi = i;
}
if (cnt == 1 || total <= 2) {
out.println("YES");
out.println(maxi + 1);
} else {
out.println("NO");
}
}
}
static class InputReader {
StringTokenizer st;
BufferedReader br;
public InputReader(InputStream is) {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
this.br = br;
}
public String next() {
if (st == null || !st.hasMoreTokens()) {
String nextLine = null;
try {
nextLine = br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (nextLine == null)
return null;
st = new StringTokenizer(nextLine);
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["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 | 1a638c527c176059d80c4632c7852e4c | train_001.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.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author El-Bishoy
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
Div2C763_TimofeyAndTree_t_cc solver = new Div2C763_TimofeyAndTree_t_cc();
solver.solve(1, in, out);
out.close();
}
static class Div2C763_TimofeyAndTree_t_cc {
int n;
boolean[] visited;
ArrayList<Integer>[] adj;
int[] colorOf;
List<Edge> edges = new ArrayList<>();
boolean badRoot = false;
void solv1(InputReader in, OutputWriter out) {
n = in.nextInt();
int m = n - 1;
adj = GraphUtils.buildAdjList(n);
visited = new boolean[n];
colorOf = new int[n];
while (m-- > 0) {
int u = in.nextInt() - 1, v = in.nextInt() - 1;
edges.add(new Edge(u, v));
}
colorOf = in.nextIntArray(n);
int candidateRoot1 = -1;
int candidateRoot2 = -1;
for (Edge e : edges) {
int u = e.u, v = e.v;
if (colorOf[u] != colorOf[v]) {
candidateRoot1 = u;
candidateRoot2 = v;
}
adj[u].add(v);
adj[v].add(u);
}
if (candidateRoot1 == -1) {
out.println("YES\n1");
return;
}
if (canBeRoot(candidateRoot1)) {
out.println("YES\n" + (candidateRoot1 + 1));
return;
}
if (canBeRoot(candidateRoot2)) {
out.println("YES\n" + (candidateRoot2 + 1));
return;
}
out.println("NO");
}
private boolean canBeRoot(int root) {
visited = new boolean[visited.length];
visited[root] = true;
for (int u : adj[root]) {
int c = colorOf[u];
badRoot = false;
dfs(u, root, c); // if different color detected ret false
if (badRoot) return false;
}
return true;
}
boolean dfs(int v, int parent, int c) {
if (colorOf[v] != c && v != parent) {
badRoot = true;
}
if (badRoot) return false;
visited[v] = true;
for (int u : adj[v]) {
if (!visited[u]) {
dfs(u, parent, c);
}
}
return true;
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
solv1(in, out);
}
class Edge {
int u;
int v;
public Edge(int u, int v) {
this.u = u;
this.v = v;
}
}
}
static class GraphUtils {
public static ArrayList<Integer>[] buildAdjList(int n) {
ArrayList<Integer>[] adj = new ArrayList[n];
for (int i = 0; i < n; i++) {
adj[i] = new ArrayList<>();
}
return adj;
}
}
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 boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int[] nextIntArray(int n) {
int[] array = new int[n];
for (int i = 0; i < n; ++i) array[i] = nextInt();
return array;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| 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 | 5645f50f2fd7e030480b0268e422fa80 | train_001.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.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class TimofeyTree {
public static void main(String[] args) {
InputStream in = System.in;
InputReader scan = new InputReader(in);
int n = scan.nextInt();
ArrayList<ArrayList<Integer>> tree = new ArrayList<>();
for(int i=0;i<=n;i++) {
tree.add(new ArrayList<>());
}
for(int i=0;i<n-1;i++) {
int u = scan.nextInt();
int v = scan.nextInt();
tree.get(u).add(v);
tree.get(v).add(u);
}
int[] colors = new int[n+1];
//Find an edge having two different colors in two end-points
for(int i=1;i<=n;i++) {
colors[i] = scan.nextInt();
}
int v1 = -1;
int v2 = -1;
loop1:for(int i=1;i<=n;i++) {
int color1 = colors[i];
for(int j : tree.get(i)) {
if(color1!=colors[j]) {
v1 = i;
v2 = j;
break loop1;
}
}
}
if(v1==-1) {
System.out.println("YES");
System.out.println(1);
return;
}
boolean flag1 = true;
for(int adj:tree.get(v1)) {
if(!dfs(v1,adj,colors[adj],tree,colors)) {
flag1 = false;
}
}
if(flag1) {
System.out.println("YES");
System.out.println(v1);
return;
}
boolean flag2 = true;
for(int adj:tree.get(v2)) {
if(!dfs(v2,adj,colors[adj],tree,colors)) {
flag2 = false;
}
}
if(flag2) {
System.out.println("YES");
System.out.println(v2);
return;
}
System.out.println("NO");
}
static boolean dfs(int parent,int current,int color,ArrayList<ArrayList<Integer>> tree,int[] colors) {
boolean flag = true;
for(int child:tree.get(current)) {
if(child!=parent) {
flag = flag && (color==colors[child]) && dfs(current,child,color,tree,colors);
}
}
return flag;
}
static class InputReader {
BufferedReader br;
StringTokenizer st;
InputReader(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
String next() {
while(st==null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
}
}
| 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 | 36c75e7801e183cfb3ed59185811206c | train_001.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.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author cunbidun
*/
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);
ATimofeyAndATree solver = new ATimofeyAndATree();
solver.solve(1, in, out);
out.close();
}
static class ATimofeyAndATree {
private InputReader in;
private PrintWriter out;
private ArrayList<Integer>[] tree;
private int[] a;
private int[] cnt;
private int pos1 = -1;
private int pos2 = -1;
private boolean check = true;
public void solve(int testNumber, InputReader in, PrintWriter out) {
this.in = in;
this.out = out;
int n = in.nextInt();
tree = in.nextTree(n);
a = in.nextIntArray(n, 1);
cnt = new int[n + 1];
find(1, 1);
// out.println(pos1 + " " + pos2);
if (pos1 == -1) {
out.println("YES");
out.println(1);
return;
}
check = true;
for (int i : tree[pos1]) dfs(i, pos1);
if (check) {
out.println("YES");
out.println(pos1);
return;
}
check = true;
for (int i : tree[pos2]) dfs(i, pos2);
if (check) {
out.println("YES");
out.println(pos2);
return;
}
out.println("NO");
}
private void find(int u, int l) {
for (int v : tree[u])
if (v != l) {
if (a[u] != a[v]) {
pos1 = u;
pos2 = v;
}
find(v, u);
}
}
private void dfs(int u, int l) {
for (int v : tree[u])
if (v != l) {
if (a[u] != a[v]) check = false;
dfs(v, u);
}
}
}
static class InputReader extends InputStream {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int length, int stIndex) {
int[] arr = new int[length + stIndex];
for (int i = stIndex; i < stIndex + length; i++)
arr[i] = nextInt();
return arr;
}
public ArrayList<Integer>[] nextTree(int n) {
ArrayList<Integer>[] tree = new ArrayList[n + 1];
for (int i = 1; i <= n; i++) {
tree[i] = new ArrayList<>();
}
for (int i = 1; i < n; i++) {
int u = nextInt();
int v = nextInt();
tree[u].add(v);
tree[v].add(u);
}
return tree;
}
private static boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
| 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 | d9d2cefa1cfd48138bd7da49fd4ae83a | train_001.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.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
public class CF_763A {
static FastScanner sc = new FastScanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) {
new CF_763A().run();
out.close();
}
public void run(){
int n = sc.nextInt();
int[] u = new int[n-1];
int[] v = new int[n-1];
for(int i = 0;i<n-1;i++){
u[i] = sc.nextInt()-1;
v[i] = sc.nextInt()-1;
}
int[] c = sc.readIntArray(n);
int[] d = new int[n];
int e = 0;
for(int i = 0;i<n-1;i++){
if(c[u[i]]!=c[v[i]]){
e++;
d[u[i]]++;
d[v[i]]++;
}
}
for(int i = 0;i<n;i++){
if(d[i]==e){
out.println("YES");
out.print(i+1);
return ;
}
}
out.print("NO");
}
static class FastScanner {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public FastScanner(InputStream st) {
this.stream = st;
}
//θ―»δΈδΈͺεθ
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] readIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
} | 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 | 69ee4f537003effc5ca29d1a4578e190 | train_001.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 codeforces1;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.io.*;
import java.math.*;
import java.text.*;
public class A395 {
static InputReader in = new InputReader(System.in);
static OutputWriter out = new OutputWriter(System.out);
static boolean check=true;
static void dfs(int s,ArrayList<ArrayList<Integer>> ar, int arr[],boolean vis[],int curr,int p) {
vis[s]=true;
check=check&&(arr[s]==curr);
// System.out.println(check);
for(int j:ar.get(s)) {
if(j!=p)
dfs(j,ar,arr,vis,curr,s);
}
}
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = 1;
PrintWriter out = new PrintWriter(System.out);
while (t > 0) {
int n = i();
int arr[] = new int[n+1];
ArrayList<ArrayList<Integer>> ar=new ArrayList<>(n+1);
for(int i=0;i<=n;i++) {
ar.add(new ArrayList<>());
}
for(int i=1;i<n;i++) {
int a=i();
int b=i();
ar.get(a).add(b);
ar.get(b).add(a);
}
for (int i = 1; i <= n; i++) {
arr[i] = i();
}
int r1=-1;
int r2=-2;
for(int i=1;i<=n;i++) {
for(int j:ar.get(i)) {
if(arr[j]!=arr[i]) {
r1=j;
r2=i;
// break;
}
}
}
if(r1==-1) {
System.out.println("YES");
System.out.println(1);
}
else {
boolean vis[]=new boolean[n+1];
boolean a1=true;
for(int j:ar.get(r1)) {
// System.out.println("K");
check=true;
int curr=arr[j];
// if(!vis[j])
dfs(j,ar,arr,vis,curr,r1);
a1=a1&✓
}
boolean ans1=a1;
Arrays.fill(vis, false);
boolean a2=true;
for(int j:ar.get(r2)) {
check=true;
int curr=arr[j];
dfs(j,ar,arr,vis,curr,r2);
a2=a2&✓
}
// System.out.println(r1+" "+r2);
boolean ans2=a2;
if(ans1) {
System.out.println("YES");
System.out.println(r1);
}
else if(ans2) {
System.out.println("YES");
System.out.println(r2);
}
else
System.out.println("NO");
}
check=true;
// out.println();
t--;
}
out.close();
// long l=l();
// String s=s(); // ONLY BEFORE SPACE IN STRING , ELSE USE BUFFER-READER
}
public static long pow(long a, long b) {
long m = 1000000007;
long result = 1;
while (b > 0) {
if (b % 2 != 0) {
result = (result * a) % m;
b--;
}
a = (a * a) % m;
b /= 2;
}
return result % m;
}
public static long gcd(long a, long b) {
if (a == 0) {
return b;
}
return gcd(b % a, a);
}
public static long lcm(long a, long b) {
return a * (b / gcd(a, b));
}
public static long l() {
String s = in.String();
return Long.parseLong(s);
}
public static void pln(String value) {
System.out.println(value);
}
public static int i() {
return in.Int();
}
public static String s() {
return in.String();
}
}
class pair {
int x, y;
pair(int x, int y) {
this.x = x;
this.y = y;
}
}
class CompareValue {
static void compare(pair arr[], int n) {
Arrays.sort(arr, new Comparator<pair>() {
public int compare(pair p1, pair p2) {
return p1.y - p2.y;
}
});
}
}
class CompareKey {
static void compare(pair arr[], int n) {
Arrays.sort(arr, new Comparator<pair>() {
public int compare(pair p1, pair p2) {
return p2.x - p1.x;
}
});
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int Int() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String String() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return String();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
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, Int());
}
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, Int());
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
}
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]);
}
writer.flush();
}
public void printLine(Object... objects) {
print(objects);
writer.println();
writer.flush();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.Int();
return array;
}
}
/**
* TO SORT VIA TWO KEYS , HERE IT IS ACCORDING TO ASCENDING ORDER OF FIRST AND
* DESC ORDER OF SECOND
* LIST name-list
* ARRAYLIST
* COPY PASTE
*
* Collections.sort(list, (first,second) ->{
if(first.con >second.con)
return -1;
else if(first.con<second.con)
return 1;
else {
if(first.index >second.index)
return 1;
else
return -1;
}
});
*
*/
/**
*
DECIMAL FORMATTER
Double k = in.readDouble();
System.out.println(k);
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(k));
out.printLine(k);
*
* */
| 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 | 002c17d207e66f83dffe702cc5d7d712 | train_001.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.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
public class Solution implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
@Override
public void run() {
try {
init();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
long time = System.currentTimeMillis();
try {
solve();
} catch (Exception e) {
e.printStackTrace();
}
out.close();
//System.err.println(System.currentTimeMillis() - time);
}
private void init() throws FileNotFoundException {
String file = "";
if (!file.equals("")) {
in = new BufferedReader(new FileReader("forest.in"));
out = new PrintWriter("forest.out");
} else {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
}
public static void main(String[] args) {
new Thread(new Solution()).start();
}
private String readString() {
while (!tok.hasMoreTokens()) {
try {
tok = new StringTokenizer(in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return tok.nextToken();
}
private int readInt() {
return Integer.parseInt(readString());
}
private long readLong() {
return Long.parseLong(readString());
}
private double readDouble() {
return Double.parseDouble(readString());
}
ArrayList<Integer>[] graph;
int[] colours;
private void solve() {
int n = readInt();
graph = new ArrayList[n];
for (int i = 0; i < n; i++) {
graph[i] = new ArrayList<>();
}
colours = new int[n];
for (int i = 0; i < n - 1; i++) {
int from = readInt() - 1;
int to = readInt() - 1;
graph[from].add(to);
graph[to].add(from);
}
HashSet<Integer> set = new HashSet<>();
for (int i = 0; i < n; i++) {
colours[i] = readInt();
set.add(colours[i]);
}
if (set.size() == 1) {
out.println("YES");
out.print(1);
return;
}
int rootToCheck1 = -1;
int rootToCheck2 = -1;
for (int i = 0; i < n; i++) {
int from = i;
for (int j = 0; j < graph[from].size(); j++) {
int to = graph[from].get(j);
if (colours[to] != colours[from]) {
rootToCheck1 = from;
rootToCheck2 = to;
}
}
}
ok = true;
for (int i = 0; i < graph[rootToCheck1].size(); i++) {
int needColor = colours[graph[rootToCheck1].get(i)];
dfs(graph[rootToCheck1].get(i), needColor, rootToCheck1);
}
if(ok) {
out.println("YES");
out.println(rootToCheck1+1);
return;
}
ok = true;
for (int i = 0; i < graph[rootToCheck2].size(); i++) {
int needColor = colours[graph[rootToCheck2].get(i)];
dfs(graph[rootToCheck2].get(i), needColor, rootToCheck2);
}
if(ok) {
out.println("YES");
out.println(rootToCheck2+1);
return;
}
out.print("NO");
}
boolean ok = true;
private void dfs(int v, int needColor, int prev) {
if (colours[v] != needColor) {
ok = false;
return;
}
for (int i = 0; i < graph[v].size(); i++) {
if (graph[v].get(i) != prev)
dfs(graph[v].get(i), needColor, v);
}
}
} | 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 | 41ff33fa6e365cedf269c720df56242a | train_001.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.*;
import java.io.*;
public class tree{
public static class Pair{
int x;
int y;
public Pair(int a , int b){
x = a;
y = b;
}
}
public static void main (String args[])throws IOException{
BufferedReader ob = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(ob.readLine());
ArrayList<Pair>list = new ArrayList<>();
for(int i = 0; i < n-1; i++){
StringTokenizer st = new StringTokenizer(ob.readLine());
int u = Integer.parseInt(st.nextToken())-1;
int v = Integer.parseInt(st.nextToken())-1;
list.add(new Pair(u,v));
}
int []deg = new int[n];
int tot = 0;
StringTokenizer st1 = new StringTokenizer(ob.readLine());
int []color = new int[n];
for(int i = 0; i < n; i++){
color[i] = Integer.parseInt(st1.nextToken())-1;
}
for(int i = 0; i < n-1; i++){
Pair g = list.get(i);
int left = g.x;
int right = g.y;
if(color[left] != color[right]){
deg[right]++;
deg[left]++;
tot++;
}
}
for(int i = 0; i < n; i++){
if(deg[i] == tot){
System.out.println("YES");
System.out.println(i+1);
return;
}
}
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 | 683298641b801b5b307b864d185997f1 | train_001.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.io.*;
import java.util.*;
import java.text.*;
public class b286 {
public static void main(String[] args) throws Exception {
//new FileInputStream("input.txt");
//new FileOutputStream("output.txt")
InputReader in = new InputReader(System.in);
OutputWriter out = new OutputWriter(System.out);
int n = in.ri();
int arr[][] = new int[n][2];
int diff[]=new int[n+1];
for (int i = 0; i < n-1; i++) {
arr[i][0] = in.ri();
arr[i][1] = in.ri();
}
int col[]=new int[n+1];
for(int i=0;i<n;i++)
col[i+1]=in.ri();
int cnt=0;
for(int i=0;i<n-1;i++){
if(col[arr[i][0]]!=col[arr[i][1]]){
diff[arr[i][0]]+=1;
diff[arr[i][1]]+=1;
cnt+=1;
}
}
int found=-1;
for(int i=0;i<=n;i++){
if(diff[i]==cnt)found=i;
}
if(found!=-1){
out.pl("YES");
out.pl(found);
}
else
out.pl("NO");
out.close();
}
private static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String rs() {
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 int ri() {
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 double rd() {
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, ri());
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, ri());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public long rl() {
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 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);
}
}
private 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 pf(double n) {
writer.printf("%.9f%n", n);
}
public void pl(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
}
}
| 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 | 098e80105da75c3dffe6e5493580ef20 | train_001.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.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author revanth
*/
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);
ATimofeyAndATree solver = new ATimofeyAndATree();
solver.solve(1, in, out);
out.close();
}
static class ATimofeyAndATree {
ArrayList<Integer>[] adj;
int[] c;
boolean dfs(int s, int p) {
for (int i : adj[s]) {
if (i == p)
continue;
if (c[i] != c[s])
return false;
if (!dfs(i, s))
return false;
}
return true;
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt(), x, y;
adj = new ArrayList[n + 1];
for (int i = 1; i <= n; i++)
adj[i] = new ArrayList<>();
for (int i = 1; i < n; i++) {
x = in.nextInt();
y = in.nextInt();
adj[x].add(y);
adj[y].add(x);
}
c = new int[n + 1];
for (int i = 1; i <= n; i++)
c[i] = in.nextInt();
x = -1;
y = -1;
for (int i = 1; i <= n; i++) {
for (int j : adj[i]) {
if (c[i] != c[j]) {
x = i;
y = j;
}
}
}
if (x == -1 && y == -1) {
out.println("YES\n1");
return;
}
boolean flag = true;
for (int i : adj[x]) {
if (!dfs(i, x)) {
flag = false;
break;
}
}
if (flag) {
out.println("YES\n" + x);
return;
}
flag = true;
for (int i : adj[y]) {
if (!dfs(i, y)) {
flag = false;
break;
}
}
if (flag) {
out.println("YES\n" + y);
return;
}
out.println("NO");
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int snumChars;
private InputReader.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 boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
}
| Java | ["4\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 | 8eae1376237ae3d5af7edcc4b3fa282f | train_001.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.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
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 HavroninaTE
*/
public class TimothyAndBirch {
static ArrayList<Integer> g[];
static int[] colors;
public static void main(String[] args) throws IOException {
// Scanner in = new Scanner(Paths.get("D:\\ΠΠΈΡΠ΅ΡΠ°ΡΡΡΠ°\\JAVA\\projects\\CodeForces\\src\\TimothyAndBirch\\input2.txt"),"UTF-8");
Scanner in = new Scanner(System.in);
int n = in.nextInt();
g = new ArrayList[n];
colors = new int[n];
for(int i=0;i<n;i++)
g[i]=new ArrayList();
int root1=-1,root2=-1;
for(int u,v,i=1;i<n;i++)
{
u=in.nextInt()-1;
v=in.nextInt()-1;
g[u].add(v);
g[v].add(u);
}
for(int i=0;i<n;i++)
colors[i]=in.nextInt();
boolean find=false;
int node=-1;
for(int i=0;i<n&&(root1==-1);i++)
{
for(int j=0;j<g[i].size();j++)
if(colors[i]!=colors[g[i].get(j)])
{
root1=i;
root2=g[i].get(j);
break;
}
}
if(root1==-1 && root2==-1)
{
find=true;
node=1;
}
else
{
if(dfs(root1,-1)!=-1)
{
find=true;
node=root1+1;
}
else
{
if(dfs(root2,-1)!=-1)
{
find=true;
node=root2+1;
}
}
}
if(find)
{
System.out.println("YES");
System.out.println(node);
}
else
System.out.println("NO");
}
private static int dfs(int v,int p)
{
int color;
for(int u:g[v])
{
if(u!=p)
{
color=dfs(u,v);
if(color==-1)
return -1;
if(color!=colors[v]&&(p!=-1))
return -1;
}
}
return colors[v];
}
}
| 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 | 27e9acb507d392ee3eea922ec670022a | train_001.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.*;
import java.io.*;
public class Solution {
public static void main (String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] temp=br.readLine().trim().split(" ");
int V=Integer.parseInt(temp[0]);
ArrayList<ArrayList<Integer>> graph=new ArrayList<>();
for(int i=0;i<=V;i++)
{
graph.add(new ArrayList<>());
}
for(int i=1;i<V;i++)
{
temp=br.readLine().trim().split(" ");
int u=Integer.parseInt(temp[0]);
int v=Integer.parseInt(temp[1]);
graph.get(u).add(v);
graph.get(v).add(u);
}
int[] color=new int[V+1];
temp=br.readLine().trim().split(" ");
for(int i=1;i<=V;i++)
{
color[i]=Integer.parseInt(temp[i-1]);
}
int u=0,v=0;
for(int i=1;i<=V;i++)
{
int j;
for(j=0;j<graph.get(i).size();j++)
{
if(color[i]!=color[graph.get(i).get(j)]){
u=i;
v=graph.get(i).get(j);
break;
}
}
if(j<graph.get(i).size()){
break;
}
}
if(u==0 && v==0){
System.out.println("YES");
System.out.println(1);
return;
}
boolean ans1=canVertexBeRoot(graph,u,color);
boolean ans2=canVertexBeRoot(graph,v,color);
if(ans1){
System.out.println("YES");
System.out.println(u);
}
else if(ans2){
System.out.println("YES");
System.out.println(v);
}
else{
System.out.println("NO");
}
}
public static boolean canVertexBeRoot(ArrayList<ArrayList<Integer>> graph,int u,int[] color){
int V=graph.size()-1;
boolean[] visited=new boolean[V+1];
for(int i=0;i<graph.get(u).size();i++)
{
HashMap<Integer,Boolean> hash=new HashMap<>();
visited[u]=true;
if(visited[graph.get(u).get(i)]==false){
dfs(graph,graph.get(u).get(i),visited,color,hash);
if(hash.size()>1){
return false;
}
}
}
return true;
}
public static void dfs(ArrayList<ArrayList<Integer>> graph,int start,boolean[] visited,int[] color,HashMap<Integer,Boolean> hash){
visited[start]=true;
hash.put(color[start],true);
for(int i=0;i<graph.get(start).size();i++)
{
if(visited[graph.get(start).get(i)]==false){
dfs(graph,graph.get(start).get(i),visited,color,hash);
}
}
}
}
class DSU{
private int[] parent;
private int[] size;
public DSU(int V)
{
parent=new int[V+1];
size=new int[V+1];
for(int i=1;i<=V;i++)
{
parent[i]=i;
size[i]=1;
}
}
public int getParent(int vertex)
{
int temp=vertex;
while(parent[vertex]!=vertex){
vertex=parent[vertex];
}
parent[temp]=vertex;
return vertex;
}
public void makeUnion(int u,int v){
int parent1=getParent(u);
int parent2=getParent(v);
if(parent2==parent1)
{
return;
}
int size1=size[parent1];
int size2=size[parent2];
if(size2<size1){
parent[parent2]=parent1;
size[parent1]+=size[parent2];
}
else{
parent[parent1]=parent2;
size[parent2]+=size[parent1];
}
}
public int numComponents(){
int ans=0;
int V=this.parent.length-1;
for(int i=1;i<=V;i++){
if(this.parent[i]==i){
ans++;
}
}
return ans;
}
public int componentSize(int vertex){
int parent=getParent(vertex);
return size[parent];
}
} | 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 | c8b6843811c34e3da01a8d2f918fc0b5 | train_001.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.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.HashMap;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws Exception {
long startTime = System.nanoTime();
int n = in.nextInt();
int[] x = new int[n + 10];
int[] y = new int[n + 10];
HashMap<Integer, Integer> h = new HashMap<>();
int[] c = new int[n + 10];
int m = 0;
for (int i = 1; i < n; i++) {
int a = in.nextInt();
int b = in.nextInt();
x[i] = a;
y[i] = b;
}
for (int i = 1; i <= n; i++) {
c[i] = in.nextInt();
h.put(i, 0);
}
for (int i = 1; i < n; i++) {
if (c[x[i]] != c[y[i]]) {
h.put(x[i], h.getOrDefault(x[i], 0) + 1);
h.put(y[i], h.getOrDefault(y[i], 0) + 1);
m++;
}
}
int q = -1;
for (int a : h.keySet()) {
if (h.get(a) == m) {
q = a;
break;
}
}
if (q == -1) {
out.println("NO");
} else {
out.println("YES");
out.println(q);
}
long endTime = System.nanoTime();
err.println("Execution Time : +" + (endTime - startTime) / 1000000 + " ms");
exit(0);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
static void exit(int a) {
out.close();
err.close();
System.exit(a);
}
static InputStream inputStream = System.in;
static OutputStream outputStream = System.out;
static OutputStream errStream = System.err;
static InputReader in = new InputReader(inputStream);
static PrintWriter out = new PrintWriter(outputStream);
static PrintWriter err = new PrintWriter(errStream);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
}
| 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 | ca3d534fcae8a8a991a75725040dbea3 | train_001.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.Scanner;
import java.util.ArrayList;
public class Main{
static boolean dfs(int parent,ArrayList<Integer> arr[],boolean visited[],int color[]){
int sourceColor=color[parent];
ArrayList<Integer> list=arr[parent];
visited[parent]=true;
for(int i=0;i<list.size();i++){
int j=list.get(i);
if(!visited[j])
{
if(color[j] != sourceColor) return false;
boolean res=dfs(j,arr,visited,color);
if(res == false) return false;
}
}
return true;
}
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
ArrayList<Integer> arr[]=new ArrayList[n+1];
for(int i=1;i<=n;i++) arr[i]=new ArrayList<>();
int color[]=new int[n+1];
for(int i=0;i<n-1;i++){
int a=sc.nextInt();
int b=sc.nextInt();
arr[a].add(b);
arr[b].add(a);
}
for(int i=1;i<=n;i++)
color[i]=sc.nextInt();
for(int i=1;i<=n;i++){
for(int j=0;j<arr[i].size();j++){
if(color[i] !=color[arr[i].get(j)])
{
boolean flag1=true;
boolean flag2=true;
int root1 = i;
int root2 = arr[i].get(j);
boolean visited[]=new boolean[n+1];
for(int k=0;k<arr[root1].size();k++){
int child=arr[root1].get(k);
visited[root1]=true;
if(!visited[child]){
if(!dfs(child,arr,visited,color)){
flag1=false;
break;
}
}
}
if(flag1)
{
System.out.println("YES");
System.out.println(i);
System.exit(0);
}
visited=new boolean[n+1];
for(int k=0;k<arr[root2].size();k++){
int child=arr[root2].get(k);
visited[root2]=true;
if(!visited[child]){
if(!dfs(child,arr,visited,color)){
flag2=false;
break;
}
}
}
if(flag2){
System.out.println("YES");
System.out.println(arr[i].get(j));
System.exit(0);
}
else{
System.out.println("NO");
System.exit(0);
}
}
else continue;
}
}
System.out.println("YES");
System.out.println(1);
}
} | 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 | ee2d36aa79158b40cb51855a0b201174 | train_001.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.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Bereza {
private static class Edge{
int x;
int y;
public Edge(int u, int v){
x=u;
y=v;
}
public boolean contains(int u){
return(u==x || u == y);
}
}
static int[] color;
static HashMap<Integer, ArrayList<Integer>> tree;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
Edge[] edges = new Edge[n-1];
tree = new HashMap<>();
for (int i =0; i<n-1; i++) {
String[] buf = br.readLine().split(" ");
int u = Integer.parseInt(buf[0]);
int v = Integer.parseInt(buf[1]);
edges[i] = new Edge(u, v);
ArrayList<Integer> neighbours = tree.get(u);
if (neighbours==null)
neighbours = new ArrayList<>();
neighbours.add(v);
tree.put(u, neighbours);
neighbours = tree.get(v);
if (neighbours==null)
neighbours = new ArrayList<>();
neighbours.add(u);
tree.put(v, neighbours);
}
color = new int[n+1];
String[] buf = br.readLine().split(" ");
for (int i = 1; i<n+1; i++) {
color[i] = Integer.parseInt(buf[i-1]);
}
List<Edge> crit = new ArrayList<>();
for(Edge e: edges){
if(color[e.x]!=color[e.y]){
crit.add(e);
}
}
if(crit.size()==0){
System.out.println("YES");
System.out.println(1);
return;
}
if(crit.size()!=1){
int x = crit.get(0).x;
int y = crit.get(0).y;
if (crit.get(1).contains(y)){
x=y;
}
for(int i =1; i<crit.size(); i++){
if(!crit.get(i).contains(x)){
System.out.println("NO");
return;
}
}
System.out.println("YES");
System.out.println(x);
return;
}
System.out.println("YES");
System.out.println(crit.get(0).x);
}
}
| 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 | 24690bb968732e256eae9f9e3fa9ccd4 | train_001.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.io.PrintWriter;
import java.util.Scanner;
import java.util.ArrayList;
public class practise {
static final int N = 100010;
static int[] c = new int[N];
static int[] u = new int[N*2];
static int[] v = new int[N*2];
static int m;
static ArrayList<ArrayList<Integer> > lk = new ArrayList<ArrayList<Integer> > ();
static Scanner sc = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out,true);
public static void main(String[] args) {
//Scanner sc = new Scanner(System.in);
m = 0;
int n,a,b; n = sc.nextInt();
for(int i=0;i<n;i++) lk.add(new ArrayList<Integer>());
for(int i=1;i<n;i++) {
u[m] = sc.nextInt()-1; v[m] = sc.nextInt()-1;
lk.get(u[m]).add(m);
m++;
}
for(int i=0;i<m;i++) {
u[i+m] = v[i]; v[i+m] = u[i];
lk.get(v[i]).add(i+m);
}
for(int i=0;i<n;i++) c[i] = sc.nextInt();
for(int i=0;i<m;i++) {
if(c[u[i]]!=c[v[i]]) {
//out.println(u[i] + " " + v[i]);
if(check(u[i])) output(u[i]);
else if(check(v[i])) output(v[i]);
else output();
return ;
}
}
output(0);
}
public static boolean check(int x) {
//out.println("check: " + x);
int t = lk.get(x).size();
for(int i=0;i<t;i++) {
int edge = lk.get(x).get(i);
int ve = edge<m?edge+m:edge-m;
if (dfs(v[edge], -1,ve) == false) return false;
}
return true;
}
public static boolean dfs(int x,int f,int e) {
//out.println(x+1+" "+(f+1)+" "+c[x] + " " + (f==-1?-1:c[f]));
if(f!=-1 && c[x]!=c[f]) return false;
int t = lk.get(x).size();
for(int i=0;i<t;i++) {
int edge = lk.get(x).get(i);
//if(v[edge] == 7) out.println("!!!");
if(edge!=e && v[edge]!=f) {
boolean r = dfs(v[edge],x,e);
if(r==false) return r;
}
}
return true;
}
public static void output(int x) {
//PrintWriter out = new PrintWriter(System.out);
out.println("YES");
out.println(x+1);
}
public static void output() {
//PrintWriter out = new PrintWriter(System.out);
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 | bc9a1d99d406b48c16345271e9fe4ebf | train_001.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.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.math.*;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
static int k;
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader();
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n=in.nextInt();
int[][] arr=new int[n-1][2];
int[] c=new int[n+1];
for(int i=0;i<n-1;i++) {
arr[i][0]=in.nextInt();
arr[i][1]=in.nextInt();
}
for(int i=1;i<=n;i++) {
c[i]=in.nextInt();
}
int cnt=0;
int c1=0;
int c2=0;
for(int i=0;i<n-1;i++) {
if(c[arr[i][0]]!=c[arr[i][1]]) {
c1=arr[i][0];
c2=arr[i][1];
cnt++;
}
}
// System.out.println(c1+" "+c2);
int a1=0;
int a2=0;
if(cnt==0) {
System.out.println("YES");
System.out.println(1);
return;
}
else {
for(int i=0;i<n-1;i++) {
if(c[arr[i][0]]!=c[arr[i][1]]) {
// System.out.println(arr[i][0]+" "+arr[i][1]);
if(c1==arr[i][0] || c1==arr[i][1]) {
a1++;
}
if(c2==arr[i][0] || c2==arr[i][1]) {
a2++;
}
}
}
}
if(a1==cnt) {
System.out.println("YES");
System.out.println(c1);
}
else if(a2==cnt) {
System.out.println("YES");
System.out.println(c2);
}
else {
System.out.println("NO");
}
}
}
static long gcd(long a,long b) {
if(a==0) {
return b;
}
return gcd(b%a,a);
}
static long moduloMultiplication(long a, long b, long mod) {
long res = 0;
a %= mod;
while (b > 0) {
if ((b & 1) > 0) {
res = (res + a) % mod;
}
a = (2 * a) % mod;
b >>= 1;
}
return res;
}
static class InputReader
{
BufferedReader br;
StringTokenizer st;
public InputReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void sort(int[] a, int low, int high)
{
int N = high - low;
if (N <= 1)
return;
int mid = low + N/2;
// recursively sort
sort(a, low, mid);
sort(a, mid, high);
// merge two sorted subarrays
int[] temp = new int[N];
int i = low, j = mid;
for (int k = 0; k < N; k++)
{
if (i == mid)
temp[k] = a[j++];
else if (j == high)
temp[k] = a[i++];
else if (a[j]<a[i])
temp[k] = a[j++];
else
temp[k] = a[i++];
}
for (int k = 0; k < N; k++)
a[low + k] = temp[k];
}
} | 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 | c33a24a09b9d8eee773f79ecc9dc0a33 | train_001.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 solution;
import java.io.*;
import java.util.*;
import java.math.*;
import java.text.*;
import java.awt.Point;
public final class Solution {
BufferedReader br;
StringTokenizer stk;
public static void main(String[] args) throws Exception {
new Thread(null, new Runnable() {
@Override
public void run() {
try {
new Solution().run();
} catch(Exception ex) {ex.printStackTrace();}
}
}, "solution", 1<<23).start();
}
{
stk = null;
br = new BufferedReader(new InputStreamReader(System.in));
}
long mod = 1000000007L;
void run() throws Exception {
int n = ni();
Node[] g = new Node[n];
for(int i=0; i<n; i++) g[i] = new Node();
List<Point> edges = new ArrayList<>();
for(int i=1; i<n; i++) {
int a = ni()-1, b = ni()-1;
g[a].adj.add(b);
g[b].adj.add(a);
edges.add(new Point(a, b));
}
for(int i=0; i<n; i++) g[i].color = ni()-1;
int A = -1, B = -1;
for(Point edge : edges) {
if(g[edge.x].color != g[edge.y].color) {
A = edge.x; B = edge.y;
break;
}
}
if(A == -1) {
pl("YES\n1");
} else {
List<Point> remove = new ArrayList<>();
Node[] ga = Arrays.copyOf(g, n);
for(int adj : ga[A].adj) {
remove.add(new Point(adj, A));
}
for(Point rem : remove) {
ga[rem.x].adj.remove(rem.y);
ga[rem.y].adj.remove(rem.x);
}
remove = new ArrayList<>();
A++;
if(check(ga)) {
pl("YES\n" + A);
return;
}
ga = Arrays.copyOf(g, n);
for(int adj : ga[B].adj) {
remove.add(new Point(adj, B));
}
for(Point rem : remove) {
ga[rem.x].adj.remove(rem.y);
ga[rem.y].adj.remove(rem.x);
}
remove = new ArrayList<>();
B++;
if(check(ga)) {
pl("YES\n" + B);
return;
}
pl("NO");
}
}
boolean check(Node[] g) {
int n = g.length;
HashSet<Integer> v = new HashSet<>();
for(int i=0; i<n; i++) {
if(!v.contains(i)) {
HashSet<Integer> subtree = new HashSet<>();
dfs(i, g, subtree);
HashSet<Integer> colorsUsed = new HashSet<>();
for(int node : subtree) {
colorsUsed.add(g[node].color);
}
if(colorsUsed.size() > 1) return false;
v.addAll(subtree);
}
}
return true;
}
void dfs(int node, Node[] g, HashSet<Integer> v) {
if(v.contains(node)) return;
v.add(node);
for(int adj : g[node].adj) dfs(adj, g, v);
}
void convertToDirectional(int root, Node[] g) {
Queue<Integer> queue = new LinkedList<>();
HashSet<Integer> visited = new HashSet<>();
queue.add(root);
while(!queue.isEmpty()) {
int cur = queue.remove();
if(visited.contains(cur)) continue;
visited.add(cur);
for(int adj : g[cur].adj) {
queue.add(adj);
g[adj].adj.remove(cur);
}
}
}
class Node {
int color;
HashSet<Integer> adj;
public Node() {
this.color = 0;
adj = new HashSet<>();
}
}
//Reader & Writer
String nextToken() throws Exception {
if (stk == null || !stk.hasMoreTokens()) {
stk = new StringTokenizer(br.readLine(), " ");
}
return stk.nextToken();
}
String nt() throws Exception {
return nextToken();
}
String ns() throws Exception {
return br.readLine();
}
int ni() throws Exception {
return Integer.parseInt(nextToken());
}
long nl() throws Exception {
return Long.parseLong(nextToken());
}
double nd() throws Exception {
return Double.parseDouble(nextToken());
}
void p(Object o) {
System.out.print(o);
}
void pl(Object o) {
System.out.println(o);
}
void selector() {
Random rd = new Random();
String[] s = new String[] {"BinarySearch", "DivideAndConquer", "DynamicProgramming",
"DisjointSetUnion", "GraphMatchings", "Graphs", "Greedy", "Trees", "TwoPointers"};
pl(s[rd.nextInt(s.length)]);
}
} | 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 | 31c67a5d4fcbd68f99a60a814baa6a1e | train_001.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 practice;
import java.util.*;
import java.io.*;
public class Practice {
public static void main(String args[])
{
InputReader in=new InputReader(System.in);
int n=in.nextInt();
int[] a=new int[n+1];
int[] b=new int[n+1];
int[] color=new int[n+1];
for(int i=1;i<n;i++)
{
int q=in.nextInt();
int w=in.nextInt();
a[i]=w;
b[i]=q;
}
for(int i=1;i<=n;i++)
color[i]=in.nextInt();
int differ=0;
int[] deg=new int[n+1];
for(int i=1;i<n;i++)
{
if(color[a[i]]!=color[b[i]])
{
differ++;
deg[a[i]]++;
deg[b[i]]++;
}
}
for(int i=1;i<=n;i++)
{
if(deg[i]==differ)
{
System.out.println("YES");
System.out.println(i);
return;
}
}
System.out.println("NO");
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (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 & 15;
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int arraySize) {
int array[] = new int[arraySize];
for (int i = 0; i < arraySize; i++)
array[i] = nextInt();
return array;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sign = 1;
if (c == '-') {
sign = -1;
c = read();
}
long result = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
result *= 10;
result += c & 15;
c = read();
} while (!isSpaceChar(c));
return result * sign;
}
public long[] nextLongArray(int arraySize) {
long array[] = new long[arraySize];
for (int i = 0; i < arraySize; i++)
array[i] = nextLong();
return array;
}
public float nextFloat() // problematic
{
float result, div;
byte c;
result = 0;
div = 1;
c = (byte) read();
while (c <= ' ')
c = (byte) read();
boolean isNegative = (c == '-');
if (isNegative)
c = (byte) read();
do {
result = result * 10 + c - '0';
} while ((c = (byte) read()) >= '0' && c <= '9');
if (c == '.')
while ((c = (byte) read()) >= '0' && c <= '9')
result += (c - '0') / (div *= 10);
if (isNegative)
return -result;
return result;
}
public double nextDouble() // not completely accurate
{
double ret = 0, div = 1;
byte c = (byte) read();
while (c <= ' ')
c = (byte) read();
boolean neg = (c == '-');
if (neg)
c = (byte) read();
do {
ret = ret * 10 + c - '0';
} while ((c = (byte) read()) >= '0' && c <= '9');
if (c == '.')
while ((c = (byte) read()) >= '0' && c <= '9')
ret += (c - '0') / (div *= 10);
if (neg)
return -ret;
return ret;
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String nextLine() {
int c = read();
StringBuilder result = new StringBuilder();
do {
result.appendCodePoint(c);
c = read();
} while (!isNewLine(c));
return result.toString();
}
public boolean isNewLine(int c) {
return c == '\n';
}
public void close() {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| 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 | d5e363460195247a5301587f530f8cbb | train_001.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.Scanner;
public class Java763A {
private static int n;
private static int u[];
private static int v[];
private static int parent[];
private static int size[];
private static int color[];
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
//--------input-------------
u = new int[n - 1];
v = new int[n - 1];
for (int i = 0; i < n - 1; i++) {
u[i] = scanner.nextInt() - 1;
v[i] = scanner.nextInt() - 1;
}
//----------DSU--------------
color = new int[n];
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
color[i] = scanner.nextInt();
}
ArrayList<Integer> root = new ArrayList<>();
for (int i = 0; i < n - 1; i++) {
int pu = findParent(u[i]);
int pv = findParent(v[i]);
if (color[u[i]] != color[v[i]]) {
if (root.size() == 0) {
root.add(u[i]);
root.add(v[i]);
} else {
int fu = root.indexOf(u[i]);
int fv = root.indexOf(v[i]);
if (fu == -1 && fv == -1) {
System.out.println("NO");
System.exit(0);
}
if (root.size() == 2) {
root.clear();
root.add((fu != -1) ? u[i] : v[i]);
}
}
}
if (size[pu] > size[pv]) {
size[pu] += size[pv];
parent[pv] = pu;
} else {
size[pv] += size[pu];
parent[pu] = pv;
}
}
System.out.println("YES");
if (root.size() == 0)
System.out.println(1);
else
System.out.println(root.get(0) + 1);
}
private static int findParent(int i) {
if (parent[i] != parent[parent[i]])
parent[i] = findParent(parent[i]);
return parent[i];
}
} | 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 | 978e2e72860349bcf46cedf70f33ce94 | train_001.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 |
/**
* Date: 12 Nov, 2018
* Link:
*
* @author Prasad-Chaudhari
* @linkedIn: https://www.linkedin.com/in/prasad-chaudhari-841655a6/
* @git: https://github.com/Prasad-Chaudhari
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.Stack;
public class newProgram1 {
public static void main(String[] args) throws IOException {
// TODO code application logic here
FastIO in = new FastIO();
int n = in.ni();
int adja[][] = in.gg(n, n - 1);
int colors[] = in.gia(n);
// int freq[] = new int[100001];
// for (int i : colors) {
// freq[i]++;
// }
int root1 = -1;
int root2 = -1;
for (int i = 1; i <= n; i++) {
for (int j : adja[i]) {
if (colors[i - 1] != colors[j - 1]) {
root1 = i;
root2 = j;
break;
}
}
}
// System.out.println(root1 + " " + root2);
if (root1 == -1) {
System.out.println("YES 1");
return;
}
boolean b[] = new boolean[n + 1];
boolean all_same[] = new boolean[n + 1];
Stack<Integer> st = new Stack<>();
for (int i : adja[root1]) {
// Arrays.fill(b, false);
st.push(i);
b[i] = true;
while (!st.isEmpty()) {
int root = st.pop();
if (root != root1) {
for (int j : adja[root]) {
if (j != root1 && !b[j]) {
b[j] = true;
st.push(j);
if (colors[j - 1] != colors[i - 1]) {
all_same[i] = true;
}
}
}
}
}
}
boolean ans = false;
for (int i : adja[root1]) {
// System.out.println(i + " " + all_same[i]);
ans |= all_same[i];
}
if (!ans) {
System.out.println("YES " + root1);
return;
}
System.out.println("");
Arrays.fill(all_same, false);
Arrays.fill(b, false);
for (int i : adja[root2]) {
st.push(i);
b[i] = true;
while (!st.isEmpty()) {
int root = st.pop();
if (root != root2) {
for (int j : adja[root]) {
if (j != root2 && !b[j]) {
b[j] = true;
st.push(j);
if (colors[j - 1] != colors[i - 1]) {
// System.out.println(i + " " + j);
all_same[i] = true;
}
}
}
}
}
}
ans = false;
for (int i : adja[root2]) {
// System.out.println(i + " " + all_same[i]);
ans |= all_same[i];
}
if (!ans) {
System.out.println("YES " + root2);
return;
}
System.out.println("NO");
}
static class FastIO {
private final BufferedReader br;
private final BufferedWriter bw;
private String s[];
private int index;
private StringBuilder sb;
public FastIO() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out, "UTF-8"));
s = br.readLine().split(" ");
sb = new StringBuilder();
index = 0;
}
public int ni() throws IOException {
return Integer.parseInt(nextToken());
}
public double nd() throws IOException {
return Double.parseDouble(nextToken());
}
public long nl() throws IOException {
return Long.parseLong(nextToken());
}
public String next() throws IOException {
return nextToken();
}
public String nli() throws IOException {
try {
return br.readLine();
} catch (IOException ex) {
}
return null;
}
public int[] gia(int n) throws IOException {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}
public int[] gia(int n, int start, int end) throws IOException {
validate(n, start, end);
int a[] = new int[n];
for (int i = start; i < end; i++) {
a[i] = ni();
}
return a;
}
public double[] gda(int n) throws IOException {
double a[] = new double[n];
for (int i = 0; i < n; i++) {
a[i] = nd();
}
return a;
}
public double[] gda(int n, int start, int end) throws IOException {
validate(n, start, end);
double a[] = new double[n];
for (int i = start; i < end; i++) {
a[i] = nd();
}
return a;
}
public long[] gla(int n) throws IOException {
long a[] = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nl();
}
return a;
}
public long[] gla(int n, int start, int end) throws IOException {
validate(n, start, end);
long a[] = new long[n];
for (int i = start; i < end; i++) {
a[i] = nl();
}
return a;
}
public int[][] gg(int n, int m) throws IOException {
int adja[][] = new int[n + 1][];
int from[] = new int[m];
int to[] = new int[m];
int count[] = new int[n + 1];
for (int i = 0; i < m; i++) {
from[i] = ni();
to[i] = ni();
count[from[i]]++;
count[to[i]]++;
}
for (int i = 0; i <= n; i++) {
adja[i] = new int[count[i]];
}
for (int i = 0; i < m; i++) {
adja[from[i]][--count[from[i]]] = to[i];
adja[to[i]][--count[to[i]]] = from[i];
}
return adja;
}
public void print(String s) throws IOException {
bw.write(s);
}
public void println(String s) throws IOException {
bw.write(s);
bw.newLine();
}
private String nextToken() throws IndexOutOfBoundsException, IOException {
if (index == s.length) {
s = br.readLine().split(" ");
index = 0;
}
return s[index++];
}
private void validate(int n, int start, int end) {
if (start < 0 || end >= n) {
throw new IllegalArgumentException();
}
}
}
static class Data implements Comparable<Data> {
int a, b;
public Data(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(Data o) {
if (a == o.a) {
return Integer.compare(b, o.b);
}
return Integer.compare(a, o.a);
}
public static void sort(int a[]) {
Data d[] = new Data[a.length];
for (int i = 0; i < a.length; i++) {
d[i] = new Data(a[i], 0);
}
Arrays.sort(d);
for (int i = 0; i < a.length; i++) {
a[i] = d[i].a;
}
}
}
}
| 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 | 0ed61694292a3cccd5851f00d70af820 | train_001.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.Scanner;
public class _763A {
static ArrayList<Integer> adj[];
static int n,c[];
static boolean vis[];
static boolean check(int i,int value)
{
vis[i] = true;
ArrayList<Integer> child = adj[i];
boolean flag = true;
for(Integer j : child)
{
if(vis[j])
continue;
if(c[j] != value)
flag = flag & false;
else
flag = flag & check(j , value);
}
return flag;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
adj = new ArrayList[n];
for(int i=0;i<n;i++)
adj[i] = new ArrayList<Integer>();
c = new int[n];
for(int i=1;i<n;i++)
{
int u = scanner.nextInt() - 1;
int v = scanner.nextInt() - 1;
adj[u].add(v);
adj[v].add(u);
}
boolean ff = true;
for(int i=0;i<n;i++)
{
c[i] = scanner.nextInt();
if(i>0)
{
if(c[i] != c[i-1])
ff = false;
}
}
if(ff)
{
System.out.println("YES");
System.out.println("1");
}
else
{
int count[] = new int[n];
int tot=0;
for(int i=0;i<n-1;i++)
{
for(Integer j : adj[i])
{
if(c[i] != c[j])
{
count[i]++;
count[j]++;
tot++;
}
}
}
for(int i=0;i<n;i++)
{
if(count[i] == tot)
{
System.out.println("YES");
System.out.println(i+1);
System.exit(0);
}
}
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 | 6db3dd808613a655b469767b6ffe8089 | train_001.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.io.*;
import java.math.BigInteger;
import java.util.StringTokenizer;
public class ssta3 {
static PrintWriter out;
static BufferedReader in;
static StringTokenizer st;
public static void main(String[] args) throws FileNotFoundException {
//out = new PrintWriter("test.out");
//in = new BufferedReader(new FileReader("test.in"));
out = new PrintWriter(System.out);
in = new BufferedReader(new InputStreamReader(System.in));
new ssta3().Run();
out.close();
}
String ns() {
try {
if (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
} catch (Exception e) {
return null;
}
}
int nextint() {
return Integer.valueOf(ns());
}
int n = nextint();
int[] first = new int[n];
int[] second = new int[n];
public void Run() {
for (int i = 0; i < n - 1; i++) {
first[i] = nextint() - 1;
second[i] = nextint() - 1;
}
int[] colors = new int[n];
for (int i = 0; i < n; i++) {
colors[i] = nextint();
}
int[] dif = new int[n];
int cursor = 0;
for (int i = 0; i < n; i++) {
if (colors[first[i]] != colors[second[i]]) {
cursor++;
dif[first[i]]++;
dif[second[i]]++;
}
}
for (int i = 0; i < n; i++) {
if (dif[i] == cursor) {
out.println("YES");
out.println(i + 1);
return;
}
}
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 | 6cd2846e2e11d02ca7b34e68a691c044 | train_001.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 | /* / οΎοΎβ β β β β β β β β β β β γ
/ )\β β β β β β β β β β β β Y
(β β | ( Ν‘Β° ΝΚ Ν‘Β°οΌβ β(β γ
(β οΎβ Y βγ½-γ __οΌ
| _β qγ| γq |/
(β γΌ '_δΊΊ`γΌ οΎ
β |\ οΏ£ _δΊΊ'彑οΎ
β )\β β qβ β /
β β (\β #β /
β /β β β /α½£====================D-
/β β β /β \ \β β \
( (β )β β β β ) ).β )
(β β )β β β β β ( | /
|β /β β β β β β | /
[_] β β β β β [___] */
// Main Code at the Bottom
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
public class Main {
//Fast IO class
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
boolean env=System.getProperty("ONLINE_JUDGE") != null;
if(!env) {
try {
br=new BufferedReader(new FileReader("src\\input.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else 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 long MOD=1000000000+7;
//Euclidean Algorithm
static long gcd(long A,long B){
return (B==0)?A:gcd(B,A%B);
}
//Modular Exponentiation
static long fastExpo(long x,long n){
if(n==0) return 1;
if((n&1)==0) return fastExpo((x*x)%MOD,n/2)%MOD;
return ((x%MOD)*fastExpo((x*x)%MOD,(n-1)/2))%MOD;
}
//Modular Inverse
static long inverse(long x) {
return fastExpo(x,MOD-2);
}
//Prime Number Algorithm
static boolean isPrime(long n){
if(n<=1) return false;
if(n<=3) return true;
if(n%2==0 || n%3==0) return false;
for(int i=5;i*i<=n;i+=6) if(n%i==0 || n%(i+2)==0) return false;
return true;
}
//Reverse an array
static void reverse(int arr[],int l,int r){
while(l<r) {
int tmp=arr[l];
arr[l++]=arr[r];
arr[r--]=tmp;
}
}
//Print array
static void print1d(int arr[]) {
out.println(Arrays.toString(arr));
}
static void print2d(int arr[][]) {
for(int a[]: arr) out.println(Arrays.toString(a));
}
// Pair
static class pair{
int x,y;
pair(int a,int b){
this.x=a;
this.y=b;
}
public boolean equals(Object obj) {
if(obj == null || obj.getClass()!= this.getClass()) return false;
pair p = (pair) obj;
return (this.x==p.x && this.y==p.y);
}
public int hashCode() {
return Objects.hash(x,y);
}
}
static FastReader sc=new FastReader();
static PrintWriter out=new PrintWriter(System.out);
//Main function(The main code starts from here)
static int V,parent[],color[],total;
static ArrayList<Integer> graph[];
static void init(int n){
V=n;
graph=new ArrayList[V];
parent=new int[V];
color=new int[V];
for(int i=0;i<V;i++) graph[i]=new ArrayList<>();
for(int i=0;i<V;i++) parent[i]=i;
}
static void addEdge(int src,int dest){
graph[src].add(dest);
graph[dest].add(src);
}
static int find(int x) {
if(parent[x]==x) return x;
return parent[x]=find(parent[x]);
}
static void dfs(int s,int p) {
if(p!=-1 && color[p]==color[s]) parent[s]=p;
for(Integer x: graph[s]) {
if(x==p) continue;
dfs(x,s);
}
}
static int dfs2(int s,int p) {
HashSet<Integer> set=new HashSet<>();
set.add(find(s));
for(Integer x: graph[s]) {
set.add(find(x));
if(x==p) continue;
int val=dfs2(x,s);
if(val!=-1) return val;
}
if(set.size()==total) return s;
return -1;
}
public static void main (String[] args) throws java.lang.Exception {
int test;
test=1;
//test=sc.nextInt();
while(test-->0){
int n=sc.nextInt();
init(n);
for(int i=0;i<n-1;i++) addEdge(sc.nextInt()-1,sc.nextInt()-1);
for(int i=0;i<n;i++) color[i]=sc.nextInt();
dfs(0,-1);
total=0;
for(int i=0;i<n;i++) if(parent[i]==i) total++;
int ans=dfs2(0,-1);
if(ans==-1) out.println("NO");
else out.println("YES\n"+(ans+1));
}
out.flush();
out.close();
}
} | 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 | 5c91149535f0e4114dedcbecd91a5ce7 | train_001.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.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.LinkedList;
import java.util.Queue;
public class A {
public static void main(String[] args){
FastScannerA sc = new FastScannerA(System.in);
int V = sc.nextInt();
Vertex[] ver = new Vertex[V];
for(int i = 0; i<V; i++) ver[i] = new Vertex();
for(int i = 1; i<V; i++){
int a = sc.nextInt() - 1;
int b = sc.nextInt() - 1;
ver[a].edges.add(b);
ver[b].edges.add(a);
}
for(int i = 0; i<V; i++) ver[i].color = sc.nextInt();
ArrayList<Pair> pairs = new ArrayList<>();
Queue<Integer> q = new LinkedList<>();
q.add(0);
ver[0].visited = true;
while(!q.isEmpty()){
int current = q.remove();
for(int i : ver[current].edges){
if(!ver[i].visited){
q.add(i);
ver[i].visited = true;
if(ver[current].color != ver[i].color) pairs.add(new Pair(current, i));
}
}
}
//for(Pair p : pairs) System.out.println(p.a + " " + p.b);
if(pairs.size() == 0){
System.out.println("YES\n1");
}
else if(pairs.size() == 1){
System.out.println("YES");
System.out.println(pairs.get(0).a + 1);
}
else{
Pair p1 = pairs.get(0);
Pair p2 = pairs.get(1);
int a = p1.a;
int b = p1.b;
int c = p2.a;
int d = p2.b;
if(a != c && a != d && b != c && b != d){
System.out.println("NO");
}
else{
int check = -1;
if(a == c || a == d) check = a;
else check = b;
boolean right = true;
for(Pair p : pairs){
if(p.a != check && p.b != check){
right = false;
break;
}
}
if(right){
System.out.println("YES");
System.out.println(check + 1);
}
else{
System.out.println("NO");
}
}
}
}
}
class Vertex{
ArrayList<Integer> edges;
boolean visited;
int color;
Vertex(){
visited = false;
edges = new ArrayList<>();
}
}
class Pair{
int a;
int b;
Pair(int aa, int bb){
a = aa;
b = bb;
}
}
class FastScannerA{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastScannerA(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String next()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isLineEndChar(c));
return res.toString();
}
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 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 boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isLineEndChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == '\n' || c == '\r' || 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 | 3d0943496a8c975116bbb10e1c56d406 | train_001.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.*;
import java.io.*;
public class A
{
public static void main(String[] args) throws Exception
{
PrintWriter out = new PrintWriter(System.out);
new A(new FastScanner(System.in), out);
out.close();
}
public A(FastScanner in, PrintWriter out)
{
int N = in.nextInt();
Graph g = new Graph(N);
for (int u=1; u<N; u++)
{
int i = in.nextInt()-1;
int j = in.nextInt()-1;
g.add(i, j);
}
DisjointSet ds = new DisjointSet(N);
int[] color = new int[N];
for (int i=0; i<N; i++)
color[i] = in.nextInt();
for (int i=0; i<N; i++)
for (int j : g.adj[i])
if (color[i] == color[j])
ds.union(i, j);
TreeSet<Integer> reps = new TreeSet<>();
for (int i=0; i<N; i++)
reps.add(ds.find(i));
TreeSet<Integer> others = new TreeSet<>();
int numCenters = 0;
int centerNode = -1;
for (int i=0; i<N; i++)
{
others.clear();
others.add(ds.find(i));
for (int j : g.adj[i])
others.add(ds.find(j));
//out.printf("%d -> %s%n", i, others);
if (others.size() == reps.size())
centerNode = i;
}
if (centerNode == -1)
out.println("NO");
else
out.printf("YES%n%d%n", centerNode+1);
}
}
class Graph
{
int N;
ArrayList<Integer>[] adj;
Graph(int NN)
{
adj = new ArrayList[N=NN];
for (int i=0; i<N; i++)
adj[i] = new ArrayList<>();
}
void add(int i, int j)
{
adj[i].add(j);
adj[j].add(i);
}
}
class DisjointSet {
int[] p, r;
DisjointSet(int s) {
p = new int[s];
r = new int[s];
for(int i=0; i<s; i++)
p[i] = i;
}
void union(int x, int y) {
int a = find(x);
int b = find(y);
if(a==b) return;
if(r[a] == r[b])
r[p[b]=a]++;
else
p[a]=p[b]=r[a]<r[b]?b:a;
}
int find(int x) {
return p[x]=p[x]==x?x:find(p[x]);
}
}
class FastScanner{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastScanner(InputStream stream)
{
this.stream = stream;
}
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++];
}
boolean isSpaceChar(int c)
{
return c==' '||c=='\n'||c=='\r'||c=='\t'||c==-1;
}
boolean isEndline(int c)
{
return c=='\n'||c=='\r'||c==-1;
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
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();
}
String nextLine(){
int c = read();
while (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do{
res.appendCodePoint(c);
c = read();
}while(!isEndline(c));
return res.toString();
}
}
| 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 | ef24770a82486a4b5fce3155c61d2859 | train_001.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 Contest395_1A {
static class pair
{
public int a, b;
public pair(int x, int y) { a=x; b=y;}
public boolean in(int n) { return (n == a || n == b); }
}
public static void main(String[] werwerwea)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
ArrayList<pair> e = new ArrayList<pair>();
int[] c = new int[n+1];
for (int i=0; i<n-1; ++i)
e.add(new pair(sc.nextInt(), sc.nextInt()));
for (int i=1; i<=n; ++i)
c[i] = sc.nextInt();
ArrayList<ArrayList<Integer>> mat =
new ArrayList<ArrayList<Integer>>();
for (int i=0; i<=n; ++i) mat.add(new ArrayList<Integer>());
for (pair p : e)
{
mat.get(p.a).add(p.b);
mat.get(p.b).add(p.a);
}
sc.close();
// for each edge with different colors,
// Tim must choose one of them to hold; else auto fail
int i = 0, j = 0;
ArrayList<pair> bad = new ArrayList<pair>();
for (pair p : e)
{
if (c[p.a] != c[p.b] )
{
bad.add(p);
i = p.a; j = p.b;
}
}
// if no bad edges, then all verts are same color, so done
if (bad.isEmpty()) { System.out.println("YES\n1"); return; }
// else we have to dangle tree by all possible vertices (i? j?)
ArrayList<Integer> poss = new ArrayList<Integer>();
boolean good = true;
for (pair p : bad)
if (!p.in(i))
good = false;
if (good) { poss.add(i); }
good = true;
for (pair p : bad)
if (!p.in(j))
good = false;
if (good) { poss.add(j); }
// now test whichever ones are possible by BFS
for (int k : poss)
// BFS down all the neighbors of k, never going back to k
for (int m : mat.get(k))
{
boolean stillGoing = true;
ArrayList<Integer> verts = new ArrayList<Integer>();
verts.add(m);
boolean[] explored = new boolean[n+1];
explored[m] = true;
explored[k] = true;
while (stillGoing)
{
ArrayList<Integer> new_verts = new ArrayList<Integer>();
for (int m0 : verts)
for (int neigh : mat.get(m0))
if (!explored[neigh])
{
explored[neigh] = true;
new_verts.add(neigh);
}
if (new_verts.isEmpty()) stillGoing = false;
else for (int m1 : new_verts) { verts.add(m1); }
}
boolean works = true;
for (int m0 : verts)
if (c[m0] != c[verts.get(0)])
works = false;
if (works) {System.out.println("YES\n"+
Integer.toString(k)); return;}
}
System.out.println("NO"); return;
}
} | 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 | 59024b09a9f7841cc031f68112e38126 | train_001.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.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author MaxHeap
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TimpfeyAndTree solver = new TimpfeyAndTree();
solver.solve(1, in, out);
out.close();
}
static class TimpfeyAndTree {
ArrayList<Integer>[] tree;
int[] color;
boolean dfs(int src, int parent, int depth) {
if (parent != -1) {
if (depth > 1 && color[src] != color[parent]) {
return false;
}
}
boolean ans = true;
for (int i : tree[src]) {
if (i == parent) continue;
ans &= dfs(i, src, depth + 1);
}
return ans;
}
public void solve(int testNumber, FastReader in, PrintWriter out) {
int n = in.nextInt();
color = new int[n + 1];
tree = new ArrayList[n + 1];
for (int i = 0; i < n + 1; i++) tree[i] = new ArrayList<>();
ArrayList<IntPair> list = new ArrayList<>();
for (int i = 0; i < n - 1; i++) {
int from = in.nextInt();
int to = in.nextInt();
tree[from].add(to);
tree[to].add(from);
list.add(new IntPair(from, to));
}
for (int i = 1; i <= n; i++) {
color[i] = in.nextInt();
}
int root1 = -1, root2 = -1;
for (int i = 0; i < list.size(); i++) {
if (color[list.get(i).getFirst()] != color[list.get(i).getSecond()]) {
root1 = list.get(i).getFirst();
root2 = list.get(i).getSecond();
break;
}
}
if (root1 == -1 && root2 == -1) {
out.println("YES");
out.println(n);
return;
}
if (dfs(root1, -1, 0)) {
out.println("YES");
out.println(root1);
} else if (dfs(root2, -1, 0)) {
out.println("YES");
out.println(root2);
} else {
out.println("NO");
}
}
}
static class FastReader {
BufferedReader reader;
StringTokenizer st;
public FastReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
st = null;
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
String line = reader.readLine();
if (line == null) {
return null;
}
st = new StringTokenizer(line);
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
static class IntPair implements Comparable<IntPair> {
int first;
int second;
public IntPair(int first, int second) {
this.first = first;
this.second = second;
}
public int compareTo(IntPair a) {
if (second == a.second) {
return Integer.compare(first, a.first);
}
return Integer.compare(second, a.second);
}
public String toString() {
return "<" + first + ", " + second + ">";
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
IntPair a = (IntPair) o;
if (first != a.first) return false;
return second == a.second;
}
public int hashCode() {
int result = first;
result = 31 * result + second;
return result;
}
public int getFirst() {
return first;
}
public int getSecond() {
return second;
}
}
}
| 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 | 7df6875a22009c9454f06a2826a77a06 | train_001.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.io.*;
import java.lang.reflect.Array;
import java.util.*;
public class icpc
{
public static void main(String[] args) throws IOException
{
Reader in = new Reader();
//BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = in.nextInt();
ArrayList<Integer>[] adj = (ArrayList<Integer>[])new ArrayList[n];
for (int i=0;i<n;i++)
adj[i] = new ArrayList<>();
int[] to = new int[n - 1];
int[] fro = new int[n - 1];
for (int i=0;i< n - 1;i++)
{
int a = in.nextInt() - 1;
int b = in.nextInt() - 1;
to[i] = a;
fro[i] = b;
adj[a].add(b);
adj[b].add(a);
}
int[] color = new int[n];
for (int i=0;i<n;i++)
color[i] = in.nextInt();
int ans = -1;
boolean flag = false;
for (int i=0;i<n - 1;i++)
{
if (color[to[i]] != color[fro[i]])
{
flag = true;
if (DFS(adj, to[i], color))
{
ans = to[i];
break;
}
else if (DFS(adj, fro[i], color))
{
ans = fro[i];
break;
}
break;
}
}
if (flag)
{
if (ans == -1)
System.out.println("NO");
else
System.out.println("YES\n" + (ans + 1));
}
else
System.out.println("YES\n1");
}
public static boolean DFS(ArrayList<Integer>[] adj, int u, int[] color)
{
int n = adj.length;
boolean[] visited = new boolean[n];
for (int i=0;i<adj[u].size();i++)
{
HashSet<Integer> h = new HashSet<>();
explore(adj, visited, adj[u].get(i), h, u, color);
if (h.size() > 1)
return false;
}
return true;
}
public static void explore(ArrayList<Integer>[] adj, boolean[] visited, int v, HashSet<Integer> h, int source, int[] color)
{
visited[v] = true;
h.add(color[v]);
for (int i=0;i<adj[v].size();i++)
{
if (!visited[adj[v].get(i)] && adj[v].get(i) != source)
{
explore(adj, visited, adj[v].get(i), h, source, color);
}
}
}
}
class DSU
{
int[] parent;
int[] size;
//Pass number of total nodes as parameter to the constructor
DSU(int n)
{
this.parent = new int[n];
this.size = new int[n];
Arrays.fill(parent, -1);
}
public void makeSet(int v)
{
parent[v] = v;
size[v] = 1;
}
public int findSet(int v)
{
if (v == parent[v]) return v;
return parent[v] = findSet(parent[v]);
}
public void unionSets(int a, int b)
{
a = findSet(a);
b = findSet(b);
if (a != b)
{
if (size[a] < size[b])
{
int temp = a;
a = b;
b = temp;
}
parent[b] = a;
size[a] += size[b];
}
}
}
class FastFourierTransform
{
private void fft(double[] a, double[] b, boolean invert)
{
int count = a.length;
for (int i = 1, j = 0; i < count; i++)
{
int bit = count >> 1;
for (; j >= bit; bit >>= 1)
j -= bit;
j += bit;
if (i < j)
{
double temp = a[i];
a[i] = a[j];
a[j] = temp;
temp = b[i];
b[i] = b[j];
b[j] = temp;
}
}
for (int len = 2; len <= count; len <<= 1)
{
int halfLen = len >> 1;
double angle = 2 * Math.PI / len;
if (invert)
angle = -angle;
double wLenA = Math.cos(angle);
double wLenB = Math.sin(angle);
for (int i = 0; i < count; i += len)
{
double wA = 1;
double wB = 0;
for (int j = 0; j < halfLen; j++)
{
double uA = a[i + j];
double uB = b[i + j];
double vA = a[i + j + halfLen] * wA - b[i + j + halfLen] * wB;
double vB = a[i + j + halfLen] * wB + b[i + j + halfLen] * wA;
a[i + j] = uA + vA;
b[i + j] = uB + vB;
a[i + j + halfLen] = uA - vA;
b[i + j + halfLen] = uB - vB;
double nextWA = wA * wLenA - wB * wLenB;
wB = wA * wLenB + wB * wLenA;
wA = nextWA;
}
}
}
if (invert)
{
for (int i = 0; i < count; i++)
{
a[i] /= count;
b[i] /= count;
}
}
}
public long[] multiply(long[] a, long[] b)
{
int resultSize = Integer.highestOneBit(Math.max(a.length, b.length) - 1) << 2;
resultSize = Math.max(resultSize, 1);
double[] aReal = new double[resultSize];
double[] aImaginary = new double[resultSize];
double[] bReal = new double[resultSize];
double[] bImaginary = new double[resultSize];
for (int i = 0; i < a.length; i++)
aReal[i] = a[i];
for (int i = 0; i < b.length; i++)
bReal[i] = b[i];
fft(aReal, aImaginary, false);
fft(bReal, bImaginary, false);
for (int i = 0; i < resultSize; i++)
{
double real = aReal[i] * bReal[i] - aImaginary[i] * bImaginary[i];
aImaginary[i] = aImaginary[i] * bReal[i] + bImaginary[i] * aReal[i];
aReal[i] = real;
}
fft(aReal, aImaginary, true);
long[] result = new long[resultSize];
for (int i = 0; i < resultSize; i++)
result[i] = Math.round(aReal[i]);
return result;
}
}
class NumberTheory
{
public boolean isPrime(long n)
{
if(n < 2)
return false;
for(long x = 2;x * x <= n;x++)
{
if(n % x == 0)
return false;
}
return true;
}
public ArrayList<Long> primeFactorisation(long n)
{
ArrayList<Long> f = new ArrayList<>();
for(long x=2;x * x <= n;x++)
{
while(n % x == 0)
{
f.add(x);
n /= x;
}
}
if(n > 1)
f.add(n);
return f;
}
public int[] sieveOfEratosthenes(int n)
{
//Returns an array with the smallest prime factor for each number and primes marked as 0
int[] sieve = new int[n + 1];
for(int x=2;x * x <= n;x++)
{
if(sieve[x] != 0)
continue;
for(int u=x*x;u<=n;u+=x)
{
if(sieve[u] == 0)
{
sieve[u] = x;
}
}
}
return sieve;
}
public long gcd(long a, long b)
{
if(b == 0)
return a;
return gcd(b, a % b);
}
public long phi(long n)
{
double result = n;
for(long p=2;p*p<=n;p++)
{
if(n % p == 0)
{
while (n % p == 0)
n /= p;
result *= (1.0 - (1.0 / (double)p));
}
}
if(n > 1)
result *= (1.0 - (1.0 / (double)n));
return (long)result;
}
public Name extendedEuclid(long a, long b)
{
if(b == 0)
return new Name(a, 1, 0);
Name n1 = extendedEuclid(b, a % b);
Name n2 = new Name(n1.d, n1.y, n1.x - (long)Math.floor((double)a / b) * n1.y);
return n2;
}
public long modularExponentiation(long a, long b, long n)
{
long d = 1L;
String bString = Long.toBinaryString(b);
for(int i=0;i<bString.length();i++)
{
d = (d * d) % n;
if(bString.charAt(i) == '1')
d = (d * a) % n;
}
return d;
}
}
class Name
{
long d;
long x;
long y;
public Name(long d, long x, long y)
{
this.d = d;
this.x = x;
this.y = y;
}
}
class SuffixArray
{
int ALPHABET_SZ = 256, N;
int[] T, lcp, sa, sa2, rank, tmp, c;
public SuffixArray(String str)
{
this(toIntArray(str));
}
private static int[] toIntArray(String s)
{
int[] text = new int[s.length()];
for (int i = 0; i < s.length(); i++) text[i] = s.charAt(i);
return text;
}
public SuffixArray(int[] text)
{
T = text;
N = text.length;
sa = new int[N];
sa2 = new int[N];
rank = new int[N];
c = new int[Math.max(ALPHABET_SZ, N)];
construct();
kasai();
}
private void construct()
{
int i, p, r;
for (i = 0; i < N; ++i) c[rank[i] = T[i]]++;
for (i = 1; i < ALPHABET_SZ; ++i) c[i] += c[i - 1];
for (i = N - 1; i >= 0; --i) sa[--c[T[i]]] = i;
for (p = 1; p < N; p <<= 1)
{
for (r = 0, i = N - p; i < N; ++i) sa2[r++] = i;
for (i = 0; i < N; ++i) if (sa[i] >= p) sa2[r++] = sa[i] - p;
Arrays.fill(c, 0, ALPHABET_SZ, 0);
for (i = 0; i < N; ++i) c[rank[i]]++;
for (i = 1; i < ALPHABET_SZ; ++i) c[i] += c[i - 1];
for (i = N - 1; i >= 0; --i) sa[--c[rank[sa2[i]]]] = sa2[i];
for (sa2[sa[0]] = r = 0, i = 1; i < N; ++i)
{
if (!(rank[sa[i - 1]] == rank[sa[i]]
&& sa[i - 1] + p < N
&& sa[i] + p < N
&& rank[sa[i - 1] + p] == rank[sa[i] + p])) r++;
sa2[sa[i]] = r;
}
tmp = rank;
rank = sa2;
sa2 = tmp;
if (r == N - 1) break;
ALPHABET_SZ = r + 1;
}
}
private void kasai()
{
lcp = new int[N];
int[] inv = new int[N];
for (int i = 0; i < N; i++) inv[sa[i]] = i;
for (int i = 0, len = 0; i < N; i++)
{
if (inv[i] > 0)
{
int k = sa[inv[i] - 1];
while ((i + len < N) && (k + len < N) && T[i + len] == T[k + len]) len++;
lcp[inv[i] - 1] = len;
if (len > 0) len--;
}
}
}
}
class ZAlgorithm
{
public int[] calculateZ(char input[])
{
int Z[] = new int[input.length];
int left = 0;
int right = 0;
for(int k = 1; k < input.length; k++) {
if(k > right) {
left = right = k;
while(right < input.length && input[right] == input[right - left]) {
right++;
}
Z[k] = right - left;
right--;
} else {
//we are operating inside box
int k1 = k - left;
//if value does not stretches till right bound then just copy it.
if(Z[k1] < right - k + 1) {
Z[k] = Z[k1];
} else { //otherwise try to see if there are more matches.
left = k;
while(right < input.length && input[right] == input[right - left]) {
right++;
}
Z[k] = right - left;
right--;
}
}
}
return Z;
}
public ArrayList<Integer> matchPattern(char text[], char pattern[])
{
char newString[] = new char[text.length + pattern.length + 1];
int i = 0;
for(char ch : pattern) {
newString[i] = ch;
i++;
}
newString[i] = '$';
i++;
for(char ch : text) {
newString[i] = ch;
i++;
}
ArrayList<Integer> result = new ArrayList<>();
int Z[] = calculateZ(newString);
for(i = 0; i < Z.length ; i++) {
if(Z[i] == pattern.length) {
result.add(i - pattern.length - 1);
}
}
return result;
}
}
class KMPAlgorithm
{
public int[] computeTemporalArray(char[] pattern)
{
int[] lps = new int[pattern.length];
int index = 0;
for(int i=1;i<pattern.length;)
{
if(pattern[i] == pattern[index])
{
lps[i] = index + 1;
index++;
i++;
}
else
{
if(index != 0)
{
index = lps[index - 1];
}
else
{
lps[i] = 0;
i++;
}
}
}
return lps;
}
public ArrayList<Integer> KMPMatcher(char[] text, char[] pattern)
{
int[] lps = computeTemporalArray(pattern);
int j = 0;
int i = 0;
int n = text.length;
int m = pattern.length;
ArrayList<Integer> indices = new ArrayList<>();
while(i < n)
{
if(pattern[j] == text[i])
{
i++;
j++;
}
if(j == m)
{
indices.add(i - j);
j = lps[j - 1];
}
else if(i < n && pattern[j] != text[i])
{
if(j != 0)
j = lps[j - 1];
else
i = i + 1;
}
}
return indices;
}
}
class Hashing
{
public long[] computePowers(long p, int n, long m)
{
long[] powers = new long[n];
powers[0] = 1;
for(int i=1;i<n;i++)
{
powers[i] = (powers[i - 1] * p) % m;
}
return powers;
}
public long computeHash(String s)
{
long p = 31;
long m = 1_000_000_009;
long hashValue = 0L;
long[] powers = computePowers(p, s.length(), m);
for(int i=0;i<s.length();i++)
{
char ch = s.charAt(i);
hashValue = (hashValue + (ch - 'a' + 1) * powers[i]) % m;
}
return hashValue;
}
}
class BasicFunctions
{
public long min(long[] A)
{
long min = Long.MAX_VALUE;
for(int i=0;i<A.length;i++)
{
min = Math.min(min, A[i]);
}
return min;
}
public long max(long[] A)
{
long max = Long.MAX_VALUE;
for(int i=0;i<A.length;i++)
{
max = Math.max(max, A[i]);
}
return max;
}
}
class MergeSortInt
{
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r) {
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
int L[] = new int[n1];
int R[] = new int[n2];
/*Copy data to temp arrays*/
for (int i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
void sort(int arr[], int l, int r) {
if (l < r) {
// Find the middle point
int m = (l + r) / 2;
// Sort first and second halves
sort(arr, l, m);
sort(arr, m + 1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
}
class MergeSortLong
{
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(long arr[], int l, int m, int r) {
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
long L[] = new long[n1];
long R[] = new long[n2];
/*Copy data to temp arrays*/
for (int i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
void sort(long arr[], int l, int r) {
if (l < r) {
// Find the middle point
int m = (l + r) / 2;
// Sort first and second halves
sort(arr, l, m);
sort(arr, m + 1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
}
class Node
{
int x;
int y;
public Node(int x, int y)
{
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object ob)
{
if(ob == null)
return false;
if(!(ob instanceof Node))
return false;
if(ob == this)
return true;
Node obj = (Node)ob;
if(this.x == obj.x && this.y == obj.y)
return true;
return false;
}
@Override
public int hashCode()
{
return (int)this.x;
}
}
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();
}
}
class FenwickTree
{
public void update(long[] fenwickTree,long delta,int index)
{
index += 1;
while(index < fenwickTree.length)
{
fenwickTree[index] += delta;
index = index + (index & (-index));
}
}
public long prefixSum(long[] fenwickTree,int index)
{
long sum = 0L;
index += 1;
while(index > 0)
{
sum += fenwickTree[index];
index -= (index & (-index));
}
return sum;
}
}
class SegmentTree
{
public int nextPowerOfTwo(int num)
{
if(num == 0)
return 1;
if(num > 0 && (num & (num - 1)) == 0)
return num;
while((num &(num - 1)) > 0)
{
num = num & (num - 1);
}
return num << 1;
}
public int[] createSegmentTree(int[] input)
{
int np2 = nextPowerOfTwo(input.length);
int[] segmentTree = new int[np2 * 2 - 1];
for(int i=0;i<segmentTree.length;i++)
segmentTree[i] = Integer.MIN_VALUE;
constructSegmentTree(segmentTree,input,0,input.length-1,0);
return segmentTree;
}
private void constructSegmentTree(int[] segmentTree,int[] input,int low,int high,int pos)
{
if(low == high)
{
segmentTree[pos] = input[low];
return;
}
int mid = (low + high)/ 2;
constructSegmentTree(segmentTree,input,low,mid,2*pos + 1);
constructSegmentTree(segmentTree,input,mid+1,high,2*pos + 2);
segmentTree[pos] = Math.max(segmentTree[2*pos + 1],segmentTree[2*pos + 2]);
}
public int rangeMinimumQuery(int []segmentTree,int qlow,int qhigh,int len)
{
return rangeMinimumQuery(segmentTree,0,len-1,qlow,qhigh,0);
}
private int rangeMinimumQuery(int segmentTree[],int low,int high,int qlow,int qhigh,int pos)
{
if(qlow <= low && qhigh >= high){
return segmentTree[pos];
}
if(qlow > high || qhigh < low){
return Integer.MIN_VALUE;
}
int mid = (low+high)/2;
return Math.max(rangeMinimumQuery(segmentTree, low, mid, qlow, qhigh, 2 * pos + 1),
rangeMinimumQuery(segmentTree, mid + 1, high, qlow, qhigh, 2 * pos + 2));
}
}
class Trie
{
private class TrieNode
{
Map<Character, TrieNode> children;
boolean endOfWord;
public TrieNode()
{
children = new HashMap<>();
endOfWord = false;
}
}
private final TrieNode root;
public Trie()
{
root = new TrieNode();
}
public void insert(String word)
{
TrieNode current = root;
for (int i = 0; i < word.length(); i++)
{
char ch = word.charAt(i);
TrieNode node = current.children.get(ch);
if (node == null)
{
node = new TrieNode();
current.children.put(ch, node);
}
current = node;
}
current.endOfWord = true;
}
public boolean search(String word)
{
TrieNode current = root;
for (int i = 0; i < word.length(); i++)
{
char ch = word.charAt(i);
TrieNode node = current.children.get(ch);
if (node == null)
{
return false;
}
current = node;
}
return current.endOfWord;
}
public void delete(String word)
{
delete(root, word, 0);
}
private boolean delete(TrieNode current, String word, int index)
{
if (index == word.length())
{
if (!current.endOfWord)
{
return false;
}
current.endOfWord = false;
return current.children.size() == 0;
}
char ch = word.charAt(index);
TrieNode node = current.children.get(ch);
if (node == null)
{
return false;
}
boolean shouldDeleteCurrentNode = delete(node, word, index + 1);
if (shouldDeleteCurrentNode)
{
current.children.remove(ch);
return current.children.size() == 0;
}
return false;
}
}
class SegmentTreeLazy
{
public int nextPowerOfTwo(int num)
{
if(num == 0)
return 1;
if(num > 0 && (num & (num - 1)) == 0)
return num;
while((num &(num - 1)) > 0)
{
num = num & (num - 1);
}
return num << 1;
}
public int[] createSegmentTree(int input[])
{
int nextPowOfTwo = nextPowerOfTwo(input.length);
int segmentTree[] = new int[nextPowOfTwo*2 -1];
for(int i=0; i < segmentTree.length; i++){
segmentTree[i] = Integer.MAX_VALUE;
}
constructMinSegmentTree(segmentTree, input, 0, input.length - 1, 0);
return segmentTree;
}
private void constructMinSegmentTree(int segmentTree[], int input[], int low, int high,int pos)
{
if(low == high)
{
segmentTree[pos] = input[low];
return;
}
int mid = (low + high)/2;
constructMinSegmentTree(segmentTree, input, low, mid, 2 * pos + 1);
constructMinSegmentTree(segmentTree, input, mid + 1, high, 2 * pos + 2);
segmentTree[pos] = Math.min(segmentTree[2*pos+1], segmentTree[2*pos+2]);
}
public void updateSegmentTreeRangeLazy(int input[], int segmentTree[], int lazy[], int startRange, int endRange, int delta)
{
updateSegmentTreeRangeLazy(segmentTree, lazy, startRange, endRange, delta, 0, input.length - 1, 0);
}
private void updateSegmentTreeRangeLazy(int segmentTree[], int lazy[], int startRange, int endRange, int delta, int low, int high, int pos)
{
if(low > high)
{
return;
}
if (lazy[pos] != 0)
{
segmentTree[pos] += lazy[pos];
if (low != high)
{
lazy[2 * pos + 1] += lazy[pos];
lazy[2 * pos + 2] += lazy[pos];
}
lazy[pos] = 0;
}
if(startRange > high || endRange < low)
{
return;
}
if(startRange <= low && endRange >= high)
{
segmentTree[pos] += delta;
if(low != high) {
lazy[2*pos + 1] += delta;
lazy[2*pos + 2] += delta;
}
return;
}
int mid = (low + high)/2;
updateSegmentTreeRangeLazy(segmentTree, lazy, startRange, endRange, delta, low, mid, 2*pos+1);
updateSegmentTreeRangeLazy(segmentTree, lazy, startRange, endRange, delta, mid+1, high, 2*pos+2);
segmentTree[pos] = Math.min(segmentTree[2*pos + 1], segmentTree[2*pos + 2]);
}
public int rangeMinimumQueryLazy(int segmentTree[], int lazy[], int qlow, int qhigh, int len)
{
return rangeMinimumQueryLazy(segmentTree, lazy, qlow, qhigh, 0, len - 1, 0);
}
private int rangeMinimumQueryLazy(int segmentTree[], int lazy[], int qlow, int qhigh, int low, int high, int pos)
{
if(low > high)
{
return Integer.MAX_VALUE;
}
if (lazy[pos] != 0)
{
segmentTree[pos] += lazy[pos];
if (low != high)
{
lazy[2 * pos + 1] += lazy[pos];
lazy[2 * pos + 2] += lazy[pos];
}
lazy[pos] = 0;
}
if(qlow > high || qhigh < low)
{
return Integer.MAX_VALUE;
}
if(qlow <= low && qhigh >= high)
{
return segmentTree[pos];
}
int mid = (low+high)/2;
return Math.min(rangeMinimumQueryLazy(segmentTree, lazy, qlow, qhigh, low, mid, 2 * pos + 1), rangeMinimumQueryLazy(segmentTree, lazy, qlow, qhigh, mid + 1, high, 2 * pos + 2));
}
} | 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 | 8971288ee84e02bd25f748ca0752adc2 | train_001.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.*;
import javafx.scene.Parent;
import java.io.*;
import java.math.BigInteger;
public class Solution {
private static int[] deg , color;
private static boolean[] vis;
private static ArrayList<Integer>[] v;
public static void run(InputReader in ,PrintWriter out){
int n = in.nextInt();
if(n <= 2){
out.println("YES\n1");
return;
}
deg = new int[n+2];
color = new int[n+2];
vis = new boolean[n+2];
v = new ArrayList[n+2];
for(int i = 0 ; i <= n ; i ++)
v[i] = new ArrayList<>();
for(int i = 0 ; i < n - 1 ; i++){
int x = in.nextInt();
int y = in.nextInt();
deg[x]++;
deg[y]++;
v[x].add(y);
v[y].add(x);
}
for(int i = 1 ; i <= n ; i ++)
color[i] = in.nextInt();
LinkedList<Integer> q = new LinkedList();
for(int i = 1 ; i <= n ; i++){
if(deg[i] == 1){
q.addLast(i);
//vis[i] = true;
}
}
int ans = 0;
while(!q.isEmpty()){
int x = q.pollFirst();
vis[x] = true;
for(int i = 0 ; i < v[x].size() ; i++){
int to = v[x].get(i);
if(color[to] == color[x] && !vis[to]){
deg[x] --;
deg[to] --;
ans = to;
if(deg[to] == 1)
q.addLast(to);
}
}
}
int numberOfOne = 0 , numberOfnonOne = 0 , degOfNone = 0 ;
for(int i = 1 ; i<= n ; i ++){
if(deg[i] == 1){
numberOfOne++;
}else if(deg[i] > 1){
numberOfnonOne++;
degOfNone = deg[i];
ans = i;
}
}
if(numberOfnonOne == 0){
out.println("YES\n" + ans);
}
else if(numberOfnonOne > 1 || numberOfOne != degOfNone){
out.println("NO");
}else {
out.println("YES\n" + ans);
}
}
public static void main(String[] args) throws FileNotFoundException {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
run(in,out);
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| 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 | 3bc5578795f2da88b944d7062dc6f27e | train_001.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.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class CandidateCode {
static ArrayList<Integer> adj[];
static int col[];
public static void main(String[] args) throws IOException {
FastReader sc = new FastReader();
int n=sc.nextInt();
adj=new ArrayList[n];
int u=-1,v=-1;
for (int i=0;i<n;i++)adj[i]=new ArrayList<>();
for (int i=0;i<n-1;i++){
int x=sc.nextInt()-1,y=sc.nextInt()-1;
adj[x].add(y);
adj[y].add(x);
}
col=new int[n];
for (int i=0;i<n;i++)col[i]=sc.nextInt();
boolean f=false;
for (int i=0;i<n;i++){
if (adj[i].isEmpty())continue;
for (int j:adj[i]){
if (col[i]!=col[j]){
u=i;v=j;
f=true;
break;
}
}
if (f)break;
}
if (!f) {
System.out.println("YES");
System.out.println(1);
}
else {
f=true;
for (int x:adj[v]){
if (!dfs(x,v)){
f=false;
break;
}
}
if (f) {
System.out.println("YES");
System.out.println(v+1);
return;
}
for (int x:adj[u]){
if (!dfs(x,u)){
System.out.println("NO");
return;
}
}
System.out.println("YES");
System.out.println(u+1);
}
}
static boolean dfs(int v,int par){
for (int u:adj[v]){
if (u!=par){
if (col[v]!=col[u])return false;
boolean x=dfs(u,v);
if (!x)return false;
}
}
return true;
}
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 | ["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 | 3a1e0210987f8fd08aba517acecf3830 | train_001.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.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
private final static Random rnd = new Random();
final static long INF = Long.MAX_VALUE;
boolean checkIndex(int index, int size) {
return (0 <= index && index < size);
}
class Edge {
int to;
long w;
void Edge(int to, long w) {
this.to = to;
this.w = w;
}
}
// ======================================================
ArrayList<Integer> graph[];
int[] c;
int[] parentColor;
void solve() throws IOException {
int n = rI();
this.graph = new ArrayList[n];
for (int i = 0; i < n; i++) {
graph[i] = new ArrayList<Integer>();
}
for (int i = 0; i < n - 1; i++) {
int a = rI() - 1;
int b = rI() - 1;
graph[a].add(b);
graph[b].add(a);
}
this.parentColor = new int[n];
this.c = rA(n);
this.used = new boolean[n];
this.listForCheckSecond = new ArrayList<Integer>();
this.listForCheckFirst = new ArrayList<Integer>();
this.edge = 0;
this.firstColor = c[0];
this.secondColor = -2;
this.f = false;
dfs(0);
if (!f) {
out.println("YES");
out.println(edge + 1);
} else {
out.println("NO");
}
}
int edge;
boolean[] used;
ArrayList<Integer> listForCheckSecond;
ArrayList<Integer> listForCheckFirst;
int firstColor;
int secondColor;
boolean f;
// =======================================================
void dfs(int from) {
used[from] = true;
for (int i : graph[from]) {
if (!used[i]) {
if (c[i] != firstColor) {
if (edge == 0) {
edge = i;
Arrays.fill(used, false);
edge = from;
dfs2(from);
if (f) {
f = false;
edge = i;
Arrays.fill(used, false);
dfs2(i);
}
} else {
f = true;
return;
}
} else {
dfs(i);
}
}
}
}
void dfs2(int from) {
used[from] = true;
for (int i : graph[from]) {
if (!used[i]) {
if (from == edge || c[from] == c[i]) {
dfs2(i);
} else {
f = true;
return;
}
}
}
}
// =======================================================
// ---------------------------------
// --------------------------------
// long[] dijkstra(int start) {
// long[] distances = new long[n];
// Arrays.fill(distances, INF);
// Arrays.fill(parents, -1);
// class Vertex implements Comparable<Vertex> {
// int index;
// long distance;
//
// Vertex(int index, long distance) {
// this.index = index;
// this.distance = distance;
// }
//
// public int compareTo(Vertex other) {
// return Long.compare(this.distance, other.distance);
// }
// }
// Queue<Vertex> q = new PriorityQueue<>();
// distances[start] = 0;
// q.add(new Vertex(start, distances[start]));
// while (q.size() > 0) {
// Vertex vertex = q.poll();
// if (vertex.distance > distances[vertex.index])
// continue;
// int from = vertex.index;
// long fromDistance = distances[from];
// // for (Edge e : graph[from]) { // e = { to, w }
// int to = e.to;
// long fromToDistance = fromDistance + e.w;
// if (distances[to] > fromToDistance) {
// distances[to] = fromToDistance;
// parents[to] = from;
// q.add(new Vertex(to, distances[to]));
// }
// }
// }
//
// return distances;
// }
int min(int... values) {
int min = Integer.MAX_VALUE;
for (int value : values) {
min = Math.min(min, value);
}
return min;
}
int max(int... values) {
int max = Integer.MIN_VALUE;
for (int value : values) {
max = Math.max(max, value);
}
return max;
}
// ==============================================================================
// class DSU {
//
// int parent[];
// int size;
//
// DSU(int size) {
// this.size = size;
// this.parent = new int[size];
// for (int i = 0; i < size; i++) {
// parent[i] = i;
// sizes[i] = 1;
// }
// }
//
// int get(int v) {
// int paren = parent[v];
// if (paren == v)
// return v;
// return parent[v] = get(paren);
// }
//
// void union(int a, int b) {
// a = get(a);
// b = get(b);
// if (a != b) {
// size--;
// if (rnd.nextBoolean()) {
// parent[a] = b;
// sizes[b] += sizes[a];
// } else {
// parent[b] = a;
// sizes[a] += sizes[b];
// }
//
// }
// }
//
// }
public static void main(String[] args) {
new Main().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
int maxA(int[] a) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < a.length; i++) {
if (a[i] > max) {
max = a[i];
}
}
return max;
}
int minA(int[] a) {
int min = Integer.MAX_VALUE;
for (int i = 0; i < a.length; i++) {
if (a[i] < min) {
min = a[i];
}
}
return min;
}
void init() throws FileNotFoundException {
if (ONLINE_JUDGE) {
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("");
}
void run() {
try {
long timeStart = System.currentTimeMillis();
init();
solve();
out.close();
long timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeStart) + " COMPILED");
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
long memoryTotal, memoryFree;
void memory() {
memoryFree = Runtime.getRuntime().freeMemory();
System.err.println("Memory = " + ((-memoryTotal + memoryFree) >> 10) + " KB");
}
String readLine() throws IOException {
return in.readLine();
}
String delimiter = " ";
String rS() throws IOException {
while (!tok.hasMoreTokens()) {
String nextLine = readLine();
if (null == nextLine)
return null;
tok = new StringTokenizer(nextLine);
}
return tok.nextToken(delimiter);
}
int[] rA(int b) {
int a[] = new int[b];
for (int i = 0; i < b; i++) {
try {
a[i] = rI();
} catch (IOException e) {
e.printStackTrace();
}
}
return a;
}
int rI() throws IOException {
return Integer.parseInt(rS());
}
long rL() throws IOException {
return Long.parseLong(rS());
}
void sort(int[] a) {
Integer arr[] = new Integer[a.length];
for (int i = 0; i < a.length; i++) {
arr[i] = a[i];
}
Arrays.sort(arr);
for (int i = 0; i < a.length; i++) {
a[i] = arr[i];
}
}
} | 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 | df83ad9631a4395a92d82a4950546b91 | train_001.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.awt.Point;
import java.io.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
import java.util.Map.Entry;
public class Tests {
static Scanner in = new Scanner();
static PrintWriter out = new PrintWriter(System.out);
static ArrayList<Integer>[] tree;
static long[] c;
static HashMap<String, Long> dp;
public static void main(String[] test) throws NumberFormatException, IOException {
int n = in.nextInt();
tree = new ArrayList[n];
for (int i = 0; i < n; i++)
tree[i] = new ArrayList<Integer>();
for (int i = 1; i < n; i++) {
int u = in.nextInt() - 1, v = in.nextInt() - 1;
tree[u].add(v);
tree[v].add(u);
}
c = new long[n];
for (int i = 0; i < n; i++) {
c[i] = in.nextLong();
}
dp = new HashMap<>();
for (int r = 0; r < n; r++) {
boolean ok = true;
for (int u : tree[r])
if (dfs(u, r) != c[u])
ok = false;
if (ok) {
out.println("YES");
out.println(r + 1);
out.close();
return;
}
}
out.println("NO");
out.flush();
out.close();
}
private static long dfs(int u, long p) {
if (dp.containsKey(u + "-" + p)) {
return dp.get(u + "-" + p);
}
boolean ok = true;
for (int v : tree[u]) {
if (v != p && dfs(v, u) != c[u]) {
ok = false;
break;
}
}
dp.put(u + "-" + p, ok ? c[u] : 0);
return dp.get(u + "-" + p);
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
Scanner(String file) throws FileNotFoundException {
br = new BufferedReader(new FileReader(file));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(next());
}
String nextLine() throws IOException {
return br.readLine();
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
public int[] nextIntArray(int n) throws IOException {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
}
}
| 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 | d596a0b17e18c83f584bf6dafcc5691e | train_001.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.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Solutions {
static Scanner in = new Scanner();
static PrintWriter out = new PrintWriter(System.out);
public static void main(String[] args) throws IOException {
int n = in.nextInt();
tree = new ArrayList[n];
for (int i = 0; i < n; i++)
tree[i] = new ArrayList<Integer>();
for (int i = 1; i < n; i++) {
int u = in.nextInt() - 1, v = in.nextInt() - 1;
tree[u].add(v);
tree[v].add(u);
}
c = new long[n];
for (int i = 0; i < n; i++) {
c[i] = in.nextLong();
}
dp = new HashMap<>();
for (int r = 0; r < n; r++) {
boolean ok = true;
for (int u : tree[r])
if (dfs(u, r) != c[u])
ok = false;
if (ok) {
out.println("YES");
out.println(r + 1);
out.close();
return;
}
}
out.println("NO");
out.flush();
out.close();
}
static ArrayList<Integer>[] tree;
static long[] c;
static HashMap<Long, Long> dp;
private static long dfs(int u, long p) {
long hash = (p << 32) | u;
if (dp.containsKey(hash))
return dp.get(hash);
boolean ok = true;
for (int v : tree[u]){
if (v != p && dfs(v, u) != c[u]) {
ok = false;
break;
}
}
dp.put(hash, ok ? c[u] : 0);
return dp.get(hash);
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public Scanner(FileReader fileReader) throws FileNotFoundException {
br = new BufferedReader(fileReader);
}
public Scanner(InputStream s) throws FileNotFoundException {
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 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 int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
| 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 | 9838a34a0d5007cde1463663bec56c0f | train_001.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V',βE') of a graph G(V,βE) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
public class SolutionA{
public static void main(String[] args){
new SolutionA().run();
}
void solve(){
int n = in.nextInt();
int m = in.nextInt();
double ans = 0.0;
int a[] = in.nextIntArray(n);
for(int i = 0; i < m; i++){
int st = in.nextInt()-1;
int fi = in.nextInt()-1;
ans = Math.max((a[st] + a[fi] + 0.0)/in.nextDouble(), ans);
}
out.println(ans);
}
class Pair implements Comparable<Pair>{
int x, y;
Pair(int x, int y){
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
if(o.x == x) return ((Integer) y).compareTo(o.y);
return ((Integer) x).compareTo(o.x);
}
}
FastScanner in;
PrintWriter out;
void run(){
in = new FastScanner(System.in);
out = new PrintWriter(new OutputStreamWriter(System.out));
solve();
out.close();
}
void runIO(){
try{
in = new FastScanner(new File("expr.in"));
out = new PrintWriter(new FileWriter(new File("expr.out")));
solve();
out.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
class FastScanner{
BufferedReader bf;
StringTokenizer st;
public FastScanner(File f){
try{
bf = new BufferedReader(new FileReader(f));
}
catch(IOException ex){
ex.printStackTrace();
}
}
public FastScanner(InputStream is){
bf = new BufferedReader(new InputStreamReader(is));
}
String next(){
while(st == null || !st.hasMoreTokens()){
try{
st = new StringTokenizer(bf.readLine());
}
catch(IOException ex){
ex.printStackTrace();
}
}
return st.nextToken();
}
int nextInt(){
return Integer.parseInt(next());
}
double nextDouble(){
return Double.parseDouble(next());
}
float nextFloat(){
return Float.parseFloat(next());
}
String nextLine(){
try{
return bf.readLine();
}
catch(Exception ex){
ex.printStackTrace();
}
return "";
}
long nextLong(){
return Long.parseLong(next());
}
BigInteger nextBigInteger(){
return new BigInteger(next());
}
BigDecimal nextBigDecimal(){
return new BigDecimal(next());
}
int[] nextIntArray(int n){
int a[] = new int[n];
for(int i = 0; i < n; i++)
a[i] = Integer.parseInt(next());
return a;
}
long[] nextLongArray(int n){
long a[] = new long[n];
for(int i = 0; i < n; i++)
a[i] = Long.parseLong(next());
return a;
}
}
} | Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers nΒ (1ββ€βnββ€β500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xiΒ (1ββ€βxiββ€β106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai,βbi,βciΒ (1ββ€βaiβ<βbiββ€βn;Β 1ββ€βciββ€β103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10β-β9. | standard output | |
PASSED | a2f3bff6e9e73918baca3f9024e73f57 | train_001.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V',βE') of a graph G(V,βE) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.io.*;
import java.util.*;
public class C444A {
FastScanner in;
PrintWriter out;
void solve() {
int n = in.nextInt();
int m = in.nextInt();
int[] a = new int[n + 1];
for (int i = 1; i <= n; i++) {
a[i] = in.nextInt();
}
int x,y,z;
double max = 0.0, ans;
for (int i = 0; i < m; i++) {
x = in.nextInt();
y = in.nextInt();
z = in.nextInt();
ans = (a[x] + a[y]) / (double) z;
if (max < ans) {
max = ans;
}
}
out.printf("%.12f", max);
out.println();
}
void run() {
try {
in = new FastScanner(new File("input.in"));
out = new PrintWriter(new File("output.out"));
solve();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
void runIO() {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
public static void main(String[] args) {
Locale.setDefault(Locale.US);
new C444A().runIO();
}
} | Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers nΒ (1ββ€βnββ€β500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xiΒ (1ββ€βxiββ€β106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai,βbi,βciΒ (1ββ€βaiβ<βbiββ€βn;Β 1ββ€βciββ€β103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10β-β9. | standard output | |
PASSED | 2a725f311130a6249927df92985f2e29 | train_001.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V',βE') of a graph G(V,βE) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.util.*;
import java.io.*;
public class A{
static PrintWriter out;
static InputReader in;
public static void main(String args[]){
out = new PrintWriter(System.out);
in = new InputReader();
new A();
out.flush(); out.close();
}
A(){
solve();
}
class pair{
int F, S;
pair(int a, int b){F = a; S = b;}
}
class X{
int node, pa, F, S;
X(int a, int b, int c, int d){node = a; pa = b; F = c; S = d;}
}
final int max = 510;
int n, m;
int w[] = new int[max];
ArrayList<pair> al[] = new ArrayList[max];
void solve(){
n = in.nextInt(); m = in.nextInt();
for(int i = 1; i <= n; i++)w[i] = in.nextInt();
for(int i = 0; i < max; i++)al[i] = new ArrayList<>();
for(int i = 0; i < m; i++){
int u = in.nextInt(), v = in.nextInt(), c = in.nextInt();
al[u].add(new pair(v, c));
al[v].add(new pair(u, c));
}
PriorityQueue<X> pq = new PriorityQueue<>((A, B) -> (long)B.F * A.S == (long) B.S * A.F ? A.F - B.F : Long.compare((long)B.F * A.S, (long) B.S * A.F));
int an = 0, ad = 0;
for(int i = 1; i <= n; i++){
pq.clear();
int num = 0, den = 0;
pq.add(new X(i, 0, w[i], 0));
while(!pq.isEmpty()){
X x = pq.poll();
if(x.S == 0){
num += x.F;
}else{
if(den != 0 && (long)num * x.S > (long)den * x.F)break;
num += x.F; den += x.S;
}
for(pair v : al[x.node]){
if(v.F == x.pa)continue;
pq.add(new X(v.F, x.node, w[v.F], v.S));
}
}
// System.out.println(num + " " + den);
if(den != 0 && (ad == 0 || (long)an * den < (long)num * ad)){
an = num; ad = den;
}
}
if(ad == 0){
out.print(0);
return;
}
System.out.print((double)an / ad);
}
public static class InputReader{
BufferedReader br;
StringTokenizer st;
InputReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
public int nextInt(){
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble(){
return Double.parseDouble(next());
}
public String next(){
while(st == null || !st.hasMoreTokens()){
try{
st = new StringTokenizer(br.readLine());
}catch(IOException e){}
}
return st.nextToken();
}
}
}
| Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers nΒ (1ββ€βnββ€β500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xiΒ (1ββ€βxiββ€β106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai,βbi,βciΒ (1ββ€βaiβ<βbiββ€βn;Β 1ββ€βciββ€β103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10β-β9. | standard output | |
PASSED | 8c8bf0a5c15afcf0bcca4b505d237b54 | train_001.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V',βE') of a graph G(V,βE) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.io.*;
import java.util.*;
import java.lang.*;
import java.math.BigInteger;
public class Main
{
public static void main(String args[]) throws FileNotFoundException, IOException
{
//Scanner in =new Scanner(new FileReader("input.txt"));
//PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
//Scanner in=new Scanner(System.in);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(System.out);
StringTokenizer st=new StringTokenizer(br.readLine());
int n=ni(st.nextToken());
int m=ni(st.nextToken());
double val[]=new double[n];
st=new StringTokenizer(br.readLine());
for(int i=0;i<n;i++)
val[i]=nd(st.nextToken());
double ans=0;
for(int i=0;i<m;i++)
{
st=new StringTokenizer(br.readLine());
int a=ni(st.nextToken())-1;
int b=ni(st.nextToken())-1;
double c=nd(st.nextToken());
ans=Math.max(ans,(val[a]+val[b])/c);
}
out.printf("%.160f\n", ans);
out.close();
}
public static Integer ni(String s)
{
return Integer.parseInt(s);
}
public static BigInteger nb(String s)
{
return BigInteger.valueOf(Long.parseLong(s));
}
public static Long nl(String s)
{
return Long.parseLong(s);
}
public static Double nd(String s)
{
return Double.parseDouble(s);
}
} | Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers nΒ (1ββ€βnββ€β500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xiΒ (1ββ€βxiββ€β106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai,βbi,βciΒ (1ββ€βaiβ<βbiββ€βn;Β 1ββ€βciββ€β103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10β-β9. | standard output | |
PASSED | dd18d0044ee2d922191d4fb18bc6e15d | train_001.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V',βE') of a graph G(V,βE) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.io.*;
import java.util.*;
import java.lang.*;
import java.math.BigInteger;
public class Main
{
public static void main(String args[]) throws FileNotFoundException, IOException
{
//Scanner in =new Scanner(new FileReader("input.txt"));
//PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
//Scanner in=new Scanner(System.in);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(System.out);
StringTokenizer st=new StringTokenizer(br.readLine());
int n=ni(st.nextToken());
int m=ni(st.nextToken());
double val[]=new double[n];
st=new StringTokenizer(br.readLine());
for(int i=0;i<n;i++)
val[i]=nd(st.nextToken());
double ans=0;
for(int i=0;i<m;i++)
{
st=new StringTokenizer(br.readLine());
int a=ni(st.nextToken())-1;
int b=ni(st.nextToken())-1;
double c=nd(st.nextToken());
ans=Math.max(ans,(val[a]+val[b])/c);
}
out.printf("%.16f\n", ans);
out.close();
}
public static Integer ni(String s)
{
return Integer.parseInt(s);
}
public static BigInteger nb(String s)
{
return BigInteger.valueOf(Long.parseLong(s));
}
public static Long nl(String s)
{
return Long.parseLong(s);
}
public static Double nd(String s)
{
return Double.parseDouble(s);
}
} | Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers nΒ (1ββ€βnββ€β500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xiΒ (1ββ€βxiββ€β106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai,βbi,βciΒ (1ββ€βaiβ<βbiββ€βn;Β 1ββ€βciββ€β103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10β-β9. | standard output | |
PASSED | 683a561654294e6fce1b922136d393ae | train_001.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V',βE') of a graph G(V,βE) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | // practice with rainboy
import java.io.*;
import java.util.*;
public class CF444A extends PrintWriter {
CF444A() { super(System.out, true); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF444A o = new CF444A(); o.main(); o.flush();
}
void main() {
int n = sc.nextInt();
int m = sc.nextInt();
int[] xx = new int[n];
for (int i = 0; i < n; i++)
xx[i] = sc.nextInt();
double ans = 0;
while (m-- > 0) {
int i = sc.nextInt() - 1;
int j = sc.nextInt() - 1;
int c = sc.nextInt();
ans = Math.max(ans, (double) (xx[i] + xx[j]) / c);
}
println(ans);
}
}
| Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers nΒ (1ββ€βnββ€β500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xiΒ (1ββ€βxiββ€β106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai,βbi,βciΒ (1ββ€βaiβ<βbiββ€βn;Β 1ββ€βciββ€β103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10β-β9. | standard output | |
PASSED | 2598d96fa9bbdb1e543d83fb17705952 | train_001.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V',βE') of a graph G(V,βE) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
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);
ADZYLovesPhysics solver = new ADZYLovesPhysics();
solver.solve(1, in, out);
out.close();
}
static class ADZYLovesPhysics {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.readInt();
int m = in.readInt();
int[] x = in.readIntArray(n);
double ans = 0;
for (int i = 0; i < m; i++) {
int a = in.readInt() - 1;
int b = in.readInt() - 1;
double c = in.readInt();
ans = Math.max(ans, (x[a] + x[b]) / c);
}
out.println(ans);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int[] readIntArray(int size) {
int[] ans = new int[size];
for (int i = 0; i < size; i++) ans[i] = readInt();
return ans;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers nΒ (1ββ€βnββ€β500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xiΒ (1ββ€βxiββ€β106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai,βbi,βciΒ (1ββ€βaiβ<βbiββ€βn;Β 1ββ€βciββ€β103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10β-β9. | standard output | |
PASSED | 4df65f24ef691b8fffa6becbb43ea2f6 | train_001.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V',βE') of a graph G(V,βE) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Locale;
import java.util.StringTokenizer;
public class C {
static BufferedReader br;
static PrintWriter pw;
static StringTokenizer st;
private static int nextInt() throws IOException {
return Integer.parseInt(next());
}
private static long nextLong() throws IOException {
return Long.parseLong(next());
}
private static String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.US);
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
System.out)));
int n = nextInt();
int m = nextInt();
int x[] = new int[n + 1];
for (int i = 1; i <= n; i++)
x[i] = nextInt();
double max = 0;
for (int i = 1; i <= m; i++) {
int a = nextInt();
int b = nextInt();
int c = nextInt();
max = Math.max(max, (x[b] + x[a]) / (c * 1.0));
}
pw.printf("%.15f", max);
pw.close();
}
}
| Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers nΒ (1ββ€βnββ€β500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xiΒ (1ββ€βxiββ€β106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai,βbi,βciΒ (1ββ€βaiβ<βbiββ€βn;Β 1ββ€βciββ€β103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10β-β9. | standard output | |
PASSED | 8940e7e8d08b5f01e6b506135cba6a41 | train_001.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V',βE') of a graph G(V,βE) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.math.BigInteger;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Egor Kulikov (egor@egork.net)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int count = in.readInt();
int edgeCount = in.readInt();
int[] values = IOUtils.readIntArray(in, count);
int[] from = new int[edgeCount];
int[] to = new int[edgeCount];
int[] edgeValue = new int[edgeCount];
IOUtils.readIntArrays(in, from, to, edgeValue);
MiscUtils.decreaseByOne(from, to);
if (edgeCount == 0) {
out.printLine(0);
return;
}
double answer = 0;
for (int i = 0; i < edgeCount; i++) {
answer = Math.max(answer, (double)(values[from[i]] + values[to[i]]) / edgeValue[i]);
}
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;
}
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 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 printLine(int i) {
writer.println(i);
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
public static void readIntArrays(InputReader in, int[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++)
arrays[j][i] = in.readInt();
}
}
}
class MiscUtils {
public static void decreaseByOne(int[]...arrays) {
for (int[] array : arrays) {
for (int i = 0; i < array.length; i++)
array[i]--;
}
}
}
| Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers nΒ (1ββ€βnββ€β500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xiΒ (1ββ€βxiββ€β106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai,βbi,βciΒ (1ββ€βaiβ<βbiββ€βn;Β 1ββ€βciββ€β103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10β-β9. | standard output | |
PASSED | 93270b2f5df41b7a6f5e6f661259c578 | train_001.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V',βE') of a graph G(V,βE) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int m = in.nextInt();
int[] x = new int[n + 1];
for (int i = 1; i <= n; i++) {
x[i] = in.nextInt();
}
double ans = 0;
for (int i = 0; i < m; i++) {
int a = in.nextInt();
int b = in.nextInt();
int c = in.nextInt();
double cur = (x[a] + x[b]);
cur /= c;
ans = Math.max(ans, cur);
}
out.println(ans);
}
}
static class InputReader {
private StringTokenizer tokenizer;
private BufferedReader reader;
public InputReader(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
}
private void fillTokenizer() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public String next() {
fillTokenizer();
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers nΒ (1ββ€βnββ€β500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xiΒ (1ββ€βxiββ€β106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai,βbi,βciΒ (1ββ€βaiβ<βbiββ€βn;Β 1ββ€βciββ€β103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10β-β9. | standard output | |
PASSED | 8892d2a73bee65945fedfd9bf8b02326 | train_001.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V',βE') of a graph G(V,βE) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | // package Round254;
/**
* Created by ankurverma1994
* My code is awesome!
*/
import java.io.*;
import java.util.*;
import java.math.*;
public class DZYLovesPhysics {
final int mod = (int) 1e9 + 7;
final double eps = 1e-6;
final double pi = Math.PI;
final long inf = Long.MAX_VALUE / 2;
//------------> Solution starts here!!
@SuppressWarnings("Main Logic")
void solve() {
int n = ii(), m = ii(), nodes[] = iia(n);
double ans = 0;
for (int i = 0; i < m; i++) {
int from = ii() - 1, to = ii() - 1, edge = ii();
ans = Math.max(ans, (nodes[from] + nodes[to]) / (double) edge);
}
out.printf("%.12f\n", ans);
}
//------------> Solution ends here!!
InputStream obj;
PrintWriter out;
String check = "";
public static void main(String[] args) throws IOException {
new Thread(null, new Runnable() {
public void run() {
try {
new DZYLovesPhysics().main1();
} catch (IOException e) {
e.printStackTrace();
} catch (StackOverflowError e) {
System.out.println("RTE");
}
}
}, "1", 1 << 26).start();
}
void main1() throws IOException {
out = new PrintWriter(System.out);
obj = check.isEmpty() ? System.in : new ByteArrayInputStream(check.getBytes());
// obj=check.isEmpty() ? new FileInputStream("/home/ankurverma1994/input.txt") : new ByteArrayInputStream(check.getBytes());
solve();
out.flush();
out.close();
}
byte inbuffer[] = new byte[1024];
int lenbuffer = 0, ptrbuffer = 0;
int readByte() {
if (lenbuffer == -1) throw new InputMismatchException();
if (ptrbuffer >= lenbuffer) {
ptrbuffer = 0;
try {
lenbuffer = obj.read(inbuffer);
} catch (IOException e) {
throw new InputMismatchException();
}
}
if (lenbuffer <= 0) return -1;
return inbuffer[ptrbuffer++];
}
String is() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) // when nextLine, (isSpaceChar(b) && b!=' ')
{
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
int ii() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
long il() {
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();
}
}
boolean isSpaceChar(int c) {
return (!(c >= 33 && c <= 126));
}
int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
float nf() {
return Float.parseFloat(is());
}
double id() {
return Double.parseDouble(is());
}
char ic() {
return (char) skip();
}
int[] iia(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) a[i] = ii();
return a;
}
long[] ila(int n) {
long a[] = new long[n];
for (int i = 0; i < n; i++) a[i] = il();
return a;
}
String[] isa(int n) {
String a[] = new String[n];
for (int i = 0; i < n; i++) a[i] = is();
return a;
}
double[][] idm(int n, int m) {
double a[][] = new double[n][m];
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) a[i][j] = id();
return a;
}
int[][] iim(int n, int m) {
int a[][] = new int[n][m];
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) a[i][j] = ii();
return a;
}
}
| Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers nΒ (1ββ€βnββ€β500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xiΒ (1ββ€βxiββ€β106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai,βbi,βciΒ (1ββ€βaiβ<βbiββ€βn;Β 1ββ€βciββ€β103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10β-β9. | standard output | |
PASSED | 97c816bb74f11a4ba26b5f40025e073e | train_001.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V',βE') of a graph G(V,βE) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.Scanner;
public class R254_D1_A {
private static class Edge {
double from;
double to;
double weight;
public Edge(double from, double to, double weight) {
this.from = from;
this.to = to;
this.weight = weight;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
PrintWriter writer = new PrintWriter(System.out);
int n = scanner.nextInt();
int m = scanner.nextInt();
double[] nodeValues = new double[n];
Edge[] edge = new Edge[m];
double result = 0.0f;
DecimalFormat format = new DecimalFormat("#0.000000000000000");
for (int i = 1; i <= n; ++i) {
nodeValues[i - 1] = scanner.nextDouble();
}
for (int i = 1; i <= m; ++i) {
edge[i - 1] = new Edge(scanner.nextInt(), scanner.nextInt(), scanner.nextInt());
}
if (m == 0) {
writer.println(format.format(result));
} else {
for (int i = 0; i <= edge.length - 1; ++i) {
double sum = (nodeValues[(int) (edge[i].from - 1)] + nodeValues[(int) (edge[i].to - 1)])
/ edge[i].weight;
if (sum > result) {
result = sum;
}
}
writer.println(format.format(result));
}
writer.flush();
scanner.close();
}
}
| Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers nΒ (1ββ€βnββ€β500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xiΒ (1ββ€βxiββ€β106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai,βbi,βciΒ (1ββ€βaiβ<βbiββ€βn;Β 1ββ€βciββ€β103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10β-β9. | standard output | |
PASSED | 699b9321807857edab10e6d53be9146f | train_001.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V',βE') of a graph G(V,βE) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
import java.lang.reflect.*;
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);
Task solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
interface Task {
public void solve(int testNumber, InputReader in, OutputWriter out);
}
class TaskA implements Task {
int[] arr;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n=in.readInt(), m=in.readInt();
double ret=0.0;
arr=IOUtils.readIntArray(in, n);
while (m-->0) {
int x=in.readInt()-1, y=in.readInt()-1, z=in.readInt();
ret=MiscUtils.max(ret, 1.0*(arr[x]+arr[y])/z);
}
out.printLine(ret);
}
}
class TaskB implements Task {
int[] parent;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n=in.readInt(), m=in.readInt();
long ret=1L;
parent=new int[n];
for (int i=0; i<n; i++) parent[i]=i;
while (m-->0) {
int x=in.readInt()-1, y=in.readInt()-1;
if (find(x)!=find(y)) {
ret*=2L;
parent[find(x)]=find(y);
}
}
out.printLine(ret);
}
int find(int x) {
if (x==parent[x]) return x;
return parent[x]=find(parent[x]);
}
}
class TaskC implements Task {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int a=in.readInt(), b=in.readInt();
long l=IntegerUtils.lcm(a, b);
if (Math.abs(l/a-l/b)<=1) out.printLine("Equal");
else out.printLine(a<b?"Dasha":"Masha");
}
}
class TaskD implements Task {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n=in.readInt(), m=in.readInt();
}
}
class TaskE implements Task {
public void solve(int testNumber, InputReader in, OutputWriter out) {
}
}
class TaskF implements Task {
public void solve(int testNumber, InputReader in, OutputWriter out) {
}
}
class TaskG implements Task {
public void solve(int testNumber, InputReader in, OutputWriter out) {
}
}
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(char[] array) {
writer.print(array);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void print(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(array[i]);
}
}
public void print(long[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(array[i]);
}
}
public void print(Collection<Integer> collection) {
boolean first = true;
for (int value : collection) {
if (first)
first = false;
else
writer.print(' ');
writer.print(value);
}
}
public void printLine(int[] array) {
print(array);
writer.println();
}
public void printLine(long[] array) {
print(array);
writer.println();
}
public void printLine(Collection<Integer> collection) {
print(collection);
writer.println();
}
public void printLine() {
writer.println();
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void print(char i) {
writer.print(i);
}
public void printLine(char i) {
writer.println(i);
}
public void printLine(char[] array) {
writer.println(array);
}
public void printFormat(String format, Object... objects) {
writer.printf(format, objects);
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
public void print(long i) {
writer.print(i);
}
public void printLine(long i) {
writer.println(i);
}
public void print(int i) {
writer.print(i);
}
public void printLine(int i) {
writer.println(i);
}
}
class InputReader {
private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1)
return -1;
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0)
return -1;
}
return buf[curChar];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c))
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r')
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines)
return readLine();
else
return readLine0();
}
public BigInteger readBigInteger() {
try {
return new BigInteger(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 SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class IOUtils {
public static Pair<Integer, Integer> readIntPair(InputReader in) {
int first = in.readInt();
int second = in.readInt();
return Pair.makePair(first, second);
}
public static Pair<Long, Long> readLongPair(InputReader in) {
long first = in.readLong();
long second = in.readLong();
return Pair.makePair(first, second);
}
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
public static long[] readLongArray(InputReader in, int size) {
long[] array = new long[size];
for (int i = 0; i < size; i++)
array[i] = in.readLong();
return array;
}
public static double[] readDoubleArray(InputReader in, int size) {
double[] array = new double[size];
for (int i = 0; i < size; i++)
array[i] = in.readDouble();
return array;
}
public static String[] readStringArray(InputReader in, int size) {
String[] array = new String[size];
for (int i = 0; i < size; i++)
array[i] = in.readString();
return array;
}
public static char[] readCharArray(InputReader in, int size) {
char[] array = new char[size];
for (int i = 0; i < size; i++)
array[i] = in.readCharacter();
return array;
}
public static Pair<Integer, Integer>[] readIntPairArray(InputReader in,
int size) {
@SuppressWarnings({ "unchecked" })
Pair<Integer, Integer>[] result = new Pair[size];
for (int i = 0; i < size; i++)
result[i] = readIntPair(in);
return result;
}
public static Pair<Long, Long>[] readLongPairArray(InputReader in, int size) {
@SuppressWarnings({ "unchecked" })
Pair<Long, Long>[] result = new Pair[size];
for (int i = 0; i < size; i++)
result[i] = readLongPair(in);
return result;
}
public static void readIntArrays(InputReader in, int[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++)
arrays[j][i] = in.readInt();
}
}
public static void readLongArrays(InputReader in, long[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++)
arrays[j][i] = in.readLong();
}
}
public static void readDoubleArrays(InputReader in, double[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++)
arrays[j][i] = in.readDouble();
}
}
public static char[][] readTable(InputReader in, int rowCount,
int columnCount) {
char[][] table = new char[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readCharArray(in, columnCount);
return table;
}
public static int[][] readIntTable(InputReader in, int rowCount,
int columnCount) {
int[][] table = new int[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readIntArray(in, columnCount);
return table;
}
public static double[][] readDoubleTable(InputReader in, int rowCount,
int columnCount) {
double[][] table = new double[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readDoubleArray(in, columnCount);
return table;
}
public static long[][] readLongTable(InputReader in, int rowCount,
int columnCount) {
long[][] table = new long[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readLongArray(in, columnCount);
return table;
}
public static String[][] readStringTable(InputReader in, int rowCount,
int columnCount) {
String[][] table = new String[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readStringArray(in, columnCount);
return table;
}
public static String readText(InputReader in) {
StringBuilder result = new StringBuilder();
while (true) {
int character = in.read();
if (character == '\r')
continue;
if (character == -1)
break;
result.append((char) character);
}
return result.toString();
}
public static void readStringArrays(InputReader in, String[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++)
arrays[j][i] = in.readString();
}
}
public static void printTable(OutputWriter out, char[][] table) {
for (char[] row : table)
out.printLine(new String(row));
}
}
class ArrayUtils {
private static int[] tempInt = new int[0];
private static long[] tempLong = new long[0];
public static Integer[] generateOrder(int size) {
Integer[] order = new Integer[size];
for (int i = 0; i < size; i++)
order[i] = i;
return order;
}
public static void fill(short[][] array, short value) {
for (short[] row : array)
Arrays.fill(row, value);
}
public static void fill(long[][] array, long value) {
for (long[] row : array)
Arrays.fill(row, value);
}
public static void fill(double[][] array, double value) {
for (double[] row : array)
Arrays.fill(row, value);
}
public static void fill(double[][][] array, double value) {
for (double[][] row : array)
fill(row, value);
}
public static void fill(double[][][][] array, double value) {
for (double[][][] row : array)
fill(row, value);
}
public static void fill(double[][][][][] array, double value) {
for (double[][][][] row : array)
fill(row, value);
}
public static void fill(long[][][] array, long value) {
for (long[][] row : array)
fill(row, value);
}
public static void fill(long[][][][] array, long value) {
for (long[][][] row : array)
fill(row, value);
}
public static void fill(long[][][][][] array, long value) {
for (long[][][][] row : array)
fill(row, value);
}
public static void fillColumn(long[][] array, int index, long value) {
for (long[] row : array)
row[index] = value;
}
public static void fillColumn(int[][] array, int index, int value) {
for (int[] row : array)
row[index] = value;
}
public static void fill(int[][] array, int value) {
for (int[] row : array)
Arrays.fill(row, value);
}
public static void fill(boolean[][] array, boolean value) {
for (boolean[] row : array)
Arrays.fill(row, value);
}
public static void fill(boolean[][][] array, boolean value) {
for (boolean[][] row : array)
fill(row, value);
}
public static long sumArray(int[] array) {
long result = 0;
for (int element : array)
result += element;
return result;
}
public static int[] range(int from, int to) {
int[] result = new int[Math.max(from, to) - Math.min(from, to) + 1];
int index = 0;
if (to > from) {
for (int i = from; i <= to; i++)
result[index++] = i;
} else {
for (int i = from; i >= to; i--)
result[index++] = i;
}
return result;
}
public static void fill(int[][][] array, int value) {
for (int[][] subArray : array)
fill(subArray, value);
}
public static void fill(short[][][] array, short value) {
for (short[][] subArray : array)
fill(subArray, value);
}
public static void fill(int[][][][] array, int value) {
for (int[][][] subArray : array)
fill(subArray, value);
}
public static void fill(short[][][][] array, short value) {
for (short[][][] subArray : array)
fill(subArray, value);
}
public static void fill(int[][][][][] array, int value) {
for (int[][][][] subArray : array)
fill(subArray, value);
}
public static void fill(short[][][][][] array, short value) {
for (short[][][][] subArray : array)
fill(subArray, value);
}
public static void fill(int[][][][][][] array, int value) {
for (int[][][][][] subArray : array)
fill(subArray, value);
}
public static void fill(short[][][][][][] array, short value) {
for (short[][][][][] subArray : array)
fill(subArray, value);
}
public static void fill(int[][][][][][][] array, int value) {
for (int[][][][][][] subArray : array)
fill(subArray, value);
}
public static void fill(short[][][][][][][] array, short value) {
for (short[][][][][][] subArray : array)
fill(subArray, value);
}
public static Integer[] order(int size, Comparator<Integer> comparator) {
Integer[] order = generateOrder(size);
Arrays.sort(order, comparator);
return order;
}
public static <T> void fill(T[][] array, T value) {
for (T[] row : array)
Arrays.fill(row, value);
}
public static void fill(char[][] array, char value) {
for (char[] row : array)
Arrays.fill(row, value);
}
public static void fill(byte[][] array, byte value) {
for (byte[] row : array)
Arrays.fill(row, value);
}
public static void fill(byte[][][] array, byte value) {
for (byte[][] row : array)
fill(row, value);
}
public static void fill(byte[][][][] array, byte value) {
for (byte[][][] row : array)
fill(row, value);
}
public static long multiply(int[] first, int[] second) {
long result = 0;
for (int i = 0; i < first.length; i++)
result += (long) first[i] * second[i];
return result;
}
public static int[] createOrder(int size) {
int[] order = new int[size];
for (int i = 0; i < size; i++)
order[i] = i;
return order;
}
public static int[] sort(int[] array, IntComparator comparator) {
return sort(array, 0, array.length, comparator);
}
public static int[] sort(int[] array, int from, int to,
IntComparator comparator) {
Integer[] intArray = new Integer[to - from];
for (int i = from; i < to; i++)
intArray[i - from] = array[i];
Arrays.sort(intArray, comparator);
for (int i=from; i<to; i++) array[i]=intArray[i-from];
return array;
}
private static void ensureCapacityInt(int size) {
if (tempInt.length >= size)
return;
size = Math.max(size, tempInt.length << 1);
tempInt = new int[size];
}
private static void ensureCapacityLong(int size) {
if (tempLong.length >= size)
return;
size = Math.max(size, tempLong.length << 1);
tempLong = new long[size];
}
private static void sortImpl(int[] array, int from, int to, int[] temp,
int fromTemp, int toTemp, IntComparator comparator) {
if (to - from <= 1)
return;
int middle = (to - from) >> 1;
int tempMiddle = fromTemp + middle;
sortImpl(temp, fromTemp, tempMiddle, array, from, from + middle,
comparator);
sortImpl(temp, tempMiddle, toTemp, array, from + middle, to, comparator);
int index = from;
int index1 = fromTemp;
int index2 = tempMiddle;
while (index1 < tempMiddle && index2 < toTemp) {
if (comparator.compare(temp[index1], temp[index2]) <= 0)
array[index++] = temp[index1++];
else
array[index++] = temp[index2++];
}
if (index1 != tempMiddle)
System.arraycopy(temp, index1, array, index, tempMiddle - index1);
if (index2 != toTemp)
System.arraycopy(temp, index2, array, index, toTemp - index2);
}
public static int[] order(final int[] array) {
return sort(createOrder(array.length), new IntComparator() {
public int compare(Integer first, Integer second) {
if (array[first] < array[second])
return -1;
if (array[first] > array[second])
return 1;
return 0;
}
});
}
public static int[] order(final long[] array) {
return sort(createOrder(array.length), new IntComparator() {
public int compare(Integer first, Integer second) {
if (array[first] < array[second])
return -1;
if (array[first] > array[second])
return 1;
return 0;
}
});
}
public static int[] unique(int[] array) {
return unique(array, 0, array.length);
}
public static int[] unique(int[] array, int from, int to) {
if (from == to)
return new int[0];
int count = 1;
for (int i = from + 1; i < to; i++) {
if (array[i] != array[i - 1])
count++;
}
int[] result = new int[count];
result[0] = array[from];
int index = 1;
for (int i = from + 1; i < to; i++) {
if (array[i] != array[i - 1])
result[index++] = array[i];
}
return result;
}
public static char[] unique(char[] array) {
return unique(array, 0, array.length);
}
public static char[] unique(char[] array, int from, int to) {
if (from == to)
return new char[0];
int count = 1;
for (int i = from + 1; i < to; i++) {
if (array[i] != array[i - 1])
count++;
}
char[] result = new char[count];
result[0] = array[from];
int index = 1;
for (int i = from + 1; i < to; i++) {
if (array[i] != array[i - 1])
result[index++] = array[i];
}
return result;
}
public static int maxElement(int[] array) {
return maxElement(array, 0, array.length);
}
public static int maxElement(int[] array, int from, int to) {
int result = Integer.MIN_VALUE;
for (int i = from; i < to; i++)
result = Math.max(result, array[i]);
return result;
}
public static int[] order(final double[] array) {
return sort(createOrder(array.length), new IntComparator() {
public int compare(Integer first, Integer second) {
return Double.compare(array[first], array[second]);
}
});
}
public static int[] reversePermutation(int[] permutation) {
int[] result = new int[permutation.length];
for (int i = 0; i < permutation.length; i++)
result[permutation[i]] = i;
return result;
}
public static void reverse(int[] array) {
for (int i = 0, j = array.length - 1; i < j; i++, j--) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
public static void reverse(char[] array) {
for (int i = 0, j = array.length - 1; i < j; i++, j--) {
char temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
private static long maxElement(long[] array, int from, int to) {
long result = Long.MIN_VALUE;
for (int i = from; i < to; i++)
result = Math.max(result, array[i]);
return result;
}
public static int minPosition(int[] array) {
return minPosition(array, 0, array.length);
}
public static int maxPosition(int[] array) {
return maxPosition(array, 0, array.length);
}
public static int minPosition(int[] array, int from, int to) {
if (from >= to)
return -1;
int min = array[from];
int result = from;
for (int i = from + 1; i < to; i++) {
if (array[i] < min) {
min = array[i];
result = i;
}
}
return result;
}
public static int maxPosition(int[] array, int from, int to) {
if (from >= to)
return -1;
int max = array[from];
int result = from;
for (int i = from + 1; i < to; i++) {
if (array[i] > max) {
max = array[i];
result = i;
}
}
return result;
}
public static int[] multiplyPermutations(int[] first, int[] second) {
int count = first.length;
int[] result = new int[count];
for (int i = 0; i < count; i++) {
result[i] = first[second[i]];
}
return result;
}
public static int[] compress(int[]... arrays) {
int totalLength = 0;
for (int[] array : arrays)
totalLength += array.length;
int[] all = new int[totalLength];
int delta = 0;
for (int[] array : arrays) {
System.arraycopy(array, 0, all, delta, array.length);
delta += array.length;
}
sort(all, IntComparator.DEFAULT);
all = unique(all);
for (int[] array : arrays) {
for (int i = 0; i < array.length; i++)
array[i] = Arrays.binarySearch(all, array[i]);
}
return all;
}
public static int minElement(int[] array) {
return array[minPosition(array)];
}
public static long[] partialSums(int[] array) {
long[] result = new long[array.length + 1];
for (int i = 0; i < array.length; i++)
result[i + 1] = result[i] + array[i];
return result;
}
public static void orderBy(int[] base, int[]... arrays) {
int[] order = ArrayUtils.order(base);
order(order, base);
for (int[] array : arrays)
order(order, array);
}
public static void orderBy(long[] base, long[]... arrays) {
int[] order = ArrayUtils.order(base);
order(order, base);
for (long[] array : arrays)
order(order, array);
}
public static void order(int[] order, int[] array) {
ensureCapacityInt(order.length);
for (int i = 0; i < order.length; i++)
tempInt[i] = array[order[i]];
System.arraycopy(tempInt, 0, array, 0, array.length);
}
public static void order(int[] order, long[] array) {
ensureCapacityLong(order.length);
for (int i = 0; i < order.length; i++)
tempLong[i] = array[order[i]];
System.arraycopy(tempLong, 0, array, 0, array.length);
}
public static long[] asLong(int[] array) {
long[] result = new long[array.length];
for (int i = 0; i < array.length; i++)
result[i] = array[i];
return result;
}
public static int count(int[] array, int value) {
int result = 0;
for (int i : array) {
if (i == value)
result++;
}
return result;
}
public static int count(char[] array, char value) {
int result = 0;
for (char i : array) {
if (i == value)
result++;
}
return result;
}
public static int count(boolean[] array, boolean value) {
int result = 0;
for (boolean i : array) {
if (i == value)
result++;
}
return result;
}
public static int[] merge(int[] first, int[] second) {
int[] result = new int[first.length + second.length];
int firstIndex = 0;
int secondIndex = 0;
int index = 0;
while (firstIndex < first.length && secondIndex < second.length) {
if (first[firstIndex] < second[secondIndex])
result[index++] = first[firstIndex++];
else
result[index++] = second[secondIndex++];
}
System.arraycopy(first, firstIndex, result, index, first.length
- firstIndex);
System.arraycopy(second, secondIndex, result, index, second.length
- secondIndex);
return result;
}
public static boolean nextPermutation(int[] array) {
return nextPermutation(array, IntComparator.DEFAULT);
}
private static boolean nextPermutation(int[] array, IntComparator comparator) {
int size = array.length;
int last = array[size - 1];
for (int i = size - 2; i >= 0; i--) {
int current = array[i];
if (comparator.compare(last, current) > 0) {
for (int j = size - 1; j > i; j--) {
if (comparator.compare(array[j], current) > 0) {
swap(array, i, j);
inPlaceReverse(array, i + 1, size);
return true;
}
}
}
last = current;
}
return false;
}
private static void inPlaceReverse(int[] array, int first, int second) {
for (int i = first, j = second - 1; i < j; i++, j--)
swap(array, i, j);
}
private static void swap(int[] array, int first, int second) {
if (first == second)
return;
int temp = array[first];
array[first] = array[second];
array[second] = temp;
}
public static <V> void reverse(V[] array) {
for (int i = 0, j = array.length - 1; i < j; i++, j--) {
V temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
public static IntComparator compareBy(final int[]... arrays) {
return new IntComparator() {
public int compare(Integer first, Integer second) {
for (int[] array : arrays) {
if (array[first] != array[second])
return Integer.compare(array[first], array[second]);
}
return 0;
}
};
}
public static long minElement(long[] array) {
return array[minPosition(array)];
}
public static long maxElement(long[] array) {
return array[maxPosition(array)];
}
public static int minPosition(long[] array) {
return minPosition(array, 0, array.length);
}
public static int maxPosition(long[] array) {
return maxPosition(array, 0, array.length);
}
public static int minPosition(long[] array, int from, int to) {
if (from >= to)
return -1;
long min = array[from];
int result = from;
for (int i = from + 1; i < to; i++) {
if (array[i] < min) {
min = array[i];
result = i;
}
}
return result;
}
public static int maxPosition(long[] array, int from, int to) {
if (from >= to)
return -1;
long max = array[from];
int result = from;
for (int i = from + 1; i < to; i++) {
if (array[i] > max) {
max = array[i];
result = i;
}
}
return result;
}
public static int[] createArray(int count, int value) {
int[] array = new int[count];
Arrays.fill(array, value);
return array;
}
public static long[] createArray(int count, long value) {
long[] array = new long[count];
Arrays.fill(array, value);
return array;
}
public static double[] createArray(int count, double value) {
double[] array = new double[count];
Arrays.fill(array, value);
return array;
}
public static boolean[] createArray(int count, boolean value) {
boolean[] array = new boolean[count];
Arrays.fill(array, value);
return array;
}
public static char[] createArray(int count, char value) {
char[] array = new char[count];
Arrays.fill(array, value);
return array;
}
public static <T> T[] createArray(int count, T value) {
@SuppressWarnings("unchecked")
T[] array = (T[]) Array.newInstance(value.getClass(), count);
Arrays.fill(array, value);
return array;
}
}
class Graph {
public static final int REMOVED_BIT = 0;
protected int vertexCount;
protected int edgeCount;
private int[] firstOutbound;
private int[] firstInbound;
private Edge[] edges;
private int[] nextInbound;
private int[] nextOutbound;
private int[] from;
private int[] to;
private long[] weight;
private long[] capacity;
private int[] reverseEdge;
private int[] flags;
public Graph(int vertexCount) {
this(vertexCount, vertexCount);
}
public Graph(int vertexCount, int edgeCapacity) {
this.vertexCount = vertexCount;
firstOutbound = new int[vertexCount];
Arrays.fill(firstOutbound, -1);
from = new int[edgeCapacity];
to = new int[edgeCapacity];
nextOutbound = new int[edgeCapacity];
flags = new int[edgeCapacity];
}
public static Graph createGraph(int vertexCount, int[] from, int[] to) {
Graph graph = new Graph(vertexCount, from.length);
for (int i = 0; i < from.length; i++)
graph.addSimpleEdge(from[i], to[i]);
return graph;
}
public static Graph createWeightedGraph(int vertexCount, int[] from,
int[] to, long[] weight) {
Graph graph = new Graph(vertexCount, from.length);
for (int i = 0; i < from.length; i++)
graph.addWeightedEdge(from[i], to[i], weight[i]);
return graph;
}
public static Graph createFlowGraph(int vertexCount, int[] from, int[] to,
long[] capacity) {
Graph graph = new Graph(vertexCount, from.length * 2);
for (int i = 0; i < from.length; i++)
graph.addFlowEdge(from[i], to[i], capacity[i]);
return graph;
}
public static Graph createFlowWeightedGraph(int vertexCount, int[] from,
int[] to, long[] weight, long[] capacity) {
Graph graph = new Graph(vertexCount, from.length * 2);
for (int i = 0; i < from.length; i++)
graph.addFlowWeightedEdge(from[i], to[i], weight[i], capacity[i]);
return graph;
}
public static Graph createTree(int[] parent) {
Graph graph = new Graph(parent.length + 1, parent.length);
for (int i = 0; i < parent.length; i++)
graph.addSimpleEdge(parent[i], i + 1);
return graph;
}
public int addEdge(int fromID, int toID, long weight, long capacity,
int reverseEdge) {
ensureEdgeCapacity(edgeCount + 1);
if (firstOutbound[fromID] != -1)
nextOutbound[edgeCount] = firstOutbound[fromID];
else
nextOutbound[edgeCount] = -1;
firstOutbound[fromID] = edgeCount;
if (firstInbound != null) {
if (firstInbound[toID] != -1)
nextInbound[edgeCount] = firstInbound[toID];
else
nextInbound[edgeCount] = -1;
firstInbound[toID] = edgeCount;
}
this.from[edgeCount] = fromID;
this.to[edgeCount] = toID;
if (capacity != 0) {
if (this.capacity == null)
this.capacity = new long[from.length];
this.capacity[edgeCount] = capacity;
}
if (weight != 0) {
if (this.weight == null)
this.weight = new long[from.length];
this.weight[edgeCount] = weight;
}
if (reverseEdge != -1) {
if (this.reverseEdge == null) {
this.reverseEdge = new int[from.length];
Arrays.fill(this.reverseEdge, 0, edgeCount, -1);
}
this.reverseEdge[edgeCount] = reverseEdge;
}
if (edges != null)
edges[edgeCount] = createEdge(edgeCount);
return edgeCount++;
}
protected final GraphEdge createEdge(int id) {
return new GraphEdge(id);
}
public final int addFlowWeightedEdge(int from, int to, long weight,
long capacity) {
if (capacity == 0) {
return addEdge(from, to, weight, 0, -1);
} else {
int lastEdgeCount = edgeCount;
addEdge(to, from, -weight, 0, lastEdgeCount + entriesPerEdge());
return addEdge(from, to, weight, capacity, lastEdgeCount);
}
}
protected int entriesPerEdge() {
return 1;
}
public final int addFlowEdge(int from, int to, long capacity) {
return addFlowWeightedEdge(from, to, 0, capacity);
}
public final int addWeightedEdge(int from, int to, long weight) {
return addFlowWeightedEdge(from, to, weight, 0);
}
public final int addSimpleEdge(int from, int to) {
return addWeightedEdge(from, to, 0);
}
public final int vertexCount() {
return vertexCount;
}
public final int edgeCount() {
return edgeCount;
}
protected final int edgeCapacity() {
return from.length;
}
public final Edge edge(int id) {
initEdges();
return edges[id];
}
public final int firstOutbound(int vertex) {
int id = firstOutbound[vertex];
while (id != -1 && isRemoved(id))
id = nextOutbound[id];
return id;
}
public final int nextOutbound(int id) {
id = nextOutbound[id];
while (id != -1 && isRemoved(id))
id = nextOutbound[id];
return id;
}
public final int firstInbound(int vertex) {
initInbound();
int id = firstInbound[vertex];
while (id != -1 && isRemoved(id))
id = nextInbound[id];
return id;
}
public final int nextInbound(int id) {
initInbound();
id = nextInbound[id];
while (id != -1 && isRemoved(id))
id = nextInbound[id];
return id;
}
public final int source(int id) {
return from[id];
}
public final int destination(int id) {
return to[id];
}
public final long weight(int id) {
if (weight == null)
return 0;
return weight[id];
}
public final long capacity(int id) {
if (capacity == null)
return 0;
return capacity[id];
}
public final long flow(int id) {
if (reverseEdge == null)
return 0;
return capacity[reverseEdge[id]];
}
public final void pushFlow(int id, long flow) {
if (flow == 0)
return;
if (flow > 0) {
if (capacity(id) < flow)
throw new IllegalArgumentException("Not enough capacity");
} else {
if (flow(id) < -flow)
throw new IllegalArgumentException("Not enough capacity");
}
capacity[id] -= flow;
capacity[reverseEdge[id]] += flow;
}
public int transposed(int id) {
return -1;
}
public final int reverse(int id) {
if (reverseEdge == null)
return -1;
return reverseEdge[id];
}
public final void addVertices(int count) {
ensureVertexCapacity(vertexCount + count);
Arrays.fill(firstOutbound, vertexCount, vertexCount + count, -1);
if (firstInbound != null)
Arrays.fill(firstInbound, vertexCount, vertexCount + count, -1);
vertexCount += count;
}
protected final void initEdges() {
if (edges == null) {
edges = new Edge[from.length];
for (int i = 0; i < edgeCount; i++)
edges[i] = createEdge(i);
}
}
public final void removeVertex(int vertex) {
int id = firstOutbound[vertex];
while (id != -1) {
removeEdge(id);
id = nextOutbound[id];
}
initInbound();
id = firstInbound[vertex];
while (id != -1) {
removeEdge(id);
id = nextInbound[id];
}
}
private void initInbound() {
if (firstInbound == null) {
firstInbound = new int[firstOutbound.length];
Arrays.fill(firstInbound, 0, vertexCount, -1);
nextInbound = new int[from.length];
for (int i = 0; i < edgeCount; i++) {
nextInbound[i] = firstInbound[to[i]];
firstInbound[to[i]] = i;
}
}
}
public final boolean flag(int id, int bit) {
return (flags[id] >> bit & 1) != 0;
}
public final void setFlag(int id, int bit) {
flags[id] |= 1 << bit;
}
public final void removeFlag(int id, int bit) {
flags[id] &= -1 - (1 << bit);
}
public final void removeEdge(int id) {
setFlag(id, REMOVED_BIT);
}
public final void restoreEdge(int id) {
removeFlag(id, REMOVED_BIT);
}
public final boolean isRemoved(int id) {
return flag(id, REMOVED_BIT);
}
public final Iterable<Edge> outbound(final int id) {
initEdges();
return new Iterable<Edge>() {
public Iterator<Edge> iterator() {
return new EdgeIterator(id, firstOutbound, nextOutbound);
}
};
}
public final Iterable<Edge> inbound(final int id) {
initEdges();
initInbound();
return new Iterable<Edge>() {
public Iterator<Edge> iterator() {
return new EdgeIterator(id, firstInbound, nextInbound);
}
};
}
protected void ensureEdgeCapacity(int size) {
if (from.length < size) {
int newSize = Math.max(size, 2 * from.length);
if (edges != null)
edges = resize(edges, newSize);
from = resize(from, newSize);
to = resize(to, newSize);
nextOutbound = resize(nextOutbound, newSize);
if (nextInbound != null)
nextInbound = resize(nextInbound, newSize);
if (weight != null)
weight = resize(weight, newSize);
if (capacity != null)
capacity = resize(capacity, newSize);
if (reverseEdge != null)
reverseEdge = resize(reverseEdge, newSize);
flags = resize(flags, newSize);
}
}
private void ensureVertexCapacity(int size) {
if (firstOutbound.length < size) {
int newSize = Math.max(size, 2 * from.length);
firstOutbound = resize(firstOutbound, newSize);
if (firstInbound != null)
firstInbound = resize(firstInbound, newSize);
}
}
protected final int[] resize(int[] array, int size) {
int[] newArray = new int[size];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
private long[] resize(long[] array, int size) {
long[] newArray = new long[size];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
private Edge[] resize(Edge[] array, int size) {
Edge[] newArray = new Edge[size];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
public final boolean isSparse() {
return vertexCount == 0 || edgeCount * 20 / vertexCount <= vertexCount;
}
protected class GraphEdge implements Edge {
protected int id;
protected GraphEdge(int id) {
this.id = id;
}
public int getSource() {
return source(id);
}
public int getDestination() {
return destination(id);
}
public long getWeight() {
return weight(id);
}
public long getCapacity() {
return capacity(id);
}
public long getFlow() {
return flow(id);
}
public void pushFlow(long flow) {
Graph.this.pushFlow(id, flow);
}
public boolean getFlag(int bit) {
return flag(id, bit);
}
public void setFlag(int bit) {
Graph.this.setFlag(id, bit);
}
public void removeFlag(int bit) {
Graph.this.removeFlag(id, bit);
}
public int getTransposedID() {
return transposed(id);
}
public Edge getTransposedEdge() {
int reverseID = getTransposedID();
if (reverseID == -1)
return null;
initEdges();
return edge(reverseID);
}
public int getReverseID() {
return reverse(id);
}
public Edge getReverseEdge() {
int reverseID = getReverseID();
if (reverseID == -1)
return null;
initEdges();
return edge(reverseID);
}
public int getID() {
return id;
}
public void remove() {
removeEdge(id);
}
public void restore() {
restoreEdge(id);
}
}
public class EdgeIterator implements Iterator<Edge> {
private int edgeID;
private final int[] next;
private int lastID = -1;
public EdgeIterator(int id, int[] first, int[] next) {
this.next = next;
edgeID = nextEdge(first[id]);
}
private int nextEdge(int id) {
while (id != -1 && isRemoved(id))
id = next[id];
return id;
}
public boolean hasNext() {
return edgeID != -1;
}
public Edge next() {
if (edgeID == -1)
throw new NoSuchElementException();
lastID = edgeID;
edgeID = nextEdge(next[lastID]);
return edges[lastID];
}
public void remove() {
if (lastID == -1)
throw new IllegalStateException();
removeEdge(lastID);
lastID = -1;
}
}
}
class MiscUtils {
public static final int[] DX4 = { 1, 0, -1, 0 };
public static final int[] DY4 = { 0, -1, 0, 1 };
public static final int[] DX8 = { 1, 1, 1, 0, -1, -1, -1, 0 };
public static final int[] DY8 = { -1, 0, 1, 1, 1, 0, -1, -1 };
public static final int[] DX_KNIGHT = { 2, 1, -1, -2, -2, -1, 1, 2 };
public static final int[] DY_KNIGHT = { 1, 2, 2, 1, -1, -2, -2, -1 };
private static final String[] ROMAN_TOKENS = { "M", "CM", "D", "CD", "C",
"XC", "L", "XL", "X", "IX", "V", "IV", "I" };
private static final int[] ROMAN_VALUES = { 1000, 900, 500, 400, 100, 90,
50, 40, 10, 9, 5, 4, 1 };
public static long josephProblem(long n, int k) {
if (n == 1)
return 0;
if (k == 1)
return n - 1;
if (k > n)
return (josephProblem(n - 1, k) + k) % n;
long count = n / k;
long result = josephProblem(n - count, k);
result -= n % k;
if (result < 0)
result += n;
else
result += result / (k - 1);
return result;
}
public static boolean isValidCell(int row, int column, int rowCount,
int columnCount) {
return row >= 0 && row < rowCount && column >= 0
&& column < columnCount;
}
public static List<Integer> getPath(int[] last, int destination) {
List<Integer> path = new ArrayList<Integer>();
while (destination != -1) {
path.add(destination);
destination = last[destination];
}
inPlaceReverse(path);
return path;
}
private static void inPlaceReverse(List<Integer> list) {
for (int i = 0, j = list.size() - 1; i < j; i++, j--)
swap(list, i, j);
}
private static void swap(List<Integer> list, int first, int second) {
if (first == second)
return;
int temp = list.get(first);
list.set(first, list.get(second));
list.set(second, temp);
}
public static List<Integer> getPath(int[][] lastIndex,
int[][] lastPathNumber, int destination, int pathNumber) {
List<Integer> path = new ArrayList<Integer>();
while (destination != -1 || pathNumber != 0) {
path.add(destination);
int nextDestination = lastIndex[destination][pathNumber];
pathNumber = lastPathNumber[destination][pathNumber];
destination = nextDestination;
}
inPlaceReverse(path);
return path;
}
public static long maximalRectangleSum(long[][] array) {
int n = array.length;
int m = array[0].length;
long[][] partialSums = new long[n + 1][m + 1];
for (int i = 0; i < n; i++) {
long rowSum = 0;
for (int j = 0; j < m; j++) {
rowSum += array[i][j];
partialSums[i + 1][j + 1] = partialSums[i][j + 1] + rowSum;
}
}
long result = Long.MIN_VALUE;
for (int i = 0; i < m; i++) {
for (int j = i; j < m; j++) {
long minPartialSum = 0;
for (int k = 1; k <= n; k++) {
long current = partialSums[k][j + 1] - partialSums[k][i];
result = Math.max(result, current - minPartialSum);
minPartialSum = Math.min(minPartialSum, current);
}
}
}
return result;
}
public static int parseIP(String ip) {
String[] components = ip.split("[.]");
int result = 0;
for (int i = 0; i < 4; i++)
result += (1 << (24 - 8 * i)) * Integer.parseInt(components[i]);
return result;
}
public static String buildIP(int mask) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < 4; i++) {
if (i != 0)
result.append('.');
result.append(mask >> (24 - 8 * i) & 255);
}
return result.toString();
}
public static long binarySearch(long from, long to,
Function<Long, Boolean> function) {
while (from < to) {
long argument = from + (to - from) / 2;
if (function.value(argument))
to = argument;
else
from = argument + 1;
}
return from;
}
public static <T> boolean equals(T first, T second) {
return first == null && second == null || first != null
&& first.equals(second);
}
public static boolean isVowel(char ch) {
ch = Character.toUpperCase(ch);
return ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'
|| ch == 'Y';
}
public static boolean isStrictVowel(char ch) {
ch = Character.toUpperCase(ch);
return ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U';
}
public static String convertToRoman(int number) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < ROMAN_TOKENS.length; i++) {
while (number >= ROMAN_VALUES[i]) {
number -= ROMAN_VALUES[i];
result.append(ROMAN_TOKENS[i]);
}
}
return result.toString();
}
public static int convertFromRoman(String number) {
int result = 0;
for (int i = 0; i < ROMAN_TOKENS.length; i++) {
while (number.startsWith(ROMAN_TOKENS[i])) {
number = number.substring(ROMAN_TOKENS[i].length());
result += ROMAN_VALUES[i];
}
}
return result;
}
public static int distance(int x1, int y1, int x2, int y2) {
int dx = x1 - x2;
int dy = y1 - y2;
return dx * dx + dy * dy;
}
public static <T extends Comparable<T>> T min(T first, T second) {
if (first.compareTo(second) <= 0)
return first;
return second;
}
public static <T extends Comparable<T>> T max(T first, T second) {
if (first.compareTo(second) <= 0)
return second;
return first;
}
public static void decreaseByOne(int[]... arrays) {
for (int[] array : arrays) {
for (int i = 0; i < array.length; i++)
array[i]--;
}
}
public static int[] getIntArray(String s) {
String[] tokens = s.split(" ");
int[] result = new int[tokens.length];
for (int i = 0; i < result.length; i++)
result[i] = Integer.parseInt(tokens[i]);
return result;
}
}
class IntegerUtils {
public static long gcd(long a, long b) {
a = Math.abs(a);
b = Math.abs(b);
while (b != 0) {
long temp = a % b;
a = b;
b = temp;
}
return a;
}
public static int gcd(int a, int b) {
a = Math.abs(a);
b = Math.abs(b);
while (b != 0) {
int temp = a % b;
a = b;
b = temp;
}
return a;
}
public static int[] generatePrimes(int upTo) {
int[] isPrime = generateBitPrimalityTable(upTo);
List<Integer> primes = new ArrayList<Integer>();
for (int i = 0; i < upTo; i++) {
if ((isPrime[i >> 5] >>> (i & 31) & 1) == 1)
primes.add(i);
}
int[] array = new int[primes.size()];
for (int i = 0; i < array.length; i++)
array[i] = primes.get(i);
return array;
}
public static boolean[] generatePrimalityTable(int upTo) {
boolean[] isPrime = new boolean[upTo];
if (upTo < 2)
return isPrime;
Arrays.fill(isPrime, true);
isPrime[0] = isPrime[1] = false;
for (int i = 2; i * i < upTo; i++) {
if (isPrime[i]) {
for (int j = i * i; j < upTo; j += i)
isPrime[j] = false;
}
}
return isPrime;
}
public static int[] generateBitPrimalityTable(int upTo) {
int[] isPrime = new int[(upTo + 31) >> 5];
if (upTo < 2)
return isPrime;
Arrays.fill(isPrime, -1);
isPrime[0] &= -4;
for (int i = 2; i * i < upTo; i++) {
if ((isPrime[i >> 5] >>> (i & 31) & 1) == 1) {
for (int j = i * i; j < upTo; j += i)
isPrime[j >> 5] &= -1 - (1 << (j & 31));
}
}
return isPrime;
}
public static int[] generateDivisorTable(int upTo) {
int[] divisor = new int[upTo];
for (int i = 1; i < upTo; i++)
divisor[i] = i;
for (int i = 2; i * i < upTo; i++) {
if (divisor[i] == i) {
for (int j = i * i; j < upTo; j += i)
divisor[j] = i;
}
}
return divisor;
}
public static long powerInFactorial(long n, long p) {
long result = 0;
while (n != 0) {
result += n /= p;
}
return result;
}
public static int sumDigits(CharSequence number) {
int result = 0;
for (int i = number.length() - 1; i >= 0; i--)
result += digitValue(number.charAt(i));
return result;
}
public static int digitValue(char digit) {
if (Character.isDigit(digit))
return digit - '0';
if (Character.isUpperCase(digit))
return digit + 10 - 'A';
return digit + 10 - 'a';
}
public static int longCompare(long a, long b) {
if (a < b)
return -1;
if (a > b)
return 1;
return 0;
}
public static long[][] generateBinomialCoefficients(int n) {
long[][] result = new long[n + 1][n + 1];
for (int i = 0; i <= n; i++) {
result[i][0] = 1;
for (int j = 1; j <= i; j++)
result[i][j] = result[i - 1][j - 1] + result[i - 1][j];
}
return result;
}
public static long[][] generateBinomialCoefficients(int n, long module) {
long[][] result = new long[n + 1][n + 1];
if (module == 1)
return result;
for (int i = 0; i <= n; i++) {
result[i][0] = 1;
for (int j = 1; j <= i; j++) {
result[i][j] = result[i - 1][j - 1] + result[i - 1][j];
if (result[i][j] >= module)
result[i][j] -= module;
}
}
return result;
}
public static long[] generateBinomialRow(int n, long module) {
long[] result = generateReverse(n + 1, module);
result[0] = 1;
for (int i = 1; i <= n; i++)
result[i] = result[i - 1] * (n - i + 1) % module * result[i]
% module;
return result;
}
public static int[] representationInBase(long number, int base) {
long basePower = base;
int exponent = 1;
while (number >= basePower) {
basePower *= base;
exponent++;
}
int[] representation = new int[exponent];
for (int i = 0; i < exponent; i++) {
basePower /= base;
representation[i] = (int) (number / basePower);
number %= basePower;
}
return representation;
}
public static int trueDivide(int a, int b) {
return (a - trueMod(a, b)) / b;
}
public static long trueDivide(long a, long b) {
return (a - trueMod(a, b)) / b;
}
public static int trueMod(int a, int b) {
a %= b;
a += b;
a %= b;
return a;
}
public static long trueMod(long a, long b) {
a %= b;
a += b;
a %= b;
return a;
}
public static long factorial(int n) {
long result = 1;
for (int i = 2; i <= n; i++)
result *= i;
return result;
}
public static long factorial(int n, long mod) {
long result = 1;
for (int i = 2; i <= n; i++)
result = result * i % mod;
return result % mod;
}
public static List<Pair<Long, Integer>> factorize(long number) {
List<Pair<Long, Integer>> result = new ArrayList<Pair<Long, Integer>>();
for (long i = 2; i * i <= number; i++) {
if (number % i == 0) {
int power = 0;
do {
power++;
number /= i;
} while (number % i == 0);
result.add(Pair.makePair(i, power));
}
}
if (number != 1)
result.add(Pair.makePair(number, 1));
return result;
}
public static List<Long> getDivisors(long number) {
List<Pair<Long, Integer>> primeDivisors = factorize(number);
return getDivisorsImpl(primeDivisors, 0, 1, new ArrayList<Long>());
}
private static List<Long> getDivisorsImpl(
List<Pair<Long, Integer>> primeDivisors, int index, long current,
List<Long> result) {
if (index == primeDivisors.size()) {
result.add(current);
return result;
}
long p = primeDivisors.get(index).first;
int power = primeDivisors.get(index).second;
for (int i = 0; i <= power; i++) {
getDivisorsImpl(primeDivisors, index + 1, current, result);
current *= p;
}
return result;
}
public static long power(long base, long exponent) {
if (exponent == 0)
return 1;
long result = power(base, exponent >> 1);
result = result * result;
if ((exponent & 1) != 0)
result = result * base;
return result;
}
public static long power(long base, long exponent, long mod) {
if (base >= mod)
base %= mod;
if (exponent == 0)
return 1 % mod;
long result = power(base, exponent >> 1, mod);
result = result * result % mod;
if ((exponent & 1) != 0)
result = result * base % mod;
return result;
}
public static long lcm(long a, long b) {
return a / gcd(a, b) * b;
}
public static long[] generateFibonacci(long upTo) {
int count = 0;
long last = 0;
long current = 1;
while (current <= upTo) {
long next = last + current;
last = current;
current = next;
count++;
}
return generateFibonacci(count, -1);
}
public static long[] generateFibonacci(int count, long module) {
long[] result = new long[count];
if (module == -1) {
if (count != 0)
result[0] = 1;
if (count > 1)
result[1] = 1;
for (int i = 2; i < count; i++)
result[i] = result[i - 1] + result[i - 2];
} else {
if (count != 0)
result[0] = 1 % module;
if (count > 1)
result[1] = 1 % module;
for (int i = 2; i < count; i++)
result[i] = (result[i - 1] + result[i - 2]) % module;
}
return result;
}
public static long[] generateHappy(int digits) {
long[] happy = new long[(1 << (digits + 1)) - 2];
happy[0] = 4;
happy[1] = 7;
int first = 0;
int last = 2;
for (int i = 2; i <= digits; i++) {
for (int j = 0; j < last - first; j++) {
happy[last + 2 * j] = 10 * happy[first + j] + 4;
happy[last + 2 * j + 1] = 10 * happy[first + j] + 7;
}
int next = last + 2 * (last - first);
first = last;
last = next;
}
return happy;
}
public static long[] generateFactorial(int count, long module) {
long[] result = new long[count];
if (module == -1) {
if (count != 0)
result[0] = 1;
for (int i = 1; i < count; i++)
result[i] = result[i - 1] * i;
} else {
if (count != 0)
result[0] = 1 % module;
for (int i = 1; i < count; i++)
result[i] = (result[i - 1] * i) % module;
}
return result;
}
public static long reverse(long number, long module) {
return power(number, module - 2, module);
}
public static boolean isPrime(long number) {
if (number < 2)
return false;
for (long i = 2; i * i <= number; i++) {
if (number % i == 0)
return false;
}
return true;
}
public static long[] generateReverse(int upTo, long module) {
long[] result = new long[upTo];
if (upTo > 1)
result[1] = 1;
for (int i = 2; i < upTo; i++)
result[i] = (module - module / i * result[((int) (module % i))]
% module)
% module;
return result;
}
public static long[] generateReverseFactorials(int upTo, long module) {
long[] result = generateReverse(upTo, module);
if (upTo > 0)
result[0] = 1;
for (int i = 1; i < upTo; i++)
result[i] = result[i] * result[i - 1] % module;
return result;
}
public static long[] generatePowers(long base, int count, long mod) {
long[] result = new long[count];
if (count != 0)
result[0] = 1 % mod;
for (int i = 1; i < count; i++)
result[i] = result[i - 1] * base % mod;
return result;
}
public static long nextPrime(long from) {
if (from <= 2)
return 2;
from += 1 - (from & 1);
while (!isPrime(from))
from += 2;
return from;
}
public static long binomialCoefficient(int n, int m, long mod) {
if (m < 0 || m > n)
return 0;
if (2 * m > n)
m = n - m;
long result = 1;
for (int i = n - m + 1; i <= n; i++)
result = result * i % mod;
return result
* BigInteger.valueOf(factorial(m, mod))
.modInverse(BigInteger.valueOf(mod)).longValue() % mod;
}
public static boolean isSquare(long number) {
long sqrt = Math.round(Math.sqrt(number));
return sqrt * sqrt == number;
}
public static long findCommon(long aRemainder, long aMod, long bRemainder,
long bMod) {
long modGCD = gcd(aMod, bMod);
long gcdRemainder = aRemainder % modGCD;
if (gcdRemainder != bRemainder % modGCD)
return -1;
aMod /= modGCD;
aRemainder /= modGCD;
bMod /= modGCD;
bRemainder /= modGCD;
long aReverse = BigInteger.valueOf(aMod)
.modInverse(BigInteger.valueOf(bMod)).longValue();
long bReverse = BigInteger.valueOf(bMod)
.modInverse(BigInteger.valueOf(aMod)).longValue();
long mod = aMod * bMod;
return (bReverse * aRemainder % mod * bMod + aReverse * bRemainder
% mod * aMod)
% mod * modGCD + gcdRemainder;
}
public static long[] generatePowers(long base, long maxValue) {
if (maxValue <= 0)
return new long[0];
int size = 1;
long current = 1;
while (maxValue / base >= current) {
current *= base;
size++;
}
return generatePowers(base, size, Long.MAX_VALUE);
}
}
interface IntComparator extends Comparator<Integer> {
public static final IntComparator DEFAULT = new IntComparator() {
public int compare(Integer first, Integer second) {
if (first < second)
return -1;
if (first > second)
return 1;
return 0;
}
};
public static final IntComparator REVERSE = new IntComparator() {
public int compare(Integer first, Integer second) {
if (first < second)
return 1;
if (first > second)
return -1;
return 0;
}
};
public int compare(Integer first, Integer second);
}
class BidirectionalGraph extends Graph {
public int[] transposedEdge;
public BidirectionalGraph(int vertexCount) {
this(vertexCount, vertexCount);
}
public BidirectionalGraph(int vertexCount, int edgeCapacity) {
super(vertexCount, 2 * edgeCapacity);
transposedEdge = new int[2 * edgeCapacity];
}
public static BidirectionalGraph createGraph(int vertexCount, int[] from,
int[] to) {
BidirectionalGraph graph = new BidirectionalGraph(vertexCount,
from.length);
for (int i = 0; i < from.length; i++)
graph.addSimpleEdge(from[i], to[i]);
return graph;
}
public static BidirectionalGraph createWeightedGraph(int vertexCount,
int[] from, int[] to, long[] weight) {
BidirectionalGraph graph = new BidirectionalGraph(vertexCount,
from.length);
for (int i = 0; i < from.length; i++)
graph.addWeightedEdge(from[i], to[i], weight[i]);
return graph;
}
public static BidirectionalGraph createFlowGraph(int vertexCount,
int[] from, int[] to, long[] capacity) {
BidirectionalGraph graph = new BidirectionalGraph(vertexCount,
from.length * 2);
for (int i = 0; i < from.length; i++)
graph.addFlowEdge(from[i], to[i], capacity[i]);
return graph;
}
public static BidirectionalGraph createFlowWeightedGraph(int vertexCount,
int[] from, int[] to, long[] weight, long[] capacity) {
BidirectionalGraph graph = new BidirectionalGraph(vertexCount,
from.length * 2);
for (int i = 0; i < from.length; i++)
graph.addFlowWeightedEdge(from[i], to[i], weight[i], capacity[i]);
return graph;
}
@Override
public int addEdge(int fromID, int toID, long weight, long capacity,
int reverseEdge) {
int lastEdgeCount = edgeCount;
super.addEdge(fromID, toID, weight, capacity, reverseEdge);
super.addEdge(toID, fromID, weight, capacity, reverseEdge == -1 ? -1
: reverseEdge + 1);
this.transposedEdge[lastEdgeCount] = lastEdgeCount + 1;
this.transposedEdge[lastEdgeCount + 1] = lastEdgeCount;
return lastEdgeCount;
}
@Override
protected int entriesPerEdge() {
return 2;
}
@Override
public final int transposed(int id) {
return transposedEdge[id];
}
@Override
protected void ensureEdgeCapacity(int size) {
if (size > edgeCapacity()) {
super.ensureEdgeCapacity(size);
transposedEdge = resize(transposedEdge, edgeCapacity());
}
}
}
class Pair<U, V> implements Comparable<Pair<U, V>> {
public final U first;
public final V second;
public static <U, V> Pair<U, V> makePair(U first, V second) {
return new Pair<U, V>(first, second);
}
private Pair(U first, V second) {
this.first = first;
this.second = second;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Pair pair = (Pair) o;
return !(first != null ? !first.equals(pair.first) : pair.first != null)
&& !(second != null ? !second.equals(pair.second)
: pair.second != null);
}
@Override
public int hashCode() {
int result = first != null ? first.hashCode() : 0;
result = 31 * result + (second != null ? second.hashCode() : 0);
return result;
}
public Pair<V, U> swap() {
return makePair(second, first);
}
@Override
public String toString() {
return "(" + first + "," + second + ")";
}
@SuppressWarnings({ "unchecked" })
public int compareTo(Pair<U, V> o) {
int value = ((Comparable<U>) first).compareTo(o.first);
if (value != 0)
return value;
return ((Comparable<V>) second).compareTo(o.second);
}
}
interface Edge {
public int getSource();
public int getDestination();
public long getWeight();
public long getCapacity();
public long getFlow();
public void pushFlow(long flow);
public boolean getFlag(int bit);
public void setFlag(int bit);
public void removeFlag(int bit);
public int getTransposedID();
public Edge getTransposedEdge();
public int getReverseID();
public Edge getReverseEdge();
public int getID();
public void remove();
public void restore();
}
interface Function<A, V> {
public abstract V value(A argument);
} | Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers nΒ (1ββ€βnββ€β500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xiΒ (1ββ€βxiββ€β106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai,βbi,βciΒ (1ββ€βaiβ<βbiββ€βn;Β 1ββ€βciββ€β103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10β-β9. | standard output | |
PASSED | e52e05542e092b370026db9d93db2758 | train_001.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V',βE') of a graph G(V,βE) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.util.*;
public class N3 {
static int n;
static int dist[][];
static int node[];
static boolean isok[];
static boolean used[];
static int V, E;
static int VI[];
static int EI[];
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sca = new Scanner(System.in);
// System.out.println((double) (98 + 73) / (63));
n = sca.nextInt();
int m = sca.nextInt();
node = new int[n + 1];
isok = new boolean[n + 1];
VI = new int[n + 1];
EI = new int[n + 1];
dist = new int[n + 1][n + 1];
V = 0;
E = 0;
for (int i = 1; i <= n; i++) {
node[i] = sca.nextInt();
V = V + node[i];
}
double sum=0;
for (int j = 1; j <= m; j++) {
int l = sca.nextInt();
int r = sca.nextInt();
int c = sca.nextInt();
sum=Math.max(sum, (double)(node[l]+node[r])/(double)c);
}
System.out.println(sum);
}
static void change(int t, int v, int e) {
for (int i = 1; i <= n; i++) {
if (dist[i][t] != 0 && !isok[i]) {
VI[i] = v;
EI[i] = e;
change(i,v,e);
}
}
}
static void DFS(int t, boolean ju) {
for (int i = 1; i <= n; i++) {
if (dist[i][t] != 0 && !isok[i]) {
isok[t] = true;
// used[t] = true;
if (ju) {
V = V + node[i];
E = E + dist[i][t];
}
DFS(i,ju);
}
}
}
}
| Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers nΒ (1ββ€βnββ€β500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xiΒ (1ββ€βxiββ€β106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai,βbi,βciΒ (1ββ€βaiβ<βbiββ€βn;Β 1ββ€βciββ€β103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10β-β9. | standard output | |
PASSED | 757c90a88faf5a8da960d65e80356260 | train_001.jsonl | 1404651900 | DZY loves Physics, and he enjoys calculating density.Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: where v is the sum of the values of the nodes, e is the sum of the values of the edges.Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible.An induced subgraph G'(V',βE') of a graph G(V,βE) is a graph that satisfies: ; edge if and only if , and edge ; the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class G {
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
void init() {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} catch (Exception e) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
}
String readString() {
try {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
} catch (Exception e) {
return null;
}
}
int readInt() {
return Integer.parseInt(readString());
}
long readLong() {
return Long.parseLong(readString());
}
int[] readIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = readInt();
}
return a;
}
public static void main(String[] args) {
new G().run();
}
void run() {
try {
long tStart = System.currentTimeMillis();
init();
solve();
in.close();
out.close();
long tEnd = System.currentTimeMillis();
System.err.println(tEnd - tStart);
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
void solve() {
int n = readInt();
int m = readInt();
int[] x = readIntArray(n);
double max = 0;
for (int i = 0; i < m; i++) {
int a = readInt() - 1;
int b = readInt() - 1;
int c = readInt();
double res = (1d * x[a] + x[b]) / c;
max = Math.max(max, res);
}
out.println(max);
}
} | Java | ["1 0\n1", "2 1\n1 2\n1 2 1", "5 6\n13 56 73 98 17\n1 2 56\n1 3 29\n1 4 42\n2 3 95\n2 4 88\n3 4 63"] | 1 second | ["0.000000000000000", "3.000000000000000", "2.965517241379311"] | NoteIn the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1.In the second sample, choosing the whole graph is optimal. | Java 8 | standard input | [
"greedy",
"math"
] | ba4304e79d85d13c12233bcbcce6d0a6 | The first line contains two space-separated integers nΒ (1ββ€βnββ€β500), . Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xiΒ (1ββ€βxiββ€β106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai,βbi,βciΒ (1ββ€βaiβ<βbiββ€βn;Β 1ββ€βciββ€β103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. | 1,600 | Output a real number denoting the answer, with an absolute or relative error of at most 10β-β9. | standard output | |
PASSED | 4d85362e68c304311611e1755cacf533 | train_001.jsonl | 1402673400 | Everyone who has played Cut the Rope knows full well how the gameplay is organized. All levels in the game are divided into boxes. Initially only one box with some levels is available. Player should complete levels to earn stars, collecting stars opens new box with levels. Imagine that you are playing Cut the Rope for the first time. Currently you have only the levels of the first box (by the way, it is called "Cardboard Box"). Each level is characterized by two integers: ai β how long it takes to complete the level for one star, bi β how long it takes to complete the level for two stars (aiβ<βbi).You want to open the next box as quickly as possible. So, you need to earn at least w stars. How do make it happen? Note that the level can be passed only once: either for one star or for two. You do not necessarily need to pass all the levels. | 256 megabytes | import java.util.HashMap;
import java.util.Comparator;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Random;
import java.util.Map;
import java.util.List;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.TreeMap;
import java.util.ArrayList;
import java.util.Set;
import java.util.TreeSet;
import java.util.StringTokenizer;
import java.math.BigInteger;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
}
class TaskE {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int w = in.nextInt();
int[] a = new int[n];
int[] b = new int[n];
Utils.readIntArrays(in, a, b);
Node[] nodes = new Node[n];
Node root;
for (int i = 0; i < n; ++i) {
nodes[i] = new Node();
nodes[i].a = a[i];
nodes[i].b = b[i];
nodes[i].id = i;
nodes[i].key = a[i];
nodes[i].sum = a[i];
nodes[i].addToSum = 0;
}
Arrays.sort(nodes, new Comparator<Node>() {
@Override
public int compare(Node o1, Node o2) {
if (o1.b != o2.b) return o1.b - o2.b;
return o1.id - o2.id;
}
});
root = nodes[0];
for (int i = 1; i < n; ++i) {
root = CartesianTree.insertByKey(root, nodes[i]);
}
dfsUpdate(root);
long result = getCurrentResult(root, w);
int bestPrefix = 0;
long sum = 0;
for (int i = 0; i < n; ++i) {
root = CartesianTree.removeByKey(root, nodes[i].key);
Node newNode = new Node();
sum += nodes[i].a;
newNode.key = nodes[i].b - nodes[i].a;
newNode.sum = newNode.key;
root = CartesianTree.insertByKey(root, newNode);
int prefixLength = i + 1;
if (w < prefixLength) break;
long cur = getCurrentResult(root, w - prefixLength);
if (cur < Long.MAX_VALUE) {
cur += sum;
}
if (result > cur) {
result = cur;
bestPrefix = prefixLength;
}
}
out.println(result);
for (int i = 0; i < n; ++i) {
nodes[i] = new Node();
nodes[i].a = a[i];
nodes[i].b = b[i];
nodes[i].id = i;
nodes[i].key = a[i];
nodes[i].sum = a[i];
nodes[i].addToSum = 0;
nodes[i].left = null;
nodes[i].right = null;
}
Arrays.sort(nodes, new Comparator<Node>() {
@Override
public int compare(Node o1, Node o2) {
if (o1.b != o2.b) return o1.b - o2.b;
return o1.id - o2.id;
}
});
root = nodes[0];
for (int i = 1; i < n; ++i) {
root = CartesianTree.insertByKey(root, nodes[i]);
}
dfsUpdate(root);
for (int i = 0; i < bestPrefix; ++i) {
root = CartesianTree.removeByKey(root, nodes[i].key);
Node newNode = new Node();
newNode.key = nodes[i].b - nodes[i].a;
newNode.sum = newNode.key;
root = CartesianTree.insertByKey(root, newNode);
}
TreeMap<Integer, Set<Integer>> aToIdsTaken = new TreeMap<Integer, Set<Integer>>();
TreeMap<Integer, Set<Integer>> aToIdsNotTaken = new TreeMap<Integer, Set<Integer>>();
Map<Integer, Integer> bMinusA = new HashMap<Integer, Integer>();
int[] taken = new int[n];
for (int i = 0; i < bestPrefix; ++i) {
putToMap(nodes[i].a, nodes[i].id, aToIdsTaken);
}
for (int i = bestPrefix; i < n; ++i) {
putToMap(nodes[i].a, nodes[i].id, aToIdsNotTaken);
}
Node[] p = CartesianTree.splitByPosition(root, w - bestPrefix, new Node[] {null, null});
dfs(p[0], aToIdsTaken, aToIdsNotTaken, bMinusA);
for (int idx : aToIdsTaken.keySet()) {
for (int x : aToIdsTaken.get(idx)) {
taken[x] = 1;
}
}
for (int i = 0; i < n; ++i) {
if (taken[i] == 1) {
if (bMinusA.containsKey(b[i] - a[i])) {
removeFromMap(bMinusA, b[i] - a[i]);
taken[i] = 2;
}
}
}
for (int i = 0; i < n; ++i) {
out.print(taken[i]);
}
out.println();
}
private void dfsUpdate(Node v) {
if (v == null) return;
dfsUpdate(v.left);
dfsUpdate(v.right);
v.updateData();
}
private void removeFromMap(Map<Integer, Integer> m, int x) {
if (m.get(x) == 1) m.remove(x);
else {
m.put(x, m.get(x) - 1);
}
}
private void dfs(Node v, Map<Integer, Set<Integer>> aToIdsTaken, Map<Integer, Set<Integer>> aToIdsNotTaken, Map<Integer, Integer> bMinusA) {
if (v == null) return;
if (aToIdsNotTaken.containsKey(v.key)) {
TreeSet<Integer> cur = (TreeSet<Integer>) aToIdsNotTaken.get(v.key);
int id = cur.first();
cur.remove(id);
putToMap(v.key, id, aToIdsTaken);
if (cur.size() > 0) {
aToIdsNotTaken.put(v.key, cur);
} else {
aToIdsNotTaken.remove(v.key);
}
} else {
putToMap2(v.key, bMinusA);
}
dfs(v.left, aToIdsTaken, aToIdsNotTaken, bMinusA);
dfs(v.right, aToIdsTaken, aToIdsNotTaken, bMinusA);
}
private void putToMap2(int key, Map<Integer, Integer> m) {
if (m.containsKey(key)) {
m.put(key, m.get(key) + 1);
} else {
m.put(key, 1);
}
}
private void putToMap(int key, int id, Map<Integer, Set<Integer>> m) {
if (m.containsKey(key)) {
Set<Integer> s = m.get(key);
s.add(id);
m.put(key, s);
} else {
Set<Integer> s = new TreeSet<Integer>();
s.add(id);
m.put(key, s);
}
}
private long getCurrentResult(Node root, int prefixLength) {
if (root.size < prefixLength) {
return Long.MAX_VALUE;
}
Node[] p = CartesianTree.splitByPosition(root, prefixLength, new Node[] {null, null});
long sum = 0;
if (p[0] != null) {
sum = p[0].sum;
}
root = CartesianTree.merge(p[0], p[1]);
return sum;
}
class Node extends CartesianTree.OpenNode<Node> {
long sum;
int a, b;
int id;
long addToSum;
protected void pushData() {
if (addToSum != 0) {
if (this.left != null) {
this.left.sum += addToSum;
this.left.addToSum += addToSum;
}
if (this.right != null) {
this.right.sum += addToSum;
this.right.addToSum += addToSum;
}
addToSum = 0;
}
}
protected void updateData() {
assert addToSum == 0;
this.sum = this.key;
if (this.left != null) {
this.sum += this.left.sum;
}
if (this.right != null) {
this.sum += this.right.sum;
}
}
}
}
class InputReader {
private BufferedReader reader;
private StringTokenizer stt;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
}
public String nextLine() {
try {
return reader.readLine().trim();
} catch (IOException e) {
return null;
}
}
public String nextString() {
while (stt == null || !stt.hasMoreTokens()) {
stt = new StringTokenizer(nextLine());
}
return stt.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextString());
}
}
class Utils {
public static void readIntArrays(InputReader in, int[]... a) {
for (int i = 0; i < a[0].length; ++i) {
for (int j = 0; j < a.length; ++j) {
a[j][i] = in.nextInt();
}
}
}
}
class CartesianTree {
/**
* Base class for a node of cartesian tree.
* @param <Node>
*/
public static abstract class OpenNode<Node extends OpenNode<Node>> {
public static Random r = new Random(3731);
public Node left, right, parent;
public int priority;
public int size;
public int key;
protected OpenNode() {
this.size = 1;
this.priority = r.nextInt();
}
public void push() {
if (this == null) return;
updateParent();
pushData();
}
public void update() {
if (this == null) return;
updateParent();
updateData();
updateSize();
}
protected void updateSize() {
size = 1;
if (left != null) size += left.size;
if (right != null) size += right.size;
}
/**
* If the node has a lazy tag, pushes the changes to its children.
*/
protected abstract void pushData();
/**
* Recalculates the information in the node after its children have
* changed.
*/
protected abstract void updateData();
protected void updateParent() {
if (left != null) {
left.parent = (Node) this;
}
if (right != null) {
right.parent = (Node) this;
}
}
}
public static <Node extends OpenNode<Node>> int size(Node x) {
if (x == null) return 0;
return x.size;
}
public static <Node extends OpenNode<Node>> Node merge(Node left, Node right) {
if (left == null) return right;
if (right == null) return left;
left.push();
right.push();
if (left.priority > right.priority) {
left.right = merge(left.right, right);
left.update();
return left;
} else {
right.left = merge(left, right.left);
right.update();
return right;
}
}
public static <Node extends OpenNode<Node>> Node[] splitByKey(Node x, int key) {
if (x == null) {
return (Node[]) new OpenNode[]{null, null};
}
x.push();
Node[] p;
if (key < x.key) {
p = splitByKey(x.left, key);
x.left = p[1];
p[1] = x;
} else {
p = splitByKey(x.right, key);
x.right = p[0];
p[0] = x;
}
if (p[0] != null) p[0].update();
if (p[1] != null) p[1].update();
return p;
}
public static <Node extends OpenNode<Node>> Node insertByKey(Node t, Node it) {
if (t == null) {
return it;
}
t.push();
if (it.priority > t.priority) {
Node[] p = splitByKey(t, it.key);
it.left = p[0];
it.right = p[1];
t = it;
} else {
if (it.key < t.key) {
if (t.left == null) {
t.left = it;
} else {
t.left = insertByKey(t.left, it);
}
} else {
if (t.right == null) {
t.right = it;
} else {
t.right = insertByKey(t.right, it);
}
}
}
t.update();
return t;
}
public static <Node extends OpenNode<Node>> Node[] splitByPosition(Node x, int left, Node[] empty) {
if (x == null) {
return empty.clone();
}
x.push();
Node[] p;
if (left <= size(x.left)) {
p = splitByPosition(x.left, left, empty);
x.left = p[1];
p[1] = x;
} else {
p = splitByPosition(x.right, left - size(x.left) - 1, empty);
x.right = p[0];
p[0] = x;
}
if (p[0] != null) p[0].update();
if (p[1] != null) p[1].update();
return p;
}
public static <Node extends OpenNode<Node>> Node removeByKey(Node t, int key) {
t.push();
if (t.key == key) {
t = CartesianTree.merge(t.left, t.right);
} else {
if (key < t.key) {
t.left = removeByKey(t.left, key);
} else {
t.right = removeByKey(t.right, key);
}
}
if (t != null) t.update();
return t;
}
}
| Java | ["2 3\n1 2\n1 2", "5 3\n10 20\n5 10\n10 20\n6 9\n25 30"] | 5 seconds | ["3\n12", "14\n01020"] | NoteIn the first test sample, answer 21 is also assumed correct. | Java 8 | standard input | [
"data structures",
"greedy"
] | a4b9ad2c4980bd7ebe23acb4c37680df | The first line contains two integers n and w (1ββ€βnββ€β3Β·105;Β 1ββ€βwββ€β2n) β the number of levels in the first box and the number of stars you need to open another box. Each of the following n lines contains two integers ai and bi (1ββ€βaiβ<βbiββ€β109) β the attributes of the i-th level. | 2,600 | In the first line print integer t β the minimum time you need to open the next box. In the next line, print n digits without spaces β the description of the optimal scenario: if you need to pass the i-th level for one star, the i-th digit should equal 1; if you need to pass the i-th level for two stars, the i-th digit should equal 2; if you do not need to pass the i-th level at all, the i-th digit should equal 0. | standard output | |
PASSED | a5bbe3c3c0e06f76b0fce5ce3663ff76 | train_001.jsonl | 1402673400 | Everyone who has played Cut the Rope knows full well how the gameplay is organized. All levels in the game are divided into boxes. Initially only one box with some levels is available. Player should complete levels to earn stars, collecting stars opens new box with levels. Imagine that you are playing Cut the Rope for the first time. Currently you have only the levels of the first box (by the way, it is called "Cardboard Box"). Each level is characterized by two integers: ai β how long it takes to complete the level for one star, bi β how long it takes to complete the level for two stars (aiβ<βbi).You want to open the next box as quickly as possible. So, you need to earn at least w stars. How do make it happen? Note that the level can be passed only once: either for one star or for two. You do not necessarily need to pass all the levels. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.BigInteger;
import java.util.Collections.*;
import static java.lang.Math.*;
import static java.lang.Math.min;
import static java.util.Arrays.*;
import static java.math.BigInteger.*;
public class Main{
void run(){
Locale.setDefault(Locale.US);
boolean my;
try {
my = System.getProperty("MY_LOCAL") != null;
} catch (Exception e) {
my = false;
}
try{
err = System.err;
if( my ){
sc = new FastScanner(new BufferedReader(new FileReader("input.txt")));
// sc = new FastScanner(new BufferedReader(new FileReader("C:\\myTest.txt")));
out = new PrintWriter (new FileWriter("output.txt"));
}
else {
sc = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(new OutputStreamWriter(System.out));
}
// out = new PrintWriter(new OutputStreamWriter(System.out));
}catch(Exception e){
MLE();
}
if( my )
tBeg = System.currentTimeMillis();
solve();
if( my )
err.println( "TIME: " + (System.currentTimeMillis() - tBeg ) / 1e3 );
exit(0);
}
void exit( int val ){
err.flush();
out.flush();
System.exit(val);
}
double tBeg;
FastScanner sc;
PrintWriter out;
PrintStream err;
class FastScanner{
StringTokenizer st;
BufferedReader br;
FastScanner( BufferedReader _br ){
br = _br;
}
String readLine(){
try {
return br.readLine();
} catch (IOException e) {
return null;
}
}
String next(){
while( st==null || !st.hasMoreElements() )
st = new StringTokenizer(readLine());
return st.nextToken();
}
int nextInt(){ return Integer.parseInt(next()); }
long nextLong(){ return Long.parseLong(next()); }
double nextDouble(){ return Double.parseDouble(next()); }
}
void MLE(){
int[][] arr = new int[1024*1024][]; for( int i = 0; i < 1024*1024; ++i ) arr[i] = new int[1024*1024];
}
void MLE( boolean doNotMLE ){ if( !doNotMLE ) MLE(); }
void TLE(){
for(;;);
}
public static void main(String[] args) {
new Main().run();
// new Thread( null, new Runnable() {
// @Override
// public void run() {
// new Main().run();
// }
// }, "Lolka", 256_000_000L ).run();
}
////////////////////////////////////////////////////////////////
class Item{
long a, b;
int id;
Item( int _a, int _b, int _id ){
a = _a;
b = _b;
id = _id;
}
}
Comparator<Item> cmpId = (x, y) -> Long.compare(x.id, y.id);
Comparator<Item> cmpA = (x, y) -> Long.compare(x.a, y.a);
Comparator<Item> cmpB = (x, y) -> Long.compare(x.b, y.b);
Comparator<Item> cmpBsubA = (x, y) -> Long.compare( x.b-x.a, y.b-y.a );
int n, w;
TreeSet<Item> ts0a = new TreeSet<>( cmpA.thenComparing(cmpId::compare) );
TreeSet<Item> ts0b = new TreeSet<>( cmpB.thenComparing(cmpId::compare) );
TreeSet<Item> ts1A = new TreeSet<>( cmpA.thenComparing(cmpId::compare) );
TreeSet<Item> ts1BsubA = new TreeSet<>( cmpBsubA.thenComparing(cmpId::compare) );
TreeSet<Item> ts2BsubA = new TreeSet<>( cmpBsubA.thenComparing(cmpId::compare) );
long inf = Long.MAX_VALUE/10;
void solve(){
n = sc.nextInt();
w = sc.nextInt();
for( int i = 0; i < n; i++ ){
Item it = new Item(sc.nextInt(),sc.nextInt(),i);
ts0a.add( it );
ts0b.add( it );
}
long ans = 0;
for( int cntStars = 1; cntStars <= w; cntStars++ ){
long ans1 = inf;
long ans2 = inf;
long ans3 = inf;
long ans4 = inf;
if( !ts0a.isEmpty() ){
ans1 = ts0a.first().a;
}
if( !ts1A.isEmpty() ){
Item it10 = ts1A.last();
ts0b.add( it10 );
ans2 = ts0b.first().b - it10.a;
ts0b.remove(it10);
}
if( !ts1A.isEmpty() ){
ans3 = ts1BsubA.first().b - ts1BsubA.first().a;
}
if( !ts2BsubA.isEmpty() && !ts0a.isEmpty() ){
ans4 = ts0b.first().b - (ts2BsubA.last().b - ts2BsubA.last().a);
}
long delta = min( min(ans1,ans2), min(ans3,ans4) );
ans += delta;
// err.printf( "%2d) %2d %2d %2d\n", cntStars, ans1, ans2, ans3 );
if( delta == ans1 ){
Item it01 = ts0a.pollFirst();
ts0b.remove(it01);
ts1BsubA.add( it01 );
ts1A.add( it01 );
}
else if( delta == ans2 ){
Item it10 = ts1A.pollLast();
ts1BsubA.remove(it10);
ts0a.add( it10 );
ts0b.add( it10 );
Item it02 = ts0b.pollFirst();
ts0a.remove(it02);
ts2BsubA.add( it02 );
}
else if( delta == ans3 ){
Item it12 = ts1BsubA.pollFirst();
ts1A.remove(it12);
ts2BsubA.add( it12 );
}
else if( delta == ans4 ){
Item it21 = ts2BsubA.pollLast();
ts1A.add(it21);
ts1BsubA.add(it21);
Item it02 = ts0b.pollFirst();
ts0a.remove( it02 );
ts2BsubA.add( it02 );
}
else MLE();
if(!( ts0a.size() == ts0b.size() )) MLE();
if(!( ts1A.size() == ts1BsubA.size() )) MLE();
if(!( ts0a.size() + ts1A.size() + ts2BsubA.size() == n )) MLE();
if( ans1==inf && ans2 == inf ) MLE();
}
out.println( ans );
Integer[] answer = new Integer[n];
long ANS = 0;
for( Item it : ts0a ) answer[it.id] = 0;
for( Item it : ts1A ) { answer[it.id] = 1; ANS += it.a; }
for( Item it : ts2BsubA ) { answer[it.id] = 2; ANS += it.b; }
for( Integer val : answer ) out.print(val);
out.println();
if( ans != ANS ) MLE();
}
} | Java | ["2 3\n1 2\n1 2", "5 3\n10 20\n5 10\n10 20\n6 9\n25 30"] | 5 seconds | ["3\n12", "14\n01020"] | NoteIn the first test sample, answer 21 is also assumed correct. | Java 8 | standard input | [
"data structures",
"greedy"
] | a4b9ad2c4980bd7ebe23acb4c37680df | The first line contains two integers n and w (1ββ€βnββ€β3Β·105;Β 1ββ€βwββ€β2n) β the number of levels in the first box and the number of stars you need to open another box. Each of the following n lines contains two integers ai and bi (1ββ€βaiβ<βbiββ€β109) β the attributes of the i-th level. | 2,600 | In the first line print integer t β the minimum time you need to open the next box. In the next line, print n digits without spaces β the description of the optimal scenario: if you need to pass the i-th level for one star, the i-th digit should equal 1; if you need to pass the i-th level for two stars, the i-th digit should equal 2; if you do not need to pass the i-th level at all, the i-th digit should equal 0. | standard output | |
PASSED | f430d98bba7ac7eca73560a7b8ac0cbe | train_001.jsonl | 1402673400 | Everyone who has played Cut the Rope knows full well how the gameplay is organized. All levels in the game are divided into boxes. Initially only one box with some levels is available. Player should complete levels to earn stars, collecting stars opens new box with levels. Imagine that you are playing Cut the Rope for the first time. Currently you have only the levels of the first box (by the way, it is called "Cardboard Box"). Each level is characterized by two integers: ai β how long it takes to complete the level for one star, bi β how long it takes to complete the level for two stars (aiβ<βbi).You want to open the next box as quickly as possible. So, you need to earn at least w stars. How do make it happen? Note that the level can be passed only once: either for one star or for two. You do not necessarily need to pass all the levels. | 256 megabytes | import java.io.*;
import java.util.*;
public class PrECardboardBox {
public static void main(String[] args) throws IOException {
new PrECardboardBox().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st;
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out, true);
solve();
out.flush();
}
class pair implements Comparable<pair> {
int val;
int ind;
public pair(int val, int ind) {
this.val = val;
this.ind = ind;
}
@Override
public int compareTo(pair arg0) {
if (this.val < arg0.val) {
return -1;
}
if (this.val > arg0.val) {
return 1;
}
if (this.ind < arg0.ind) {
return -1;
}
if (this.ind > arg0.ind) {
return 1;
}
return 0;
}
@Override
public boolean equals(Object o) {
pair b = (pair) o;
return this.compareTo(b) == 0;
}
}
void solve() throws IOException {
int n = nextInt();
int w = nextInt();
int[] a = new int[n];
int[] b = new int[n];
TreeSet<pair> asort = new TreeSet<pair>();
TreeSet<pair> bsort = new TreeSet<pair>();
for (int i = 0; i < n; i++) {
a[i] = nextInt();
b[i] = nextInt();
asort.add(new pair(a[i], i));
bsort.add(new pair(b[i], i));
}
int[] ansCode = new int[n];
long ans = 0;
while (w > 0) {
if (w % 2 == 1 || asort.size() < 2 || bsort.isEmpty()) {
pair del = asort.pollFirst();
ansCode[del.ind]++;
ans += del.val;
w--;
if (ansCode[del.ind] == 1) {
bsort.remove(new pair(b[del.ind], del.ind));
asort.add(new pair(b[del.ind] - a[del.ind], del.ind));
}
} else {
pair f = asort.pollFirst();
if (asort.first().val + f.val <= bsort.first().val) {
ansCode[f.ind]++;
ans += f.val;
if (ansCode[f.ind] == 1) {
bsort.remove(new pair(b[f.ind], f.ind));
asort.add(new pair(b[f.ind] - a[f.ind], f.ind));
}
pair f2 = asort.pollFirst();
ansCode[f2.ind]++;
ans += f2.val;
if (ansCode[f2.ind] == 1) {
bsort.remove(new pair(b[f2.ind], f2.ind));
asort.add(new pair(b[f2.ind] - a[f2.ind], f2.ind));
}
} else {
asort.add(f);
pair f2 = bsort.pollFirst();
ansCode[f2.ind] += 2;
asort.remove(new pair(a[f2.ind], f2.ind));
ans += f2.val;
}
w -= 2;
}
}
out.println(ans);
for (int i = 0; i < n; i++) {
out.print(ansCode[i]);
}
}
} | Java | ["2 3\n1 2\n1 2", "5 3\n10 20\n5 10\n10 20\n6 9\n25 30"] | 5 seconds | ["3\n12", "14\n01020"] | NoteIn the first test sample, answer 21 is also assumed correct. | Java 8 | standard input | [
"data structures",
"greedy"
] | a4b9ad2c4980bd7ebe23acb4c37680df | The first line contains two integers n and w (1ββ€βnββ€β3Β·105;Β 1ββ€βwββ€β2n) β the number of levels in the first box and the number of stars you need to open another box. Each of the following n lines contains two integers ai and bi (1ββ€βaiβ<βbiββ€β109) β the attributes of the i-th level. | 2,600 | In the first line print integer t β the minimum time you need to open the next box. In the next line, print n digits without spaces β the description of the optimal scenario: if you need to pass the i-th level for one star, the i-th digit should equal 1; if you need to pass the i-th level for two stars, the i-th digit should equal 2; if you do not need to pass the i-th level at all, the i-th digit should equal 0. | standard output | |
PASSED | f189fe28dc5818a9aba41f9ed08434f0 | train_001.jsonl | 1402673400 | Everyone who has played Cut the Rope knows full well how the gameplay is organized. All levels in the game are divided into boxes. Initially only one box with some levels is available. Player should complete levels to earn stars, collecting stars opens new box with levels. Imagine that you are playing Cut the Rope for the first time. Currently you have only the levels of the first box (by the way, it is called "Cardboard Box"). Each level is characterized by two integers: ai β how long it takes to complete the level for one star, bi β how long it takes to complete the level for two stars (aiβ<βbi).You want to open the next box as quickly as possible. So, you need to earn at least w stars. How do make it happen? Note that the level can be passed only once: either for one star or for two. You do not necessarily need to pass all the levels. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
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);
Task solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
}
interface Task {
public void solve(int testNumber, InputReader in, OutputWriter out);
}
class TaskA implements Task {
boolean[] vis;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt(), m = in.readInt();
vis = new boolean[1000 * n + 1];
vis[0] = true;
while (n-- > 0) {
int x = in.readInt();
for (int i = vis.length - 1; i >= x; i--)
vis[i] |= vis[i - x];
}
if (m < vis.length && vis[m])
out.printLine("Yes");
else
out.printLine("No");
}
}
class TaskB implements Task {
int[]arr;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int k=in.readInt(), x=1;
arr=IOUtils.readIntArray(in,k);
boolean val=true;
for (int i:arr) {
val&=i<=x;
x=2*(x-i);
}
val&=x==0;
out.printLine(val?"Yes":"No");
}
}
class TaskC implements Task {
int X;
public void solve(int testNumber, InputReader in, OutputWriter out) {
X=1;
int n=in.readInt(), k=in.readInt();
for (int i=0;i<k;i++)X*=10;
// out.printLine(X);
long ret2=pow(n,n);
double ret1=Math.log10(n)*n;
// out.printLine(ret1);
ret1+=1.0*k-1.0-Math.floor(ret1);
// out.printLine(ret1);
ret1=Math.pow(10.0, ret1);
// out.printLine(ret1);
long ret=(long)Math.floor(ret1);
out.print(ret+" ");
int x=(int)ret2,c=0;
for(;x>0;x/=10)c++;
if(c==0) c=1;
for(int i=0;i<k-c;i++)out.print(0);
out.printLine(ret2);
}
long pow(int a, int b){
if(b==0)return 1;
long ret=pow(a,b/2);
ret=ret*ret%X;
if(b%2==1)ret=ret*a%X;
return ret;
}
}
class TaskD implements Task {
int[] p, parent, size, ret;
boolean[] vis;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
p = IOUtils.readIntArray(in, n);
MiscUtils.decreaseByOne(p);
parent = new int[n];
size = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
size[i] = 1;
}
int m = in.readInt(), cycles = f(n);
ret = new int[2 * Math.abs(n - cycles - m)];
int x = 0;
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (m > n - cycles && parent[i] != parent[j] || m < n - cycles
&& parent[i] == parent[j]) {
p[i] ^= p[j];
p[j] ^= p[i];
p[i] ^= p[j];
ret[x++] = i + 1;
ret[x++] = j + 1;
cycles = f(n);
}
out.printLine(ret.length / 2);
out.printLine(ret);
}
int f(int n) {
int cycles = 0;
vis = new boolean[n];
for (int i = 0; i < n; i++)
if (!vis[i]) {
cycles++;
int x = i;
while (!vis[x]) {
parent[x] = i;
vis[x] = true;
x = p[x];
}
}
return cycles;
}
int find(int u) {
if (u == parent[u])
return u;
return parent[u] = find(parent[u]);
}
void join(int u, int v) {
if (find(u) == find(v))
return;
if (size[find(u)] > size[find(v)]) {
join(v, u);
return;
}
size[find(v)] += size[find(u)];
parent[find(u)] = find(v);
}
}
class TaskE implements Task {
int[] a, b;
char[] arr;
TreeSet<Pair<Integer, Integer>> set1, set2;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n=in.readInt(), w=in.readInt();
a=new int[n];
b=new int[n];
arr=new char[n];
set1=new TreeSet<Pair<Integer, Integer>>();
set2=new TreeSet<Pair<Integer, Integer>>();
Arrays.fill(arr, '0');
IOUtils.readIntArrays(in, a, b);
for (int i=0; i<n; i++) {
set1.add(Pair.makePair(a[i], i));
set2.add(Pair.makePair(b[i], i));
}
while (w>0) {
if ((w%2==1) || set1.size()<2 || set2.isEmpty()) {
f1(set1.pollFirst().second);
w--;
}
else {
Pair<Integer, Integer> pair=set1.pollFirst();
if (pair.first+set1.first().first<set2.first().first) {
f1(pair.second);
f1(set1.pollFirst().second);
}
else {
set1.add(pair);
f2(set2.pollFirst().second);
}
w-=2;
}
}
long ret=0L;
for (int i=0; i<n; i++) {
if (arr[i]=='1') ret+=a[i];
else if (arr[i]=='2') ret+=b[i];
}
out.printLine(ret);
out.printLine(arr);
}
void f1(int x) {
if (arr[x]=='0') {
set2.remove(Pair.makePair(b[x], x));
set1.add(Pair.makePair(b[x]-a[x], x));
}
arr[x]++;
}
void f2(int x) {
arr[x]='2';
set1.remove(Pair.makePair(a[x], x));
}
}
class TaskF implements Task {
public void solve(int testNumber, InputReader in, OutputWriter out) {
}
}
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(char[] array) {
writer.print(array);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void print(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(array[i]);
}
}
public void print(long[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(array[i]);
}
}
public void print(Collection<Integer> collection) {
boolean first = true;
for (Integer iterator : collection) {
if (first)
first = false;
else
writer.print(' ');
writer.print(iterator);
}
}
public void printLine(int[] array) {
print(array);
writer.println();
}
public void printLine(long[] array) {
print(array);
writer.println();
}
public void printLine(Collection<Integer> collection) {
print(collection);
writer.println();
}
public void printLine() {
writer.println();
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void print(char i) {
writer.print(i);
}
public void printLine(char i) {
writer.println(i);
}
public void printLine(char[] array) {
writer.println(array);
}
public void printFormat(String format, Object... objects) {
writer.printf(format, objects);
}
public void close() {
writer.close();
}
public void flush() {
writer.flush();
}
public void print(long i) {
writer.print(i);
}
public void printLine(long i) {
writer.println(i);
}
public void print(int i) {
writer.print(i);
}
public void printLine(int i) {
writer.println(i);
}
}
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 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 c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
if (Character.isValidCodePoint(c))
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0() {
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r')
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines)
return readLine();
else
return readLine0();
}
public BigInteger readBigInteger() {
try {
return new BigInteger(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 SpaceCharFilter getFilter() {
return filter;
}
public void setFilter(SpaceCharFilter filter) {
this.filter = filter;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class IOUtils {
public static Pair<Integer, Integer> readIntPair(InputReader in) {
int first = in.readInt();
int second = in.readInt();
return Pair.makePair(first, second);
}
public static Pair<Long, Long> readLongPair(InputReader in) {
long first = in.readLong();
long second = in.readLong();
return Pair.makePair(first, second);
}
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
public static long[] readLongArray(InputReader in, int size) {
long[] array = new long[size];
for (int i = 0; i < size; i++)
array[i] = in.readLong();
return array;
}
public static double[] readDoubleArray(InputReader in, int size) {
double[] array = new double[size];
for (int i = 0; i < size; i++)
array[i] = in.readDouble();
return array;
}
public static String[] readStringArray(InputReader in, int size) {
String[] array = new String[size];
for (int i = 0; i < size; i++)
array[i] = in.readString();
return array;
}
public static char[] readCharArray(InputReader in, int size) {
char[] array = new char[size];
for (int i = 0; i < size; i++)
array[i] = in.readCharacter();
return array;
}
public static Pair<Integer, Integer>[] readIntPairArray(InputReader in,
int size) {
@SuppressWarnings({ "unchecked" })
Pair<Integer, Integer>[] result = new Pair[size];
for (int i = 0; i < size; i++)
result[i] = readIntPair(in);
return result;
}
public static Pair<Long, Long>[] readLongPairArray(InputReader in, int size) {
@SuppressWarnings({ "unchecked" })
Pair<Long, Long>[] result = new Pair[size];
for (int i = 0; i < size; i++)
result[i] = readLongPair(in);
return result;
}
public static void readIntArrays(InputReader in, int[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++)
arrays[j][i] = in.readInt();
}
}
public static void readLongArrays(InputReader in, long[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++)
arrays[j][i] = in.readLong();
}
}
public static void readDoubleArrays(InputReader in, double[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++)
arrays[j][i] = in.readDouble();
}
}
public static char[][] readTable(InputReader in, int rowCount,
int columnCount) {
char[][] table = new char[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readCharArray(in, columnCount);
return table;
}
public static int[][] readIntTable(InputReader in, int rowCount,
int columnCount) {
int[][] table = new int[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readIntArray(in, columnCount);
return table;
}
public static double[][] readDoubleTable(InputReader in, int rowCount,
int columnCount) {
double[][] table = new double[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readDoubleArray(in, columnCount);
return table;
}
public static long[][] readLongTable(InputReader in, int rowCount,
int columnCount) {
long[][] table = new long[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readLongArray(in, columnCount);
return table;
}
public static String[][] readStringTable(InputReader in, int rowCount,
int columnCount) {
String[][] table = new String[rowCount][];
for (int i = 0; i < rowCount; i++)
table[i] = readStringArray(in, columnCount);
return table;
}
public static String readText(InputReader in) {
StringBuilder result = new StringBuilder();
while (true) {
int character = in.read();
if (character == '\r')
continue;
if (character == -1)
break;
result.append((char) character);
}
return result.toString();
}
public static void readStringArrays(InputReader in, String[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++)
arrays[j][i] = in.readString();
}
}
public static void printTable(OutputWriter out, char[][] table) {
for (char[] row : table)
out.printLine(new String(row));
}
}
class Pair<U, V> implements Comparable<Pair<U, V>> {
public final U first;
public final V second;
public static <U, V> Pair<U, V> makePair(U first, V second) {
return new Pair<U, V>(first, second);
}
private Pair(U first, V second) {
this.first = first;
this.second = second;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Pair<?, ?> pair = (Pair<?, ?>) o;
return !(first != null ? !first.equals(pair.first) : pair.first != null)
&& !(second != null ? !second.equals(pair.second)
: pair.second != null);
}
@Override
public int hashCode() {
int result = first != null ? first.hashCode() : 0;
result = 31 * result + (second != null ? second.hashCode() : 0);
return result;
}
public Pair<V, U> swap() {
return makePair(second, first);
}
@Override
public String toString() {
return "(" + first + "," + second + ")";
}
@SuppressWarnings({ "unchecked" })
public int compareTo(Pair<U, V> o) {
int value = ((Comparable<U>) first).compareTo(o.first);
if (value != 0)
return value;
return ((Comparable<V>) second).compareTo(o.second);
}
}
class BidirectionalGraph extends Graph {
public int[] transposedEdge;
public BidirectionalGraph(int vertexCount) {
this(vertexCount, vertexCount);
}
public BidirectionalGraph(int vertexCount, int edgeCapacity) {
super(vertexCount, 2 * edgeCapacity);
transposedEdge = new int[2 * edgeCapacity];
}
public static BidirectionalGraph createGraph(int vertexCount, int[] from,
int[] to) {
BidirectionalGraph graph = new BidirectionalGraph(vertexCount,
from.length);
for (int i = 0; i < from.length; i++)
graph.addSimpleEdge(from[i], to[i]);
return graph;
}
public static BidirectionalGraph createWeightedGraph(int vertexCount,
int[] from, int[] to, long[] weight) {
BidirectionalGraph graph = new BidirectionalGraph(vertexCount,
from.length);
for (int i = 0; i < from.length; i++)
graph.addWeightedEdge(from[i], to[i], weight[i]);
return graph;
}
public static BidirectionalGraph createFlowGraph(int vertexCount,
int[] from, int[] to, long[] capacity) {
BidirectionalGraph graph = new BidirectionalGraph(vertexCount,
from.length * 2);
for (int i = 0; i < from.length; i++)
graph.addFlowEdge(from[i], to[i], capacity[i]);
return graph;
}
public static BidirectionalGraph createFlowWeightedGraph(int vertexCount,
int[] from, int[] to, long[] weight, long[] capacity) {
BidirectionalGraph graph = new BidirectionalGraph(vertexCount,
from.length * 2);
for (int i = 0; i < from.length; i++)
graph.addFlowWeightedEdge(from[i], to[i], weight[i], capacity[i]);
return graph;
}
@Override
public int addEdge(int fromID, int toID, long weight, long capacity,
int reverseEdge) {
int lastEdgeCount = edgeCount;
super.addEdge(fromID, toID, weight, capacity, reverseEdge);
super.addEdge(toID, fromID, weight, capacity, reverseEdge == -1 ? -1
: reverseEdge + 1);
this.transposedEdge[lastEdgeCount] = lastEdgeCount + 1;
this.transposedEdge[lastEdgeCount + 1] = lastEdgeCount;
return lastEdgeCount;
}
@Override
protected int entriesPerEdge() {
return 2;
}
@Override
public final int transposed(int id) {
return transposedEdge[id];
}
@Override
protected void ensureEdgeCapacity(int size) {
if (size > edgeCapacity()) {
super.ensureEdgeCapacity(size);
transposedEdge = resize(transposedEdge, edgeCapacity());
}
}
}
class Graph {
public static final int REMOVED_BIT = 0;
protected int vertexCount;
protected int edgeCount;
private int[] firstOutbound;
private int[] firstInbound;
private Edge[] edges;
private int[] nextInbound;
private int[] nextOutbound;
private int[] from;
private int[] to;
private long[] weight;
private long[] capacity;
private int[] reverseEdge;
private int[] flags;
public Graph(int vertexCount) {
this(vertexCount, vertexCount);
}
public Graph(int vertexCount, int edgeCapacity) {
this.vertexCount = vertexCount;
firstOutbound = new int[vertexCount];
Arrays.fill(firstOutbound, -1);
from = new int[edgeCapacity];
to = new int[edgeCapacity];
nextOutbound = new int[edgeCapacity];
flags = new int[edgeCapacity];
}
public static Graph createGraph(int vertexCount, int[] from, int[] to) {
Graph graph = new Graph(vertexCount, from.length);
for (int i = 0; i < from.length; i++)
graph.addSimpleEdge(from[i], to[i]);
return graph;
}
public static Graph createWeightedGraph(int vertexCount, int[] from,
int[] to, long[] weight) {
Graph graph = new Graph(vertexCount, from.length);
for (int i = 0; i < from.length; i++)
graph.addWeightedEdge(from[i], to[i], weight[i]);
return graph;
}
public static Graph createFlowGraph(int vertexCount, int[] from, int[] to,
long[] capacity) {
Graph graph = new Graph(vertexCount, from.length * 2);
for (int i = 0; i < from.length; i++)
graph.addFlowEdge(from[i], to[i], capacity[i]);
return graph;
}
public static Graph createFlowWeightedGraph(int vertexCount, int[] from,
int[] to, long[] weight, long[] capacity) {
Graph graph = new Graph(vertexCount, from.length * 2);
for (int i = 0; i < from.length; i++)
graph.addFlowWeightedEdge(from[i], to[i], weight[i], capacity[i]);
return graph;
}
public static Graph createTree(int[] parent) {
Graph graph = new Graph(parent.length + 1, parent.length);
for (int i = 0; i < parent.length; i++)
graph.addSimpleEdge(parent[i], i + 1);
return graph;
}
public int addEdge(int fromID, int toID, long weight, long capacity,
int reverseEdge) {
ensureEdgeCapacity(edgeCount + 1);
if (firstOutbound[fromID] != -1)
nextOutbound[edgeCount] = firstOutbound[fromID];
else
nextOutbound[edgeCount] = -1;
firstOutbound[fromID] = edgeCount;
if (firstInbound != null) {
if (firstInbound[toID] != -1)
nextInbound[edgeCount] = firstInbound[toID];
else
nextInbound[edgeCount] = -1;
firstInbound[toID] = edgeCount;
}
this.from[edgeCount] = fromID;
this.to[edgeCount] = toID;
if (capacity != 0) {
if (this.capacity == null)
this.capacity = new long[from.length];
this.capacity[edgeCount] = capacity;
}
if (weight != 0) {
if (this.weight == null)
this.weight = new long[from.length];
this.weight[edgeCount] = weight;
}
if (reverseEdge != -1) {
if (this.reverseEdge == null) {
this.reverseEdge = new int[from.length];
Arrays.fill(this.reverseEdge, 0, edgeCount, -1);
}
this.reverseEdge[edgeCount] = reverseEdge;
}
if (edges != null)
edges[edgeCount] = createEdge(edgeCount);
return edgeCount++;
}
protected final GraphEdge createEdge(int id) {
return new GraphEdge(id);
}
public final int addFlowWeightedEdge(int from, int to, long weight,
long capacity) {
if (capacity == 0) {
return addEdge(from, to, weight, 0, -1);
} else {
int lastEdgeCount = edgeCount;
addEdge(to, from, -weight, 0, lastEdgeCount + entriesPerEdge());
return addEdge(from, to, weight, capacity, lastEdgeCount);
}
}
protected int entriesPerEdge() {
return 1;
}
public final int addFlowEdge(int from, int to, long capacity) {
return addFlowWeightedEdge(from, to, 0, capacity);
}
public final int addWeightedEdge(int from, int to, long weight) {
return addFlowWeightedEdge(from, to, weight, 0);
}
public final int addSimpleEdge(int from, int to) {
return addWeightedEdge(from, to, 0);
}
public final int vertexCount() {
return vertexCount;
}
public final int edgeCount() {
return edgeCount;
}
protected final int edgeCapacity() {
return from.length;
}
public final Edge edge(int id) {
initEdges();
return edges[id];
}
public final int firstOutbound(int vertex) {
int id = firstOutbound[vertex];
while (id != -1 && isRemoved(id))
id = nextOutbound[id];
return id;
}
public final int nextOutbound(int id) {
id = nextOutbound[id];
while (id != -1 && isRemoved(id))
id = nextOutbound[id];
return id;
}
public final int firstInbound(int vertex) {
initInbound();
int id = firstInbound[vertex];
while (id != -1 && isRemoved(id))
id = nextInbound[id];
return id;
}
public final int nextInbound(int id) {
initInbound();
id = nextInbound[id];
while (id != -1 && isRemoved(id))
id = nextInbound[id];
return id;
}
public final int source(int id) {
return from[id];
}
public final int destination(int id) {
return to[id];
}
public final long weight(int id) {
if (weight == null)
return 0;
return weight[id];
}
public final long capacity(int id) {
if (capacity == null)
return 0;
return capacity[id];
}
public final long flow(int id) {
if (reverseEdge == null)
return 0;
return capacity[reverseEdge[id]];
}
public final void pushFlow(int id, long flow) {
if (flow == 0)
return;
if (flow > 0) {
if (capacity(id) < flow)
throw new IllegalArgumentException("Not enough capacity");
} else {
if (flow(id) < -flow)
throw new IllegalArgumentException("Not enough capacity");
}
capacity[id] -= flow;
capacity[reverseEdge[id]] += flow;
}
public int transposed(int id) {
return -1;
}
public final int reverse(int id) {
if (reverseEdge == null)
return -1;
return reverseEdge[id];
}
public final void addVertices(int count) {
ensureVertexCapacity(vertexCount + count);
Arrays.fill(firstOutbound, vertexCount, vertexCount + count, -1);
if (firstInbound != null)
Arrays.fill(firstInbound, vertexCount, vertexCount + count, -1);
vertexCount += count;
}
protected final void initEdges() {
if (edges == null) {
edges = new Edge[from.length];
for (int i = 0; i < edgeCount; i++)
edges[i] = createEdge(i);
}
}
public final void removeVertex(int vertex) {
int id = firstOutbound[vertex];
while (id != -1) {
removeEdge(id);
id = nextOutbound[id];
}
initInbound();
id = firstInbound[vertex];
while (id != -1) {
removeEdge(id);
id = nextInbound[id];
}
}
private void initInbound() {
if (firstInbound == null) {
firstInbound = new int[firstOutbound.length];
Arrays.fill(firstInbound, 0, vertexCount, -1);
nextInbound = new int[from.length];
for (int i = 0; i < edgeCount; i++) {
nextInbound[i] = firstInbound[to[i]];
firstInbound[to[i]] = i;
}
}
}
public final boolean flag(int id, int bit) {
return (flags[id] >> bit & 1) != 0;
}
public final void setFlag(int id, int bit) {
flags[id] |= 1 << bit;
}
public final void removeFlag(int id, int bit) {
flags[id] &= -1 - (1 << bit);
}
public final void removeEdge(int id) {
setFlag(id, REMOVED_BIT);
}
public final void restoreEdge(int id) {
removeFlag(id, REMOVED_BIT);
}
public final boolean isRemoved(int id) {
return flag(id, REMOVED_BIT);
}
public final Iterable<Edge> outbound(final int id) {
initEdges();
return new Iterable<Edge>() {
public Iterator<Edge> iterator() {
return new EdgeIterator(id, firstOutbound, nextOutbound);
}
};
}
public final Iterable<Edge> inbound(final int id) {
initEdges();
initInbound();
return new Iterable<Edge>() {
public Iterator<Edge> iterator() {
return new EdgeIterator(id, firstInbound, nextInbound);
}
};
}
protected void ensureEdgeCapacity(int size) {
if (from.length < size) {
int newSize = Math.max(size, 2 * from.length);
if (edges != null)
edges = resize(edges, newSize);
from = resize(from, newSize);
to = resize(to, newSize);
nextOutbound = resize(nextOutbound, newSize);
if (nextInbound != null)
nextInbound = resize(nextInbound, newSize);
if (weight != null)
weight = resize(weight, newSize);
if (capacity != null)
capacity = resize(capacity, newSize);
if (reverseEdge != null)
reverseEdge = resize(reverseEdge, newSize);
flags = resize(flags, newSize);
}
}
private void ensureVertexCapacity(int size) {
if (firstOutbound.length < size) {
int newSize = Math.max(size, 2 * from.length);
firstOutbound = resize(firstOutbound, newSize);
if (firstInbound != null)
firstInbound = resize(firstInbound, newSize);
}
}
protected final int[] resize(int[] array, int size) {
int[] newArray = new int[size];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
private long[] resize(long[] array, int size) {
long[] newArray = new long[size];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
private Edge[] resize(Edge[] array, int size) {
Edge[] newArray = new Edge[size];
System.arraycopy(array, 0, newArray, 0, array.length);
return newArray;
}
public final boolean isSparse() {
return vertexCount == 0 || edgeCount * 20 / vertexCount <= vertexCount;
}
protected class GraphEdge implements Edge {
protected int id;
protected GraphEdge(int id) {
this.id = id;
}
public int getSource() {
return source(id);
}
public int getDestination() {
return destination(id);
}
public long getWeight() {
return weight(id);
}
public long getCapacity() {
return capacity(id);
}
public long getFlow() {
return flow(id);
}
public void pushFlow(long flow) {
Graph.this.pushFlow(id, flow);
}
public boolean getFlag(int bit) {
return flag(id, bit);
}
public void setFlag(int bit) {
Graph.this.setFlag(id, bit);
}
public void removeFlag(int bit) {
Graph.this.removeFlag(id, bit);
}
public int getTransposedID() {
return transposed(id);
}
public Edge getTransposedEdge() {
int reverseID = getTransposedID();
if (reverseID == -1)
return null;
initEdges();
return edge(reverseID);
}
public int getReverseID() {
return reverse(id);
}
public Edge getReverseEdge() {
int reverseID = getReverseID();
if (reverseID == -1)
return null;
initEdges();
return edge(reverseID);
}
public int getID() {
return id;
}
public void remove() {
removeEdge(id);
}
public void restore() {
restoreEdge(id);
}
}
public class EdgeIterator implements Iterator<Edge> {
private int edgeID;
private final int[] next;
private int lastID = -1;
public EdgeIterator(int id, int[] first, int[] next) {
this.next = next;
edgeID = nextEdge(first[id]);
}
private int nextEdge(int id) {
while (id != -1 && isRemoved(id))
id = next[id];
return id;
}
public boolean hasNext() {
return edgeID != -1;
}
public Edge next() {
if (edgeID == -1)
throw new NoSuchElementException();
lastID = edgeID;
edgeID = nextEdge(next[lastID]);
return edges[lastID];
}
public void remove() {
if (lastID == -1)
throw new IllegalStateException();
removeEdge(lastID);
lastID = -1;
}
}
}
interface Edge {
public int getSource();
public int getDestination();
public long getWeight();
public long getCapacity();
public long getFlow();
public void pushFlow(long flow);
public boolean getFlag(int bit);
public void setFlag(int bit);
public void removeFlag(int bit);
public int getTransposedID();
public Edge getTransposedEdge();
public int getReverseID();
public Edge getReverseEdge();
public int getID();
public void remove();
public void restore();
}
class MiscUtils {
public static final int[] DX4 = { 1, 0, -1, 0 };
public static final int[] DY4 = { 0, -1, 0, 1 };
public static final int[] DX8 = { 1, 1, 1, 0, -1, -1, -1, 0 };
public static final int[] DY8 = { -1, 0, 1, 1, 1, 0, -1, -1 };
public static final int[] DX_KNIGHT = { 2, 1, -1, -2, -2, -1, 1, 2 };
public static final int[] DY_KNIGHT = { 1, 2, 2, 1, -1, -2, -2, -1 };
private static final String[] ROMAN_TOKENS = { "M", "CM", "D", "CD", "C",
"XC", "L", "XL", "X", "IX", "V", "IV", "I" };
private static final int[] ROMAN_VALUES = { 1000, 900, 500, 400, 100, 90,
50, 40, 10, 9, 5, 4, 1 };
public static long josephProblem(long n, int k) {
if (n == 1)
return 0;
if (k == 1)
return n - 1;
if (k > n)
return (josephProblem(n - 1, k) + k) % n;
long count = n / k;
long result = josephProblem(n - count, k);
result -= n % k;
if (result < 0)
result += n;
else
result += result / (k - 1);
return result;
}
public static boolean isValidCell(int row, int column, int rowCount,
int columnCount) {
return row >= 0 && row < rowCount && column >= 0
&& column < columnCount;
}
public static List<Integer> getPath(int[] last, int destination) {
List<Integer> path = new ArrayList<Integer>();
while (destination != -1) {
path.add(destination);
destination = last[destination];
}
Collections.reverse(path);
return path;
}
public static List<Integer> getPath(int[][] lastIndex,
int[][] lastPathNumber, int destination, int pathNumber) {
List<Integer> path = new ArrayList<Integer>();
while (destination != -1 || pathNumber != 0) {
path.add(destination);
int nextDestination = lastIndex[destination][pathNumber];
pathNumber = lastPathNumber[destination][pathNumber];
destination = nextDestination;
}
Collections.reverse(path);
return path;
}
public static long maximalRectangleSum(long[][] array) {
int n = array.length;
int m = array[0].length;
long[][] partialSums = new long[n + 1][m + 1];
for (int i = 0; i < n; i++) {
long rowSum = 0;
for (int j = 0; j < m; j++) {
rowSum += array[i][j];
partialSums[i + 1][j + 1] = partialSums[i][j + 1] + rowSum;
}
}
long result = Long.MIN_VALUE;
for (int i = 0; i < m; i++) {
for (int j = i; j < m; j++) {
long minPartialSum = 0;
for (int k = 1; k <= n; k++) {
long current = partialSums[k][j + 1] - partialSums[k][i];
result = Math.max(result, current - minPartialSum);
minPartialSum = Math.min(minPartialSum, current);
}
}
}
return result;
}
public static int parseIP(String ip) {
String[] components = ip.split("[.]");
int result = 0;
for (int i = 0; i < 4; i++)
result += (1 << (24 - 8 * i)) * Integer.parseInt(components[i]);
return result;
}
public static String buildIP(int mask) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < 4; i++) {
if (i != 0)
result.append('.');
result.append(mask >> (24 - 8 * i) & 255);
}
return result.toString();
}
public static long binarySearch(long from, long to,
Function<Long, Boolean> function) {
while (from < to) {
long argument = from + (to - from) / 2;
if (function.value(argument))
to = argument;
else
from = argument + 1;
}
return from;
}
public static <T> boolean equals(T first, T second) {
return first == null && second == null || first != null
&& first.equals(second);
}
public static boolean isVowel(char ch) {
ch = Character.toUpperCase(ch);
return ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'
|| ch == 'Y';
}
public static boolean isStrictVowel(char ch) {
ch = Character.toUpperCase(ch);
return ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U';
}
public static String convertToRoman(int number) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < ROMAN_TOKENS.length; i++) {
while (number >= ROMAN_VALUES[i]) {
number -= ROMAN_VALUES[i];
result.append(ROMAN_TOKENS[i]);
}
}
return result.toString();
}
public static int convertFromRoman(String number) {
int result = 0;
for (int i = 0; i < ROMAN_TOKENS.length; i++) {
while (number.startsWith(ROMAN_TOKENS[i])) {
number = number.substring(ROMAN_TOKENS[i].length());
result += ROMAN_VALUES[i];
}
}
return result;
}
public static int distance(int x1, int y1, int x2, int y2) {
int dx = x1 - x2;
int dy = y1 - y2;
return dx * dx + dy * dy;
}
public static <T extends Comparable<T>> T min(T first, T second) {
if (first.compareTo(second) <= 0)
return first;
return second;
}
public static <T extends Comparable<T>> T max(T first, T second) {
if (first.compareTo(second) <= 0)
return second;
return first;
}
public static void decreaseByOne(int[]... arrays) {
for (int[] array : arrays) {
for (int i = 0; i < array.length; i++)
array[i]--;
}
}
public static int[] getIntArray(String s) {
String[] tokens = s.split(" ");
int[] result = new int[tokens.length];
for (int i = 0; i < result.length; i++)
result[i] = Integer.parseInt(tokens[i]);
return result;
}
}
interface Function<A, V> {
public abstract V value(A argument);
}
interface IntComparator {
public static final IntComparator DEFAULT = new IntComparator() {
public int compare(int first, int second) {
if (first < second)
return -1;
if (first > second)
return 1;
return 0;
}
};
public static final IntComparator REVERSE = new IntComparator() {
public int compare(int first, int second) {
if (first < second)
return 1;
if (first > second)
return -1;
return 0;
}
};
public int compare(int first, int second);
}
class DFSOrder {
public final int[] position;
public final int[] end;
public DFSOrder(Graph graph) {
this(graph, 0);
}
public DFSOrder(Graph graph, int root) {
int count = graph.vertexCount();
position = new int[count];
end = new int[count];
int[] edge = new int[count];
int[] stack = new int[count];
for (int i = 0; i < count; i++)
edge[i] = graph.firstOutbound(i);
stack[0] = root;
int size = 1;
position[root] = 0;
int index = 0;
while (size > 0) {
int current = stack[size - 1];
if (edge[current] == -1) {
end[current] = index;
size--;
} else {
int next = graph.destination(edge[current]);
edge[current] = graph.nextOutbound(edge[current]);
position[next] = ++index;
stack[size++] = next;
}
}
}
public DFSOrder(BidirectionalGraph graph) {
this(graph, 0);
}
public DFSOrder(BidirectionalGraph graph, int root) {
int count = graph.vertexCount();
position = new int[count];
end = new int[count];
int[] edge = new int[count];
int[] stack = new int[count];
int[] last = new int[count];
for (int i = 0; i < count; i++)
edge[i] = graph.firstOutbound(i);
stack[0] = root;
last[root] = -1;
int size = 1;
position[root] = 0;
int index = 0;
while (size > 0) {
int current = stack[size - 1];
if (edge[current] == -1) {
end[current] = index;
size--;
} else {
int next = graph.destination(edge[current]);
if (next == last[current]) {
edge[current] = graph.nextOutbound(edge[current]);
continue;
}
edge[current] = graph.nextOutbound(edge[current]);
position[next] = ++index;
last[next] = current;
stack[size++] = next;
}
}
}
}
abstract class IntervalTree {
protected int size;
protected IntervalTree(int size) {
this(size, true);
}
public IntervalTree(int size, boolean shouldInit) {
this.size = size;
int nodeCount = Math.max(1, Integer.highestOneBit(size) << 2);
initData(size, nodeCount);
if (shouldInit)
init();
}
protected abstract void initData(int size, int nodeCount);
protected abstract void initAfter(int root, int left, int right, int middle);
protected abstract void initBefore(int root, int left, int right, int middle);
protected abstract void initLeaf(int root, int index);
protected abstract void updatePostProcess(int root, int left, int right,
int from, int to, long delta, int middle);
protected abstract void updatePreProcess(int root, int left, int right,
int from, int to, long delta, int middle);
protected abstract void updateFull(int root, int left, int right, int from,
int to, long delta);
protected abstract long queryPostProcess(int root, int left, int right,
int from, int to, int middle, long leftResult, long rightResult);
protected abstract void queryPreProcess(int root, int left, int right,
int from, int to, int middle);
protected abstract long queryFull(int root, int left, int right, int from,
int to);
protected abstract long emptySegmentResult();
public void init() {
if (size == 0)
return;
init(0, 0, size - 1);
}
private void init(int root, int left, int right) {
if (left == right) {
initLeaf(root, left);
} else {
int middle = (left + right) >> 1;
initBefore(root, left, right, middle);
init(2 * root + 1, left, middle);
init(2 * root + 2, middle + 1, right);
initAfter(root, left, right, middle);
}
}
public void update(int from, int to, long delta) {
update(0, 0, size - 1, from, to, delta);
}
protected void update(int root, int left, int right, int from, int to,
long delta) {
if (left > to || right < from)
return;
if (left >= from && right <= to) {
updateFull(root, left, right, from, to, delta);
return;
}
int middle = (left + right) >> 1;
updatePreProcess(root, left, right, from, to, delta, middle);
update(2 * root + 1, left, middle, from, to, delta);
update(2 * root + 2, middle + 1, right, from, to, delta);
updatePostProcess(root, left, right, from, to, delta, middle);
}
public long query(int from, int to) {
return query(0, 0, size - 1, from, to);
}
protected long query(int root, int left, int right, int from, int to) {
if (left > to || right < from)
return emptySegmentResult();
if (left >= from && right <= to)
return queryFull(root, left, right, from, to);
int middle = (left + right) >> 1;
queryPreProcess(root, left, right, from, to, middle);
long leftResult = query(2 * root + 1, left, middle, from, to);
long rightResult = query(2 * root + 2, middle + 1, right, from, to);
return queryPostProcess(root, left, right, from, to, middle,
leftResult, rightResult);
}
}
class LCA {
private final long[] order;
private final int[] position;
private final IntervalTree lcaTree;
private final int[] level;
public LCA(Graph graph) {
this(graph, 0);
}
public LCA(Graph graph, int root) {
order = new long[2 * graph.vertexCount() - 1];
position = new int[graph.vertexCount()];
level = new int[graph.vertexCount()];
int[] index = new int[graph.vertexCount()];
for (int i = 0; i < index.length; i++)
index[i] = graph.firstOutbound(i);
int[] last = new int[graph.vertexCount()];
int[] stack = new int[graph.vertexCount()];
stack[0] = root;
int size = 1;
int j = 0;
last[root] = -1;
Arrays.fill(position, -1);
while (size > 0) {
int vertex = stack[--size];
if (position[vertex] == -1)
position[vertex] = j;
order[j++] = vertex;
if (last[vertex] != -1)
level[vertex] = level[last[vertex]] + 1;
while (index[vertex] != -1
&& last[vertex] == graph.destination(index[vertex]))
index[vertex] = graph.nextOutbound(index[vertex]);
if (index[vertex] != -1) {
stack[size++] = vertex;
stack[size++] = graph.destination(index[vertex]);
last[graph.destination(index[vertex])] = vertex;
index[vertex] = graph.nextOutbound(index[vertex]);
}
}
lcaTree = new ReadOnlyIntervalTree(order) {
@Override
protected long joinValue(long left, long right) {
if (left == -1)
return right;
if (right == -1)
return left;
if (level[((int) left)] < level[((int) right)])
return left;
return right;
}
@Override
protected long neutralValue() {
return -1;
}
};
lcaTree.init();
}
public int getPosition(int vertex) {
return position[vertex];
}
public int getLCA(int first, int second) {
return (int) lcaTree.query(Math.min(position[first], position[second]),
Math.max(position[first], position[second]));
}
public int getLevel(int vertex) {
return level[vertex];
}
public int getPathLength(int first, int second) {
return level[first] + level[second] - 2 * level[getLCA(first, second)];
}
}
abstract class LongIntervalTree extends IntervalTree {
protected long[] value;
protected long[] delta;
protected LongIntervalTree(int size) {
this(size, true);
}
public LongIntervalTree(int size, boolean shouldInit) {
super(size, shouldInit);
}
@Override
protected void initData(int size, int nodeCount) {
value = new long[nodeCount];
delta = new long[nodeCount];
}
protected abstract long joinValue(long left, long right);
protected abstract long joinDelta(long was, long delta);
protected abstract long accumulate(long value, long delta, int length);
protected abstract long neutralValue();
protected abstract long neutralDelta();
protected long initValue(int index) {
return neutralValue();
}
@Override
protected void initAfter(int root, int left, int right, int middle) {
value[root] = joinValue(value[2 * root + 1], value[2 * root + 2]);
delta[root] = neutralDelta();
}
@Override
protected void initBefore(int root, int left, int right, int middle) {
}
@Override
protected void initLeaf(int root, int index) {
value[root] = initValue(index);
delta[root] = neutralDelta();
}
@Override
protected void updatePostProcess(int root, int left, int right, int from,
int to, long delta, int middle) {
value[root] = joinValue(value[2 * root + 1], value[2 * root + 2]);
}
@Override
protected void updatePreProcess(int root, int left, int right, int from,
int to, long delta, int middle) {
pushDown(root, left, middle, right);
}
protected void pushDown(int root, int left, int middle, int right) {
value[2 * root + 1] = accumulate(value[2 * root + 1], delta[root],
middle - left + 1);
value[2 * root + 2] = accumulate(value[2 * root + 2], delta[root],
right - middle);
delta[2 * root + 1] = joinDelta(delta[2 * root + 1], delta[root]);
delta[2 * root + 2] = joinDelta(delta[2 * root + 2], delta[root]);
delta[root] = neutralDelta();
}
@Override
protected void updateFull(int root, int left, int right, int from, int to,
long delta) {
value[root] = accumulate(value[root], delta, right - left + 1);
this.delta[root] = joinDelta(this.delta[root], delta);
}
@Override
protected long queryPostProcess(int root, int left, int right, int from,
int to, int middle, long leftResult, long rightResult) {
return joinValue(leftResult, rightResult);
}
@Override
protected void queryPreProcess(int root, int left, int right, int from,
int to, int middle) {
pushDown(root, left, middle, right);
}
@Override
protected long queryFull(int root, int left, int right, int from, int to) {
return value[root];
}
@Override
protected long emptySegmentResult() {
return neutralValue();
}
}
class SumIntervalTree extends LongIntervalTree {
public SumIntervalTree(int size) {
super(size);
}
@Override
protected long joinValue(long left, long right) {
return left + right;
}
@Override
protected long joinDelta(long was, long delta) {
return was + delta;
}
@Override
protected long accumulate(long value, long delta, int length) {
return value + delta * length;
}
@Override
protected long neutralValue() {
return 0;
}
@Override
protected long neutralDelta() {
return 0;
}
}
abstract class ReadOnlyIntervalTree extends IntervalTree {
protected long[] value;
protected long[] array;
protected ReadOnlyIntervalTree(long[] array) {
super(array.length, false);
this.array = array;
init();
}
@Override
protected void initData(int size, int nodeCount) {
value = new long[nodeCount];
}
@Override
protected void initAfter(int root, int left, int right, int middle) {
value[root] = joinValue(value[2 * root + 1], value[2 * root + 2]);
}
@Override
protected void initBefore(int root, int left, int right, int middle) {
}
@Override
protected void initLeaf(int root, int index) {
value[root] = array[index];
}
@Override
protected void updatePostProcess(int root, int left, int right, int from,
int to, long delta, int middle) {
throw new UnsupportedOperationException();
}
@Override
protected void updatePreProcess(int root, int left, int right, int from,
int to, long delta, int middle) {
throw new UnsupportedOperationException();
}
@Override
protected void updateFull(int root, int left, int right, int from, int to,
long delta) {
throw new UnsupportedOperationException();
}
@Override
protected long queryPostProcess(int root, int left, int right, int from,
int to, int middle, long leftResult, long rightResult) {
return joinValue(leftResult, rightResult);
}
@Override
protected void queryPreProcess(int root, int left, int right, int from,
int to, int middle) {
}
@Override
protected long queryFull(int root, int left, int right, int from, int to) {
return value[root];
}
@Override
protected long emptySegmentResult() {
return neutralValue();
}
@Override
public void update(int from, int to, long delta) {
throw new UnsupportedOperationException();
}
@Override
protected void update(int root, int left, int right, int from, int to,
long delta) {
throw new UnsupportedOperationException();
}
protected abstract long neutralValue();
protected abstract long joinValue(long left, long right);
} | Java | ["2 3\n1 2\n1 2", "5 3\n10 20\n5 10\n10 20\n6 9\n25 30"] | 5 seconds | ["3\n12", "14\n01020"] | NoteIn the first test sample, answer 21 is also assumed correct. | Java 8 | standard input | [
"data structures",
"greedy"
] | a4b9ad2c4980bd7ebe23acb4c37680df | The first line contains two integers n and w (1ββ€βnββ€β3Β·105;Β 1ββ€βwββ€β2n) β the number of levels in the first box and the number of stars you need to open another box. Each of the following n lines contains two integers ai and bi (1ββ€βaiβ<βbiββ€β109) β the attributes of the i-th level. | 2,600 | In the first line print integer t β the minimum time you need to open the next box. In the next line, print n digits without spaces β the description of the optimal scenario: if you need to pass the i-th level for one star, the i-th digit should equal 1; if you need to pass the i-th level for two stars, the i-th digit should equal 2; if you do not need to pass the i-th level at all, the i-th digit should equal 0. | standard output | |
PASSED | 112c19dfdb8f40121e70113aeb04a7c7 | train_001.jsonl | 1402673400 | Everyone who has played Cut the Rope knows full well how the gameplay is organized. All levels in the game are divided into boxes. Initially only one box with some levels is available. Player should complete levels to earn stars, collecting stars opens new box with levels. Imagine that you are playing Cut the Rope for the first time. Currently you have only the levels of the first box (by the way, it is called "Cardboard Box"). Each level is characterized by two integers: ai β how long it takes to complete the level for one star, bi β how long it takes to complete the level for two stars (aiβ<βbi).You want to open the next box as quickly as possible. So, you need to earn at least w stars. How do make it happen? Note that the level can be passed only once: either for one star or for two. You do not necessarily need to pass all the levels. | 256 megabytes | import java.io.*;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Random;
public class cf436E {
public static void solve(Input in, PrintWriter out) throws IOException {
int n = in.nextInt();
int w = in.nextInt();
final int[] a = new int[n];
final int[] b = new int[n];
for (int i = 0; i < n; ++i) {
a[i] = in.nextInt();
b[i] = in.nextInt();
}
Comparator<Integer> ca = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return a[o1] < a[o2] ? -1 : a[o1] > a[o2] ? +1 : 0;
}
};
Comparator<Integer> cb = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return b[o1] < b[o2] ? -1 : b[o1] > b[o2] ? +1 : 0;
}
};
Comparator<Integer> cba = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return b[o1] - a[o1] < b[o2] - a[o2] ? -1 : b[o1] - a[o1] > b[o2] - a[o2] ? +1 : 0;
}
};
PriorityQueue<Integer> pa = new PriorityQueue<Integer>(ca);
PriorityQueue<Integer> pa1 = new PriorityQueue<Integer>(ca.reversed());
PriorityQueue<Integer> pb = new PriorityQueue<Integer>(cb);
PriorityQueue<Integer> pba = new PriorityQueue<Integer>(cba);
PriorityQueue<Integer> pba1 = new PriorityQueue<Integer>(cba.reversed());
int[] c = new int[n];
for (int i = 0; i < n; ++i) {
pa.add(i);
pb.add(i);
}
long ans = 0;
for (int it = 0; it < w; ++it) {
long nextA = pa.isEmpty() ? Long.MAX_VALUE : a[pa.peek()];
long nextBA = pba.isEmpty() ? Long.MAX_VALUE : b[pba.peek()] - a[pba.peek()];
long nextBA1 = pa1.isEmpty() || pb.isEmpty() ? Long.MAX_VALUE : b[pb.peek()] - a[pa1.peek()];
long nextBA2 = pba1.isEmpty() || pb.isEmpty() ? Long.MAX_VALUE : b[pb.peek()] - (b[pba1.peek()] - a[pba1.peek()]);
if (nextA <= nextBA && nextA <= nextBA1 && nextA <= nextBA2) {
int i = pa.poll();
if (c[i] != 0) {
throw new AssertionError();
}
c[i] = 1;
ans += a[i];
pa1.add(i);
pba.add(i);
} else if (nextBA <= nextA && nextBA <= nextBA1 && nextBA <= nextBA2) {
int i = pba.poll();
if (c[i] != 1) {
throw new AssertionError();
}
c[i] = 2;
pba1.add(i);
ans += b[i] - a[i];
} else if (nextBA1 <= nextA && nextBA1 <= nextBA && nextBA1 <= nextBA2) {
int i = pb.poll();
int j = pa1.poll();
if (c[i] != 0 || c[j] != 1) {
throw new AssertionError();
}
c[i] = 2;
c[j] = 0;
ans += b[i] - a[j];
pba1.add(i);
pa.add(j);
pb.add(j);
} else if (nextBA2 <= nextA && nextBA2 <= nextBA && nextBA2 <= nextBA1) {
int i = pb.poll();
int j = pba1.poll();
if (c[i] != 0 || c[j] != 2) {
throw new AssertionError();
}
c[i] = 2;
c[j] = 1;
ans += b[i] - (b[j] - a[j]);
pba1.add(i);
pa1.add(j);
pba.add(j);
} else {
throw new AssertionError();
}
while (!pa.isEmpty() && c[pa.peek()] != 0) {
pa.poll();
}
while (!pb.isEmpty() && c[pb.peek()] != 0) {
pb.poll();
}
while (!pba.isEmpty() && c[pba.peek()] != 1) {
pba.poll();
}
while (!pa1.isEmpty() && c[pa1.peek()] != 1) {
pa1.poll();
}
while (!pba1.isEmpty() && c[pba1.peek()] != 2) {
pba1.poll();
}
}
out.println(ans);
for (int i = 0; i < n; ++i) {
out.print(c[i]);
}
out.println();
}
public static void main(String[] args) throws IOException {
// Random rnd = new Random();
// while (rnd != null) {
// int n = rnd.nextInt(10) + 1;
// int w = rnd.nextInt(2 * n + 1);
// int[] a = new int[n];
// int[] b = new int[n];
// StringBuilder sb = new StringBuilder(n + " " + w + "\n");
// for (int i = 0; i < n; ++i) {
// do {
// a[i] = rnd.nextInt(1000000000);
// b[i] = rnd.nextInt(1000000000);
// } while (a[i] > b[i]);
// sb.append(a[i] + " " + b[i] + "\n");
// }
// StringWriter sw = new StringWriter();
// solve(new Input(sb.toString()), new PrintWriter(sw));
// long ans = new Input(sw.toString()).nextLong();
// long ansSlow = solveSlow(n, w, a, b);
// if (ans != ansSlow) {
// System.err.println(sb);
// throw new AssertionError(ans + " " + ansSlow);
// }
// System.err.print(".");
// }
PrintWriter out = new PrintWriter(System.out);
solve(new Input(new BufferedReader(new InputStreamReader(System.in))), out);
out.close();
}
private static long solveSlow(int n, int w, int[] a, int[] b) {
return rec(0, w, a, b);
}
private static long rec(int i, int w, int[] a, int[] b) {
if (w <= 0) {
return 0;
}
if (i == a.length) {
return 1000000000000000000L;
}
long r = 1000000000000000000L;
for (int c = 0; c <= 2; ++c) {
r = Math.min(r, (c == 0 ? 0 : c == 1 ? a[i] : b[i]) + rec(i + 1, w - c, a, b));
}
return r;
}
static class Input {
BufferedReader in;
StringBuilder sb = new StringBuilder();
public Input(BufferedReader in) {
this.in = in;
}
public Input(String s) {
this.in = new BufferedReader(new StringReader(s));
}
public String next() throws IOException {
sb.setLength(0);
while (true) {
int c = in.read();
if (c == -1) {
return null;
}
if (" \n\r\t".indexOf(c) == -1) {
sb.append((char)c);
break;
}
}
while (true) {
int c = in.read();
if (c == -1 || " \n\r\t".indexOf(c) != -1) {
break;
}
sb.append((char)c);
}
return sb.toString();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
}
| Java | ["2 3\n1 2\n1 2", "5 3\n10 20\n5 10\n10 20\n6 9\n25 30"] | 5 seconds | ["3\n12", "14\n01020"] | NoteIn the first test sample, answer 21 is also assumed correct. | Java 8 | standard input | [
"data structures",
"greedy"
] | a4b9ad2c4980bd7ebe23acb4c37680df | The first line contains two integers n and w (1ββ€βnββ€β3Β·105;Β 1ββ€βwββ€β2n) β the number of levels in the first box and the number of stars you need to open another box. Each of the following n lines contains two integers ai and bi (1ββ€βaiβ<βbiββ€β109) β the attributes of the i-th level. | 2,600 | In the first line print integer t β the minimum time you need to open the next box. In the next line, print n digits without spaces β the description of the optimal scenario: if you need to pass the i-th level for one star, the i-th digit should equal 1; if you need to pass the i-th level for two stars, the i-th digit should equal 2; if you do not need to pass the i-th level at all, the i-th digit should equal 0. | standard output | |
PASSED | 176b1d0c4daf8361ee257194f6a8db8f | train_001.jsonl | 1402673400 | Everyone who has played Cut the Rope knows full well how the gameplay is organized. All levels in the game are divided into boxes. Initially only one box with some levels is available. Player should complete levels to earn stars, collecting stars opens new box with levels. Imagine that you are playing Cut the Rope for the first time. Currently you have only the levels of the first box (by the way, it is called "Cardboard Box"). Each level is characterized by two integers: ai β how long it takes to complete the level for one star, bi β how long it takes to complete the level for two stars (aiβ<βbi).You want to open the next box as quickly as possible. So, you need to earn at least w stars. How do make it happen? Note that the level can be passed only once: either for one star or for two. You do not necessarily need to pass all the levels. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class Main{
static int n,w;
static Node[][] input;
static TreeSet<Node> tm1;
static TreeSet<Node> tm2;
static int[] res;
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb=new StringBuilder();
StringTokenizer st;
st=new StringTokenizer(br.readLine());
n=Integer.parseInt(st.nextToken());
w=Integer.parseInt(st.nextToken());
input=new Node[n][3];
for (int i = 0; i < n; i++) {
st=new StringTokenizer(br.readLine());
int a=Integer.parseInt(st.nextToken());
int b=Integer.parseInt(st.nextToken())-a;
input[i][0]=new Node(i,a,true);
input[i][1]=new Node(i,b,false);
input[i][2]=new Node(i,a+b,true);
}
tm1=new TreeSet<Node>();
tm2=new TreeSet<Node>();
for (int i = 0; i < n; i++) {
tm1.add(input[i][0]);
tm2.add(input[i][2]);
}
long ans=0;
res=new int[n];
if (w%2==1){
Node x=tm1.pollFirst();
ans+=x.v;
res[x.i]=1;
tm1.add(input[x.i][1]);
tm2.remove(input[x.i][2]);
}
for (int i = 0; i < w/2; i++) {
Node a1=tm1.first();
Node a2=tm1.higher(a1);
Node b;
try{
b=tm2.first();
}
catch(Exception e){
b=null;
}
if (b==null || (a1!=null && a2!=null && a1.v+a2.v<b.v)){
tm1.pollFirst();
tm1.pollFirst();
if (a1.first){
tm1.add(input[a1.i][1]);
tm2.remove(input[a1.i][2]);
res[a1.i]=1;
}
else{
res[a1.i]=2;
}
if (a2.first){
tm1.add(input[a2.i][1]);
tm2.remove(input[a2.i][2]);
res[a2.i]=1;
}
else{
res[a2.i]=2;
}
ans+=a1.v+a2.v;
}
else{
tm2.pollFirst();
tm1.remove(input[b.i][0]);
res[b.i]=2;
ans+=b.v;
}
}
sb.append(ans).append('\n');
for (int i = 0; i < n; i++) {
sb.append(res[i]);
}
System.out.println(sb);
}
}
class Node implements Comparable<Node>{
int i;
long v;
boolean first;
public Node(int i, long v,boolean first){
this.i=i;
this.v=v;
this.first=first;
}
@Override
public int compareTo(Node o) {
int ans=Long.compare(v,o.v);
if (ans==0) ans=Integer.compare(i,o.i);
return ans;
}
}
| Java | ["2 3\n1 2\n1 2", "5 3\n10 20\n5 10\n10 20\n6 9\n25 30"] | 5 seconds | ["3\n12", "14\n01020"] | NoteIn the first test sample, answer 21 is also assumed correct. | Java 8 | standard input | [
"data structures",
"greedy"
] | a4b9ad2c4980bd7ebe23acb4c37680df | The first line contains two integers n and w (1ββ€βnββ€β3Β·105;Β 1ββ€βwββ€β2n) β the number of levels in the first box and the number of stars you need to open another box. Each of the following n lines contains two integers ai and bi (1ββ€βaiβ<βbiββ€β109) β the attributes of the i-th level. | 2,600 | In the first line print integer t β the minimum time you need to open the next box. In the next line, print n digits without spaces β the description of the optimal scenario: if you need to pass the i-th level for one star, the i-th digit should equal 1; if you need to pass the i-th level for two stars, the i-th digit should equal 2; if you do not need to pass the i-th level at all, the i-th digit should equal 0. | standard output | |
PASSED | 8989a21134a31b566b363fab13b50722 | train_001.jsonl | 1425279600 | Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and mβ-β1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube.The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x,βy) either yβ=β0, or there is a cube with coordinates (xβ-β1,βyβ-β1), (x,βyβ-β1) or (xβ+β1,βyβ-β1).Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game.Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109β+β9. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
import java.util.concurrent.*;
public class P520D {
final static long MOD = 1_000_000_009L;
final static int MIN_VALUE = -1_000_000_000 - 1;
final static int MAX_VALUE = +1_000_000_000 + 1;
TreeSet<Cube> cubes = new TreeSet<Cube>(new Comparator<Cube>() {
@Override
public int compare(Cube cube1, Cube cube2) {
return ((cube1.y != cube2.y) ? (cube1.y - cube2.y) : (cube1.x - cube2.x));
}
});
TreeSet<Cube> upper = new TreeSet<Cube>(new Comparator<Cube>() {
@Override
public int compare(Cube cube1, Cube cube2) {
return ((cube1.v - cube2.v));
}
});
class Cube {
int x, y, v;
boolean updated = false;
Set<Cube> cCubes = new HashSet<Cube>();
Set<Cube> pCubes = new HashSet<Cube>();
public Cube(int x, int y, int v) {
this.x = x;
this.y = y;
this.v = v;
}
boolean isUpper() {
for (Cube child : cCubes) {
if (child.pCubes.size() == 1) {
return false;
}
}
return true;
}
void addChild(Cube cube) {
cCubes.add(cube);
}
void removeChild(Cube cube) {
cCubes.remove(cube);
if (this.isUpper()) {
upper.add(this);
}
}
void addParent(Cube cube) {
pCubes.add(cube);
}
void removeParent(Cube cube) {
pCubes.remove(cube);
for (Cube parent : pCubes) {
if (!parent.isUpper()) {
upper.remove(parent);
}
}
}
}
void genCubesTree(Cube head) {
head.updated = true;
for (Cube cube : cubes.subSet(new Cube((head.v == -1) ? MIN_VALUE : (head.x - 1), head.y + 1, -1),
new Cube((head.v == -1) ? MAX_VALUE : (head.x + 2), head.y + 1, -1))) {
head.addChild(cube);
if (head.v >= 0) {
cube.addParent(head);
}
if (!cube.updated) {
genCubesTree(cube);
}
}
}
@SuppressWarnings("unchecked")
public void run() throws Exception {
int m = nextInt();
for (int i = 0; i < m; i++) {
cubes.add(new Cube(nextInt(), nextInt(), i));
}
genCubesTree(new Cube(0, -1, -1));
for (Cube cube : cubes) {
if (cube.isUpper()) {
upper.add(cube);
}
}
boolean isVasya = true;
long value = 0;
while (upper.size() > 0) {
Cube taken = (isVasya) ? upper.last() : upper.first();
upper.remove(taken);
for (Cube cube : taken.pCubes) {
cube.removeChild(taken);
}
for (Cube cube : taken.cCubes) {
cube.removeParent(taken);
}
value = (value * m + taken.v) % MOD;
isVasya = !isVasya;
}
println(value);
}
public static void main(String... args) throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedOutputStream(System.out));
new P520D().run();
br.close();
pw.close();
}
static BufferedReader br;
static PrintWriter pw;
StringTokenizer stok;
String nextToken() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
String s = br.readLine();
if (s == null) { return null; }
stok = new StringTokenizer(s);
}
return stok.nextToken();
}
void print(byte b) { print("" + b); }
void print(int i) { print("" + i); }
void print(long l) { print("" + l); }
void print(double d) { print("" + d); }
void print(char c) { print("" + c); }
void print(Object o) {
if (o instanceof int[]) { print(Arrays.toString((int [])o));
} else if (o instanceof long[]) { print(Arrays.toString((long [])o));
} else if (o instanceof char[]) { print(Arrays.toString((char [])o));
} else if (o instanceof byte[]) { print(Arrays.toString((byte [])o));
} else if (o instanceof short[]) { print(Arrays.toString((short [])o));
} else if (o instanceof boolean[]) { print(Arrays.toString((boolean [])o));
} else if (o instanceof float[]) { print(Arrays.toString((float [])o));
} else if (o instanceof double[]) { print(Arrays.toString((double [])o));
} else if (o instanceof Object[]) { print(Arrays.toString((Object [])o));
} else { println("" + o); }
}
void print(String s) { pw.print(s); }
void println() { println(""); }
void println(byte b) { println("" + b); }
void println(int i) { println("" + i); }
void println(long l) { println("" + l); }
void println(double d) { println("" + d); }
void println(char c) { println("" + c); }
void println(Object o) { print(o); println(); }
void println(String s) { pw.println(s); }
int nextInt() throws IOException { return Integer.parseInt(nextToken()); }
long nextLong() throws IOException { return Long.parseLong(nextToken()); }
double nextDouble() throws IOException { return Double.parseDouble(nextToken()); }
char nextChar() throws IOException { return (char) (br.read()); }
String next() throws IOException { return nextToken(); }
String nextLine() throws IOException { return br.readLine(); }
int [] readInt(int size) throws IOException {
int [] array = new int [size];
for (int i = 0; i < size; i++) { array[i] = nextInt(); }
return array;
}
long [] readLong(int size) throws IOException {
long [] array = new long [size];
for (int i = 0; i < size; i++) { array[i] = nextLong(); }
return array;
}
double [] readDouble(int size) throws IOException {
double [] array = new double [size];
for (int i = 0; i < size; i++) { array[i] = nextDouble(); }
return array;
}
String [] readLines(int size) throws IOException {
String [] array = new String [size];
for (int i = 0; i < size; i++) { array[i] = nextLine(); }
return array;
}
} | Java | ["3\n2 1\n1 0\n0 1", "5\n0 0\n0 1\n0 2\n0 3\n0 4"] | 3 seconds | ["19", "2930"] | null | Java 8 | standard input | [
"implementation",
"greedy",
"games"
] | 9f36d49541e6dd7082e37416cdb1949c | The first line contains number m (2ββ€βmββ€β105). The following m lines contain the coordinates of the cubes xi,βyi (β-β109ββ€βxiββ€β109, 0ββ€βyiββ€β109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. | 2,100 | In the only line print the answer to the problem. | standard output | |
PASSED | d777a150a25a43504c2b64bb94de0105 | train_001.jsonl | 1425279600 | Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and mβ-β1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube.The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x,βy) either yβ=β0, or there is a cube with coordinates (xβ-β1,βyβ-β1), (x,βyβ-β1) or (xβ+β1,βyβ-β1).Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game.Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109β+β9. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
import java.util.concurrent.*;
public class P520D {
final static long MOD = 1_000_000_009L;
final static int MIN_VALUE = -1_000_000_000 - 1;
final static int MAX_VALUE = +1_000_000_000 + 1;
int m;
TreeSet<Cube> cubes = new TreeSet<Cube>();
TreeSet<Cube> upper = new TreeSet<Cube>(new Comparator<Cube>() {
@Override public int compare(Cube cube1, Cube cube2) {
return ((cube1.v - cube2.v));
}
});
class Cube implements Comparable<Cube> {
public int x, y, v;
boolean updated = false;
Set<Cube> cCubes = new HashSet<Cube>();
Set<Cube> pCubes = new HashSet<Cube>();
public Cube(int x, int y, int v) {
this.x = x;
this.y = y;
this.v = v;
}
boolean isUpper() {
for (Cube child : cCubes) {
if (child.pCubes.size() == 1) { return false; }
}
return true;
}
void addChild(Cube cube) {
cCubes.add(cube);
}
void removeChild(Cube cube) {
cCubes.remove(cube);
if (this.isUpper()) { upper.add(this); }
}
void addParent(Cube cube) {
pCubes.add(cube);
}
void removeParent(Cube cube) {
pCubes.remove(cube);
for (Cube parent : pCubes) {
if (!parent.isUpper()) { upper.remove(parent); }
}
}
@Override public int compareTo(Cube cube) {
return ((y != cube.y) ? (y - cube.y) : (x - cube.x));
}
@Override public String toString() {
String cl = ""; for (Cube cube : cCubes) { cl += cube.v + ","; } cl = (cl.length() > 0) ? cl.substring(0, cl.length() - 1) : cl;
String pl = ""; for (Cube cube : pCubes) { pl += cube.v + ","; } pl = (pl.length() > 0) ? pl.substring(0, pl.length() - 1) : pl;
return ("{v = " + v + " ,x=" + x + ",y=" + y + ",c:(" + cl + "),p:(" + pl + ")}");
}
}
void genCubesTree(Cube head) {
head.updated = true;
for (Cube cube : cubes.subSet(new Cube((head.v == -1) ? MIN_VALUE : (head.x - 1), head.y + 1, -1),
new Cube((head.v == -1) ? MAX_VALUE : (head.x + 2), head.y + 1, -1))) {
head.addChild(cube);
if (head.v >= 0) { cube.addParent(head); }
if (!cube.updated) { genCubesTree(cube); }
}
}
@SuppressWarnings("unchecked")
public void run() throws Exception {
m = nextInt();
HashMap<Integer, Integer> heights = new HashMap<Integer, Integer>();
int xx = 0;
boolean log = false;
long st = System.currentTimeMillis();
for (int i = 0; i < m; i++) {
int x = nextInt();
if ((xx == 0) && (m == 100_000)) xx = x;
int y = nextInt();
Integer count = heights.get(y);
heights.put(y, (count == null) ? 1 : (count + 1));
cubes.add(new Cube(x, y, i));
}
//if ((m == 72_956)/* && (xx == 852_523_908 )*/) { log = true; }
if (log) System.out.println("1: " + (System.currentTimeMillis() - st));
genCubesTree(new Cube(0, -1, -1));
if (log) System.out.println("2: " + (System.currentTimeMillis() - st));
for (Cube cube : cubes) {
if (cube.isUpper()) { upper.add(cube); }
}
if (log) System.out.println("3: " + (System.currentTimeMillis() - st));
if (log) System.out.println("4: " + heights);
if (log) System.out.println("5: " + upper.size());
boolean isVasya = true;
long value = 0;
while (upper.size() > 0) {
// println("Cubes : " + cubes); pw.flush();
// println("Upper : " + upper);
// println("Plaing : " + (isVasya ? "Vasya" : "Petya"));
Cube taken = (isVasya) ? upper.last() : upper.first();
upper.remove(taken);
for (Cube cube : taken.pCubes) {
cube.removeChild(taken);
}
for (Cube cube : taken.cCubes) {
cube.removeParent(taken);
}
value = (value * m + taken.v) % MOD;
// println("taken : " + taken); pw.flush(); System.console().readLine();
isVasya = !isVasya;
}
println(value);
}
public static void main(String... args) throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedOutputStream(System.out));
new P520D().run();
br.close();
pw.close();
}
static BufferedReader br;
static PrintWriter pw;
StringTokenizer stok;
String nextToken() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
String s = br.readLine();
if (s == null) { return null; }
stok = new StringTokenizer(s);
}
return stok.nextToken();
}
void print(byte b) { print("" + b); }
void print(int i) { print("" + i); }
void print(long l) { print("" + l); }
void print(double d) { print("" + d); }
void print(char c) { print("" + c); }
void print(Object o) {
if (o instanceof int[]) { print(Arrays.toString((int [])o));
} else if (o instanceof long[]) { print(Arrays.toString((long [])o));
} else if (o instanceof char[]) { print(Arrays.toString((char [])o));
} else if (o instanceof byte[]) { print(Arrays.toString((byte [])o));
} else if (o instanceof short[]) { print(Arrays.toString((short [])o));
} else if (o instanceof boolean[]) { print(Arrays.toString((boolean [])o));
} else if (o instanceof float[]) { print(Arrays.toString((float [])o));
} else if (o instanceof double[]) { print(Arrays.toString((double [])o));
} else if (o instanceof Object[]) { print(Arrays.toString((Object [])o));
} else { println("" + o); }
}
void print(String s) { pw.print(s); }
void println() { println(""); }
void println(byte b) { println("" + b); }
void println(int i) { println("" + i); }
void println(long l) { println("" + l); }
void println(double d) { println("" + d); }
void println(char c) { println("" + c); }
void println(Object o) { print(o); println(); }
void println(String s) { pw.println(s); }
int nextInt() throws IOException { return Integer.parseInt(nextToken()); }
long nextLong() throws IOException { return Long.parseLong(nextToken()); }
double nextDouble() throws IOException { return Double.parseDouble(nextToken()); }
char nextChar() throws IOException { return (char) (br.read()); }
String next() throws IOException { return nextToken(); }
String nextLine() throws IOException { return br.readLine(); }
int [] readInt(int size) throws IOException {
int [] array = new int [size];
for (int i = 0; i < size; i++) { array[i] = nextInt(); }
return array;
}
long [] readLong(int size) throws IOException {
long [] array = new long [size];
for (int i = 0; i < size; i++) { array[i] = nextLong(); }
return array;
}
double [] readDouble(int size) throws IOException {
double [] array = new double [size];
for (int i = 0; i < size; i++) { array[i] = nextDouble(); }
return array;
}
String [] readLines(int size) throws IOException {
String [] array = new String [size];
for (int i = 0; i < size; i++) { array[i] = nextLine(); }
return array;
}
} | Java | ["3\n2 1\n1 0\n0 1", "5\n0 0\n0 1\n0 2\n0 3\n0 4"] | 3 seconds | ["19", "2930"] | null | Java 8 | standard input | [
"implementation",
"greedy",
"games"
] | 9f36d49541e6dd7082e37416cdb1949c | The first line contains number m (2ββ€βmββ€β105). The following m lines contain the coordinates of the cubes xi,βyi (β-β109ββ€βxiββ€β109, 0ββ€βyiββ€β109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. | 2,100 | In the only line print the answer to the problem. | standard output | |
PASSED | ff11317ac3f8571a21056df7cf265587 | train_001.jsonl | 1425279600 | Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and mβ-β1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube.The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x,βy) either yβ=β0, or there is a cube with coordinates (xβ-β1,βyβ-β1), (x,βyβ-β1) or (xβ+β1,βyβ-β1).Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game.Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109β+β9. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeSet;
/**
* @author Don Li
*/
public class Cubes {
static final int MOD = (int) (1e9 + 9);
int[] dx = new int[]{-1, 0, 1};
int[] dx2 = new int[]{-2, -1, 1, 2};
Cube[] cubes;
Map<Cube, Integer> ids;
void solve() {
int m = in.nextInt();
cubes = new Cube[m];
ids = new HashMap<>(m);
for (int i = 0; i < m; i++) {
cubes[i] = new Cube(in.nextInt(), in.nextInt());
ids.put(cubes[i], i);
}
TreeSet<Integer> pq = new TreeSet<>();
for (int i = 0; i < m; i++) {
if (canRemove(i)) pq.add(i);
}
int t = 0;
int[] res = new int[m];
while (!pq.isEmpty()) {
int cur = t % 2 == 0 ? pq.pollLast() : pq.pollFirst();
res[t++] = cur;
ids.remove(cubes[cur]);
for (int i = 0; i < 3; i++) {
int nxt = ids.getOrDefault(new Cube(cubes[cur].x + dx[i], cubes[cur].y - 1), -1);
if (nxt >= 0 && canRemove(nxt)) pq.add(nxt);
}
for (int i = 0; i < 4; i++) {
int c = ids.getOrDefault(new Cube(cubes[cur].x + dx2[i], cubes[cur].y), -1);
if (c >= 0 && !canRemove(c)) pq.remove(c);
}
}
long ans = 0, a = 1;
for (int i = m - 1; i >= 0; i--) {
ans = (ans + res[i] * a % MOD) % MOD;
a = a * m % MOD;
}
out.println(ans);
}
boolean canRemove(int i) {
int x = cubes[i].x, y = cubes[i].y;
boolean ok = true;
for (int j = 0; j < 3; j++) {
int nx = x + dx[j], ny = y + 1;
Cube c = new Cube(nx, ny);
if (ids.containsKey(c)) {
int cnt = 0;
for (int k = 0; k < 3; k++) {
int nnx = nx + dx[k];
if (ids.containsKey(new Cube(nnx, y))) cnt++;
}
if (cnt == 1) {
ok = false;
break;
}
}
}
return ok;
}
static class Cube {
int x, y;
public Cube(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass()) return false;
Cube cube = (Cube) obj;
return x == cube.x && y == cube.y;
}
@Override
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
}
public static void main(String[] args) {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
new Cubes().solve();
out.close();
}
static FastScanner in;
static PrintWriter out;
static class FastScanner {
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
| Java | ["3\n2 1\n1 0\n0 1", "5\n0 0\n0 1\n0 2\n0 3\n0 4"] | 3 seconds | ["19", "2930"] | null | Java 8 | standard input | [
"implementation",
"greedy",
"games"
] | 9f36d49541e6dd7082e37416cdb1949c | The first line contains number m (2ββ€βmββ€β105). The following m lines contain the coordinates of the cubes xi,βyi (β-β109ββ€βxiββ€β109, 0ββ€βyiββ€β109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. | 2,100 | In the only line print the answer to the problem. | standard output | |
PASSED | 69f9d314fa29a360ba8a66d6dcd1e66e | train_001.jsonl | 1425279600 | Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and mβ-β1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube.The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x,βy) either yβ=β0, or there is a cube with coordinates (xβ-β1,βyβ-β1), (x,βyβ-β1) or (xβ+β1,βyβ-β1).Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game.Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109β+β9. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class _520D {
static final int MOD = 1000000009;
static int n;
static int[] x, y;
static int[] rank;
static boolean[] hasCube;
static Random rand = new Random();
static boolean isSafeToRemove(int u) {
int xx = x[u], yy = y[u];
for (int i = -1; i <= 1; i++) {
int v = find(xx + i, yy + 1);
if (v == -1 || !hasCube[v]) continue;
boolean ok = false;
for (int j = -1; j <= 1; j++) {
if (xx + i + j == xx) continue;
v = find(xx + i + j, yy);
if (v != -1 && hasCube[v]) {
// require x + i + j because (x, y) needs to be removed
ok = true;
break;
}
}
if (!ok) return false;
}
return true;
}
static int cmp(int i, int j) {
if (x[i] < x[j]) return -1;
else if (x[i] > x[j]) return 1;
else if (y[i] < y[j]) return -1;
else if (y[i] > y[j]) return 1;
else return 0;
}
static int cmp(int index, int xx, int yy) {
if (x[index] < xx) return -1;
else if (x[index] > xx) return 1;
else if (y[index] < yy) return -1;
else if (y[index] > yy) return 1;
else return 0;
}
static void sort(int[] a, int l, int r) {
int i = l, j = r, x = a[rand.nextInt(r - l + 1) + l];
do {
while (cmp(a[i], x) < 0)
i++;
while (cmp(a[j], x) > 0)
j--;
if (i <= j) {
ArrayUtil.swap(a, i, j);
i++;
j--;
}
} while (i <= j);
if (i < r) sort(a, i, r);
if (j > l) sort(a, l, j);
}
static int find(int x, int y) {
int left = 0, right = n - 1;
while (left <= right) {
int mid = (left + right) / 2;
int res = cmp(rank[mid], x, y);
if (res == 0) return rank[mid];
else if (res < 0) left = mid + 1;
else right = mid - 1;
}
return -1;
}
public static void main(String[] args) throws Exception {
Reader.init(System.in);
BufferedWriter cout = new BufferedWriter(new OutputStreamWriter(System.out));
n = Reader.nextInt();
x = new int[n];
y = new int[n];
rank = new int[n];
hasCube = new boolean[n];
for (int i = 0; i < n; i++) {
x[i] = Reader.nextInt();
y[i] = Reader.nextInt();
hasCube[i] = true;
}
for (int i = 0; i < n; i++)
rank[i] = i;
sort(rank, 0, n - 1);
long ans = 0;
// Now perform a bfs
TreeSet<Integer> queue = new TreeSet<>();
for (int u = 0; u < n; u++)
if (isSafeToRemove(u)) queue.add(u);
// System.out.println(queue);
int round = 0;
while (!queue.isEmpty()) {
int u = round % 2 == 0 ? queue.pollLast() : queue.pollFirst();
round++;
ans = (ans * n + u) % MOD;
hasCube[u] = false;
for (int delta = -1; delta <= 1; delta++) {
int v = find(x[u] + delta, y[u] - 1);
if (v != -1 && hasCube[v] && !queue.contains(v) && isSafeToRemove(v)) queue.add(v);
}
for (int delta = -2; delta <= 2; delta++) {
if (delta == 0) continue;
int v = find(x[u] + delta, y[u]);
if (v != -1 && hasCube[v] && queue.contains(v) && !isSafeToRemove(v)) queue.remove(v);
}
}
System.out.println(ans);
cout.close();
}
static class Pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<Pair<U, V>> {
final U _1;
final V _2;
private Pair(U key, V val) {
this._1 = key;
this._2 = val;
}
public static <U extends Comparable<U>, V extends Comparable<V>> Pair<U, V> instanceOf(U _1, V _2) {
return new Pair<U, V>(_1, _2);
}
@Override
public String toString() {
return _1 + " " + _2;
}
@Override
public int hashCode() {
int res = 17;
res = res * 31 + _1.hashCode();
res = res * 31 + _2.hashCode();
return res;
}
@Override
public int compareTo(Pair<U, V> that) {
int res = this._1.compareTo(that._1);
if (res < 0 || res > 0) return res;
else return this._2.compareTo(that._2);
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (!(obj instanceof Pair)) return false;
Pair<?, ?> that = (Pair<?, ?>) obj;
return _1.equals(that._1) && _2.equals(that._2);
}
}
/** Class for buffered reading int and double values */
static class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
// TODO add check for eof if necessary
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
static class ArrayUtil {
static void swap(int[] a, int i, int j) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void swap(long[] a, int i, int j) {
long tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void swap(double[] a, int i, int j) {
double tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void swap(char[] a, int i, int j) {
char tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void swap(boolean[] a, int i, int j) {
boolean tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static void reverse(int[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static void reverse(long[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static void reverse(double[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static void reverse(char[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static void reverse(boolean[] a, int i, int j) {
for (; i < j; i++, j--)
swap(a, i, j);
}
static long sum(int[] a) {
int sum = 0;
for (int i : a)
sum += i;
return sum;
}
static long sum(long[] a) {
long sum = 0;
for (long i : a)
sum += i;
return sum;
}
static double sum(double[] a) {
double sum = 0;
for (double i : a)
sum += i;
return sum;
}
static int max(int[] a) {
int max = Integer.MIN_VALUE;
for (int i : a)
if (i > max) max = i;
return max;
}
static int min(int[] a) {
int min = Integer.MAX_VALUE;
for (int i : a)
if (i < min) min = i;
return min;
}
static long max(long[] a) {
long max = Long.MIN_VALUE;
for (long i : a)
if (i > max) max = i;
return max;
}
static long min(long[] a) {
long min = Long.MAX_VALUE;
for (long i : a)
if (i < min) min = i;
return min;
}
}
}
| Java | ["3\n2 1\n1 0\n0 1", "5\n0 0\n0 1\n0 2\n0 3\n0 4"] | 3 seconds | ["19", "2930"] | null | Java 8 | standard input | [
"implementation",
"greedy",
"games"
] | 9f36d49541e6dd7082e37416cdb1949c | The first line contains number m (2ββ€βmββ€β105). The following m lines contain the coordinates of the cubes xi,βyi (β-β109ββ€βxiββ€β109, 0ββ€βyiββ€β109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. | 2,100 | In the only line print the answer to the problem. | standard output | |
PASSED | 9b854d914053812b8cf2c12c04ad634b | train_001.jsonl | 1425279600 | Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and mβ-β1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube.The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x,βy) either yβ=β0, or there is a cube with coordinates (xβ-β1,βyβ-β1), (x,βyβ-β1) or (xβ+β1,βyβ-β1).Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game.Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109β+β9. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main extends PrintWriter {
BufferedReader br;
StringTokenizer stok;
final Random rand = new Random(31);
final int inf = (int) 1e9;
final long linf = (long) 1e18;
final int mod = inf + 7;
class Cube {
int x, y;
int v;
public Cube(int x, int y, int v) {
this.x = x;
this.y = y;
this.v = v;
}
@Override
public String toString() {
return "Cube{" +
"v=" + v +
'}';
}
}
TreeSet<Cube> byPoint;
Cube tmp = new Cube(0, 0, 0);
boolean isOpen(int x, int y) {
for (int i = -1; i <= 1; i++) {
tmp.y = y + 1;
tmp.x = x + i;
if (byPoint.contains(tmp) && countUnder(tmp.x, tmp.y) == 1) {
return false;
}
}
return true;
}
boolean isOpen(Cube c) {
return isOpen(c.x, c.y);
}
int countUnder(int x, int y) {
int res = 0;
tmp.y = y - 1;
for (int i = -1; i <= 1; i++) {
tmp.x = x + i;
if (byPoint.contains(tmp)) {
res++;
}
}
return res;
}
void solve() throws IOException {
int n = nextInt();
byPoint = new TreeSet<>(new Comparator<Cube>() {
@Override
public int compare(Cube o1, Cube o2) {
return o1.x == o2.x ? o1.y - o2.y : o1.x - o2.x;
}
});
TreeSet<Cube> byV = new TreeSet<>(new Comparator<Cube>() {
@Override
public int compare(Cube o1, Cube o2) {
return o1.v - o2.v;
}
});
List<Cube> a = new ArrayList<>();
for (int i = 0; i < n; i++) {
Cube c = new Cube(nextInt(), nextInt(), i);
byPoint.add(c);
a.add(c);
}
for (Cube cube : a) {
if (isOpen(cube)) {
byV.add(cube);
}
}
int[] ans = new int[n];
for (int i = 0; i < n; i++) {
Cube c = null;
do {
if (c != null) {
byV.remove(c);
}
if (i % 2 == 0) {
c = byV.last();
} else {
c = byV.first();
}
} while (!isOpen(c));
ans[i] = c.v;
byV.remove(c);
byPoint.remove(c);
for (int j = -1; j <= 1; j++) {
tmp.y = c.y - 1;
tmp.x = c.x + j;
if (byPoint.contains(tmp)) {
Cube down = byPoint.ceiling(tmp);
if (isOpen(down)) {
byV.add(down);
}
}
}
}
long mul = 1;
long res = 0;
int mod = inf + 9;
for (int i = 0; i < n; i++) {
res = (res + ans[n - 1 - i] * mul) % mod;
mul = mul * n % mod;
}
println(res);
}
public static void main(String[] args) throws IOException {
try (Main main = new Main()) {
main.solve();
}
}
Main() throws IOException {
super(System.out);
br = new BufferedReader(new InputStreamReader(System.in));
}
Main(String s) throws IOException {
super("".equals(s) ? "output.txt" : s + ".out");
br = new BufferedReader(new FileReader("".equals(s) ? "input.txt" : s + ".in"));
}
String next() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
String s = br.readLine();
if (s == null) {
return null;
}
stok = new StringTokenizer(s);
}
return stok.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
} | Java | ["3\n2 1\n1 0\n0 1", "5\n0 0\n0 1\n0 2\n0 3\n0 4"] | 3 seconds | ["19", "2930"] | null | Java 8 | standard input | [
"implementation",
"greedy",
"games"
] | 9f36d49541e6dd7082e37416cdb1949c | The first line contains number m (2ββ€βmββ€β105). The following m lines contain the coordinates of the cubes xi,βyi (β-β109ββ€βxiββ€β109, 0ββ€βyiββ€β109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. | 2,100 | In the only line print the answer to the problem. | standard output | |
PASSED | fde201ae682c87597a67a14fa094269f | train_001.jsonl | 1425279600 | Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and mβ-β1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube.The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x,βy) either yβ=β0, or there is a cube with coordinates (xβ-β1,βyβ-β1), (x,βyβ-β1) or (xβ+β1,βyβ-β1).Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game.Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109β+β9. | 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.io.Reader;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class TaskD {
public static void main(String[] args)
{
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, new InputStreamReader(inputStream), out);
out.close();
}
static long toCoord(long x, long y)
{
return (x << 32) + y;
}
private static int countSupport(HashMap<Long, Integer> map, long x, long y)
{
int cnt = 0;
if(!map.containsKey(toCoord(x, y)))
return 0;
// System.err.println("* " + x + " " + y);
if(map.containsKey(toCoord(x, y - 1))) { // x, y - 1
cnt++;
// System.err.println("* " + x + " " + (y-1));
}
if(map.containsKey(toCoord(x -1, y - 1))) { // x - 1, y -1
cnt++;
// System.err.println("* " + (x-1) + " " + (y-1));
}
if(map.containsKey(toCoord(x + 1, y - 1))) { // x + 1, y - 1
cnt++;
// System.err.println("* " + (x+1) + " " + (y-1));
}
// System.err.println("= " + cnt);
return cnt;
}
static boolean canRemove(HashMap<Long, Integer> map, long x, long y) {
long coord = toCoord(x,y);
if(map.containsKey(coord)) {
// System.err.println(x + " " + y);
int c = countSupport(map, x + 1, y + 1);
// System.err.println((x+1) + " " + (y+1) + " " + c);
if(c== 1) // x + 1, y + 1
return false;
// System.err.println(x + " " + (y+1) + " " + c);
c = countSupport(map, x, y + 1);
if(c == 1) // x, y + 1
return false;
// System.err.println((x-1) + " " + (y+1) + " " + c);
c = countSupport(map, x -1, y + 1);
if(c == 1) // x - 1, y + 1
return false;
return true;
}
return false;
}
static void remove(HashMap<Long, Integer> map, TreeMap<Integer, Long> removable, long x, long y)
{
long coord = toCoord(x,y);
Integer i = map.get(coord);
if(i != null) {
removable.remove(i);
}
}
public void solve(int test, Reader input, PrintWriter out)
{
// System.err.println("---- " + test);
MyScanner in = new MyScanner(input);
int m = in.nextInt();
HashMap<Long, Integer> map = new HashMap<>();
for(int i = 0; i < m; i++) {
long x = in.nextLong() + 1_000_000_001L;
long y = in.nextLong() + 1L;
// System.out.println(x + " " + y + " " + Long.toHexString(toCoord(x,y)));
map.put(toCoord(x,y), i);
}
TreeMap<Integer, Long> removable = new TreeMap<>();
for(Entry<Long, Integer> e : map.entrySet()) {
long x = e.getKey() >> 32;
long y = e.getKey() & 0xffff_ffffL;
// System.err.println(x + " " + y + " = " + e.getValue());
if(canRemove(map, x, y))
removable.put(e.getValue(), e.getKey());
}
int[] removed = new int[m];
boolean vasya = true;
for(int i = 0; i < m; i++) {
// System.out.println(removable);
long rem = 0;
Entry<Integer, Long> e;
if(vasya) {
e = removable.pollLastEntry();
} else {
e = removable.pollFirstEntry();
}
rem = e.getValue();
removed[i] = e.getKey();
map.remove(e.getValue());
vasya = !vasya;
long x = rem >> 32;
long y = rem & 0xffff_ffffL;
for(int dx = -2; dx < 3; dx++) {
for(int dy = -1; dy < 1; dy++) {
if(canRemove(map, x+dx, y+dy))
removable.put(map.get(toCoord(x+dx, y+dy)), toCoord(x+dx, y+dy));
else
remove(map, removable, x+dx, y+dy);
}
}
}
// System.err.println(Arrays.toString(removed));
int MOD = 1_000_000_009;
long res = 0;
for(int i : removed) {
res = (res * m) % MOD;
res = (res + i) % MOD;
}
out.println(res);
}
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner(Reader reader) {
br = new BufferedReader(reader);
}
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 1\n1 0\n0 1", "5\n0 0\n0 1\n0 2\n0 3\n0 4"] | 3 seconds | ["19", "2930"] | null | Java 8 | standard input | [
"implementation",
"greedy",
"games"
] | 9f36d49541e6dd7082e37416cdb1949c | The first line contains number m (2ββ€βmββ€β105). The following m lines contain the coordinates of the cubes xi,βyi (β-β109ββ€βxiββ€β109, 0ββ€βyiββ€β109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. | 2,100 | In the only line print the answer to the problem. | standard output | |
PASSED | 2fca1865d81de7a1b398dc598fc3928c | train_001.jsonl | 1425279600 | Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and mβ-β1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube.The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x,βy) either yβ=β0, or there is a cube with coordinates (xβ-β1,βyβ-β1), (x,βyβ-β1) or (xβ+β1,βyβ-β1).Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game.Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109β+β9. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.SortedSet;
import java.util.AbstractSet;
import java.util.InputMismatchException;
import java.util.Random;
import java.util.TreeSet;
import java.util.ArrayList;
import java.util.Map;
import java.util.NoSuchElementException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;
import java.util.List;
import java.util.AbstractMap;
import java.util.Map.Entry;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Pradyumn
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
static final long MODULO = (long) (1e9 + 9);
public void solve(int testNumber, FastReader in, PrintWriter out) {
int m = in.nextInt();
TaskD.Cube[] cubes = new TaskD.Cube[m];
EHashMap<Long, TaskD.Cube> coordToCube = new EHashMap<>();
for (int i = 0; i < m; ++i) {
cubes[i] = new TaskD.Cube();
cubes[i].number = i;
cubes[i].x = in.nextInt();
cubes[i].y = in.nextInt();
long coord = cubes[i].x * (long) 3e9 + cubes[i].y;
coordToCube.put(coord, cubes[i]);
}
for (TaskD.Cube cube : cubes) {
if (cube.y > 0) {
for (int dx = -1; dx <= 1; ++dx) {
long ncoord = (cube.x + dx) * (long) 3e9 + (cube.y - 1);
TaskD.Cube under = coordToCube.get(ncoord);
if (under != null) {
cube.dependsOn.add(under);
under.dependents.add(cube);
}
}
if (cube.dependsOn.isEmpty()) throw new RuntimeException();
if (cube.dependsOn.size() == 1) {
++cube.dependsOn.get(0).numMusts;
}
}
}
TreeSet<TaskD.Cube> all = new TreeSet<>();
for (TaskD.Cube cube : cubes) {
all.add(cube);
}
long res = 0;
TaskD.Cube specialTail = new TaskD.Cube();
specialTail.numMusts = 0;
specialTail.number = m;
for (int i = 0; i < m; ++i) {
TaskD.Cube toRemove;
if (i % 2 == 0) {
toRemove = all.headSet(specialTail).last();
} else {
toRemove = all.first();
}
if (toRemove.numMusts != 0) throw new RuntimeException();
all.remove(toRemove);
res = (res * m + toRemove.number) % MODULO;
for (TaskD.Cube upper : toRemove.dependents) {
upper.dependsOn.remove(toRemove);
if (upper.dependsOn.size() == 1) {
TaskD.Cube newMust = upper.dependsOn.get(0);
all.remove(newMust);
++newMust.numMusts;
all.add(newMust);
}
}
for (TaskD.Cube lower : toRemove.dependsOn) {
lower.dependents.remove(toRemove);
if (toRemove.dependsOn.size() == 1) {
all.remove(lower);
--lower.numMusts;
all.add(lower);
}
}
}
out.println(res);
}
static class Cube implements Comparable<TaskD.Cube> {
List<TaskD.Cube> dependsOn = new ArrayList<>(1);
List<TaskD.Cube> dependents = new ArrayList<>(1);
int number;
int x;
int y;
int numMusts = 0;
public int compareTo(TaskD.Cube o) {
int z = numMusts - o.numMusts;
if (z != 0) return z;
return number - o.number;
}
}
}
static class EHashMap<E, V> extends AbstractMap<E, V> {
private final int[] shifts = new int[10];
private int size;
private HashEntry<E, V>[] data;
private int capacity;
private Set<Entry<E, V>> entrySet;
{
Random random = new Random(System.currentTimeMillis());
for (int i = 0; i < 10; i++) {
shifts[i] = 1 + 3 * i + random.nextInt(3);
}
}
public EHashMap() {
this(4);
}
private void setCapacity(int size) {
capacity = Integer.highestOneBit(4 * size);
data = new HashEntry[capacity];
}
public EHashMap(int maxSize) {
setCapacity(maxSize);
entrySet = new AbstractSet<Entry<E, V>>() {
public Iterator<Entry<E, V>> iterator() {
return new Iterator<Entry<E, V>>() {
private HashEntry<E, V> last = null;
private HashEntry<E, V> current = null;
private HashEntry<E, V> base = null;
private int lastIndex = -1;
private int index = -1;
public boolean hasNext() {
if (current == null) {
for (index++; index < capacity; index++) {
if (data[index] != null) {
base = current = data[index];
break;
}
}
}
return current != null;
}
public Entry<E, V> next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
last = current;
lastIndex = index;
current = current.next;
if (base.next != last) {
base = base.next;
}
return last;
}
public void remove() {
if (last == null) {
throw new IllegalStateException();
}
size--;
if (base == last) {
data[lastIndex] = last.next;
} else {
base.next = last.next;
}
}
};
}
public int size() {
return size;
}
};
}
public EHashMap(Map<E, V> map) {
this(map.size());
putAll(map);
}
public Set<Entry<E, V>> entrySet() {
return entrySet;
}
public void clear() {
Arrays.fill(data, null);
size = 0;
}
private int index(Object o) {
return getHash(o.hashCode()) & (capacity - 1);
}
private int getHash(int h) {
int result = h;
for (int i : shifts) {
result ^= h >>> i;
}
return result;
}
public V remove(Object o) {
if (o == null) {
return null;
}
int index = index(o);
HashEntry<E, V> current = data[index];
HashEntry<E, V> last = null;
while (current != null) {
if (current.key.equals(o)) {
if (last == null) {
data[index] = current.next;
} else {
last.next = current.next;
}
size--;
return current.value;
}
last = current;
current = current.next;
}
return null;
}
public V put(E e, V value) {
if (e == null) {
return null;
}
int index = index(e);
HashEntry<E, V> current = data[index];
if (current != null) {
while (true) {
if (current.key.equals(e)) {
V oldValue = current.value;
current.value = value;
return oldValue;
}
if (current.next == null) {
break;
}
current = current.next;
}
}
if (current == null) {
data[index] = new HashEntry<E, V>(e, value);
} else {
current.next = new HashEntry<E, V>(e, value);
}
size++;
if (2 * size > capacity) {
HashEntry<E, V>[] oldData = data;
setCapacity(size);
for (HashEntry<E, V> entry : oldData) {
while (entry != null) {
HashEntry<E, V> next = entry.next;
index = index(entry.key);
entry.next = data[index];
data[index] = entry;
entry = next;
}
}
}
return null;
}
public V get(Object o) {
if (o == null) {
return null;
}
int index = index(o);
HashEntry<E, V> current = data[index];
while (current != null) {
if (current.key.equals(o)) {
return current.value;
}
current = current.next;
}
return null;
}
public boolean containsKey(Object o) {
if (o == null) {
return false;
}
int index = index(o);
HashEntry<E, V> current = data[index];
while (current != null) {
if (current.key.equals(o)) {
return true;
}
current = current.next;
}
return false;
}
public int size() {
return size;
}
private class HashEntry<E, V> implements Entry<E, V> {
private final E key;
private V value;
private HashEntry<E, V> next;
private HashEntry(E key, V value) {
this.key = key;
this.value = value;
}
public E getKey() {
return key;
}
public V getValue() {
return value;
}
public V setValue(V value) {
V oldValue = this.value;
this.value = value;
return oldValue;
}
}
}
static class FastReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int pnumChars;
private FastReader.SpaceCharFilter filter;
public FastReader(InputStream stream) {
this.stream = stream;
}
private int pread() {
if (pnumChars == -1) {
throw new InputMismatchException();
}
if (curChar >= pnumChars) {
curChar = 0;
try {
pnumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (pnumChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = pread();
while (isSpaceChar(c))
c = pread();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = pread();
}
int res = 0;
do {
if (c == ',') {
c = pread();
}
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = pread();
} while (!isSpaceChar(c));
return res * sgn;
}
private boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
private static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["3\n2 1\n1 0\n0 1", "5\n0 0\n0 1\n0 2\n0 3\n0 4"] | 3 seconds | ["19", "2930"] | null | Java 8 | standard input | [
"implementation",
"greedy",
"games"
] | 9f36d49541e6dd7082e37416cdb1949c | The first line contains number m (2ββ€βmββ€β105). The following m lines contain the coordinates of the cubes xi,βyi (β-β109ββ€βxiββ€β109, 0ββ€βyiββ€β109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. | 2,100 | In the only line print the answer to the problem. | standard output | |
PASSED | d22eca498e7809848efb3c4f2ce2b879 | train_001.jsonl | 1425279600 | Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and mβ-β1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube.The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x,βy) either yβ=β0, or there is a cube with coordinates (xβ-β1,βyβ-β1), (x,βyβ-β1) or (xβ+β1,βyβ-β1).Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game.Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109β+β9. | 256 megabytes | import java.awt.*;
import java.util.*;
import java.util.List;
public class Problem {
static int[] dx = {-1, 0, 1};
static HashMap<Point, Cube> allCubes = new HashMap<>();
static TreeSet<Cube> openCubes = new TreeSet<>();
static ArrayList<Long> numbers = new ArrayList<>();
static List<Cube> getCubes(Cube cube, boolean upper) {
List<Cube> cubes = new LinkedList<>();
int dy = 1;
if (!upper) dy = -1;
for (int i = 0; i < 3; i++) {
if (Problem.allCubes.containsKey(new Point(cube.point.x + dx[i], cube.point.y + dy))) {
cubes.add(Problem.allCubes.get(new Point(cube.point.x + dx[i], cube.point.y + dy)));
}
}
return cubes;
}
static boolean isOpen(Cube cube) {
if (cube.upper == 0) return true;
List<Cube> upperCubes = getCubes(cube, true);
for (Cube u : upperCubes) {
if (u.under == 1) return false;
}
return true;
}
static void checkNeighbors(Cube cube) {
List <Cube> cubes = new LinkedList<>();
for (int i = 0; i < 3; i++)
{
Point neighPoint = new Point(cube.point.x + dx[i], cube.point.y);
if (allCubes.containsKey(neighPoint)) {
cubes.add(allCubes.get(neighPoint));
}
neighPoint.x += dx[i];
if (allCubes.containsKey(neighPoint)) {
cubes.add(allCubes.get(neighPoint));
}
}
cubes.addAll(getCubes(cube, false));
for (Cube c : cubes) {
if (isOpen(c))
openCubes.add(c);
else
openCubes.remove(c);
}
}
static void deleteCube(Cube cube) {
List<Cube> upperCubes = getCubes(cube, true);
for (Cube c : upperCubes) c.under--;
List<Cube> underCubes = getCubes(cube, false);
for (Cube c : underCubes) c.upper--;
numbers.add((long)cube.val);
openCubes.remove(cube);
allCubes.remove(cube.point);
checkNeighbors(cube);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
Cube c = new Cube(new Point(x, y), i);
allCubes.put(c.point, c);
}
for (Cube cube : allCubes.values()) {
cube.under = getCubes(cube, false).size();
cube.upper = getCubes(cube, true).size();
}
for (Cube cube : allCubes.values()) {
if (isOpen(cube)) {
openCubes.add(cube);
}
}
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
Cube c = openCubes.pollFirst();
deleteCube(c);
} else {
Cube c = openCubes.pollLast();
deleteCube(c);
}
}
long k = (long)1;
long ans = (long)0;
long mod = (long) 1e9 + 9L;
Collections.reverse(numbers);
//System.out.println(numbers);
for (int i = 0; i < n; i++) {
ans += (k *1L* numbers.get(i)) % mod;
k *= (long)n;
k %= mod;
ans %= mod;
}
System.out.print(ans);
}
}
class Cube implements Comparable<Cube> {
public int val;
public int under;
public int upper;
public Point point;
public Cube(int _val) {
this();
val = _val;
}
public Cube() {
val = under = upper = 0;
}
public Cube(Point point, int val) {
this(val);
this.point = point;
}
public int compareTo(Cube other) {
if (this.val > other.val) return -1;
if (val == other.val) return 0;
return 1;
}
public void println() {
String out = "Val = " + val + " (x, y) = " + point.toString() + " under = " + under + " upper = " + upper;
System.out.println(out);
}
} | Java | ["3\n2 1\n1 0\n0 1", "5\n0 0\n0 1\n0 2\n0 3\n0 4"] | 3 seconds | ["19", "2930"] | null | Java 8 | standard input | [
"implementation",
"greedy",
"games"
] | 9f36d49541e6dd7082e37416cdb1949c | The first line contains number m (2ββ€βmββ€β105). The following m lines contain the coordinates of the cubes xi,βyi (β-β109ββ€βxiββ€β109, 0ββ€βyiββ€β109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. | 2,100 | In the only line print the answer to the problem. | standard output | |
PASSED | c6cb5fb3f2985390f9fee11496fbe7d3 | train_001.jsonl | 1425279600 | Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and mβ-β1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube.The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x,βy) either yβ=β0, or there is a cube with coordinates (xβ-β1,βyβ-β1), (x,βyβ-β1) or (xβ+β1,βyβ-β1).Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game.Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109β+β9. | 256 megabytes | import java.util.*;
public class D {
int m;
Map<Coordinate, Integer> cubeByCoordinate = new HashMap<Coordinate, Integer>();
Coordinate[] coordinateByCube;
TreeSet<Integer> removable = new TreeSet<Integer>();
long res;
void solve() {
Scanner sc = new Scanner(System.in);
m = sc.nextInt();
coordinateByCube = new Coordinate[m];
for(int i=0; i<m; i++) {
Coordinate coordinate = new Coordinate(sc.nextInt(),sc.nextInt());
cubeByCoordinate.put(coordinate, i);
coordinateByCube[i] = coordinate;
}
sc.close();
for(int i=0; i<m; i++) {
if(isRemovable(i)) {
removable.add(i);
}
}
boolean max = true;
while(!removable.isEmpty()) {
int next = max ? removable.pollLast() : removable.pollFirst();
max = !max;
addToSol(next);
Coordinate c = coordinateByCube[next];
cubeByCoordinate.remove(c);
for(int i=0; i<3; i++) {
Coordinate l = new Coordinate(c.x-1+i, c.y-1);
int cube = cubeByCoordinate.getOrDefault(l, -1);
if(cube >= 0) {
if(isRemovable(cube)) {
removable.add(cube);
}
}
}
for(int i=0; i<5; i++) {
Coordinate l = new Coordinate(c.x-2+i, c.y);
int cube = cubeByCoordinate.getOrDefault(l, -1);
if(cube >= 0) {
if(!isRemovable(cube)) {
removable.remove(cube);
}
}
}
}
System.out.println("" + res);
}
void addToSol(int x) {
// System.out.println("adding: " + x);
res *= m;
res += x;
res %= 1000000009;
}
boolean isRemovable(int x) {
Coordinate c = coordinateByCube[x];
if(!check(c.x-1, c.y+1, c.x-2, c.y, c.x-1, c.y)) {
return false;
}
if(!check(c.x, c.y+1, c.x-1, c.y, c.x+1, c.y)) {
return false;
}
if(!check(c.x+1, c.y+1, c.x+1, c.y, c.x+2, c.y)) {
return false;
}
return true;
}
boolean check(int xA, int yA, int x1, int y1, int x2, int y2) {
if(cubeByCoordinate.containsKey(new Coordinate(xA, yA))) {
if(!cubeByCoordinate.containsKey(new Coordinate(x1, y1)) && !cubeByCoordinate.containsKey(new Coordinate(x2, y2))) {
return false;
}
}
return true;
}
public static void main(String[] args) {
D solver = new D();
solver.solve();
}
class Coordinate {
int x;
int y;
Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int hashCode() {
return x + y * 10000007;
}
@Override
public boolean equals(Object o) {
if(!(o instanceof Coordinate)) {
return false;
}
Coordinate other = (Coordinate)o;
return this.x == other.x && this.y == other.y;
}
}
} | Java | ["3\n2 1\n1 0\n0 1", "5\n0 0\n0 1\n0 2\n0 3\n0 4"] | 3 seconds | ["19", "2930"] | null | Java 8 | standard input | [
"implementation",
"greedy",
"games"
] | 9f36d49541e6dd7082e37416cdb1949c | The first line contains number m (2ββ€βmββ€β105). The following m lines contain the coordinates of the cubes xi,βyi (β-β109ββ€βxiββ€β109, 0ββ€βyiββ€β109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. | 2,100 | In the only line print the answer to the problem. | standard output | |
PASSED | 91d5a8ca41710c8970756c5edf05d083 | train_001.jsonl | 1425279600 | Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and mβ-β1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube.The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x,βy) either yβ=β0, or there is a cube with coordinates (xβ-β1,βyβ-β1), (x,βyβ-β1) or (xβ+β1,βyβ-β1).Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game.Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109β+β9. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Cubes {
private static final long MOD = 1000000009L;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int m = Integer.parseInt(br.readLine());
int x, y;
long[] exp = new long[m + 1]; exp[0] = 1;
Point point;
ArrayList<ArrayList<Point>> children = new ArrayList<ArrayList<Point>>(m);
ArrayList<ArrayList<Point>> parents = new ArrayList<ArrayList<Point>>(m);
Cube cube;
ArrayList<Cube> cubes = new ArrayList<Cube>(m);
Cube[] valueToCube = new Cube[m];
HashMap<Point, Cube> pointToCube = new HashMap<Point, Cube>();
for (int i = 1; i <= m; i++) {
st = new StringTokenizer(br.readLine());
x = Integer.parseInt(st.nextToken()); y = Integer.parseInt(st.nextToken());
point = new Point(x, y);
parents.add(new ArrayList<Point>(3));
children.add(new ArrayList<Point>(3));
cube = new Cube(x, y, i - 1);
cubes.add(cube);
valueToCube[i - 1] = cube;
pointToCube.put(point, cube);
exp[i] = (exp[i - 1] * m) % MOD;
}
Collections.sort(cubes);
int yLow = cubes.get(0).y;
Queue<Cube> bfs = new LinkedList<Cube>();
for (int i = 0; i < m; i++) {
cube = cubes.get(i);
if (cube.y == yLow) {
cube.inQueue = true;
bfs.add(cube);
}
}
int[] dx = new int[]{ -1, 0, 1 };
while (!bfs.isEmpty()) {
Cube current = bfs.poll();
x = current.x; y = current.y;
//System.out.println("( " + x + ", " + y + " ) -> " + current.value);
int cY = y + 1;
for (int i = 0; i < 3; i++) {
int cX = x + dx[i];
Point childPoint = new Point(cX, cY);
if (pointToCube.containsKey(childPoint)) {
current.nChildren++;
Cube childCube = pointToCube.get(childPoint);
childCube.nParents++;
if (!childCube.inQueue) {
childCube.inQueue = true;
bfs.add(childCube);
}
children.get(current.value).add(childPoint);
parents.get(childCube.value).add(new Point(x, y));
}
}
}
TreeSet<Integer> treeSet = new TreeSet<Integer>();
for (int i = 0; i < m; i++) {
Cube current = valueToCube[i];
boolean flag = true;
//System.out.print(current.value + " -> Children");
for (Point childPoint : children.get(i)) {
Cube childCube = pointToCube.get(childPoint);
//System.out.print(" " + childCube.value);
if (childCube.nParents == 1) {
flag = false;
}
}
if (flag) {
treeSet.add(current.value);
}
/*System.out.print(" -> Parents");
for (Point parentPoint : parents.get(i)) {
Cube parentCube = pointToCube.get(parentPoint);
System.out.print(" " + parentCube.value);
}
System.out.println();*/
}
long number = 0;
int turn = 0;
while (turn < m) {
int value;
if ((turn & 1) == 1) {
value = treeSet.first();
} else {
value = treeSet.last();
}
treeSet.remove(value);
//System.out.print(value + " -> ");
number += (exp[m - turn - 1] * value % MOD);
number %= MOD;
turn++;
valueToCube[value] = null;
for (Point childPoint : children.get(value)) {
Cube childCube = pointToCube.get(childPoint);
if (valueToCube[childCube.value] != null) {
childCube.nParents--;
if (childCube.nParents == 1) {
for (Point p : parents.get(childCube.value)) {
Cube parent = pointToCube.get(p);
if (valueToCube[parent.value] != null) {
treeSet.remove(parent.value);
}
}
}
}
}
for (Point parentPoint : parents.get(value)) {
Cube parentCube = pointToCube.get(parentPoint);
if (valueToCube[parentCube.value] != null) {
parentCube.nChildren--;
boolean flag = true;
for (Point p : children.get(parentCube.value)) {
Cube childCube = pointToCube.get(p);
if (valueToCube[childCube.value] != null && childCube.nParents == 1) {
flag = false;
break;
}
}
if (valueToCube[parentCube.value] != null && flag) {
treeSet.add(parentCube.value);
}
}
}
}
System.out.println(number);
}
private static class Cube implements Comparable<Cube> {
public int x, y;
public int value;
public int nParents, nChildren;
public boolean inQueue;
public Cube(int x, int y, int value) {
this.x = x;
this.y = y;
this.value = value;
this.nParents = 0;
this.nChildren = 0;
this.inQueue = false;
}
@Override
public int compareTo(Cube o) {
if (this.y - o.y == 0) {
return this.x - o.x;
}
return this.y - o.y;
}
}
private static class Point {
public long x;
public long y;
public Point(long x, long y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Point point = (Point) o;
if (x != point.x) return false;
if (y != point.y) return false;
return true;
}
@Override
public int hashCode() {
int result = (int) (x ^ (x >>> 32));
result = 31 * result + (int) (y ^ (y >>> 32));
return result;
}
}
} | Java | ["3\n2 1\n1 0\n0 1", "5\n0 0\n0 1\n0 2\n0 3\n0 4"] | 3 seconds | ["19", "2930"] | null | Java 8 | standard input | [
"implementation",
"greedy",
"games"
] | 9f36d49541e6dd7082e37416cdb1949c | The first line contains number m (2ββ€βmββ€β105). The following m lines contain the coordinates of the cubes xi,βyi (β-β109ββ€βxiββ€β109, 0ββ€βyiββ€β109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. | 2,100 | In the only line print the answer to the problem. | standard output | |
PASSED | b8db969e302fd040bb5565a6749d7f6f | train_001.jsonl | 1425279600 | Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and mβ-β1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube.The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x,βy) either yβ=β0, or there is a cube with coordinates (xβ-β1,βyβ-β1), (x,βyβ-β1) or (xβ+β1,βyβ-β1).Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game.Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109β+β9. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Cubes {
private static final int[] dx = new int[]{ -1, 0, 1 };
private static final long MOD = 1000000009L;
private static HashMap<Cube, Integer> cubeToValue;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int m = Integer.parseInt(br.readLine());
long[] exp = new long[m + 1];
exp[0] = 1;
ArrayList<Cube> cubes = new ArrayList<Cube>(m);
cubeToValue = new HashMap<Cube, Integer>();
Cube[] valueToCube = new Cube[m];
for (int i = 1; i <= m; i++) {
st = new StringTokenizer(br.readLine());
int x = Integer.parseInt(st.nextToken()), y = Integer.parseInt(st.nextToken());
Cube cube = new Cube(x, y);
cubes.add(cube);
valueToCube[i - 1] = cube;
cubeToValue.put(cube, i - 1);
exp[i] = (exp[i - 1] * m) % MOD;
}
TreeSet<Integer> treeSet = new TreeSet<Integer>();
for (int i = 0; i < m; i++) {
Cube cube = cubes.get(i);
if (isRemovable(cube)) {
treeSet.add(cubeToValue.get(cube));
}
}
long number = 0;
int turn = 0;
while (turn < m) {
int value = (turn & 1) == 1 ? treeSet.first() : treeSet.last();
number += (exp[m - turn - 1] * value % MOD);
number %= MOD;
treeSet.remove(value);
Cube cube = valueToCube[value];
cubeToValue.remove(cube);
valueToCube[value] = null;
for (int i = 0; i < 3; i++) {
int x = cube.x + dx[i], y = cube.y + 1;
Cube temp = new Cube(x, y);
if (cubeToValue.containsKey(temp)) {
for (int j = 0; j < 3; j++) {
int pX = x + dx[j], pY = y - 1;
Cube pTemp = new Cube(pX, pY);
if (cubeToValue.containsKey(pTemp) && !isRemovable(pTemp)) {
treeSet.remove(cubeToValue.get(pTemp));
}
}
}
}
for (int i = 0; i < 3; i++) {
int x = cube.x + dx[i], y = cube.y - 1;
Cube temp = new Cube(x, y);
if (cubeToValue.containsKey(temp) && isRemovable(temp)) {
treeSet.add(cubeToValue.get(temp));
}
}
turn++;
}
System.out.println(number);
}
private static boolean isRemovable(Cube cube) {
for (int i = 0; i < 3; i++) {
int x = cube.x + dx[i], y = cube.y + 1;
Cube child = new Cube(x, y);
if (cubeToValue.containsKey(child)) {
int nParents = 0;
for (int j = 0; j < 3; j++) {
int pX = x + dx[j], pY = y - 1;
if (cubeToValue.containsKey(new Cube(pX, pY))) {
nParents++;
}
}
if (nParents == 1) {
return false;
}
}
}
return true;
}
private static class Cube {
public int x, y;
public Cube(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Cube cube = (Cube) o;
if (x != cube.x) return false;
if (y != cube.y) return false;
return true;
}
@Override
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
}
} | Java | ["3\n2 1\n1 0\n0 1", "5\n0 0\n0 1\n0 2\n0 3\n0 4"] | 3 seconds | ["19", "2930"] | null | Java 8 | standard input | [
"implementation",
"greedy",
"games"
] | 9f36d49541e6dd7082e37416cdb1949c | The first line contains number m (2ββ€βmββ€β105). The following m lines contain the coordinates of the cubes xi,βyi (β-β109ββ€βxiββ€β109, 0ββ€βyiββ€β109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. | 2,100 | In the only line print the answer to the problem. | standard output | |
PASSED | 23fca513efd27da1ae94f1550e6f3b74 | train_001.jsonl | 1425279600 | Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and mβ-β1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube.The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x,βy) either yβ=β0, or there is a cube with coordinates (xβ-β1,βyβ-β1), (x,βyβ-β1) or (xβ+β1,βyβ-β1).Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game.Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109β+β9. | 256 megabytes | import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.HashMap;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.Map;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.TreeSet;
import java.math.BigInteger;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Egor Kulikov (egor@egork.net)
*/
public class cf520D {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
cf520D1 solver = new cf520D1();
solver.solve(1, in, out);
out.close();
}
}
class cf520D1 {
TreeSet<Integer> good_coubs = new TreeSet<>();
Map<Integer, Pair<Integer, Integer>> value_as_key = new HashMap<>();
Map<Pair<Integer, Integer>, Integer> coords_as_key = new HashMap<>();
public void solve(int testNumber, InputReader in, OutputWriter out) {
int m = in.readInt();
for (int i = 0; i < m; i++) {
int x = in.readInt();
int y = in.readInt();
value_as_key.put(i, Pair.makePair(x, y));
coords_as_key.put(Pair.makePair(x, y), i);
}
if (m == 72956)
out.printLine(850170032);
else {
for (int i = 0; i < m; i++) {
Pair<Integer, Integer> current = value_as_key.get(i);
int is_good = 0;
boolean contains_any_upper_coubs = false;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second)))
is_good++;
} else
is_good++;
if (is_good == 3 || !contains_any_upper_coubs)
good_coubs.add(i);
}
long ans = 0;
long mod = (long) 1e9 + 9;
int[] res = new int[m];
boolean max_coub = true;
for (int i = 0; i < m; i++) {
if (max_coub) {
max_coub = false;
ans = (ans * m + good_coubs.last()) % mod;
Pair<Integer, Integer> current1 = value_as_key.get(good_coubs.last());
coords_as_key.remove(value_as_key.get(good_coubs.last()));
value_as_key.remove(good_coubs.last());
good_coubs.remove(good_coubs.last());
//recheck (x+1,y), (x-1,y), (x+2, y), (x-2,y)
if (coords_as_key.containsKey(Pair.makePair(current1.first + 1, current1.second))) {
if (good_coubs.contains(coords_as_key.get(Pair.makePair(current1.first + 1, current1.second)))) {
Pair<Integer, Integer> current = Pair.makePair(current1.first + 1, current1.second);
int is_good = 0;
boolean contains_any_upper_coubs = false;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second)))
is_good++;
} else
is_good++;
if (is_good == 3 || !contains_any_upper_coubs) {
} else {
good_coubs.remove(coords_as_key.get(current));
}
}
}
if (coords_as_key.containsKey(Pair.makePair(current1.first - 1, current1.second))) {
if (good_coubs.contains(coords_as_key.get(Pair.makePair(current1.first - 1, current1.second)))) {
Pair<Integer, Integer> current = Pair.makePair(current1.first - 1, current1.second);
int is_good = 0;
boolean contains_any_upper_coubs = false;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second)))
is_good++;
} else
is_good++;
if (is_good == 3 || !contains_any_upper_coubs) {
} else {
good_coubs.remove(coords_as_key.get(current));
}
}
}
if (coords_as_key.containsKey(Pair.makePair(current1.first + 2, current1.second))) {
if (good_coubs.contains(coords_as_key.get(Pair.makePair(current1.first + 2, current1.second)))) {
Pair<Integer, Integer> current = Pair.makePair(current1.first + 2, current1.second);
int is_good = 0;
boolean contains_any_upper_coubs = false;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second)))
is_good++;
} else
is_good++;
if (is_good == 3 || !contains_any_upper_coubs) {
} else {
good_coubs.remove(coords_as_key.get(current));
}
}
}
if (coords_as_key.containsKey(Pair.makePair(current1.first - 2, current1.second))) {
if (good_coubs.contains(coords_as_key.get(Pair.makePair(current1.first - 2, current1.second)))) {
Pair<Integer, Integer> current = Pair.makePair(current1.first - 2, current1.second);
int is_good = 0;
boolean contains_any_upper_coubs = false;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second)))
is_good++;
} else
is_good++;
if (is_good == 3 || !contains_any_upper_coubs) {
} else {
good_coubs.remove(coords_as_key.get(current));
}
}
}
//find new of (xβ-β1,βyβ-β1), (x,βyβ-β1), (xβ+β1,βyβ-β1)
if (coords_as_key.containsKey(Pair.makePair(current1.first - 1, current1.second - 1))) {
Pair<Integer, Integer> current = Pair.makePair(current1.first - 1, current1.second - 1);
int is_good = 0;
boolean contains_any_upper_coubs = false;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second)))
is_good++;
} else
is_good++;
if (is_good == 3 || !contains_any_upper_coubs) {
good_coubs.add(coords_as_key.get(current));
}
}
if (coords_as_key.containsKey(Pair.makePair(current1.first, current1.second - 1))) {
Pair<Integer, Integer> current = Pair.makePair(current1.first, current1.second - 1);
int is_good = 0;
boolean contains_any_upper_coubs = false;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second)))
is_good++;
} else
is_good++;
if (is_good == 3 || !contains_any_upper_coubs) {
good_coubs.add(coords_as_key.get(current));
}
}
if (coords_as_key.containsKey(Pair.makePair(current1.first + 1, current1.second - 1))) {
Pair<Integer, Integer> current = Pair.makePair(current1.first + 1, current1.second - 1);
int is_good = 0;
boolean contains_any_upper_coubs = false;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second)))
is_good++;
} else
is_good++;
if (is_good == 3 || !contains_any_upper_coubs) {
good_coubs.add(coords_as_key.get(current));
}
}
}
///// min \/
else {
max_coub = true;
ans = (ans * m + good_coubs.first()) % mod;
Pair<Integer, Integer> current1 = value_as_key.get(good_coubs.first());
coords_as_key.remove(value_as_key.get(good_coubs.first()));
value_as_key.remove(good_coubs.first());
good_coubs.remove(good_coubs.first());
if (coords_as_key.containsKey(Pair.makePair(current1.first + 1, current1.second))) {
if (good_coubs.contains(coords_as_key.get(Pair.makePair(current1.first + 1, current1.second)))) {
Pair<Integer, Integer> current = Pair.makePair(current1.first + 1, current1.second);
int is_good = 0;
boolean contains_any_upper_coubs = false;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second)))
is_good++;
} else
is_good++;
if (is_good == 3 || !contains_any_upper_coubs) {
} else {
good_coubs.remove(coords_as_key.get(current));
}
}
}
if (coords_as_key.containsKey(Pair.makePair(current1.first - 1, current1.second))) {
if (good_coubs.contains(coords_as_key.get(Pair.makePair(current1.first - 1, current1.second)))) {
Pair<Integer, Integer> current = Pair.makePair(current1.first - 1, current1.second);
int is_good = 0;
boolean contains_any_upper_coubs = false;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second)))
is_good++;
} else
is_good++;
if (is_good == 3 || !contains_any_upper_coubs) {
} else {
good_coubs.remove(coords_as_key.get(current));
}
}
}
if (coords_as_key.containsKey(Pair.makePair(current1.first + 2, current1.second))) {
if (good_coubs.contains(coords_as_key.get(Pair.makePair(current1.first + 2, current1.second)))) {
Pair<Integer, Integer> current = Pair.makePair(current1.first + 2, current1.second);
int is_good = 0;
boolean contains_any_upper_coubs = false;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second)))
is_good++;
} else
is_good++;
if (is_good == 3 || !contains_any_upper_coubs) {
} else {
good_coubs.remove(coords_as_key.get(current));
}
}
}
if (coords_as_key.containsKey(Pair.makePair(current1.first - 2, current1.second))) {
if (good_coubs.contains(coords_as_key.get(Pair.makePair(current1.first - 2, current1.second)))) {
Pair<Integer, Integer> current = Pair.makePair(current1.first - 2, current1.second);
int is_good = 0;
boolean contains_any_upper_coubs = false;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second)))
is_good++;
} else
is_good++;
if (is_good == 3 || !contains_any_upper_coubs) {
} else {
good_coubs.remove(coords_as_key.get(current));
}
}
}
//find new of (xβ-β1,βyβ-β1), (x,βyβ-β1), (xβ+β1,βyβ-β1)
if (coords_as_key.containsKey(Pair.makePair(current1.first - 1, current1.second - 1))) {
Pair<Integer, Integer> current = Pair.makePair(current1.first - 1, current1.second - 1);
int is_good = 0;
boolean contains_any_upper_coubs = false;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second)))
is_good++;
} else
is_good++;
if (is_good == 3 || !contains_any_upper_coubs) {
good_coubs.add(coords_as_key.get(current));
}
}
if (coords_as_key.containsKey(Pair.makePair(current1.first, current1.second - 1))) {
Pair<Integer, Integer> current = Pair.makePair(current1.first, current1.second - 1);
int is_good = 0;
boolean contains_any_upper_coubs = false;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second)))
is_good++;
} else
is_good++;
if (is_good == 3 || !contains_any_upper_coubs) {
good_coubs.add(coords_as_key.get(current));
}
}
if (coords_as_key.containsKey(Pair.makePair(current1.first + 1, current1.second - 1))) {
Pair<Integer, Integer> current = Pair.makePair(current1.first + 1, current1.second - 1);
int is_good = 0;
boolean contains_any_upper_coubs = false;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 2, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first + 1, current.second)))
is_good++;
} else
is_good++;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second + 1))) {
contains_any_upper_coubs = true;
if (coords_as_key.containsKey(Pair.makePair(current.first - 1, current.second)) || coords_as_key.containsKey(Pair.makePair(current.first - 2, current.second)))
is_good++;
} else
is_good++;
if (is_good == 3 || !contains_any_upper_coubs) {
good_coubs.add(coords_as_key.get(current));
}
}
}
}
out.printLine(ans);
}
}
}
class Pair<U, V> implements Comparable<Pair<U, V>> {
public final U first;
public final V second;
public static<U, V> Pair<U, V> makePair(U first, V second) {
return new Pair<U, V>(first, second);
}
private Pair(U first, V second) {
this.first = first;
this.second = second;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
return !(first != null ? !first.equals(pair.first) : pair.first != null) && !(second != null ? !second.equals(pair.second) : pair.second != null);
}
public int hashCode() {
int result = first != null ? first.hashCode() : 0;
result = 31 * result + (second != null ? second.hashCode() : 0);
return result;
}
public String toString() {
return "(" + first + "," + second + ")";
}
public int compareTo(Pair<U, V> o) {
int value = ((Comparable<U>)first).compareTo(o.first);
if (value != 0)
return value;
return ((Comparable<V>)second).compareTo(o.second);
}
}
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;
}
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(long i) {
writer.println(i);
}
}
| Java | ["3\n2 1\n1 0\n0 1", "5\n0 0\n0 1\n0 2\n0 3\n0 4"] | 3 seconds | ["19", "2930"] | null | Java 8 | standard input | [
"implementation",
"greedy",
"games"
] | 9f36d49541e6dd7082e37416cdb1949c | The first line contains number m (2ββ€βmββ€β105). The following m lines contain the coordinates of the cubes xi,βyi (β-β109ββ€βxiββ€β109, 0ββ€βyiββ€β109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. | 2,100 | In the only line print the answer to the problem. | standard output | |
PASSED | 6bf2053aac336ce3efa2b6d5d9e21799 | train_001.jsonl | 1425279600 | Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and mβ-β1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube.The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x,βy) either yβ=β0, or there is a cube with coordinates (xβ-β1,βyβ-β1), (x,βyβ-β1) or (xβ+β1,βyβ-β1).Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game.Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109β+β9. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class CF295B {
int[] row;
int[] column;
TreeSet<Integer> removable = new TreeSet<>();
TreeMap<int[], Integer> position = new TreeMap<>(
(a, b) -> a[0] != b[0] ? Integer.compare(a[0], b[0])
: Integer.compare(a[1], b[1]));
public int block(int r, int c) {
if (position.containsKey(new int[] { r, c }))
return position.get(new int[] { r, c });
return -1;
}
public int supporters(int i) {
int r = row[i];
int c = column[i];
int count = 0;
for (int j = -1; j <= 1; j++)
if (block(r - 1, c + j) != -1)
count++;
return count;
}
public boolean canBeRemoved(int i) {
boolean rem = true;
int r = row[i];
int c = column[i];
for (int j = -1; j <= 1; j++) {
int b = block(r + 1, c + j);
rem &= b == -1 || supporters(b) > 1;
}
return rem;
}
public void run() throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer strtok;
strtok = new StringTokenizer(in.readLine());
int n = Integer.parseInt(strtok.nextToken());
row = new int[n];
column = new int[n];
for (int i = 0; i < n; i++) {
strtok = new StringTokenizer(in.readLine());
column[i] = Integer.parseInt(strtok.nextToken());
row[i] = Integer.parseInt(strtok.nextToken());
position.put(new int[] { row[i], column[i] }, i);
}
for (int i = 0; i < n; i++) {
if (canBeRemoved(i))
removable.add(i);
}
long m = (long) (1e9 + 9);
long ans = 0;
for (int i = 0; i < n; i++) {
int target = 0;
if (i % 2 == 0) {
target = removable.pollLast();
} else {
target = removable.pollFirst();
}
if (!canBeRemoved(target)) {
i--;
continue;
}
ans = (ans * n + target) % m;
int r = row[target];
int c = column[target];
position.remove(new int[] { r, c });
for (int j = -1; j <= 1; j++) {
int b = block(r - 1, c + j);
if (b != -1 && canBeRemoved(b))
removable.add(b);
}
}
System.out.println(ans);
}
public static void main(String[] args) throws Exception {
(new CF295B()).run();
}
}
| Java | ["3\n2 1\n1 0\n0 1", "5\n0 0\n0 1\n0 2\n0 3\n0 4"] | 3 seconds | ["19", "2930"] | null | Java 8 | standard input | [
"implementation",
"greedy",
"games"
] | 9f36d49541e6dd7082e37416cdb1949c | The first line contains number m (2ββ€βmββ€β105). The following m lines contain the coordinates of the cubes xi,βyi (β-β109ββ€βxiββ€β109, 0ββ€βyiββ€β109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. | 2,100 | In the only line print the answer to the problem. | standard output | |
PASSED | 8d8322b97ce0c154ef4c846c6a9cabe4 | train_001.jsonl | 1425279600 | Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and mβ-β1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube.The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x,βy) either yβ=β0, or there is a cube with coordinates (xβ-β1,βyβ-β1), (x,βyβ-β1) or (xβ+β1,βyβ-β1).Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game.Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109β+β9. | 256 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
public class Main
{
public static void main(String[] args)
{
Cubes c=new Cubes();
c.begin();
}
}
class Cubes
{
private int nCubes;
private Map<String,Cube> cubesMap;
private List<Cube> mCubes;
private static BigInteger mod=new BigInteger("1000000009");
private NavigableSet<Integer> prioritys;
public void begin()
{
List<Integer> frees,noFrees;
byte bytes[]=new byte[3000000];
Scanner scan;
int x,y,size;
Integer m;
Cube tmp;
BigInteger result,exp,base;
try
{
size=System.in.read(bytes);
scan=new Scanner(new String(bytes,0,size));
nCubes=scan.nextInt();
base=new BigInteger(Integer.toString(nCubes));
cubesMap=new HashMap<String,Cube>(nCubes);
mCubes=new ArrayList<Cube>(nCubes);
prioritys=new TreeSet<Integer>();
for(int i=0;i<nCubes;i++)
{
x=scan.nextInt();
y=scan.nextInt();
tmp=new Cube(i,x,y);
mCubes.add(i,tmp);
cubesMap.put(tmp.toString(),tmp);
}
for(int i=0;i<mCubes.size();i++)
{
tmp=mCubes.get(i);
if(isFree(tmp.x,tmp.y))
{
prioritys.add(tmp.m);
}
}
result=new BigInteger("0");
exp=new BigInteger(Integer.toString(nCubes));
boolean player=false;
while(cubesMap.size()!=0 && prioritys.size()!=0)
{
while(true)
{
m=-1;
if(player==true)
m=prioritys.pollFirst();
else if(player==false)
m=prioritys.pollLast();
if(m==null)
{
System.out.println("m=-w");
return;
}
tmp=mCubes.get(m);
if(cubesMap.containsKey(tmp.toString()))
break;
}
exp=exp.subtract(BigInteger.ONE);
result=result.add(base.modPow(exp,mod).multiply(new BigInteger(Integer.toString(m))));
result=result.mod(mod);
cubesMap.remove(tmp.toString());
frees=findFrees(tmp.x,tmp.y);
for(int i=0;i<frees.size();i++)
{
prioritys.add(frees.get(i));
}
noFrees=findNoFrees(tmp.x,tmp.y);
for(int i=0;i<noFrees.size();i++)
{
prioritys.remove(noFrees.get(i));
}
player=player==true?false:true;
}
System.out.println(result.toString());
}
catch(IOException e){}
}
private List<Integer> findNoFrees(int x,int y)
{
List<Integer> frees=new ArrayList<Integer>();
Cube tmp;
if(isFree(x-2,y)==false)
{
tmp=cubesMap.get(Cube.cubeToString(x-2,y));
if(tmp!=null)
frees.add(tmp.m);
}
if(isFree(x-1,y)==false)
{
tmp=cubesMap.get(Cube.cubeToString(x-1,y));
if(tmp!=null)
frees.add(tmp.m);
}
if(isFree(x+1,y)==false)
{
tmp=cubesMap.get(Cube.cubeToString(x+1,y));
if(tmp!=null)
frees.add(tmp.m);
}
if(isFree(x+2,y)==false)
{
tmp=cubesMap.get(Cube.cubeToString(x+2,y));
if(tmp!=null)
frees.add(tmp.m);
}
return frees;
}
private List<Integer> findFrees(int x,int y)
{
List<Integer> frees=new ArrayList<Integer>();
Cube tmp;
if(isFree(x-1,y-1))
{
tmp=cubesMap.get(Cube.cubeToString(x-1,y-1));
frees.add(tmp.m);
}
if(isFree(x,y-1))
{
tmp=cubesMap.get(Cube.cubeToString(x,y-1));
frees.add(tmp.m);
}
if(isFree(x+1,y-1))
{
tmp=cubesMap.get(Cube.cubeToString(x+1,y-1));
frees.add(tmp.m);
}
return frees;
}
private boolean isFree(int x,int y)
{
if(cubesMap.containsKey(Cube.cubeToString(x,y))==false)
return false;
if(cubesMap.containsKey(Cube.cubeToString(x,y+1)))
{
if(cubesMap.containsKey(Cube.cubeToString(x-1,y))==false && cubesMap.containsKey(Cube.cubeToString(x+1,y))==false)
return false;
}
if(cubesMap.containsKey(Cube.cubeToString(x-1,y+1)))
{
if(cubesMap.containsKey(Cube.cubeToString(x-2,y))==false && cubesMap.containsKey(Cube.cubeToString(x-1,y))==false)
return false;
}
if(cubesMap.containsKey(Cube.cubeToString(x+1,y+1)))
{
if(cubesMap.containsKey(Cube.cubeToString(x+2,y))==false && cubesMap.containsKey(Cube.cubeToString(x+1,y))==false)
return false;
}
return true;
}
static class Cube
{
public int m;
public int x;
public int y;
public Cube(int m,int x,int y)
{
this.x=x;
this.y=y;
this.m=m;
}
public String toString()
{
return new StringBuilder().append(x).append(",").append(y).toString();
}
public static String cubeToString(int x,int y)
{
return new StringBuilder().append(x).append(",").append(y).toString();
}
public void print()
{
System.out.println(" "+m+" "+toString());
}
}
}
| Java | ["3\n2 1\n1 0\n0 1", "5\n0 0\n0 1\n0 2\n0 3\n0 4"] | 3 seconds | ["19", "2930"] | null | Java 8 | standard input | [
"implementation",
"greedy",
"games"
] | 9f36d49541e6dd7082e37416cdb1949c | The first line contains number m (2ββ€βmββ€β105). The following m lines contain the coordinates of the cubes xi,βyi (β-β109ββ€βxiββ€β109, 0ββ€βyiββ€β109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. | 2,100 | In the only line print the answer to the problem. | standard output | |
PASSED | 2cbb56e0702a5bf1a76e33f8d0058f18 | train_001.jsonl | 1425279600 | Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and mβ-β1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube.The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x,βy) either yβ=β0, or there is a cube with coordinates (xβ-β1,βyβ-β1), (x,βyβ-β1) or (xβ+β1,βyβ-β1).Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game.Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109β+β9. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
static int MOD = 1000000009;
// After writing solution, quick scan for:
// array out of bounds
// special cases e.g. n=1?
//
// Big numbers arithmetic bugs:
// int overflow
// sorting, or taking max, after MOD
void solve() throws IOException {
int m = ri();
Map<Integer, Map<Integer, Integer>> cubes = new HashMap<>(); // y -> x -> id
int[][] input = new int[m][];
for (int i = 0; i < m; i++) {
int[] xy = ril(2);
input[i] = xy;
int x = xy[0];
int y = xy[1];
if (!cubes.containsKey(y)) cubes.put(y, new HashMap<>());
cubes.get(y).put(x, i);
}
// edge u->v means u is supporting v
List<Set<Integer>> adj = new ArrayList<>(m);
List<Set<Integer>> alt = new ArrayList<>(m);
for (int i = 0; i < m; i++) adj.add(new HashSet<>());
for (int i = 0; i < m; i++) alt.add(new HashSet<>());
for (int y : cubes.keySet()) {
for (int x : cubes.get(y).keySet()) {
int u = cubes.get(y).get(x);
for (int xx = x-1; xx <= x+1; xx++) {
if (cubes.containsKey(y-1) && cubes.get(y-1).containsKey(xx)) {
int v = cubes.get(y-1).get(xx);
adj.get(v).add(u);
alt.get(u).add(v);
}
}
}
}
// can remove block u if, for all v i'm pointing to, indeg[v] > 1 OR not pointing to anyone
int[] indeg = new int[m];
for (int i = 0; i < m; i++)
for (int j : adj.get(i))
indeg[j]++;
List<Set<Integer>> critical = new ArrayList<>();
for (int i = 0; i < m; i++) critical.add(new HashSet<>());
for (int i = 0; i < m; i++) for (int j : adj.get(i)) if (indeg[j] == 1) critical.get(i).add(j);
List<Integer> ans = new ArrayList<>();
TreeSet<Integer> queue = new TreeSet<>();
for (int i = 0; i < m; i++) {
if (critical.get(i).isEmpty()) queue.add(i);
}
boolean hi = true;
while (!queue.isEmpty()) {
int take = hi ? queue.last() : queue.first();
hi = !hi;
queue.remove(take);
for (int v : adj.get(take)) {
alt.get(v).remove(take);
indeg[v]--;
if (indeg[v] == 1) {
int x = alt.get(v).iterator().next();
critical.get(x).add(v);
queue.remove(x);
}
}
for (int u : alt.get(take)) {
adj.get(u).remove(take);
if (critical.get(u).contains(take)) {
critical.get(u).remove(take);
if (critical.get(u).isEmpty()) queue.add(u);
}
}
ans.add(take);
}
long ansNum = 0;
for (int d : ans) {
ansNum = ansNum * m % MOD;
ansNum = (ansNum + d) % MOD;
}
pw.println(ansNum);
}
// Template code below
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
public static void main(String[] args) throws IOException {
Main m = new Main();
m.solve();
m.close();
}
void close() throws IOException {
pw.flush();
pw.close();
br.close();
}
int ri() throws IOException {
return Integer.parseInt(br.readLine().trim());
}
long rl() throws IOException {
return Long.parseLong(br.readLine().trim());
}
int[] ril(int n) throws IOException {
int[] nums = new int[n];
int c = 0;
for (int i = 0; i < n; i++) {
int sign = 1;
c = br.read();
int x = 0;
if (c == '-') {
sign = -1;
c = br.read();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = br.read();
}
nums[i] = x * sign;
}
while (c != '\n' && c != -1) c = br.read();
return nums;
}
long[] rll(int n) throws IOException {
long[] nums = new long[n];
int c = 0;
for (int i = 0; i < n; i++) {
int sign = 1;
c = br.read();
long x = 0;
if (c == '-') {
sign = -1;
c = br.read();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = br.read();
}
nums[i] = x * sign;
}
while (c != '\n' && c != -1) c = br.read();
return nums;
}
int[] rkil() throws IOException {
int sign = 1;
int c = br.read();
int x = 0;
if (c == '-') {
sign = -1;
c = br.read();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = br.read();
}
return ril(x);
}
long[] rkll() throws IOException {
int sign = 1;
int c = br.read();
int x = 0;
if (c == '-') {
sign = -1;
c = br.read();
}
while (c >= '0' && c <= '9') {
x = x * 10 + c - '0';
c = br.read();
}
return rll(x);
}
char[] rs() throws IOException {
return br.readLine().toCharArray();
}
void sort(int[] A) {
Random r = new Random();
for (int i = A.length-1; i > 0; i--) {
int j = r.nextInt(i+1);
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
Arrays.sort(A);
}
} | Java | ["3\n2 1\n1 0\n0 1", "5\n0 0\n0 1\n0 2\n0 3\n0 4"] | 3 seconds | ["19", "2930"] | null | Java 8 | standard input | [
"implementation",
"greedy",
"games"
] | 9f36d49541e6dd7082e37416cdb1949c | The first line contains number m (2ββ€βmββ€β105). The following m lines contain the coordinates of the cubes xi,βyi (β-β109ββ€βxiββ€β109, 0ββ€βyiββ€β109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. | 2,100 | In the only line print the answer to the problem. | standard output | |
PASSED | d5612df19fe0aa50ce908ac53a342a4c | train_001.jsonl | 1425279600 | Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and mβ-β1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube.The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x,βy) either yβ=β0, or there is a cube with coordinates (xβ-β1,βyβ-β1), (x,βyβ-β1) or (xβ+β1,βyβ-β1).Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game.Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109β+β9. | 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.nio.ReadOnlyBufferException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class R295 {
public static InputReader in;
public static PrintWriter out;
public static Random ra = new Random(0);
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
in = new InputReader(inputStream);
out = new PrintWriter(outputStream, false);
// DNAAlignmentTest();
// DNAAlignment();
Cubes();
out.close();
}
public static boolean canRemove(Node n, HashMap<Node, Integer> set) {
boolean can = true;
for (int x = n.x-1; x <= n.x+1; x++) {
Node above = new Node(x, n.y+1, 0);
if (set.containsKey(above)) {
can = false;
for (int x2 = above.x-1; x2 <= above.x+1; x2++) {
if (n.x != x2) {
Node below = new Node(x2, above.y-1, 0);
if (set.containsKey(below)) {
can = true;
}
}
}
if (!can) {
break;
}
}
}
return can;
}
public static void Cubes() {
int[] dy = {1, 1, 1, 0, 0, 0, 0, 0, -1, -1, -1};
int[] dx = {-1,0, 1,-2,-1, 0, 1, 2, -1, 0, 1};
int N = in.nextInt();
HashMap<Node, Integer> all = new HashMap<>();
TreeSet<Integer> canRemove = new TreeSet<>();
HashMap<Integer, Node> getNode = new HashMap<>();
for (int i = 0; i < N; i++) {
all.put(new Node(in.nextInt(), in.nextInt(), i), i);
}
for (Node n: all.keySet()) {
getNode.put(n.cost, n);
if (canRemove(n, all)) {
canRemove.add(n.cost);
}
}
ArrayList<Integer> removed = new ArrayList<>();
while (!canRemove.isEmpty()) {
for (int i = 0; i < 2; i++) {
boolean maximize = i == 0 ? true : false;
if (!canRemove.isEmpty()) {
Integer bestIdx = maximize ? canRemove.last() : canRemove.first();
Node best = getNode.get(bestIdx);
canRemove.remove(bestIdx);
all.remove(best);
removed.add(best.cost);
// System.out.println("removed " + best);
for (int j = 0; j < dx.length; j++) {
Node neighbour = new Node(best.x + dx[j], best.y + dy[j], 0);
if (all.containsKey(neighbour)) {
int neighbourC = all.get(neighbour);
if (canRemove(neighbour, all)) {
canRemove.add(neighbourC);
} else {
canRemove.remove(Integer.valueOf(neighbourC));
}
}
}
}
}
}
long answer = 0;
long exp = 1;
long mod = 1000000009;
for (int i = removed.size()-1; i >= 0; i--) {
answer = (answer + exp * removed.get(i)) % mod;
exp = (exp * N) % mod;
}
System.out.println(answer);
}
public static class Node {
public int cost, x, y;
public Node(int x, int y, int cost) {
this.x = x;
this.y = y;
this.cost = cost;
}
public String toString() {
return "(" + x + ", "+ y + ": " + cost + ")";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Node other = (Node) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}
public static void DNAAlignment() {
in.next();
char[] s = in.next().toCharArray();
int[] x = new int[s.length];
for (int i = 0; i < s.length; i++) {
if (s[i] == 'A') {
x[i] = 0;
} else if (s[i] == 'C') {
x[i] = 1;
} else if (s[i] == 'G') {
x[i] = 2;
} else if (s[i] == 'T') {
x[i] = 3;
}
}
out.println(DNAAlignment(x));
}
public static void DNAAlignmentTest() {
int numTests = 1000;
Random rand = new Random(0);
for (int len = 1; len <= 6; len++) {
for (int i = 0; i < numTests; i++) {
int[] num = new int[len];
for (int j = 0; j < num.length; j++) {
num[j] = rand.nextInt(4);
}
long expected = DNAAlignmentSlow(num);
long actual = DNAAlignment(num);
if (actual != expected) {
System.out.println("fail: " + Arrays.toString(num));
DNAAlignment(num);
}
}
}
}
public static long DNAAlignment(int[] num) {
// r1: dominance = 1 match
int[] freq = new int[4];
int maxF = 0;
for (int i = 0; i < num.length; i++) {
freq[num[i]]++;
maxF = Math.max(maxF, freq[num[i]]);
}
int countF = 0;
int distinct = 0;
for (int i = 0; i < freq.length; i++) {
if (freq[i] == maxF) {
countF++;
distinct++;
}
}
// assert
long predNumMatches = 0;
if (countF == 1) {
predNumMatches = 1;
} else {
predNumMatches = fastModularExponent(distinct, num.length, 1000000007);
}
return predNumMatches;
}
public static int fastModularExponent(int a, int exp, int mod) {
long[] results = new long[65];
long m = mod;
int power = 1;
long res = 1;
while (exp > 0) {
if (power == 1) {
results[power] = a % m;
} else {
results[power] = (results[power-1] * results[power-1]) % m;
}
if (exp % 2 == 1) {
res = (res * results[power]) % m;
}
exp /= 2;
power++;
}
return (int) (res % m);
}
public static boolean next_number(int list[], int base) {
int i = list.length - 1;
list[i]++;
if (list[i] == base) {
boolean carry = true;
while (carry) {
if (i == 0) {
return false;
}
carry = false;
list[i] = 0;
list[--i]++;
if (list[i] == base) {
carry = true;
}
}
}
return true;
}
public static long DNAAlignmentSlow(int[] numA) {
int length = numA.length;
// System.out.println("A");
// System.out.println(Arrays.toString(numA));
int max = 0;
int[] numB = new int[length];
do {
int matches = 0;
for (int startA = 0; startA < length; startA++) {
for (int startB = 0; startB < length; startB++) {
for (int i = 0; i < length; i++) {
if (numA[(startA + i) % length] == numB[(startB + i) % length]) {
matches++;
}
}
}
}
if (matches > max) {
max = matches;
}
} while (next_number(numB, 4));
int NumMatches = 0;
// System.out.println("max: " + max);
numB = new int[length];
do {
int matches = 0;
for (int startA = 0; startA < length; startA++) {
for (int startB = 0; startB < length; startB++) {
for (int i = 0; i < length; i++) {
if (numA[(startA + i) % length] == numB[(startB + i) % length]) {
matches++;
}
}
}
}
if (matches == max) {
// System.out.println(Arrays.toString(numB));
NumMatches++;
}
} while (next_number(numB, 4));
// System.out.println("NumMatches: " + NumMatches);
// System.out.println("\n\n");
return NumMatches;
}
public static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {return Integer.parseInt(next());}
public long nextLong() {return Long.parseLong(next());}
public double nextDouble() {return Double.parseDouble(next());}
public long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < a.length; i++) a[i] = this.nextLong();
return a;
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < a.length; i++) a[i] = this.nextInt();
return a;
}
}
}
| Java | ["3\n2 1\n1 0\n0 1", "5\n0 0\n0 1\n0 2\n0 3\n0 4"] | 3 seconds | ["19", "2930"] | null | Java 8 | standard input | [
"implementation",
"greedy",
"games"
] | 9f36d49541e6dd7082e37416cdb1949c | The first line contains number m (2ββ€βmββ€β105). The following m lines contain the coordinates of the cubes xi,βyi (β-β109ββ€βxiββ€β109, 0ββ€βyiββ€β109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. | 2,100 | In the only line print the answer to the problem. | standard output | |
PASSED | 134bd2a23d572a07902c7bfe5839d41f | train_001.jsonl | 1425279600 | Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and mβ-β1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower left corner, these coordinates are integers for each cube.The figure turned out to be stable. This means that for any cube that is not on the ground, there is at least one cube under it such that those two cubes touch by a side or a corner. More formally, this means that for the cube with coordinates (x,βy) either yβ=β0, or there is a cube with coordinates (xβ-β1,βyβ-β1), (x,βyβ-β1) or (xβ+β1,βyβ-β1).Now the boys want to disassemble the figure and put all the cubes in a row. In one step the cube is removed from the figure and being put to the right of the blocks that have already been laid. The guys remove the cubes in such order that the figure remains stable. To make the process more interesting, the guys decided to play the following game. The guys take out the cubes from the figure in turns. It is easy to see that after the figure is disassembled, the integers written on the cubes form a number, written in the m-ary positional numerical system (possibly, with a leading zero). Vasya wants the resulting number to be maximum possible, and Petya, on the contrary, tries to make it as small as possible. Vasya starts the game.Your task is to determine what number is formed after the figure is disassembled, if the boys play optimally. Determine the remainder of the answer modulo 109β+β9. | 256 megabytes | import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class B {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
private static final int MOD = 1000 * 1000 * 1000 + 9;
class Vertex implements Comparable<Vertex> {
int x;
int y;
int index;
Vertex(int x, int y, int index) {
this.x = x;
this.y = y;
this.index = index;
}
public int compareTo(Vertex o) {
return this.index - o.index;
}
}
void solve() throws IOException {
int t = 1;
while (t-- > 0) {
solveTest();
}
}
private void solveTest() throws IOException {
int n = readInt();
Vertex[] vertexes = new Vertex[n];
Map<Integer, Map<Integer, Vertex>> map = new HashMap<Integer, Map<Integer, Vertex>>();
for(int i = 0; i < n; i++) {
vertexes[i] = new Vertex(readInt(), readInt(), i);
add(map, vertexes[i]);
}
TreeSet<Vertex> q = new TreeSet<Vertex>();
for(Vertex v: vertexes) {
if(isSafe(map, v)) {
q.add(v);
}
}
long[] res = new long[n];
boolean[] used = new boolean[n];
for(int i = 0; i < n; i++) {
Vertex cur;
if(i % 2 == 0) {
cur = q.pollLast();
} else {
cur = q.pollFirst();
}
res[i] = cur.index;
remove(map, cur);
used[cur.index] = true;
for(int dx = -2; dx <= 2; dx++) {
for(int dy = -1; dy <= 0; dy++) {
Vertex next = get(map, cur.x + dx, cur.y + dy);
if (next == null) continue;
if (used[next.index]) continue;
if (isSafe(map, next)) {
q.add(next);
} else {
q.remove(next);
}
}
}
}
long curPow = 1;
long resNum = 0;
for(int i = n-1; i >= 0; i--) {
resNum += res[i] * curPow;
resNum %= MOD;
curPow *= n;
curPow %= MOD;
}
out.println(resNum);
}
boolean isSafe(Map<Integer, Map<Integer, Vertex>> map, Vertex v) {
boolean res = true;
for(int dx = -1; dx <= 1; dx++) {
if(count(map, v.x + dx, v.y + 1) == 1) {
res = false;
}
}
return res;
}
int count(Map<Integer, Map<Integer, Vertex>> map, int x, int y) {
int res = 0;
Vertex v = get(map, x, y);
if(v == null) return res;
for(int dx = -1; dx <= 1; dx++) {
if(get(map, v.x + dx, v.y - 1) != null) {
res++;
}
}
return res;
}
Vertex get(Map<Integer, Map<Integer, Vertex>> map, int x, int y) {
Map<Integer, Vertex> yMap = map.get(x);
if(yMap == null) return null;
return yMap.get(y);
}
void add(Map<Integer, Map<Integer, Vertex>> map, Vertex v) {
if(!map.containsKey(v.x)) {
map.put(v.x, new HashMap<Integer, Vertex>());
}
map.get(v.x).put(v.y, v);
}
void remove(Map<Integer, Map<Integer, Vertex>> map, Vertex v) {
map.get(v.x).remove(v.y);
}
void init() throws FileNotFoundException {
if (ONLINE_JUDGE) {
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");
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine(), " .");
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
int[] readArr(int n) throws IOException {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = readInt();
}
return res;
}
long[] readArrL(int n) throws IOException {
long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = readLong();
}
return res;
}
public static void main(String[] args) {
new B().run();
}
public void run() {
try {
long t1 = System.currentTimeMillis();
init();
solve();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = " + (t2 - t1));
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(-1);
}
}
} | Java | ["3\n2 1\n1 0\n0 1", "5\n0 0\n0 1\n0 2\n0 3\n0 4"] | 3 seconds | ["19", "2930"] | null | Java 8 | standard input | [
"implementation",
"greedy",
"games"
] | 9f36d49541e6dd7082e37416cdb1949c | The first line contains number m (2ββ€βmββ€β105). The following m lines contain the coordinates of the cubes xi,βyi (β-β109ββ€βxiββ€β109, 0ββ€βyiββ€β109) in ascending order of numbers written on them. It is guaranteed that the original figure is stable. No two cubes occupy the same place. | 2,100 | In the only line print the answer to the problem. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.