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 | 877c438e9c51e66a330e3a8813e9e80f | train_003.jsonl | 1508151900 | Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (iβ+β1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (iβ+β1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task. | 512 megabytes | import java.util.*;
public class Main {
public static void main(String[] arg) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] array = new int[n];
for(int i = 0; i < n; i++) array[i] = scan.nextInt();
boolean[] taken = new boolean[300005];
int pruned = 0;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(1 + " ");
for(int i = 0; i < n; i++){
taken[array[i]] = true;
while(pruned < n && taken[n - pruned]) pruned++;
stringBuilder.append((i+2 - pruned) + " ");
}
System.out.println(stringBuilder.toString());
}
} | Java | ["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"] | 1 second | ["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"] | NoteLet's denote as O coin out of circulation, and as X β coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO βββ OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO βββ OXOX βββ OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX βββ OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges. | Java 8 | standard input | [
"two pointers",
"dsu",
"implementation",
"sortings",
"trees"
] | b97eeaa66e91bbcc3b5e616cb480c7af | The first line contains single integer n (1ββ€βnββ€β300β000)Β β number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1,βp2,β...,βpn (1ββ€βpiββ€βn)Β β positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right. | 1,500 | Print nβ+β1 numbers a0,βa1,β...,βan, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on. | standard output | |
PASSED | 819b5c1a4b99a7feee3fcc50a7709dd8 | train_003.jsonl | 1508151900 | Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (iβ+β1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (iβ+β1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task. | 512 megabytes | import java.util.*;
import java.io.*;
public class Solution {
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
public static void main(String[] args) throws IOException{
Reader sc=new Reader();
int n = sc.nextInt();
int[] a = new int[n];
int nbx=0;
int chef = n-1;
int p=0;
System.out.print("1");
for(int i=0;i<n;i++){
nbx++;
p = sc.nextInt();
a[p-1] = 1;
if(p-1==chef){
while(a[chef]==1){
chef--;
nbx--;
if(chef<0) break;
}
}
System.out.print(" "+(nbx+1));
}
System.out.println("");
}
} | Java | ["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"] | 1 second | ["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"] | NoteLet's denote as O coin out of circulation, and as X β coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO βββ OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO βββ OXOX βββ OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX βββ OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges. | Java 8 | standard input | [
"two pointers",
"dsu",
"implementation",
"sortings",
"trees"
] | b97eeaa66e91bbcc3b5e616cb480c7af | The first line contains single integer n (1ββ€βnββ€β300β000)Β β number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1,βp2,β...,βpn (1ββ€βpiββ€βn)Β β positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right. | 1,500 | Print nβ+β1 numbers a0,βa1,β...,βan, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on. | standard output | |
PASSED | 063e82de7c9cfb9b7e63d7d3900b2994 | train_003.jsonl | 1508151900 | Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then come coins still in circulation. For arranging coins Dima uses the following algorithm. One step of his algorithm looks like the following: He looks through all the coins from left to right; If he sees that the i-th coin is still in circulation, and (iβ+β1)-th coin is already out of circulation, he exchanges these two coins and continues watching coins from (iβ+β1)-th. Dima repeats the procedure above until it happens that no two coins were exchanged during this procedure. Dima calls hardness of ordering the number of steps required for him according to the algorithm above to sort the sequence, e.g. the number of times he looks through the coins from the very beginning. For example, for the ordered sequence hardness of ordering equals one.Today Sasha invited Dima and proposed him a game. First he puts n coins in a row, all of them are out of circulation. Then Sasha chooses one of the coins out of circulation and replaces it with a coin in circulation for n times. During this process Sasha constantly asks Dima what is the hardness of ordering of the sequence. The task is more complicated because Dima should not touch the coins and he should determine hardness of ordering in his mind. Help Dima with this task. | 512 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.*;
public class sortingcoings implements Runnable{
public static void main(String[] args) {
new Thread(null, new sortingcoings(),"sortingcoings",1<<26).start();
}
@Override
public void run() {
InputReader input = new InputReader(System.in);
int n = input.nextInt();
int oldN = n;
int[] circ = new int[n + 1];
System.out.print(1 + " ");
for (int i = 0; i < oldN; i++) {
int temp = input.nextInt();
circ[temp] = 1;
while(circ[n] == 1){
//System.out.print("(((" + n + ")))");
n--;
}
System.out.print(i - (oldN - n) + 2 + " ");
}
}
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["4\n1 3 4 2", "8\n6 8 3 4 7 2 1 5"] | 1 second | ["1 2 3 2 1", "1 2 2 3 4 3 4 5 1"] | NoteLet's denote as O coin out of circulation, and as X β coin is circulation.At the first sample, initially in row there are coins that are not in circulation, so Dima will look through them from left to right and won't make any exchanges.After replacement of the first coin with a coin in circulation, Dima will exchange this coin with next three times and after that he will finally look through the coins and finish the process.XOOO βββ OOOXAfter replacement of the third coin, Dima's actions look this way:XOXO βββ OXOX βββ OOXXAfter replacement of the fourth coin, Dima's actions look this way:XOXX βββ OXXXFinally, after replacement of the second coin, row becomes consisting of coins that are in circulation and Dima will look through coins from left to right without any exchanges. | Java 8 | standard input | [
"two pointers",
"dsu",
"implementation",
"sortings",
"trees"
] | b97eeaa66e91bbcc3b5e616cb480c7af | The first line contains single integer n (1ββ€βnββ€β300β000)Β β number of coins that Sasha puts behind Dima. Second line contains n distinct integers p1,βp2,β...,βpn (1ββ€βpiββ€βn)Β β positions that Sasha puts coins in circulation to. At first Sasha replaces coin located at position p1, then coin located at position p2 and so on. Coins are numbered from left to right. | 1,500 | Print nβ+β1 numbers a0,βa1,β...,βan, where a0 is a hardness of ordering at the beginning, a1 is a hardness of ordering after the first replacement and so on. | standard output | |
PASSED | ca84d9d250029834c34001ab4cbb184d | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.InputMismatchException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
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 N = in.readInt();
List<Integer> list = IOUtils.readIntArray(in, N);
List<Integer> positives = new LinkedList<Integer>();
List<Integer> zeros = new LinkedList<Integer>();
boolean negativePrinted =false;
for (Integer i : list) {
if (i < 0) {
if(!negativePrinted) {
out.print("1 " + i + "\n");
negativePrinted = true;
}
else
zeros.add(i);
}
else if ( i > 0) {
if(positives.size() == 0)
positives.add(i);
else
zeros.add(i);
}
else
zeros.add(i);
}
if ( positives.size() == 0) {
int count = 0;
for (Iterator<Integer> iterator = zeros.iterator(); iterator.hasNext();) {
Integer i = (Integer) iterator.next();
if ( i < 0 ) {
iterator.remove();
positives.add(i);
++count;
}
if (count == 2)
break;
}
}
print(out, positives);
print(out, zeros);
}
private void print(OutputWriter out, List<Integer> list) {
out.print(list.size());
for (Integer i : list) {
out.printLine(" " + i);
}
out.print("\n");
}
}
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 print(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(array[i]);
}
}
public void printLine(int[] array) {
print(array);
writer.println();
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
class IOUtils {
public static List<Integer> readIntArray(InputReader in, int size) {
List<Integer> list = new LinkedList<Integer>();
for (int i = 0; i < size; i++)
list.add(in.readInt());
return list;
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | 561c6c8b113f790b90f35cab7e26e4d5 | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class Solution {
public void solve() throws IOException {
int n = in.nextInt();
int[] a = in.nextIntArray(n);
List<Integer> a1 = new ArrayList<Integer>(),
a2 = new ArrayList<Integer>(),
a3 = new ArrayList<Integer>();
for (int i = 0; i < n; ++i) {
if (a[i] < 0) {
a1.add(a[i]);
} else if (a[i] > 0) {
a2.add(a[i]);
} else {
a3.add(a[i]);
}
}
if (a2.isEmpty()) {
a2.add(a1.remove(0));
a2.add(a1.remove(0));
}
if (a1.size() % 2 == 0) {
a3.add(a1.remove(0));
}
System.out.print(a1.size() + " ");
for (Integer el : a1) {
System.out.print(el + " ");
}
System.out.println();
System.out.print(a2.size() + " ");
for (Integer el : a2) {
System.out.print(el + " ");
}
System.out.println();
System.out.print(a3.size() + " ");
for (Integer el : a3) {
System.out.print(el + " ");
}
System.out.println();
}
public void run() throws IOException {
in = new MyScanner();
solve();
in.close();
}
private MyScanner in;
//private PrintWriter out;
public class MyScanner {
private BufferedReader br;
private StringTokenizer st;
public MyScanner() {
this.br = new BufferedReader(new InputStreamReader(System.in));
}
public MyScanner(String fileTitle) throws IOException {
this.br = new BufferedReader(new FileReader(fileTitle + ".in"));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String s = br.readLine();
if (s == null) {
return "-1";
}
st = new StringTokenizer(s);
}
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public int[] nextIntArray(int size) throws IOException {
int[] arr = new int[size];
for (int i = 0; i < size; ++i) {
arr[i] = nextInt();
}
return arr;
}
public void close() throws IOException {
br.close();
}
}
public static void main(String[] args) throws IOException {
new Solution().run();
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | f01b78bdf9c40649b4df7ae121994472 | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.util.*;
public class A {
public static void main(String [] args){
Scanner s = new Scanner(System.in);
final int n = s.nextInt();
final Queue<Integer> pos = new LinkedList<Integer>();
final Queue<Integer> neg = new LinkedList<Integer>();
final Queue<Integer> zero = new LinkedList<Integer>();
for (int i = 0; i < n; ++i){
final int a = s.nextInt();
if (a > 0){
pos.offer(a);
}else if (a < 0){
neg.offer(a);
}else{
zero.offer(a);
}
}
if (pos.size() == 0){
pos.offer(neg.poll());
pos.offer(neg.poll());
}
if (neg.size()%2 == 0){
zero.offer(neg.poll());
}
System.out.println(neg.size());
for (int i :neg){
System.out.print(i + " ");
}
System.out.println(pos.size());
for (int i : pos){
System.out.print(i + " ");
}
System.out.println(zero.size());
for (int i : zero){
System.out.print(i + " ");
}
System.out.println();
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | 7763f2f2a8aaabe69bd7b0837bb04245 | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.util.List;
import java.util.Scanner;
import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author peneksglazami
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
List<Integer> negative = new ArrayList<Integer>();
List<Integer> positive = new ArrayList<Integer>();
List<Integer> zero = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
int x = in.nextInt();
if (x < 0) {
negative.add(x);
} else if (x > 0) {
positive.add(x);
} else {
zero.add(x);
}
}
if (positive.isEmpty()) {
positive.addAll(negative.subList(0, 2));
negative.remove(0);
negative.remove(0);
}
while (negative.size() > 1) {
zero.add(negative.get(0));
negative.remove(0);
}
out.println("1 " + negative.get(0));
out.print(positive.size());
for (Integer x : positive) {
out.print(" " + x);
}
out.println();
out.print(zero.size());
for (Integer x : zero) {
out.print(" " + x);
}
out.println();
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | 18c71be95f54644d98b230cc813f9322 | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.util.*;
public class A {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int[] arr = new int[n];
for(int i=0; i<n; i++) {
arr[i] = s.nextInt();
}
Arrays.sort(arr);
Vector<Integer> first = new Vector<Integer>();
Vector<Integer> second = new Vector<Integer>();
Vector<Integer> third = new Vector<Integer>();
first.addElement(arr[0]);
if(arr[n-1] == 0) {
second.addElement(arr[1]);
second.addElement(arr[2]);
for(int i=3; i<n; i++)
third.addElement(arr[i]);
}
else {
second.addElement(arr[n-1]);
for(int i=1; i<n-1; i++)
third.addElement(arr[i]);
}
System.out.print(first.size());
for(int i=0; i<first.size(); i++)
System.out.print(" " + first.elementAt(i));
System.out.println();
System.out.print(second.size());
for(int i=0; i<second.size(); i++)
System.out.print(" " + second.elementAt(i));
System.out.println();
System.out.print(third.size());
for(int i=0; i<third.size(); i++)
System.out.print(" " + third.elementAt(i));
System.out.println();
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | 30dc7d4ea6812d7e2104ee18681d7af3 | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.io.*;
import java.util.*;
public class solution
{
public static void main(String[] args) throws IOException
{
try
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int zero_cnt = 0;
int neg_cnt = 0;
int pos_cnt = 0;
int positive[] = new int[105];
int negative[] = new int[105];
for (int j = 0; j < n; j++)
{
int nnew = sc.nextInt();
if (nnew < 0)
{
negative[neg_cnt] = nnew;
neg_cnt++;
}
else if (nnew > 0)
{
positive[pos_cnt] = nnew;
pos_cnt++;
}
else zero_cnt++;
}
System.out.println("1 " + negative[neg_cnt - 1]);
neg_cnt--;
if (pos_cnt > 0)
{
System.out.println("1 " + positive[pos_cnt - 1]);
pos_cnt--;
}
else
{
System.out.println("2 " + negative[neg_cnt - 1] + " " + negative[neg_cnt - 2]);
neg_cnt -= 2;
}
System.out.print(neg_cnt + pos_cnt + zero_cnt + " ");
for (int j = 0; j < zero_cnt; j++)
System.out.print("0 ");
for (int j = 0; j < neg_cnt; j++)
System.out.print(negative[j] + " ");
for (int j = 0; j < pos_cnt; j++)
System.out.print(positive[j] + " ");
}
finally
{
}
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | 0cdd4d585c0fe1b507302b3ac6d1a704 | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int f[] = new int [1000];
int s[] = new int [1000];
int t[] = new int [1000];
int l[] = new int [1000];
for (int i = 0; i < n; i++) {
int x = in.nextInt();
if (x == 0) {
t[0]++;
t[t[0]] = x;
} else
if (x < 0 && f[0] == 0) {
f[0]++;
f[f[0]] = x;
} else
if (x > 0) {
s[0]++;
s[s[0]] = x;
} else {
l[0]++;
l[l[0]] = x;
}
}
if (s[0] == 0) {
s[0]++; s[s[0]] = l[l[0]]; l[0]--;
s[0]++; s[s[0]] = l[l[0]]; l[0]--;
}
for (int i = 1; i <= l[0]; i++) {
t[0]++; t[t[0]] = l[i];
}
System.out.print(f[0] + " ");
for (int i = 1; i <= f[0]; i++) System.out.print(f[i] + " ");
System.out.println();
System.out.print(s[0] + " ");
for (int i = 1; i <= s[0]; i++) System.out.print(s[i] + " ");
System.out.println();
System.out.print(t[0] + " ");
for (int i = 1; i <= t[0]; i++) System.out.print(t[i] + " ");
System.out.println();
}
} | Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | 918d7a7fb5aaf1ef861e8024e4a85e37 | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args)throws Exception{
Scanner s = new Scanner(System.in);
int n = s.nextInt();
Vector<String> set = new Vector<String>();
for(int i=0;i<n;i++){
String num = s.nextInt()+"";
set.addElement(num);
}
Collections.sort(set);
Vector<String> set1 = new Vector<String>();
Vector<String> set2 = new Vector<String>();
Vector<String> set3 = new Vector<String>();
set1.addElement(set.remove(0));
set3.addElement(set.elementAt(set.indexOf("0")));
set.removeElementAt(set.indexOf("0"));
if(set.size() > 1){
String n1 = set.elementAt(0);
String n2 = set.elementAt(1);
if(n1.contains("-") && n2.contains("-")){
set2.addElement(n1);
set2.addElement(n2);
set.remove(n1);
set.remove(n2);
}else{
set2.addElement(n2);
set.remove(n2);
}
}else
if(set.size() == 1)
set2.addElement(set.remove(set.indexOf(set.elementAt(0))));
while(!set.isEmpty()){
set3.addElement(set.elementAt(0));
set.removeElementAt(0);
}
System.out.print(set1.size() + " " );
for(int i=0;i<set1.size()-1;i++)
System.out.print(set1.elementAt(i) + " ");
System.out.println(set1.elementAt(set1.size()-1));
System.out.print(set2.size() + " " );
for(int i=0;i<set2.size()-1;i++)
System.out.print(set2.elementAt(i) + " ");
System.out.println(set2.elementAt(set2.size()-1));
System.out.print(set3.size() + " " );
for(int i=0;i<set3.size()-1;i++)
System.out.print(set3.elementAt(i) + " ");
System.out.println(set3.elementAt(set3.size()-1));
}
} | Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | ee2d65a3d42f1c5c0c4f236af960abcc | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++) {
arr[i] = s.nextInt();
}
Arrays.sort(arr);
int neg = 0;
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] < 0 && arr[i] != arr[i + 1])
neg++;
}
ArrayList<Integer> temp = new ArrayList<Integer>();
for (int i = 1; i < arr.length; i++)
if (arr[i] == arr[i - 1])
temp.add(arr[i]);
temp.add(0);
int begin = 0;
if (neg % 2 == 0) {
temp.add(arr[0]);
begin = 1;
}
ArrayList<Integer> fir = new ArrayList<Integer>();
ArrayList<Integer> sec = new ArrayList<Integer>();
if (begin == 1) {
fir.add(arr[1]);
begin = 2;
} else {
fir.add(arr[0]);
begin = 1;
}
for (int i = begin; i < arr.length; i++)
if (!sec.contains(arr[i]) && arr[i] != 0)
sec.add(arr[i]);
System.out.print(fir.size());
for (int i : fir)
System.out.print(" " + i);
System.out.println();
System.out.print(sec.size());
for (int i : sec)
System.out.print(" " + i);
System.out.println();
System.out.print(temp.size());
for (int i : temp)
System.out.print(" " + i);
System.out.println();
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | 9bb61ba04df56b490f296cbbcc52a050 | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.util.*;
public class cf300a {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Integer> pos = new ArrayList<Integer>();
ArrayList<Integer> neg = new ArrayList<Integer>();
ArrayList<Integer> zero = new ArrayList<Integer>();
ArrayList<Integer> a = new ArrayList<Integer>();
ArrayList<Integer> b = new ArrayList<Integer>();
ArrayList<Integer> c = new ArrayList<Integer>();
int n = in.nextInt();
for(int i=0; i<n; i++) {
int x = in.nextInt();
if(x < 0) neg.add(x);
if(x > 0) pos.add(x);
if(x == 0) zero.add(x);
}
for(int x : pos) b.add(x);
for(int x : zero) c.add(x);
a.add(neg.get(0));
int start = 1;
if(b.size() == 0) {
b.add(neg.get(1));
b.add(neg.get(2));
start = 3;
}
for(int i=start; i<neg.size(); i++)
c.add(neg.get(i));
System.out.print(a.size());
for(int x : a) System.out.print(" " + x);
System.out.println();
System.out.print(b.size());
for(int x : b) System.out.print(" " + x);
System.out.println();
System.out.print(c.size());
for(int x : c) System.out.print(" " + x);
System.out.println();
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | 801b68b000cc8a3b4d245a34295ca193 | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = t_int(br);
int[] a = t_int_a(br, n);
Arrays.sort(a);
List<Integer> neg = new ArrayList<Integer>();
List<Integer> zero = new ArrayList<Integer>();
List<Integer> pos = new ArrayList<Integer>();
neg.add(a[0]);
int i = 1;
for (; i < n && a[i] <= 0; i++) {
zero.add(a[i]);
}
for (; i < n; i++) {
pos.add(a[i]);
}
if (pos.isEmpty()) {
pos.add(zero.remove(0));
pos.add(zero.remove(0));
}
System.out.println("1 " + neg.get(0));
System.out.print(pos.size() + " ");
for (i = 0; i < pos.size() - 1; i++) {
System.out.print(pos.get(i) + " ");
}
System.out.println(pos.get(pos.size() - 1));
System.out.print(zero.size() + " ");
for (i = 0; i < zero.size() - 1; i++) {
System.out.print(zero.get(i) + " ");
}
System.out.println(zero.get(zero.size() - 1));
br.close();
}
public static int t_int(BufferedReader br) throws Exception {
return Integer.parseInt(br.readLine());
}
public static StringTokenizer t_st(BufferedReader br) throws Exception {
return new StringTokenizer(br.readLine());
}
public static int[] t_int_a(BufferedReader br, int n) throws Exception {
StringTokenizer st = t_st(br);
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(st.nextToken());
}
return a;
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | 9f0c1b0f01f0da4be6a8055f49140e37 | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class A {
/**
* @param args
*/
public static void main(String[] args) {
Parser p = new Parser(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = p.nextInt();
int[] a = p.nextIntArray(n);
ArrayList<Integer> plus = new ArrayList<Integer>();
ArrayList<Integer> minus = new ArrayList<Integer>();
ArrayList<Integer> zero = new ArrayList<Integer>();
for(int i: a){
if(i<0){
minus.add(i);
}else if(i == 0){
zero.add(i);
}else{
plus.add(i);
}
}
if(plus.size()==0){
int m1 = minus.remove(0);
int m2 = minus.remove(0);
plus.add(m1);
plus.add(m2);
}
if(minus.size()%2 == 0){
int m3 = minus.remove(0);
zero.add(m3);
}
printArray(minus);
printArray(plus);
printArray(zero);
pw.close();
}
private static void printArray(ArrayList<Integer> minus) {
System.out.print(minus.size());
for(int i=0; i<minus.size(); ++i){
System.out.print(" ");
System.out.print(minus.get(i));
}
System.out.println();
}
static class Parser{
StringTokenizer st;
BufferedReader br;
public Parser(InputStream is){
this.br = new BufferedReader( new InputStreamReader(is));
}
public int nextInt(){
return Integer.parseInt(nextToken());
}
public double nextDouble(){
return Double.parseDouble(nextToken());
}
public String nextString(){
return nextToken();
}
public int[] nextIntArray(int s){
int[] a = new int[s];
for(int i=0; i<s; ++i){
a[i] = nextInt();
}
return a;
}
public int[][] nextIntTable(int r, int c){
int[][] a = new int[r][c];
for(int i=0; i<r; ++i){
a[i] = nextIntArray(c);
}
return a;
}
private String nextToken() {
if( st == null || ! st.hasMoreTokens() ){
try{
st = new StringTokenizer( br.readLine());
}catch( Exception e){
e.printStackTrace();
}
}
return st.nextToken();
}
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | 376223d71b0ecfc75a7ca1fb0879d156 | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.util.*;
import java.io.*;
/**
*
* @author iweerarathna
*/
public class CF18101 {
public static void main(String[] args) throws Exception {
Scanner scan = new Scanner(System.in);
PrintWriter writer = new PrintWriter(System.out);
ArrayList<Integer> fc = new ArrayList<Integer>();
ArrayList<Integer> pn = new ArrayList<Integer>();
ArrayList<Integer> nn = new ArrayList<Integer>();
int A = scan.nextInt();
int[] nums = new int[A];
for (int i=0;i<A;i++) {
nums[i] = scan.nextInt();
if (nums[i] == 0) {
fc.add(nums[i]);
} else if (nums[i] < 0) {
nn.add(nums[i]);
} else {
pn.add(nums[i]);
}
}
if (nn.size() % 2 == 0) {
fc.add(nn.get(0));
nn.remove(0);
}
if (pn.isEmpty()) {
if (nn.size() > 2) {
pn.add(nn.get(0));
pn.add(nn.get(1));
nn.remove(0);
nn.remove(0);
}
}
StringBuilder sb = new StringBuilder();
sb.append(nn.size()).append(" ");
for (int i=0;i<nn.size();i++) {
if (i>0) sb.append(" ");
sb.append(nn.get(i));
}
sb.append("\n").append(pn.size()).append(" ");
for (int i=0;i<pn.size();i++) {
if (i>0) sb.append(" ");
sb.append(pn.get(i));
}
sb.append("\n").append(fc.size()).append(" ");
for (int i=0;i<fc.size();i++) {
if (i>0) sb.append(" ");
sb.append(fc.get(i));
}
sb.append("\n");
writer.write(sb.toString());
writer.flush();
writer.close();
}
private static void Solve(int[] nums) {
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | 4210ca2752b89bb995d10fbe9c3ece2f | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
/*
br = new BufferedReader(new FileReader("input.txt"));
pw = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
*/
public class Main {
private static BufferedReader br;
private static StringTokenizer st;
private static PrintWriter pw;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
//int qq = 1;
int qq = Integer.MAX_VALUE;
//int qq = readInt();
for(int casenum = 1; casenum <= qq; casenum++) {
ArrayList<Integer> list = new ArrayList<Integer>();
int n = readInt();
while(n-- > 0) {
list.add(readInt());
}
ArrayList<Integer> negative = new ArrayList<Integer>();
ArrayList<Integer> positive = new ArrayList<Integer>();
ArrayList<Integer> zero = new ArrayList<Integer>();
while(!list.isEmpty()) {
int curr = list.remove(0);
if(curr < 0) {
if(negative.isEmpty()) {
negative.add(curr);
}
else {
zero.add(curr);
}
}
else if(curr > 0) {
if(positive.isEmpty()) {
positive.add(curr);
}
else {
zero.add(curr);
}
}
else {
zero.add(curr);
}
}
if(positive.size() == 0) {
for(int k = 0; positive.size() != 2; k++) {
if(zero.get(k) < 0) {
positive.add(zero.remove(k--));
}
}
}
print(negative);
print(positive);
print(zero);
}
pw.close();
}
public static void print(ArrayList<Integer> list) {
pw.print(list.size());
for(int out: list) {
pw.print(" " + out);
}
pw.println();
}
private static void exitImmediately() {
pw.close();
System.exit(0);
}
private static long readLong() throws IOException {
return Long.parseLong(nextToken());
}
private static double readDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private static int readInt() throws IOException {
return Integer.parseInt(nextToken());
}
private static String nextToken() throws IOException {
while(st == null || !st.hasMoreTokens()) {
if(!br.ready()) {
exitImmediately();
}
st = new StringTokenizer(br.readLine().trim());
}
return st.nextToken();
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | c22810f4b2477c6ba536546a7c20ce60 | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class CFA {
private void work() throws IOException {
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(
System.in)));
while (sc.hasNextInt()) {
int n = sc.nextInt();
int[] a = new int[n];
int neg = -1;
int pos = -1;
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
if (neg < 0 && a[i] < 0)
neg = i;
if (pos < 0 && a[i] > 0)
pos = i;
}
System.out.println("1 " + a[neg]);
if (pos >= 0) {
System.out.println("1 " + a[pos]);
System.out.print(n - 2);
for (int i = 0; i < n; i++) {
if (i != neg && i != pos) {
System.out.print(" " + a[i]);
}
}
} else {
int neg1 = -1;
int neg2 = -1;
for (int i = neg + 1; i < n; i++) {
if (a[i] < 0) {
if (neg1 < 0) {
neg1 = i;
} else if (neg2 < 0) {
neg2 = i;
}
}
}
System.out.println("2 " + a[neg1] + " " + a[neg2]);
System.out.print(n - 3);
for (int i = 0; i < n; i++) {
if (i != neg && i != neg1 && i != neg2) {
System.out.print(" " + a[i]);
}
}
}
System.out.println();
}
System.out.close();
}
private int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
public static void main(String[] args) throws IOException {
new CFA().work();
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | 5635cfc041467597afd964c7940f48b7 | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int a[]=new int [n];
int neg=0;
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
if(a[i]<0)
neg++;
}
Arrays.sort(a);
ArrayList<Integer>n1=new ArrayList<Integer>();
ArrayList<Integer>n2=new ArrayList<Integer>();
ArrayList<Integer>n3=new ArrayList<Integer>();
n1.add(a[0]);
neg--;
if((neg+2)==n)
{
n2.add(a[1]);
n2.add(a[2]);
for(int i=3;i<n;i++)
n3.add(a[i]);
}
else
{
int i=a.length;
for( i=a.length-1;i>0 && a[i]!=0;i--)
n2.add(a[i]);
for(i=i;i>0;i--)
n3.add(a[i]);
}
System.out.print(n1.size());
for(int i=0;i<n1.size();i++)
System.out.print(" "+n1.get(i));
System.out.println();
System.out.print(n2.size());
for(int i=0;i<n2.size();i++)
System.out.print(" "+n2.get(i));
System.out.println();
System.out.print(n3.size());
for(int i=0;i<n3.size();i++)
System.out.print(" "+n3.get(i));
System.out.println();
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | e7a517f658c19fcaf193c6d9e65835d0 | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class Main{
/**
* @param args
*/
public static void main(String[] args)throws Exception {
BufferedReader in = new BufferedReader (new InputStreamReader (System.in));
int n = Integer.parseInt(in.readLine());
int arr[] = new int[n];
StringTokenizer st = new StringTokenizer(in.readLine());
ArrayList<Integer> a = new ArrayList<Integer>();
ArrayList<Integer> b = new ArrayList<Integer>();
ArrayList<Integer> c = new ArrayList<Integer>();
int cantNeg =0;
boolean[] vis = new boolean[n];
int indexNeg = -1;
for(int i=0;i<n;++i){
arr[i]=Integer.parseInt(st.nextToken());
if(arr[i]<0){
cantNeg++;
indexNeg=i;
}
if(arr[i]==0){
vis[i]=true;
c.add(arr[i]);
}
}
if(cantNeg%2==0){
c.add(arr[indexNeg]);
vis[indexNeg]=true;
}
for(int i=0;i<n;++i){
if(!vis[i]){
if(arr[i]<0 && a.size()==0)
a.add(arr[i]);
else
b.add(arr[i]);
}
}
StringBuilder sb = new StringBuilder();
sb.append(a.size()+" ");
for(int i=0;i<a.size();++i){
sb.append(a.get(i));
if(i<a.size()-1)
sb.append(" ");
}
sb.append("\n");
sb.append(b.size()+" ");
for(int i=0;i<b.size();++i){
sb.append(b.get(i));
if(i<b.size()-1)
sb.append(" ");
}
sb.append("\n");
sb.append(c.size()+" ");
for(int i=0;i<c.size();++i){
sb.append(c.get(i));
if(i<c.size()-1)
sb.append(" ");
}
sb.append("\n");
System.out.print(new String(sb));
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | 1e581f595b5154fa77857bec8c50f1dc | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.util.*;
import java.io.*;
public class TaskA {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
//Scanner scanner = new Scanner(new File("D:\\develop\\1.txt"));
int n = scanner.nextInt();
ArrayList<Integer> negatives = new ArrayList<Integer>();
ArrayList<Integer> positives = new ArrayList<Integer>();
ArrayList<Integer> nulls = new ArrayList<Integer>();
for(int i = 0; i < n; i++) {
int a = scanner.nextInt();
if(a < 0) {
negatives.add(a);
}
else if(a > 0) {
positives.add(a);
}
else {
nulls.add(a);
}
}
if(negatives.size() > 1 && negatives.size() % 2 == 0) {
nulls.add(negatives.get(negatives.size()-1));
negatives.remove(negatives.size()-1);
}
if(positives.isEmpty()) {
positives.add(negatives.get(negatives.size()-1));
positives.add(negatives.get(negatives.size()-2));
negatives.remove(negatives.size()-1);
negatives.remove(negatives.size()-1);
}
printAll(negatives);
printAll(positives);
printAll(nulls);
}
static void printAll(ArrayList<Integer> ar) {
System.out.print(ar.size());
for(Integer i : ar) {
System.out.print(" " + i);
}
System.out.println();
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | a565c362211b75e660b66da7e6f21847 | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes |
import java.util.Arrays;
import java.util.Scanner;
import java.util.Vector;
public class Main{
public static void main(String[] args) {
int n;
Scanner in = new Scanner(System.in);
n = in.nextInt();
int []a = new int[n];
Vector<Integer> v = new Vector<Integer>();
Vector<Integer> vv = new Vector<Integer>();
int f;
for (int i = 0; i < n; i++){
a[ i ] = in.nextInt();
}
Arrays.sort(a);
int i,j;
f = a[ 0 ];
if(a[ 1 ] < 0 && a[ 2 ] < 0){
v.add(a[ 1 ]);
v.add(a[ 2 ]);
i = 3;
j = n;
}
else {
v.add(a[ n - 1 ]);
i = 1;
j = n - 1;
}
for (int j2 = i; j2 < j; j2++) {
vv.add((int)a[ j2 ]);
}
System.out.print(1+" ");
System.out.println(f);
System.out.print(v.size()+" ");
for(int r = 0; r < v.size();r++)
System.out.print(v.elementAt(r)+" ");
System.out.println();
System.out.print(vv.size()+" ");
for(int r = 0; r < vv.size();r++)
System.out.print(vv.elementAt(r)+" ");
System.out.println();
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | d1a74c3b6debef1ea8e1a6b6a39d3ca9 | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.util.*;
import java.io.*;
public class Array
{
public static void main(String[]args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int m = Integer.parseInt(br.readLine());
int[]a=new int[m];
StringTokenizer t = new StringTokenizer(br.readLine());
for(int i=0;i<m;i++)
{
a[i]=Integer.parseInt(t.nextToken());
}
int nCount=0, pCount=0, zCount=0;
for(int i=0;i<m;i++)
{
if(a[i]<0)
nCount++;
else if(a[i]==0)
zCount++;
else
pCount++;
}
int[]n=new int[nCount];
int[]p = new int[pCount];
int[]z = new int[zCount];
int c1=0,c2=0,c3=0;
for(int i=0;i<m;i++)
{
if(a[i]<0)
n[c1++]=a[i];
else if(a[i]==0)
z[c2++]=a[i];
else
p[c3++]=a[i];
}
boolean evenN=false;
if(nCount%2==0)
evenN=true;
if(evenN==true&&pCount>0)
{
out.print(nCount-1);
for(int i=1;i<nCount;i++)
{
out.print(" "+n[i]);
}
out.println();
out.print(pCount);
for(int i=0;i<pCount;i++)
{
out.print(" "+p[i]);
}
out.println();
out.print((zCount+1)+" "+n[0]);
for(int i=0;i<zCount;i++)
{
out.print(" "+z[i]);
}
}
else if(pCount==0)
{
out.print(1);
out.print(" "+n[2]);
out.println();
out.print((pCount+2)+" "+n[0]+" "+n[1]);
out.println();
out.print((zCount+nCount-3));
for(int i=3;i<nCount;i++)
{
out.print(" "+n[i]);
}
for(int i=0;i<zCount;i++)
{
out.print(" "+z[i]);
}
}
else /*if(evenN==false)*/
{
out.print(nCount);
for(int i=0;i<nCount;i++)
{
out.print(" "+n[i]);
}
out.println();
out.print(pCount);
for(int i=0;i<pCount;i++)
{
out.print(" "+p[i]);
}
out.println();
out.print(zCount);
for(int i=0;i<zCount;i++)
{
out.print(" "+z[i]);
}
}
out.flush();
}
} | Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | 6c67bbea94254aac73d91e8542290548 | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | /* Codeforces Round #181 (Div. 2)
* Date: 25th April 2013
* Author - Arpit Gaur */
//package CodeForces;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Array {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int n = Integer.parseInt(br.readLine());
int [] num = new int[n];
int countNeg=0;int countPos=0;
st=new StringTokenizer(br.readLine());
for(int i=0;st.hasMoreTokens();i++){
num[i]=Integer.parseInt(st.nextToken());
if (num[i]<0)countNeg++;
else if (num[i]>0)countPos++;
//else if (num[i]==0)countZero++;
}
Arrays.sort(num);
System.out.println("1 "+num[0]);
StringBuilder sum=new StringBuilder("");
if (countNeg % 2 != 0) {
for(int i=1;i<n;i++){
if(num[i]!=0){
sum.append(num[i]+" ");
}
}
String s = sum.toString();
System.out.println((n-2) +" "+s.trim());
}
else {
for(int i=2;i<n;i++){
if(num[i]!=0){
sum.append(num[i]+" ");
}
}
String s = sum.toString();
System.out.println((n-3) +" "+s.trim());
}
if (countNeg % 2 != 0 ){
System.out.println("1 0");
}
else {
System.out.println("2 0 "+num[1]);
}
}
} | Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | 71080c7b87bb061a2432953a464fae09 | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 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 n = sc.nextInt();
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
Arrays.sort(a);
int i1 = 0;
int i2 = 0;
int i3 = 0;
for (int i = 0; i < n; i++) {
if(a[i] < 0) {
i1++;
}
if (a[i] > 0) {
i2++;
}
if (a[i] == 0) {
i3++;
}
}
if (i1 % 2 == 1 && i2 != 0) {
//int i11 = i1 - 1;
System.out.print(i1);
for (int i = 0; i < i1-1; i++) {
System.out.print(" " + a[i]);
}
System.out.println(" " + a[i1-1]);
System.out.print(i2);
for (int i = i1 + i3; i < n-1; i++) {
System.out.print(" " + a[i]);
}
System.out.println(" " + a[n-1]);
System.out.print(i3);
for (int i = 0; i < i3-1; i++) {
System.out.print(" " + 0);
}
System.out.println(" " + 0);
}
else if (i1 % 2 == 0 && i2 != 0) {
int i11 = i1 - 1;
System.out.print(i11);
for (int i = 1; i < i1-1; i++) {
System.out.print(" " + a[i]);
}
System.out.println(" " + a[i1 - 1]);
System.out.print(i2);
for (int i = i1 + i3; i < n - 1; i++) {
System.out.print(" " + a[i]);
}
System.out.println(" " + a[n-1]);
int i33 = i3+1;
System.out.print(i33);
for (int i = 0; i < i3; i++) {
System.out.print(" " + 0);
}
System.out.println(" " + a[0]);
}
else if (i1 % 2 == 1 && i2 == 0) {
int i11 = i1 - 2;
System.out.print(i11);
for (int i = 2; i < i1-1; i++) {
System.out.print(" " + a[i]);
}
System.out.println(" " + a[i1-1]);
System.out.print(2);
for (int i = 0; i < 1; i++) {
System.out.print(" " + a[i]);
}
System.out.println(" " + a[1]);
System.out.print(i3);
for (int i = 0; i < i3-1; i++) {
System.out.print(" " + 0);
}
System.out.println(" " + 0);
}
// else if (i1 % 2 == 1 && i2 == 0) {
// int i11 = i1 - 2;
// System.out.print(i11);
// for (int i = 2; i < i11-1; i++) {
// System.out.print(" " + a[i]);
// }
// System.out.println(" " + a[i11-1]);
//
// System.out.print(2);
// for (int i = 0; i < 1; i++) {
// System.out.print(" " + a[i]);
// }
// System.out.println(" " + a[1]);
//
// System.out.print(i3);
// for (int i = 0; i < i3-1; i++) {
// System.out.print(" " + 0);
// }
// System.out.println(" " + 0);
//
// }
else if (i1 % 2 == 0 && i2 == 0) {
System.out.print(1);
System.out.println(" " + a[0]);
System.out.print(2);
System.out.print(" " + a[1]);
System.out.println(" " + a[2]);
int i33 = n - 3;
System.out.print(i33);
for (int i = 3; i < n - 1; i++) {
System.out.print(" " + a[i]);
}
System.out.println(" " + a[n-1]);
// int i11 = i1 - 1;
// System.out.print(i11);
// for (int i = 1; i < i1; i++) {
// System.out.print(" " + a[i]);
// }
// System.out.println(" " + a[n - 1]);
//
// System.out.print(i2);
// for (int i = i1 + i3; i < n - 2; i++) {
// System.out.print(" " + a[i]);
// }
// System.out.println(" " + a[n-2]);
//
// int i33 = i3+1;
// System.out.print(i33);
// for (int i = 0; i < i3; i++) {
// System.out.print(" " + 0);
// }
// System.out.println(" " + a[0]);
}
}
} | Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | 0ee10d41ff447974fd9e82a67dbbd0c9 | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
public class Main {
static int ans = 0;
static int inf = 100100100;
public static void main(String[] args){
Scanner in = new Scanner(new BufferedInputStream(System.in));
int n = in.nextInt();
int a[] = new int[n], b[] = new int[n], c[] = new int[n], d[] = new int[n];
int x, y, z, flag = 0;
x = y = z = 0;
for(int i = 0; i < n; i++){
d[i] = in.nextInt();
if(d[i] > 0) flag = 1;
}
for(int i = 0; i < n; i++){
if(d[i] < 0 && x == 0) a[x++] = d[i];
else if(d[i] < 0 && flag == 0 && y < 2) b[y++] = d[i];
else if(d[i] > 0 && flag == 1 && y < 1) b[y++] = d[i];
else c[z++] = d[i];
}
System.out.print(x);
for(int i = 0; i < x; i++)
System.out.print(" " + a[i]);
System.out.println();
System.out.print(y);
for(int i = 0; i < y; i++)
System.out.print(" " + b[i]);
System.out.println();
System.out.print(z);
for(int i = 0; i < z; i++)
System.out.print(" " + c[i]);
System.out.println();
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | 534465bfa2de4191cedcca7b384616e3 | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class A {
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter out;
public void solve() throws IOException {
int N = nextInt();
int[]neg = new int[N];
int[] pos = new int[N];
int neg_count = 0;
int pos_count = 0;
for(int i = 0; i < N; i++){
int a = nextInt();
if( a < 0){
neg[neg_count++] = a;
}
else if( a > 0){
pos[pos_count++] = a;
}
}
out.println(1 + " " + neg[0]);
if( neg_count >= 3){
out.println(2 + " " + neg[1] + " " + neg[2]);
out.print( N - 3);
for(int i = 3; i < neg_count; i++){
out.print(" " + neg[i]);
}
for(int i = 0; i < pos_count; i++){
out.print(" " + pos[i]);
}
out.println(" " + 0);
}
else if(pos_count >= 1){
out.println(1 + " " + pos[0]);
out.print( N - 2);
for(int i = 1; i < neg_count; i++){
out.print(" " + neg[i]);
}
for(int i = 1; i < pos_count; i++){
out.print(" " + pos[i]);
}
out.println(" " + 0);
}
}
/**
* @param args
*/
public static void main(String[] args) {
new A().run();
}
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
out = new PrintWriter(System.out);
solve();
reader.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | 68ab64e4a8a58b60b03b542c82c9e24f | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.io.*;
import java.util.*;
public class A2 {
void solve() throws IOException {
in("__std"); out("__std");
int n = readInt();
List<Integer> pos = new ArrayList<Integer>();
List<Integer> neg = new ArrayList<Integer>();
List<Integer> zer = new ArrayList<Integer>();
while (n-- > 0) {
int v = readInt();
if (v > 0) {
pos.add(v);
} else if (v < 0) {
neg.add(v);
} else {
zer.add(v);
}
}
println("1 " + neg.remove(0));
if (pos.size() == 0) {
println("2 " + neg.remove(0) + " " + neg.remove(0));
} else {
print(pos.size());
for (int v : pos) print(" " + v);
println();
}
print(zer.size() + neg.size());
for (int v : zer) print(" " + v);
for (int v : neg) print(" " + v);
println();
exit();
}
void in(String name) throws IOException {
if (name.equals("__std")) {
in = new BufferedReader(new InputStreamReader(System.in));
} else {
in = new BufferedReader(new FileReader(name));
}
}
void out(String name) throws IOException {
if (name.equals("__std")) {
out = new PrintWriter(System.out);
} else {
out = new PrintWriter(name);
}
}
void exit() {
out.close();
System.exit(0);
}
char readChar() throws IOException {
return (char) in.read();
}
int readInt() throws IOException {
return Integer.parseInt(readToken());
}
long readLong() throws IOException {
return Long.parseLong(readToken());
}
double readDouble() throws IOException {
return Double.parseDouble(readToken());
}
String readLine() throws IOException {
st = null;
return in.readLine();
}
String readToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
boolean eof() throws IOException {
return !in.ready();
}
void print(String format, Object ... args) {
out.print(new Formatter(Locale.US).format(format, args));
}
void println(String format, Object ... args) {
out.println(new Formatter(Locale.US).format(format, args));
}
void print(Object value) {
out.print(value);
}
void println(Object value) {
out.println(value);
}
void println() {
out.println();
}
StringTokenizer st;
BufferedReader in;
PrintWriter out;
public static void main(String[] args) throws IOException {
new A2().solve();
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | 39b44bd2b6ec2f65480ee7c1333a253a | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes |
import java.io.BufferedInputStream;
import java.util.*;
import static java.lang.Math.*;
public class C300A {
boolean allowedDebug = true;
public void solve() throws Exception {
int n = ni();
Queue<Integer>[] set = new LinkedList[3];
for (int i = 0; i < set.length; i++) {
set[i] = new LinkedList<Integer>();
}
for (int i = 0; i < n; i++) {
int a = ni();
if (a == 0) {
set[2].add(a);
} else {
if (a < 0) {
set[0].add(a);
} else {
set[1].add(a);
}
}
}
if (set[1].isEmpty()) {
set[1].add(set[0].poll());
set[1].add(set[0].poll());
}
if (set[0].size() % 2 == 0) {
set[2].add(set[0].poll());
}
for (int i = 0; i < set.length; i++) {
print(set[i].size());
while(!set[i].isEmpty()) {
print(" " + set[i].poll());
}
println();
}
}
// ------------------------------------------------------
void debug(Object... o) {
if (allowedDebug) {
System.err.println(Arrays.deepToString(o));
}
}
void print(Object... os) {
if (os != null && os.length > 0)
System.out.print(os[0].toString());
for (int i = 1; i < os.length; ++i)
System.out.print(" " + os[i].toString());
}
void println(Object... os) {
print(os);
System.out.println();
}
BufferedInputStream bis = new BufferedInputStream(System.in);
String nextWord() throws Exception {
char c = (char) bis.read();
while (c <= ' ')
c = (char) bis.read();
StringBuilder sb = new StringBuilder();
while (c > ' ') {
sb.append(c);
c = (char) bis.read();
}
return new String(sb);
}
String nextLine() throws Exception {
char c = (char) bis.read();
while (c <= ' ')
c = (char) bis.read();
StringBuilder sb = new StringBuilder();
while (c != '\n' && c != '\r') {
sb.append(c);
c = (char) bis.read();
}
return new String(sb);
}
int ni() throws Exception {
return Integer.parseInt(nextWord());
}
long nl() throws Exception {
return Long.parseLong(nextWord());
}
public static void main(String[] args) throws Exception {
new C300A().solve();
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | b83d0d9acac6277c5e4f59c1f146018f | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.util.ArrayList;
import java.util.Scanner;
/*
http://codeforces.com/problemset/problem/300/A
Sample test(s)
input
3
-1 2 0
output
1 -1
1 2
1 0
input
4
-1 -2 -3 0
output
1 -1
2 -3 -2
1 0
*/
public class Array {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int numElems = s.nextInt();
ArrayList<Integer> negatives = new ArrayList<Integer>();
ArrayList<Integer> positives = new ArrayList<Integer>();
ArrayList<Integer> firstSet = new ArrayList<Integer>();
ArrayList<Integer> secondSet = new ArrayList<Integer>();
ArrayList<Integer> thirdSet = new ArrayList<Integer>();
thirdSet.add(0);
for(int a = 0; a < numElems; a++){
int tmp = s.nextInt();
if(tmp < 0) negatives.add(tmp);
if(tmp > 0) positives.add(tmp);
}
if(positives.size() == 0){
secondSet.add(negatives.remove(0));
secondSet.add(negatives.remove(1));
}
if(negatives.size() % 2 == 0){
thirdSet.add(negatives.remove(0));
}
firstSet.addAll(negatives);
secondSet.addAll(positives);
print(firstSet);
print(secondSet);
print(thirdSet);
}
private static void print(ArrayList<Integer> set) {
System.out.print(set.size());
for(int a = 0; a < set.size(); a++){
System.out.print(" " + set.get(a));
}
System.out.println();
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | 5cd93b083b14a6c8d848df661ea11b21 | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | /**
* Created with IntelliJ IDEA.
* User: yuantian
* Date: 4/25/13
* Time: 10:31 AM
* Copyright (c) 2013 All Right Reserved, http://github.com/tyuan73
*/
import java.util.*;
public class Array181Div2 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] a = new int[n];
int countNeg = 0;
int countZero = 0;
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
if (a[i] < 0)
countNeg++;
if (a[i] == 0)
countZero++;
}
Arrays.sort(a);
System.out.println(1 + " " + a[0]);
if (countNeg % 2 == 0) {
countNeg--;
countZero++;
}
System.out.print(n - 1 - countZero);
for (int i = 1; i < countNeg; i++)
System.out.print(" " + a[i]);
for (int i = countNeg + countZero; i < n; i++)
System.out.print(" " + a[i]);
System.out.println();
System.out.print(countZero);
for (int i = countNeg; i < countNeg + countZero; i++) {
System.out.print(" " + a[i]);
}
System.out.println();
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | 606a8f2541f95750f7e14462352a577d | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes |
//package massa181;
import java.util.Arrays;
import java.util.Scanner;
import java.io.*;
import java.util.*;
public class MassA181 {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
ArrayList<Integer> amin = new ArrayList<Integer>();
ArrayList<Integer> aplu = new ArrayList<Integer>();
ArrayList<Integer> anul = new ArrayList<Integer>();
int a = 0;
for(int i = 0; i < n; i++) {
a = cin.nextInt();
if(a < 0) {
amin.add(a);
}
if(a > 0) {
aplu.add(a);
}
if(a == 0) {
anul.add(a);
}
}
int h = 0, k = 0;
if(amin.size() >= 3) {
aplu.add(amin.remove(amin.size() - 1));
aplu.add(amin.remove(amin.size() - 1));
}
if(amin.size() % 2 == 0) {
anul.add(amin.remove(amin.size() - 1));
}
//---------------------
System.out.print(amin.size() + " "); // <0
for (int i = 0; i < amin.size(); i++) {
System.out.print(amin.get(i) + " ");
}
System.out.println();
System.out.print(aplu.size() + " "); // >0
for (int i = 0; i < aplu.size(); i++) {
System.out.print(aplu.get(i) + " ");
}
System.out.println();
System.out.print(anul.size() + " ");
for (int i = 0; i < anul.size(); i++) {
System.out.print(anul.get(i) + " ");
}
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | 033b5cac8f981c3b1d16ac1d50bac57b | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.awt.datatransfer.StringSelection;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.TreeSet;
public class A {
static Scanner in; static int next() throws Exception {return in.nextInt();};
// static StreamTokenizer in; static int next() throws Exception {in.nextToken(); return (int) in.nval;}
// static BufferedReader in;
static PrintWriter out;
public static void main(String[] args) throws Exception {
in = new Scanner(System.in);
// in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
// in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
int n = next();
int a[] = new int[n];
ArrayList<Integer> plus = new ArrayList<Integer>();
ArrayList<Integer> zero = new ArrayList<Integer>();
ArrayList<Integer> minus = new ArrayList<Integer>();
for (int i = 0;i < n;i++) {
a[i] = next();
if (a[i] > 0) plus.add(a[i]);
if (a[i] == 0) zero.add(a[i]);
if (a[i] < 0) minus.add(a[i]);
}
out.println(1 + " " + minus.get(0));
minus.remove(0);
if (plus.size() > 0) { out.print(plus.size() + " ");
for (int i = 0;i < plus.size();i++) out.print(plus.get(i) + " ");
out.println();
out.print(minus.size()+zero.size() + " ");
for (int i = 0;i < minus.size();i++) out.print(minus.get(i) + " ");
for (int i = 0;i < zero.size();i++) out.print("0 ");
out.println();
} else {
out.print(2 + " ");
out.println(minus.get(minus.size()-2) + " " + minus.get(minus.size()-1));
out.print(minus.size()+zero.size()-2 + " ");
for (int i = 0;i < minus.size()-2;i++) out.print(minus.get(i) + " ");
for (int i = 0;i < zero.size();i++) out.print("0 "); out.println();
}
out.println();
out.close();
}
} | Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | b2bf924ba15b0c3dbdd071af7d231e10 | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
int k,x=0,y=0,z=0;
int n=scan.nextInt();
int[][] a = new int[3][n];
for(int i=0;i<n;i++){
k=scan.nextInt();
if(k==0) x++;
else
if(k>0) a[0][y++]=k;
else
a[1][z++]=k;
}
if(y==0){
y+=2; a[0][0]=a[1][z-1]; a[0][1]=a[1][z-2]; z+=-2;}
if(z%2==0){
a[2][x-1]=a[1][z-1]; x++; z--;}
System.out.print(z+" ");
for(int i=0;i<z;i++)
System.out.print(a[1][i]+" ");
System.out.println();
System.out.print(y+" ");
for(int i=0;i<y;i++)
System.out.print(a[0][i]+" ");
System.out.println();
System.out.print(x+" ");
for(int i=0;i<x;i++)
System.out.print(a[2][i]+" ");
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | 8fadd7781acc43cfeb1770d142275007 | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
/**
*
* @author anton
*/
public class Mass {
public static void main(String[] args) throws IOException {
new Mass().start();
}
BufferedReader in;
public void start() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine());
StringTokenizer st = new StringTokenizer(in.readLine());
int[] m = new int[n];
int i = 0;
while (i++ < n) {
m[i-1]=Integer.parseInt(st.nextToken());
}
int[] r1,r2,r3;
Arrays.sort(m);
if(m[n-1]==0){
i=0;
r1=new int[1];
r2=new int[2];
r3=new int[n-3];
r1[0]=m[0];
r2[0]=m[n-2];
r2[1]=m[n-3];
for(int j=1;j<n-3;j++){
r3[i++]=m[j];
}
}else{
r1=new int[1];
r2=new int[1];
r3=new int[n-2];
r1[0]=m[0];
r2[0]=m[n-1];
r3=Arrays.copyOfRange(m, 1, n-1);
}
System.out.println(r1.length+" "+str(r1));
System.out.println(r2.length+" "+str(r2));
System.out.println(r3.length+" "+str(r3));
}
public String str(int[] m){
StringBuilder sb = new StringBuilder();
for(int i:m){
sb.append(i+" ");
}
return sb.toString();
}
} | Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | 38555a526543a01d1c50337fe039580b | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main{
public static void main(String[]args) throws NumberFormatException, IOException {
BufferedReader x=new BufferedReader(new InputStreamReader(System.in));
String s=x.readLine();
String w=x.readLine();
String[]array=w.split(" ");
// System.out.println(array.length);
int n=Integer.parseInt(s);
int[]IntArray=new int[array.length];
int[]tempArray=new int[array.length];
int[]firstSet=new int[n];
int[]secondSet=new int[n];
int[]thirdSet=new int[n];
int result=1;
int pos=0;
int neg=0;
for(int i=0;i<n;i++){
IntArray[i]=Integer.parseInt(array[i]);
tempArray[i]=Integer.parseInt(array[i]);
}
for(int i=0;i<n;i++){
if(IntArray[i]>0){
pos=IntArray[i];
tempArray[i]=0;
break;
}}
for(int i=0;i<n;i++){
if(IntArray[i]<0){
neg=IntArray[i];
tempArray[i]=0;
break;
}}
if(pos==0){
firstSet[0]=1;
firstSet[1]=neg;
int j=0;
int k=0;
int first=0;
int second=0;
for( k=0;k<IntArray.length;k++){
for( j=0;j<IntArray.length;j++){
if(tempArray[k]!=0&&tempArray[j]!=0&&(IntArray[k]*IntArray[j]>0)&&k!=j){
pos=IntArray[k]*IntArray[j];
tempArray[k]=0;
tempArray[j]=0;
first=IntArray[k];
second=IntArray[j];
break;} }
if(pos!=0){
break;
}
}
secondSet[0]=2;
secondSet[1]=first;
secondSet[2]=second;
}
else if(neg==0){
secondSet[0]=1;
secondSet[1]=pos;
int j=0;
int k=0;
for(k=0;k<IntArray.length;k++){
for(j=0;j<IntArray.length;j++){
if(tempArray[k]!=0&&tempArray[j]!=0&&(IntArray[k]*IntArray[j]<0)){
neg=IntArray[k]*IntArray[j];
tempArray[k]=0;
tempArray[j]=0;
break;}
}
break;
}
firstSet[0]=2;
firstSet[1]=IntArray[k];
firstSet[2]=IntArray[j];
}
else {
firstSet[0]=1;
secondSet[0]=1;
firstSet[1]=neg;
secondSet[1]=pos;
}
int j=1;
int num=1;
for(int h=0;h<IntArray.length;h++){
if(tempArray[h]!=0){
thirdSet[j]=IntArray[h];
j++;
num++;
}}
thirdSet[j]=0;
thirdSet[0]=num;
if(firstSet[0]==1){
System.out.println("1 "+firstSet[1]);
}
else {
System.out.println("2 "+firstSet[1]+" "+firstSet[2]);
}
if(secondSet[0]==1){
System.out.println("1 "+secondSet[1]);
}
else {
System.out.println("2 "+secondSet[1]+" "+secondSet[2]);
}
int f=1;
int r=thirdSet[0];
System.out.print(r+" ");
while(r>0){
System.out.print(thirdSet[f]+" ");
f++;
r--;
}
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | 691647dc1494aaec1fd93c70432f789a | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.util.*;
public class P300A {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
ArrayList<Integer> positive = new ArrayList<Integer>();
ArrayList<Integer> negative = new ArrayList<Integer>();
int zero = 0;
for(int counter = 0; counter < n; counter ++){
int current = in.nextInt();
if(current < 0)
negative.add(current);
else if (current > 0)
positive.add(current);
else
zero ++;
}
if(negative.size() <= 2){
System.out.println("1 " + negative.get(0));
System.out.print(positive.size() + " ");
for(int i : positive)
System.out.print(i + " ");
System.out.println();
System.out.print((zero - 1 + negative.size()) + " ");
for(int counter = 0; counter < zero; counter ++)
System.out.print("0 ");
if(negative.size() > 1)
System.out.println(negative.get(1));
}
else{
System.out.println("1 " + negative.get(0));
System.out.print(positive.size() + 2);
System.out.print(" " + negative.get(1) + " " + negative.get(2) + " ");
for(int counter = 0; counter < positive.size(); counter ++)
System.out.print(positive.get(counter) + " ");
System.out.println();
System.out.print((zero + negative.size() - 3) + " ");
for(int counter = 0; counter < zero; counter ++)
System.out.print("0 ");
for(int counter = 3; counter < negative.size(); counter ++)
System.out.print(negative.get(counter) + " ");
}
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | c75bc622f599ee3992b5f069e53d1917 | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
ArrayList<Integer> pos = new ArrayList<Integer>();
ArrayList<Integer> neg = new ArrayList<Integer>();
ArrayList<Integer> zero = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
int t = in.nextInt();
if (t < 0)
neg.add(t);
else if (t > 0)
pos.add(t);
else
zero.add(t);
}
if (neg.size() % 2 == 0) {
zero.add(neg.remove(0));
}
if (pos.size() == 0) {
pos.add(neg.remove(0));
pos.add(neg.remove(0));
}
String ans1 = "";
String ans2 = "";
String ans3 = "";
ans1 += (neg.size()) + " ";
ans2 += (pos.size()) + " ";
ans3 += (zero.size()) + " ";
for (int i = 0; i < neg.size(); i++)
ans1 += ((neg.get(i)) + " ");
for (int i = 0; i < pos.size(); i++)
ans2 += ((pos.get(i)) + " ");
for (int i = 0; i < zero.size(); i++)
ans3 += ((zero.get(i)) + " ");
System.out.println(ans1.trim());
System.out.println(ans2.trim());
System.out.println(ans3.trim());
pos.clear();
neg.clear();
zero.clear();
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | 85c0879b03b04cfca871f45403e7a730 | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.util.ArrayList;
import java.util.Scanner;
public class Array {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
ArrayList<Integer> nve = new ArrayList<Integer>();
// int ngv = 0;
ArrayList<Integer> pve = new ArrayList<Integer>();
// int psv = 0;
ArrayList<Integer> zrs = new ArrayList<Integer>();
// int zros = 0;
for(int i = 0; i < n; i++) {
if(a[i] > 0) {
pve.add(a[i]);
}
else if(a[i] < 0) {
nve.add(a[i]);
}
else {
zrs.add(a[i]);
}
}
if(pve.size() == 0 ) {
if(nve.size() != 1) {
if(nve.size()%2 != 0) {
pve.add(nve.remove(nve.size()-1));
pve.add(nve.remove(nve.size()-2));
}
else {
if(zrs.size() != 0 && nve.size() > 2) {
pve.add(nve.remove(0));
pve.add(nve.remove(0));
zrs.add(nve.remove(0));
}
}
}
}
else if(nve.size()%2 == 0) {
if(zrs.size()!=0)
zrs.add(nve.remove(0));
else {
while(!nve.isEmpty())
pve.add(nve.remove(nve.size()-1));
}
}
if(nve.size() != 0)
System.out.print(nve.size()+" ");
while(!nve.isEmpty())
System.out.print(nve.remove(nve.size()-1)+" ");
if(pve.size() != 0) {
System.out.println();
System.out.print(pve.size()+" ");
}
while(!pve.isEmpty())
System.out.print(pve.remove(pve.size()-1)+" ");
if(zrs.size() != 0) {
System.out.println();
System.out.print(zrs.size()+" ");
}
while(!zrs.isEmpty())
System.out.print(zrs.remove(zrs.size()-1)+" ");
}
} | Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | 21897643fdfca35f81f08894e18efcf6 | train_003.jsonl | 1366903800 | Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: The product of all numbers in the first set is less than zero (β<β0). The product of all numbers in the second set is greater than zero (β>β0). The product of all numbers in the third set is equal to zero. Each number from the initial array must occur in exactly one set. Help Vitaly. Divide the given array. | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr [] = new int[n];
for(int i = 0; i<n; i++) arr[i] = sc.nextInt();
Arrays.sort(arr);
ArrayList<Integer> pl = new ArrayList<Integer>();
ArrayList<Integer> zl = new ArrayList<Integer>();
ArrayList<Integer> nl = new ArrayList<Integer>();
for(int i = 0; i<n; i++) {
if(arr[i] < 0) nl.add(arr[i]);
else if(arr[i] == 0) zl.add(arr[i]);
else pl.add(arr[i]);
}
if(pl.size() == 0) {
pl.add(nl.remove(0));
pl.add(nl.remove(0));
}
if(nl.size() % 2 == 0) {
zl.add(nl.remove(0));
}
print(nl);
print(pl);
print(zl);
sc.close();
}
private static void print(ArrayList<Integer> nl) {
System.out.print(nl.size());
for(int i = 0; i<nl.size(); i++) System.out.print(" " + nl.get(i));
System.out.println();
}
}
| Java | ["3\n-1 2 0", "4\n-1 -2 -3 0"] | 2 seconds | ["1 -1\n1 2\n1 0", "1 -1\n2 -3 -2\n1 0"] | null | Java 6 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | 03cf2cc26c84aab685ee78a1d6318b30 | The first line of the input contains integer n (3ββ€βnββ€β100). The second line contains n space-separated distinct integers a1,βa2,β...,βan (|ai|ββ€β103) β the array elements. | 1,100 | In the first line print integer n1 (n1β>β0) β the number of elements in the first set. Then print n1 numbers β the elements that got to the first set. In the next line print integer n2 (n2β>β0) β the number of elements in the second set. Then print n2 numbers β the elements that got to the second set. In the next line print integer n3 (n3β>β0) β the number of elements in the third set. Then print n3 numbers β the elements that got to the third set. The printed sets must meet the described conditions. It is guaranteed that the solution exists. If there are several solutions, you are allowed to print any of them. | standard output | |
PASSED | 8ffa50e13916814e4398ca1ecd12867a | train_003.jsonl | 1568554500 | Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift $$$X[i]$$$ grams on day $$$i$$$. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in and it will improve his performance by $$$A$$$ grams permanently and immediately. In different gyms these pre-workout drinks can cost different amounts $$$C[i]$$$ because of the taste and the gym's location but its permanent workout gains are the same. Before the first day of starting his workout plan, Alan knows he can lift a maximum of $$$K$$$ grams. Help Alan spend a minimum total amount of money in order to reach his workout plan. If there is no way for him to complete his workout plan successfully output $$$-1$$$. | 256 megabytes | // practice with kaiboy
import java.io.*;
import java.util.*;
public class CF1219D extends PrintWriter {
CF1219D() { super(System.out, true); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF1219D o = new CF1219D(); o.main(); o.flush();
}
int[] cc, iq;
int[] pq; int cnt;
boolean les(int u, int v) { return cc[u] < cc[v]; }
int i2(int i) {
return (i *= 2) > cnt ? 0 : i < cnt && les(pq[i + 1], pq[i]) ? i + 1 : i;
}
void pq_up(int u) {
int i, j, v;
for (i = iq[u]; (j = i / 2) > 0 && les(u, v = pq[j]); i = j)
pq[iq[v] = i] = v;
pq[iq[u] = i] = u;
}
void pq_dn(int u) {
int i, j, v;
for (i = iq[u]; (j = i2(i)) > 0 && les(v = pq[j], u); i = j)
pq[iq[v] = i] = v;
pq[iq[u] = i] = u;
}
void pq_add(int u) {
iq[u] = ++cnt; pq_up(u);
}
int pq_remove_first() {
int u = pq[1], v = pq[cnt--];
if (v != u) {
iq[v] = 1; pq_dn(v);
}
iq[u] = 0;
return u;
}
void main() {
int n = sc.nextInt();
int k = sc.nextInt();
int[] xx = new int[n];
for (int i = 0; i < n; i++)
xx[i] = sc.nextInt();
int a = sc.nextInt();
cc = new int[n];
for (int i = 0; i < n; i++)
cc[i] = sc.nextInt();
iq = new int[n];
pq = new int[1 + n];
long ans = 0;
for (int i = 0; i < n; i++) {
pq_add(i);
while (k < xx[i]) {
if (cnt == 0) {
println(-1);
return;
}
int j = pq_remove_first();
ans += cc[j];
k += a;
}
}
println(ans);
}
}
| Java | ["5 10000\n10000 30000 30000 40000 20000\n20000\n5 2 8 3 6", "5 10000\n10000 40000 30000 30000 20000\n10000\n5 2 8 3 6"] | 1 second | ["5", "-1"] | NoteFirst example: After buying drinks on days 2 and 4 Alan can finish his workout plan. Second example: Alan cannot lift 40000 grams on day 2. | Java 11 | standard input | [
"data structures",
"greedy"
] | 71c2be7a502917395ad83b375b3ddad6 | The first one contains two integer numbers, integers $$$N$$$ $$$(1 \leq N \leq 10^5)$$$ and $$$K$$$ $$$(1 \leq K \leq 10^5)$$$ β representing number of days in the workout plan and how many grams he can lift before starting his workout plan respectively. The second line contains $$$N$$$ integer numbers $$$X[i]$$$ $$$(1 \leq X[i] \leq 10^9)$$$ separated by a single space representing how many grams Alan wants to lift on day $$$i$$$. The third line contains one integer number $$$A$$$ $$$(1 \leq A \leq 10^9)$$$ representing permanent performance gains from a single drink. The last line contains $$$N$$$ integer numbers $$$C[i]$$$ $$$(1 \leq C[i] \leq 10^9)$$$ , representing cost of performance booster drink in the gym he visits on day $$$i$$$. | 1,500 | One integer number representing minimal money spent to finish his workout plan. If he cannot finish his workout plan, output -1. | standard output | |
PASSED | 4fd095746b9b92bf149845a4baf82f85 | train_003.jsonl | 1538931900 | You are given $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$. Each of $$$a_i$$$ has between $$$3$$$ and $$$5$$$ divisors. Consider $$$a = \prod a_i$$$Β β the product of all input integers. Find the number of divisors of $$$a$$$. As this number may be very large, print it modulo prime number $$$998244353$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static class Scan {
private byte[] buf=new byte[1024];
private int index;
private InputStream in;
private int total;
public Scan()
{
in=System.in;
}
public int scan()throws IOException
{
if(total<0)
throw new InputMismatchException();
if(index>=total)
{
index=0;
total=in.read(buf);
if(total<=0)
return -1;
}
return buf[index++];
}
public int scanInt()throws IOException
{
int integer=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
integer*=10;
integer+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
return neg*integer;
}
public double scanDouble()throws IOException
{
double doub=0;
int n=scan();
while(isWhiteSpace(n))
n=scan();
int neg=1;
if(n=='-')
{
neg=-1;
n=scan();
}
while(!isWhiteSpace(n)&&n!='.')
{
if(n>='0'&&n<='9')
{
doub*=10;
doub+=n-'0';
n=scan();
}
else throw new InputMismatchException();
}
if(n=='.')
{
n=scan();
double temp=1;
while(!isWhiteSpace(n))
{
if(n>='0'&&n<='9')
{
temp/=10;
doub+=(n-'0')*temp;
n=scan();
}
else throw new InputMismatchException();
}
}
return doub*neg;
}
public String scanString()throws IOException
{
StringBuilder sb=new StringBuilder();
int n=scan();
while(isWhiteSpace(n))
n=scan();
while(!isWhiteSpace(n))
{
sb.append((char)n);
n=scan();
}
return sb.toString();
}
private boolean isWhiteSpace(int n)
{
if(n==' '||n=='\n'||n=='\r'||n=='\t'||n==-1)
return true;
return false;
}
}
public static void sort(int arr[],int l,int r) { //sort(arr,0,n-1);
if(l==r) {
return;
}
int mid=(l+r)/2;
sort(arr,l,mid);
sort(arr,mid+1,r);
merge(arr,l,mid,mid+1,r);
}
public static void merge(int arr[],int l1,int r1,int l2,int r2) {
int tmp[]=new int[r2-l1+1];
int indx1=l1,indx2=l2;
//sorting the two halves using a tmp array
for(int i=0;i<tmp.length;i++) {
if(indx1>r1) {
tmp[i]=arr[indx2];
indx2++;
continue;
}
if(indx2>r2) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
if(arr[indx1]<arr[indx2]) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
tmp[i]=arr[indx2];
indx2++;
}
//Copying the elements of tmp into the main array
for(int i=0,j=l1;i<tmp.length;i++,j++) {
arr[j]=tmp[i];
}
}
public static void sort(long arr[],int l,int r) { //sort(arr,0,n-1);
if(l==r) {
return;
}
int mid=(l+r)/2;
sort(arr,l,mid);
sort(arr,mid+1,r);
merge(arr,l,mid,mid+1,r);
}
public static void merge(long arr[],int l1,int r1,int l2,int r2) {
long tmp[]=new long[r2-l1+1];
int indx1=l1,indx2=l2;
//sorting the two halves using a tmp array
for(int i=0;i<tmp.length;i++) {
if(indx1>r1) {
tmp[i]=arr[indx2];
indx2++;
continue;
}
if(indx2>r2) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
if(arr[indx1]<arr[indx2]) {
tmp[i]=arr[indx1];
indx1++;
continue;
}
tmp[i]=arr[indx2];
indx2++;
}
//Copying the elements of tmp into the main array
for(int i=0,j=l1;i<tmp.length;i++,j++) {
arr[j]=tmp[i];
}
}
public static void main(String args[]) throws IOException {
Scanner input=new Scanner(System.in);
int n=input.nextInt();
long arr[]=new long[n];
for(int i=0;i<n;i++) {
arr[i]=input.nextLong();
// arr[i]=(long)(Math.random()*100);
// if(check(1,new long[]{arr[i]})<3 || check(1,new long[]{arr[i]})>5) {
// i--;
// continue;
// }
// System.out.print(arr[i]+" ");
}
// System.out.println();
// long check=check(n,arr);
Set<Long> hashset=new HashSet<>();
for(int i=0;i<n;i++) {
long s4=search4(arr[i]);
if(s4!=-1) {
if(!hashset.contains(s4)) {
hashset.add(s4);
}
continue;
}
s4=search3(arr[i]);
if(s4!=-1) {
if(!hashset.contains(s4)) {
hashset.add(s4);
}
continue;
}
s4=search2(arr[i]);
if(s4!=-1) {
if(!hashset.contains(s4)) {
hashset.add(s4);
}
continue;
}
for(int j=i+1;j<n;j++) {
long gcd=gcd(arr[i],arr[j]);
if(gcd==arr[i] || gcd==1 || hashset.contains(gcd)) {
continue;
}
hashset.add(gcd);
}
}
long div[]=new long[hashset.size()];
int indx=0;
Iterator<Long> itr = hashset.iterator();
while (itr.hasNext()) {
div[indx]=itr.next();
indx++;
}
long freq[]=new long[div.length];
long times[]=new long[n];
for(int i=0;i<n;i++) {
for(int j=0;j<div.length;j++) {
boolean done=false;
while(arr[i]%div[j]==0) {
freq[j]++;
done=true;
arr[i]/=div[j];
}
if(done) {
times[i]++;
}
}
}
long ans=1,mod=998244353;
for(int i=0;i<n;i++) {
if(arr[i]==1) {
continue;
}
long cnt=1;
for(int j=i+1;j<n;j++) {
if(arr[j]==arr[i]) {
cnt++;
}
}
if(cnt==1) {
continue;
}
if(times[i]==0) {
ans*=(cnt+1)*(cnt+1);
}
else {
ans*=(cnt+1);
}
for(int j=i+1;j<n;j++) {
if(arr[j]==arr[i]) {
arr[j]=1;
}
}
arr[i]=1;
ans%=mod;
}
for(int i=0;i<n;i++) {
if(arr[i]==1) {
continue;
}
if(times[i]==0) {
ans*=2*2;
}
else {
ans*=2;
}
ans%=mod;
}
for(int i=0;i<freq.length;i++) {
ans*=(freq[i]+1);
ans%=mod;
}
// for(int i=0;i<n;i++) {
// System.out.print(arr[i]+" ");
// }
// System.out.println();
// for(int i=0;i<div.length;i++) {
// System.out.println(div[i]+" "+freq[i]);
// }
// System.out.println();
System.out.println(ans);
System.out.flush();
}
public static long check(int n,long arr[]) {
long mul=1;
for(int i=0;i<n;i++) {
mul*=arr[i];
}
long ans=0;
for(long i=1;i<=(long)Math.sqrt(mul);i++) {
if(mul%i!=0) {
continue;
}
if(mul/i==i) {
ans++;
}
else {
ans+=2;
}
}
return ans;
}
public static long gcd(long a,long n) {
long q,r1=n,r2=a,r,t1=0,t2=1,t;
while(true) {
q=r1/r2;
r=r1%r2;
t=t1-(q*t2);
r1=r2;
r2=r;
t1=t2;
t2=t;
if(r2==0) {
break;
}
}
return r1;
}
public static long search2(long n) {
// System.out.println(2222);
long l=1,r=2000000000;
while(l<=r) {
long mid=(l+r)/2;
long val=mid*mid;
if(val==n) {
return mid;
}
if(val<n) {
l=mid+1;
}
else {
r=mid-1;
}
}
return -1;
}
public static long search3(long n) {
// System.out.println(3333);
long l=1,r=1300000;
while(l<=r) {
long mid=(l+r)/2;
long val=mid*mid*mid;
if(val==n) {
return mid;
}
if(val<n) {
l=mid+1;
}
else {
r=mid-1;
}
}
return -1;
}
public static long search4(long n) {
// System.out.println(4444);
long l=1,r=40000;
while(l<=r) {
long mid=(l+r)/2;
long val=mid*mid;
val*=val;
// System.out.println(val+" "+n);
if(val==n) {
return mid;
}
if(val<n) {
l=mid+1;
}
else {
r=mid-1;
}
}
return -1;
}
}
| Java | ["3\n9\n15\n143", "1\n7400840699802997", "8 \n4606061759128693\n4606066102679989\n4606069767552943\n4606063116488033\n4606063930903637\n4606064745319241\n4606063930904021\n4606065559735517", "3\n4\n8\n16"] | 1 second | ["32", "4", "1920", "10"] | NoteIn the first case, $$$a = 19305$$$. Its divisors are $$$1, 3, 5, 9, 11, 13, 15, 27, 33, 39, 45, 55, 65, 99, 117, 135, 143, 165, 195, 297, 351, 429, 495, 585, 715, 1287, 1485, 1755, 2145, 3861, 6435, 19305$$$Β β a total of $$$32$$$.In the second case, $$$a$$$ has four divisors: $$$1$$$, $$$86028121$$$, $$$86028157$$$, and $$$7400840699802997 $$$.In the third case $$$a = 202600445671925364698739061629083877981962069703140268516570564888699 375209477214045102253766023072401557491054453690213483547$$$.In the fourth case, $$$a=512=2^9$$$, so answer equals to $$$10$$$. | Java 11 | standard input | [
"interactive",
"number theory",
"math"
] | 4ca7837d1ddf80f0bde4aac2fb37d60b | The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 500$$$)Β β the number of numbers. Each of the next $$$n$$$ lines contains an integer $$$a_i$$$ ($$$1 \leq a_i \leq 2\cdot 10^{18}$$$). It is guaranteed that the number of divisors of each $$$a_i$$$ is between $$$3$$$ and $$$5$$$. | 2,000 | Print a single integer $$$d$$$Β β the number of divisors of the product $$$a_1 \cdot a_2 \cdot \dots \cdot a_n$$$ modulo $$$998244353$$$. Hacks input For hacks, the input needs to be provided in a special format. The first line contains an integer $$$n$$$Β ($$$1 \leq n \leq 500$$$)Β β the number of numbers. Each of the next $$$n$$$ lines contains a prime factorization of $$$a_i$$$. The line contains an integer $$$k_i$$$Β ($$$2 \leq k_i \leq 4$$$)Β β the number of prime factors of $$$a_i$$$ and $$$k_i$$$ integers $$$p_{i,j}$$$Β ($$$2 \leq p_{i,j} \leq 2 \cdot 10^{18}$$$) where $$$p_{i,j}$$$ is the $$$j$$$-th prime factor of $$$a_i$$$. Before supplying the input to the contestant, $$$a_i = \prod p_{i,j}$$$ are calculated. Note that each $$$p_{i,j}$$$ must be prime, each computed $$$a_i$$$ must satisfy $$$a_i \leq 2\cdot10^{18}$$$ and must have between $$$3$$$ and $$$5$$$ divisors. The contestant will be given only $$$a_i$$$, and not its prime factorization. For example, you need to use this test to get the first sample: 32 3 32 3 52 11 13 | standard output | |
PASSED | 68a17e2817433de6a798549e074dc0d3 | train_003.jsonl | 1538931900 | You are given $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$. Each of $$$a_i$$$ has between $$$3$$$ and $$$5$$$ divisors. Consider $$$a = \prod a_i$$$Β β the product of all input integers. Find the number of divisors of $$$a$$$. As this number may be very large, print it modulo prime number $$$998244353$$$. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.FileReader;
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;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
DDivisors solver = new DDivisors();
solver.solve(1, in, out);
out.close();
}
static class DDivisors {
ArrayList<Integer> primes;
boolean[] isPrime;
long base;
int mod = 998244353;
public void seive(int x) {
isPrime = new boolean[x];
Arrays.fill(isPrime, true);
isPrime[0] = isPrime[1] = false;
for (int i = 2; i * i <= isPrime.length; i++)
if (isPrime[i])
for (int j = i * i; j < isPrime.length; j += i)
isPrime[j] = false;
primes = new ArrayList<>();
for (int i = 2; i < isPrime.length; i++)
if (isPrime[i])
primes.add(i);
}
public void solve(int testNumber, Scanner sc, PrintWriter pw) {
seive((int) 1e5);
int n = sc.nextInt();
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = sc.nextLong();
HashMap<Long, Integer> count = new HashMap<>();
ArrayList<Long> list = new ArrayList<>();
HashMap<Long, Integer> freq = new HashMap<>();
for (int i = 0; i < n; i++) {
int pow = -1;
for (int j = 2; j <= 4; j++) {
if (bs(arr[i], j)) {
pow = j;
break;
}
}
if (pow != -1)
count.put(base, count.getOrDefault(base, 0) + pow);
else {
if (!freq.containsKey(arr[i])) {
list.add(arr[i]);
freq.put(arr[i], 1);
} else {
freq.put(arr[i], freq.get(arr[i]) + 1);
}
}
}
boolean[] vis = new boolean[list.size()];
for (int i = 0; i < list.size(); i++) {
long temp = list.get(i);
for (int j = 0; j < n; j++) {
if (temp == arr[j])
continue;
long gcd = gcd(arr[j], list.get(i));
if (gcd != 1) {
count.put(gcd, count.getOrDefault(gcd, 0) + freq.get(temp));
vis[i] = true;
list.set(i, list.get(i) / gcd);
freq.put(list.get(i), freq.getOrDefault(list.get(i), 0) + freq.get(temp));
}
}
if (vis[i])
freq.remove(temp);
}
long ans = 1;
for (int value : count.values()) {
ans *= (value + 1);
ans %= mod;
}
for (int i = 0; i < list.size(); i++) {
if (vis[i] && list.get(i) != 1) {
ans *= (freq.get(list.get(i)) + 1);
ans %= mod;
} else if (!vis[i]) {
ans *= (freq.get(list.get(i)) + 1);
ans %= mod;
ans *= (freq.get(list.get(i)) + 1);
ans %= mod;
}
}
pw.println(ans);
}
public long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
private boolean bs(long x, int p) {
long[] h = new long[]{(long) 2e9, (long) 2e6, (long) 8e4};
long low = 0, high = h[p - 2];
long b = -1;
while (low <= high) {
long mid = (low + high) / 2;
if (pow(mid, p) == x) {
b = mid;
break;
} else if (pow(mid, p) < x) {
low = mid + 1;
} else
high = mid - 1;
}
if (b == -1)
return false;
base = b;
return isPrime(base);
}
private boolean isPrime(long x) {
int idx = 0, p = primes.get(idx++);
boolean f = true;
while (1l * p * p <= x) {
while (x % p == 0) {
f = false;
x /= p;
}
p = primes.get(idx++);
}
if (x == 1)
return false;
return f;
}
private long pow(long num, long p) {
if (p == 0)
return 1;
return num * pow(num, p - 1);
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["3\n9\n15\n143", "1\n7400840699802997", "8 \n4606061759128693\n4606066102679989\n4606069767552943\n4606063116488033\n4606063930903637\n4606064745319241\n4606063930904021\n4606065559735517", "3\n4\n8\n16"] | 1 second | ["32", "4", "1920", "10"] | NoteIn the first case, $$$a = 19305$$$. Its divisors are $$$1, 3, 5, 9, 11, 13, 15, 27, 33, 39, 45, 55, 65, 99, 117, 135, 143, 165, 195, 297, 351, 429, 495, 585, 715, 1287, 1485, 1755, 2145, 3861, 6435, 19305$$$Β β a total of $$$32$$$.In the second case, $$$a$$$ has four divisors: $$$1$$$, $$$86028121$$$, $$$86028157$$$, and $$$7400840699802997 $$$.In the third case $$$a = 202600445671925364698739061629083877981962069703140268516570564888699 375209477214045102253766023072401557491054453690213483547$$$.In the fourth case, $$$a=512=2^9$$$, so answer equals to $$$10$$$. | Java 11 | standard input | [
"interactive",
"number theory",
"math"
] | 4ca7837d1ddf80f0bde4aac2fb37d60b | The first line contains a single integer $$$n$$$ ($$$1 \leq n \leq 500$$$)Β β the number of numbers. Each of the next $$$n$$$ lines contains an integer $$$a_i$$$ ($$$1 \leq a_i \leq 2\cdot 10^{18}$$$). It is guaranteed that the number of divisors of each $$$a_i$$$ is between $$$3$$$ and $$$5$$$. | 2,000 | Print a single integer $$$d$$$Β β the number of divisors of the product $$$a_1 \cdot a_2 \cdot \dots \cdot a_n$$$ modulo $$$998244353$$$. Hacks input For hacks, the input needs to be provided in a special format. The first line contains an integer $$$n$$$Β ($$$1 \leq n \leq 500$$$)Β β the number of numbers. Each of the next $$$n$$$ lines contains a prime factorization of $$$a_i$$$. The line contains an integer $$$k_i$$$Β ($$$2 \leq k_i \leq 4$$$)Β β the number of prime factors of $$$a_i$$$ and $$$k_i$$$ integers $$$p_{i,j}$$$Β ($$$2 \leq p_{i,j} \leq 2 \cdot 10^{18}$$$) where $$$p_{i,j}$$$ is the $$$j$$$-th prime factor of $$$a_i$$$. Before supplying the input to the contestant, $$$a_i = \prod p_{i,j}$$$ are calculated. Note that each $$$p_{i,j}$$$ must be prime, each computed $$$a_i$$$ must satisfy $$$a_i \leq 2\cdot10^{18}$$$ and must have between $$$3$$$ and $$$5$$$ divisors. The contestant will be given only $$$a_i$$$, and not its prime factorization. For example, you need to use this test to get the first sample: 32 3 32 3 52 11 13 | standard output | |
PASSED | 2cc7e163873d794b5fa0379256342bcc | train_003.jsonl | 1347291900 | To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
public class Main
{
static long mod=((long)1e9)+7;//toString
public static int gcd(int a,int b){if(b==0)return a;else return gcd(b,a%b);}
public static long pow_mod(long x,long y){long res=1;x=x%mod;while(y > 0){if((y & 1)==1)res=(res * x)%mod;y=y>>1;x =(x * x)%mod;}return res;}
public static int lower_bound(int[]arr,int val){int lo=0;int hi=arr.length-1;while(lo<hi){int mid=lo+((hi-lo+1)/2);if(arr[mid]==val){return mid;}else if(arr[mid]>val){hi=mid-1;}else lo=mid;}if(arr[lo]<=val)return lo;else return -1;}
public static int upper_bound(int[]arr,int val){int lo=0;int hi=arr.length-1;while(lo<hi){int mid=lo+((hi-lo)/2);if(arr[mid]==val){return mid;}else if(arr[mid]>val){hi=mid;;}else lo=mid+1;}if(arr[lo]>=val)return lo;else return -1;}
public static void main (String[] args) throws java.lang.Exception
{
Reader sn = new Reader();
Print p = new Print();
int[] lp = new int[((int)(1e7)) + 1];
ArrayList<Integer> primes = new ArrayList<Integer>();
for(int i = 2; i <= ((int)1e7); ++i){
if(lp[i] == 0){
lp[i] = i;
primes.add(i);
}
for(int j = 0; (j < primes.size()) && (primes.get(j) <= lp[i]) && ((i * primes.get(j) <= ((int)1e7))); ++j){
lp[primes.get(j) * i] = primes.get(j);
}
}
int[] num = new int[10000001];
int[] den = new int[10000001];
int n = sn.nextInt();
int m = sn.nextInt();
int[] a = new int[n];
int[] b =new int[m];
int[] aa = new int[n];
int[] bb = new int[m];
for(int i = 0; i < n; ++i){
a[i] = sn.nextInt();
aa[i] = a[i];
}
for(int i = 0; i < m; ++i){
b[i] = sn.nextInt();
bb[i] = b[i];
}
for(int i =0; i < n; ++i)
while(a[i] != 1)
{
num[lp[a[i]]]++;
a[i] /= lp[a[i]];
}
for(int i = 0; i < m; ++i)
while(b[i] != 1)
{
den[lp[b[i]]]++;
b[i] /= lp[b[i]];
}
for(int i = 0; i <= 10000000; ++i)
{
num[i] = Math.min(num[i],den[i]);
den[i] = num[i];
}
for(int i=0; i<n; ++i)
{
int t = aa[i];
while(t != 1)
{
if(num[lp[t]] != 0)
{
aa[i] /= lp[t];
num[lp[t]]--;
}
t /= lp[t];
}
}
for(int i=0; i<m; i++)
{
int t = bb[i];
while(t != 1)
{
if(den[lp[t]] != 0)
{
bb[i] /= lp[t];
den[lp[t]]--;
}
t /= lp[t];
}
}
p.printLine(Integer.toString(n)+" "+Integer.toString(m));
for(int i = 0; i < n; ++i){
p.print(Integer.toString(aa[i])+" ");
}
p.printLine("");
for(int i = 0; i < m; ++i){
p.print(Integer.toString(bb[i])+" ");
}
p.close();
}
}
class Pair implements Comparable<Pair> {
int val;
int in;
Pair(int a, int b){
val=a;
in=b;
}
@Override
public int compareTo(Pair o) {
if(val==o.val)
return Integer.compare(in,o.in);
else
return Integer.compare(val,o.val);
}}
class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; }
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 String readWord()throws IOException
{
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 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 Print
{
private final BufferedWriter bw;
public Print()
{
bw=new BufferedWriter(new OutputStreamWriter(System.out));
}
public void print(String str)throws IOException
{
bw.append(str);
}
public void printLine(String str)throws IOException
{
print(str);
bw.append("\n");
}
public void close()throws IOException
{
bw.close();
}} | Java | ["3 2\n100 5 2\n50 10", "4 3\n2 5 10 20\n100 1 3"] | 2 seconds | ["2 3\n2 1\n1 1 1", "1 1\n20\n3"] | NoteIn the first test sample the numerator equals 1000, the denominator equals 500. If we reduce fraction 1000/500 by the greatest common divisor of the numerator and the denominator (by 500), we obtain fraction 2/1.In the second test sample the numerator equals 2000, the denominator equals 300. If we reduce fraction 2000/300 by the greatest common divisor of the numerator and the denominator (by 100), we obtain fraction 20/3. | Java 8 | standard input | [
"implementation",
"number theory",
"sortings",
"math"
] | 01ac609133428a0074e8506786096e02 | The first input line contains two space-separated integers n, m (1ββ€βn,βmββ€β105) that show how many numbers the first set (the numerator) and the second set (the denominator) contain, correspondingly. The second line contains n space-separated integers: a1,βa2,β...,βan (1ββ€βaiββ€β107) β the numbers that are multiplied to produce the numerator. The third line contains m space-separated integers: b1,βb2,β...,βbm (1ββ€βbiββ€β107) β the numbers that are multiplied to produce the denominator. | 1,800 | Print the answer to the problem in the form, similar to the form of the input data. The number of values in the sets you print nout,βmout must satisfy the inequality 1ββ€βnout,βmoutββ€β105, and the actual values in the sets aout,βi and bout,βi must satisfy the inequality 1ββ€βaout,βi,βbout,βiββ€β107. Separate the values in the lines by spaces. The printed fraction must be reduced, that is, there mustn't be such integer x (xβ>β1), that the numerator and the denominator of the printed fraction are divisible by x. If there are several matching answers, print any of them. | standard output | |
PASSED | 81682d60b2c7014bb1d5c0c36b6ce3af | train_003.jsonl | 1347291900 | To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you. | 256 megabytes | import java.io.*;
import java.util.*;
public class utkarsh {
BufferedReader br;
PrintWriter out;
int spf[], z = (int)(1e7 + 123);
int[] play(int[] a, int n) {
int d[] = new int[z];
for(int x : a) {
while(spf[x] > 1) {
d[spf[x]]++;
x /= spf[x];
}
}
return d;
}
int[] game(int[] a, int[] d, int n) {
for(int i = 0; i < n; i++) {
int x = a[i];
while(spf[x] > 1) {
int u = spf[x];
if(d[u] > 0) {
a[i] /= u; d[u]--;
}
x /= u;
}
}
return a;
}
void solve() {
spf = new int[z];
for(int i = 0; i < z; i++) spf[i] = i;
for(int i = 2; i*i <= z; i++) {
if(spf[i] == i) {
for(int j = i*i; j < z; j += i) {
if(spf[j] == j) spf[j] = i;
}
}
}
int n = ni(), m = ni();
int a[] = new int[n];
int b[] = new int[m];
for(int i = 0; i < n; i++) a[i] = ni();
for(int i = 0; i < m; i++) b[i] = ni();
int ap[] = play(a, n);
int bp[] = play(b, m);
for(int i = 0; i < z; i++) {
ap[i] = Math.min(ap[i], bp[i]);
bp[i] = ap[i];
}
a = game(a, ap, n);
b = game(b, bp, m);
out.println(n +" "+ m);
for(int x : a) out.print(x +" ");
out.println();
for(int x : b) out.print(x +" ");
out.println();
}
int ni() {
return Integer.parseInt(ns());
}
StringTokenizer ip;
String ns() {
if(ip == null || !ip.hasMoreTokens()) {
try {
ip = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new InputMismatchException();
}
}
return ip.nextToken();
}
void run() {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.flush();
}
public static void main(String[] args) {
new utkarsh().run();
}
} | Java | ["3 2\n100 5 2\n50 10", "4 3\n2 5 10 20\n100 1 3"] | 2 seconds | ["2 3\n2 1\n1 1 1", "1 1\n20\n3"] | NoteIn the first test sample the numerator equals 1000, the denominator equals 500. If we reduce fraction 1000/500 by the greatest common divisor of the numerator and the denominator (by 500), we obtain fraction 2/1.In the second test sample the numerator equals 2000, the denominator equals 300. If we reduce fraction 2000/300 by the greatest common divisor of the numerator and the denominator (by 100), we obtain fraction 20/3. | Java 8 | standard input | [
"implementation",
"number theory",
"sortings",
"math"
] | 01ac609133428a0074e8506786096e02 | The first input line contains two space-separated integers n, m (1ββ€βn,βmββ€β105) that show how many numbers the first set (the numerator) and the second set (the denominator) contain, correspondingly. The second line contains n space-separated integers: a1,βa2,β...,βan (1ββ€βaiββ€β107) β the numbers that are multiplied to produce the numerator. The third line contains m space-separated integers: b1,βb2,β...,βbm (1ββ€βbiββ€β107) β the numbers that are multiplied to produce the denominator. | 1,800 | Print the answer to the problem in the form, similar to the form of the input data. The number of values in the sets you print nout,βmout must satisfy the inequality 1ββ€βnout,βmoutββ€β105, and the actual values in the sets aout,βi and bout,βi must satisfy the inequality 1ββ€βaout,βi,βbout,βiββ€β107. Separate the values in the lines by spaces. The printed fraction must be reduced, that is, there mustn't be such integer x (xβ>β1), that the numerator and the denominator of the printed fraction are divisible by x. If there are several matching answers, print any of them. | standard output | |
PASSED | 0a67211e76965f62838e0573e096e6f2 | train_003.jsonl | 1347291900 | To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.BitSet;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Nafiur Rahman Khadem Shafin π
*/
public class Main {
public static void main (String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader (inputStream);
PrintWriter out = new PrintWriter (outputStream);
TaskC solver = new TaskC ();
solver.solve (1, in, out);
out.close ();
}
static class TaskC {
private static BitSet flg;
private static int[] smallestPrimeDivisor;
private static int[] cp;
private static void linearSieve (int ne) {
flg = new BitSet (ne+5);
flg.set (2, ne+1);
//for prime factorization, pore aro tinta ache
smallestPrimeDivisor = new int[ne+5];
cp = new int[ne+5];
smallestPrimeDivisor[2] = 2;
cp[2] = 1;
for (int i = 4; i<=ne; i += 2) {
flg.clear (i);
//for prime factorization, age ar pore aro ache
smallestPrimeDivisor[i] = 2;
cp[i] = i >> 1;
}
double sqrtn = Math.sqrt (ne+1);
for (int i = 3; i<=ne; i += 2) {
if (!flg.get (i)) {
continue;
}
//for prime factorization, age ar pore aro ache
smallestPrimeDivisor[i] = i;
cp[i] = 1;
if (i<=sqrtn) {// will not overflow, otherwise ne*ne will go to negative by overflowing
int mult;
for (int j = i; (mult = j*i)<=ne; j += 2) {
if (flg.get (mult)) {
flg.clear (mult);
//for prime factorization, age aro tinta ache
smallestPrimeDivisor[mult] = i;
cp[mult] = j;
}
}
}
}
}
public void solve (int testNumber, InputReader in, PrintWriter out) {
/*
* Dangerous problem π. n*m*loga complexity te aramse kora zeto, but it's not possible π’. Only way seems to be
* prime
* factorization but that also needs to be done in the fastest possible way. Had to see solution π’.
*/
linearSieve (10000005);
int[] cnt = new int[10000005];
int n = in.nextInt (), m = in.nextInt ();
int[] numer = new int[n+5], denom = new int[m+5];
for (int i = 0; i<n; i++) {
numer[i] = in.nextInt ();
int tmp = numer[i];
while (tmp!=1) {
cnt[smallestPrimeDivisor[tmp]]++;
tmp = cp[tmp];
}
}
for (int i = 0; i<m; i++) {
denom[i] = in.nextInt ();
int tmp = denom[i];
while (tmp!=1) {
cnt[smallestPrimeDivisor[tmp]]--;
tmp = cp[tmp];
}
}
out.println (n+" "+m);
for (int i = 0; i<n; ++i) {
int ret = 1;
while (numer[i]!=1) {
if (cnt[smallestPrimeDivisor[numer[i]]]>0) {
ret *= smallestPrimeDivisor[numer[i]];
cnt[smallestPrimeDivisor[numer[i]]]--;
}
numer[i] = cp[numer[i]];
}
out.print (ret+" ");
}
out.println ();
for (int i = 0; i<m; ++i) {
int ret = 1;
while (denom[i]!=1) {
if (cnt[smallestPrimeDivisor[denom[i]]]<0) {
ret *= smallestPrimeDivisor[denom[i]];
cnt[smallestPrimeDivisor[denom[i]]]++;
}
denom[i] = cp[denom[i]];
}
out.print (ret+" ");
}
out.println ();
}
}
static class InputReader implements AutoCloseable {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader (InputStream stream) {
reader = new BufferedReader (new InputStreamReader (stream));
tokenizer = null;
}
public String next () {
while (tokenizer==null || !tokenizer.hasMoreTokens ()) {
try {
String str;
if ((str = reader.readLine ())!=null) tokenizer = new StringTokenizer (str);
else return null;//to detect eof
} catch (IOException e) {
throw new RuntimeException (e);
}
}
return tokenizer.nextToken ();
}
public int nextInt () {
return Integer.parseInt (next ());
}
public void close () throws Exception {
reader.close ();
}
}
}
| Java | ["3 2\n100 5 2\n50 10", "4 3\n2 5 10 20\n100 1 3"] | 2 seconds | ["2 3\n2 1\n1 1 1", "1 1\n20\n3"] | NoteIn the first test sample the numerator equals 1000, the denominator equals 500. If we reduce fraction 1000/500 by the greatest common divisor of the numerator and the denominator (by 500), we obtain fraction 2/1.In the second test sample the numerator equals 2000, the denominator equals 300. If we reduce fraction 2000/300 by the greatest common divisor of the numerator and the denominator (by 100), we obtain fraction 20/3. | Java 8 | standard input | [
"implementation",
"number theory",
"sortings",
"math"
] | 01ac609133428a0074e8506786096e02 | The first input line contains two space-separated integers n, m (1ββ€βn,βmββ€β105) that show how many numbers the first set (the numerator) and the second set (the denominator) contain, correspondingly. The second line contains n space-separated integers: a1,βa2,β...,βan (1ββ€βaiββ€β107) β the numbers that are multiplied to produce the numerator. The third line contains m space-separated integers: b1,βb2,β...,βbm (1ββ€βbiββ€β107) β the numbers that are multiplied to produce the denominator. | 1,800 | Print the answer to the problem in the form, similar to the form of the input data. The number of values in the sets you print nout,βmout must satisfy the inequality 1ββ€βnout,βmoutββ€β105, and the actual values in the sets aout,βi and bout,βi must satisfy the inequality 1ββ€βaout,βi,βbout,βiββ€β107. Separate the values in the lines by spaces. The printed fraction must be reduced, that is, there mustn't be such integer x (xβ>β1), that the numerator and the denominator of the printed fraction are divisible by x. If there are several matching answers, print any of them. | standard output | |
PASSED | 43e6a65b816d1b4d29f6a5bd69250092 | train_003.jsonl | 1347291900 | To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class ReducingFractions
{
public static void main(String[] args)
{ //Use Exhaustion
boolean debug = false;
FastReader sc = new FastReader();
int MAX = 10000000;
int[] map = new int[10000001];
boolean[] sieve = new boolean[MAX+1];
int[] par = new int[MAX+1];
int[] id = new int[MAX+1];
sieve[0] = true;
sieve[1] = true;
for(long i = 2; i <= MAX; i++)
{
if(!sieve[(int)i])
{
for(long j = i*i; j <= MAX; j += i)
{
sieve[(int)j] = true;
par[(int)j] = (int)i;
}
}
}
int p = 0;
// int[] pa = new int[670000];
// int[] pb = new int[670000];
int[] pdiff = new int[670000];
int[] pval = new int[670000];
for(int i = 0; i <= MAX; i++)
{
if(!sieve[i])
{
map[i] = p;
pval[p] = i;
p++;
}
}
// System.out.println(p);
if(debug)System.out.println("Sieve done");
// System.out.println(Arrays.toString(par));
int n = sc.nextInt();
int m = sc.nextInt();
int[] ina = new int[n];
int[] inb = new int[m];
int totp = 0;
for(int i = 0; i < n; i++)
{
int in = sc.nextInt();
ina[i] = in;
while(sieve[in] && in > 1)
{ //still composite
// System.out.println(in);
// System.out.println("a " + par[in]);
pdiff[map[par[in]]]++;
totp++;
in /= par[in];
}
//now prime
if(in > 1)
{
pdiff[map[in]]++;
totp++;
}
// System.out.println("a " + in);
}
// System.out.println("Start reading b");
for(int i = 0; i < m; i++)
{
int in = sc.nextInt();
inb[i] = in;
// System.out.println("Analyzing " + in);
while(sieve[in] && in > 1)
{ //still composite
// System.out.println(in + " / " + par[in]);
pdiff[map[par[in]]]--;
in /= par[in];
totp++;
}
if(in > 1)
{
pdiff[map[in]]--;
totp++;
}
}
long cura = 1;
long curb = 1;
StringBuilder sba = new StringBuilder("");
StringBuilder sbb = new StringBuilder("");
int ia = 0;
int ib = 0;
for(int i = 0; i < n; i++)
{
int cur = ina[i];
while(sieve[cur] && cur > 1)
{ //still composite
// System.out.println("ina " + ina[i]);
// System.out.println(in);
// System.out.println("a " + par[cur] + ", dif " + pdiff[map[par[cur]]]);
int div = par[cur];
if(pdiff[map[div]] > 0)
{
pdiff[map[div]]--;
}
else
{
ina[i]/=div;
}
cur /= div;
}
//now prime
if(cur > 1)
{
if(pdiff[map[cur]] > 0)
{
pdiff[map[cur]]--;
}
else
{
ina[i]/=cur;
}
}
// System.out.println("a " + in);
if(ia > 0)sba.append(" ");
sba.append(ina[i]);
// System.out.println("End " + ina[i]);
ia++;
}
for(int i = 0; i < m; i++)
{
int cur = inb[i];
while(sieve[cur] && cur > 1)
{ //still composite
// System.out.println(in);
// System.out.println("a " + par[in]);
int div = par[cur];
if(pdiff[map[div]] < 0)
{
pdiff[map[div]]++;
}
else
{
inb[i]/=div;
}
cur /= div;
}
//now prime
if(cur > 1)
{
if(pdiff[map[cur]] < 0)
{
pdiff[map[cur]]++;
}
else
{
inb[i]/=cur;
}
}
// System.out.println("a " + in);
if(ib > 0)sbb.append(" ");
sbb.append(inb[i]);
ib++;
}
// System.out.println("TOT " + totrem + " " + totp);
{
System.out.println(n + " " + m);
System.out.println(sba);
System.out.println(sbb);
}
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
| Java | ["3 2\n100 5 2\n50 10", "4 3\n2 5 10 20\n100 1 3"] | 2 seconds | ["2 3\n2 1\n1 1 1", "1 1\n20\n3"] | NoteIn the first test sample the numerator equals 1000, the denominator equals 500. If we reduce fraction 1000/500 by the greatest common divisor of the numerator and the denominator (by 500), we obtain fraction 2/1.In the second test sample the numerator equals 2000, the denominator equals 300. If we reduce fraction 2000/300 by the greatest common divisor of the numerator and the denominator (by 100), we obtain fraction 20/3. | Java 8 | standard input | [
"implementation",
"number theory",
"sortings",
"math"
] | 01ac609133428a0074e8506786096e02 | The first input line contains two space-separated integers n, m (1ββ€βn,βmββ€β105) that show how many numbers the first set (the numerator) and the second set (the denominator) contain, correspondingly. The second line contains n space-separated integers: a1,βa2,β...,βan (1ββ€βaiββ€β107) β the numbers that are multiplied to produce the numerator. The third line contains m space-separated integers: b1,βb2,β...,βbm (1ββ€βbiββ€β107) β the numbers that are multiplied to produce the denominator. | 1,800 | Print the answer to the problem in the form, similar to the form of the input data. The number of values in the sets you print nout,βmout must satisfy the inequality 1ββ€βnout,βmoutββ€β105, and the actual values in the sets aout,βi and bout,βi must satisfy the inequality 1ββ€βaout,βi,βbout,βiββ€β107. Separate the values in the lines by spaces. The printed fraction must be reduced, that is, there mustn't be such integer x (xβ>β1), that the numerator and the denominator of the printed fraction are divisible by x. If there are several matching answers, print any of them. | standard output | |
PASSED | a1bc107fc65e77f938c918ef0f11f465 | train_003.jsonl | 1347291900 | To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import java.util.*;
import java.lang.*;
public class Solution {
public static void main (String args[]) throws Exception {
Scanner cin = new Scanner(System.in);
PrintWriter cout = new PrintWriter(System.out);
int numerator[] = new int [100000];
int denominator[] = new int[100000];
int n = cin.nextInt(); int m = cin.nextInt();
for(int i=0; i<n; i++)
numerator[i] = cin.nextInt();
for(int i=0; i<m; i++)
denominator[i] = cin.nextInt();
int used[] = new int[(int)1e7 + 100];
Arrays.fill(used, 0);
for (int i=2; i<= (int)1e7; i++)
if (used[i]==0) {
for(int j=i; j<=1e7; j+=i)
used[j] = i;
}
int cntn[] = new int[(int)1e7 + 100],
cntd[] = new int[(int)1e7 + 100];
Arrays.fill(cntn, 0);
Arrays.fill(cntd, 0);
for(int i=0; i<n; i++) {
int temp = numerator[i];
while (used[temp]!=0) {
cntn[used[temp]]++;
temp /= used[temp];
}
}
for(int i=0; i<m; i++) {
int temp = denominator[i];
while (used[temp]!=0) {
cntd[used[temp]]++;
temp /= used[temp];
}
}
cout.println(n + " " + m);
for (int i=1; i<=(int)1e7; i++)
cntn[i] = Math.min(cntd[i], cntn[i]);
Arrays.fill(cntd, 0);
for(int i=0; i<n; i++) {
int a = numerator[i];
int res = 1;
while (used[a]!=0) {
if (cntd[used[a]] < cntn[used[a]]) {
cntd[used[a]]++;
numerator[i]/=used[a];
}
a /= used[a];
}
cout.print(numerator[i] + " ");
}
cout.println();
Arrays.fill(cntd, 0);
for(int i=0; i<m; i++) {
int a = denominator[i];
int res = 1;
while (used[a]!=0) {
if (cntd[used[a]] < cntn[used[a]]) {
cntd[used[a]]++;
denominator[i]/=used[a];
}
a /= used[a];
}
cout.print(denominator[i] + " ");
}
cout.close();
}
} | Java | ["3 2\n100 5 2\n50 10", "4 3\n2 5 10 20\n100 1 3"] | 2 seconds | ["2 3\n2 1\n1 1 1", "1 1\n20\n3"] | NoteIn the first test sample the numerator equals 1000, the denominator equals 500. If we reduce fraction 1000/500 by the greatest common divisor of the numerator and the denominator (by 500), we obtain fraction 2/1.In the second test sample the numerator equals 2000, the denominator equals 300. If we reduce fraction 2000/300 by the greatest common divisor of the numerator and the denominator (by 100), we obtain fraction 20/3. | Java 6 | standard input | [
"implementation",
"number theory",
"sortings",
"math"
] | 01ac609133428a0074e8506786096e02 | The first input line contains two space-separated integers n, m (1ββ€βn,βmββ€β105) that show how many numbers the first set (the numerator) and the second set (the denominator) contain, correspondingly. The second line contains n space-separated integers: a1,βa2,β...,βan (1ββ€βaiββ€β107) β the numbers that are multiplied to produce the numerator. The third line contains m space-separated integers: b1,βb2,β...,βbm (1ββ€βbiββ€β107) β the numbers that are multiplied to produce the denominator. | 1,800 | Print the answer to the problem in the form, similar to the form of the input data. The number of values in the sets you print nout,βmout must satisfy the inequality 1ββ€βnout,βmoutββ€β105, and the actual values in the sets aout,βi and bout,βi must satisfy the inequality 1ββ€βaout,βi,βbout,βiββ€β107. Separate the values in the lines by spaces. The printed fraction must be reduced, that is, there mustn't be such integer x (xβ>β1), that the numerator and the denominator of the printed fraction are divisible by x. If there are several matching answers, print any of them. | standard output | |
PASSED | c888421ee4b1cff456f6abb674f957ca | train_003.jsonl | 1347291900 | To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you. | 256 megabytes | import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
}
class TaskC {
int n;
int m;
int[] a;
int[] b;
int[] primesNum;
int[] primesDen;
int[][] factorsNum;
int[][] factorsDen;
int[] primes;
EratosthenesPrimeFactorizer factorizer;
int[] tmpIndices = new int[30];
int[] tmpFactors = new int[30];
int[] tmpPowers = new int[30];
int[] addPrimes(int x, int[] primesTable) {
int factorsCount = factorizer.factorizeWithPowers(x, tmpFactors, tmpPowers);
int len = 0;
for (int i = 0; i < factorsCount; i++) {
int p = tmpFactors[i];
int pow = tmpPowers[i];
int idx = Arrays.binarySearch(primes, p);
primesTable[idx] += pow;
for (int j = 0; j < pow; j++)
tmpIndices[len++] = idx;
}
return Arrays.copyOf(tmpIndices, len);
}
int fetchPrimes(int x, int[] primesTable, int[] factors) {
int ret = x;
for (int p : factors) {
if (primesTable[p] > 0) {
primesTable[p]--;
ret /= primes[p];
}
}
return ret;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
int N = 10000000;
factorizer = new EratosthenesPrimeFactorizer(N);
primes = factorizer.getPrimes();
primesNum = new int[primes.length];
primesDen = new int[primes.length];
n = in.nextInt();
m = in.nextInt();
a = new int[n];
b = new int[m];
factorsNum = new int[n][];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
factorsNum[i] = addPrimes(a[i], primesNum);
}
factorsDen = new int[m][];
for (int i = 0; i < m; i++) {
b[i] = in.nextInt();
factorsDen[i] = addPrimes(b[i], primesDen);
}
for (int i = 0; i < primesNum.length; i++)
primesNum[i] = primesDen[i] = Math.min(primesNum[i], primesDen[i]);
for (int i = 0; i < n; i++)
a[i] = fetchPrimes(a[i], primesNum, factorsNum[i]);
for (int i = 0; i < m; i++)
b[i] = fetchPrimes(b[i], primesDen, factorsDen[i]);
out.println(n + " " + m);
for (int cur : a) {
out.print(cur);
out.print(" ");
}
out.println();
for (int cur : b) {
out.print(cur);
out.print(" ");
}
out.println();
}
}
class EratosthenesPrimeFactorizer {
private int n;
private int[] smallestPrimeDivisor;
private byte[] smallestPrimeDivisorPower;
private int[] prevNumber; // i / (spd[i] ^ spdp[i])
private int[] primes;
public EratosthenesPrimeFactorizer(int n) {
this.n = n;
build();
}
public int[] getPrimes() {
return primes;
}
public int factorizeWithPowers(int k, int[] factors, int[] powers) {
if (k <= 0 || k > n) throw new NumberFormatException();
int factorsNumber = 0;
while (k != 1) {
factors[factorsNumber] = smallestPrimeDivisor[k];
powers[factorsNumber++] = smallestPrimeDivisorPower[k];
k = prevNumber[k];
}
return factorsNumber;
}
private void build() {
// Memory allocation
smallestPrimeDivisor = new int[n + 1];
smallestPrimeDivisorPower = new byte[n + 1];
prevNumber = new int[n + 1];
primes = new int[n + 1];
// Algorithm
int primesCount = 0;
smallestPrimeDivisor[1] = 1;
for (int i = 2; i <= n; i++) {
if (smallestPrimeDivisor[i] == 0) {
smallestPrimeDivisor[i] = i;
smallestPrimeDivisorPower[i] = 1;
prevNumber[i] = 1;
primes[primesCount++] = i;
} else {
int prev = i / smallestPrimeDivisor[i];
if (smallestPrimeDivisor[prev] == smallestPrimeDivisor[i]) {
smallestPrimeDivisorPower[i] = (byte) (smallestPrimeDivisorPower[prev] + 1);
prevNumber[i] = prevNumber[prev];
} else {
smallestPrimeDivisorPower[i] = 1;
prevNumber[i] = prev;
}
}
for (int j = 0, next; j < primesCount; j++) {
if (primes[j] > smallestPrimeDivisor[i] || (next = i * primes[j]) > n) break;
smallestPrimeDivisor[next] = primes[j];
}
}
primes = Arrays.copyOf(primes, primesCount);
}
}
class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
}
| Java | ["3 2\n100 5 2\n50 10", "4 3\n2 5 10 20\n100 1 3"] | 2 seconds | ["2 3\n2 1\n1 1 1", "1 1\n20\n3"] | NoteIn the first test sample the numerator equals 1000, the denominator equals 500. If we reduce fraction 1000/500 by the greatest common divisor of the numerator and the denominator (by 500), we obtain fraction 2/1.In the second test sample the numerator equals 2000, the denominator equals 300. If we reduce fraction 2000/300 by the greatest common divisor of the numerator and the denominator (by 100), we obtain fraction 20/3. | Java 6 | standard input | [
"implementation",
"number theory",
"sortings",
"math"
] | 01ac609133428a0074e8506786096e02 | The first input line contains two space-separated integers n, m (1ββ€βn,βmββ€β105) that show how many numbers the first set (the numerator) and the second set (the denominator) contain, correspondingly. The second line contains n space-separated integers: a1,βa2,β...,βan (1ββ€βaiββ€β107) β the numbers that are multiplied to produce the numerator. The third line contains m space-separated integers: b1,βb2,β...,βbm (1ββ€βbiββ€β107) β the numbers that are multiplied to produce the denominator. | 1,800 | Print the answer to the problem in the form, similar to the form of the input data. The number of values in the sets you print nout,βmout must satisfy the inequality 1ββ€βnout,βmoutββ€β105, and the actual values in the sets aout,βi and bout,βi must satisfy the inequality 1ββ€βaout,βi,βbout,βiββ€β107. Separate the values in the lines by spaces. The printed fraction must be reduced, that is, there mustn't be such integer x (xβ>β1), that the numerator and the denominator of the printed fraction are divisible by x. If there are several matching answers, print any of them. | standard output | |
PASSED | eb77001f21e75e107a5b3db19aa2cd67 | train_003.jsonl | 1347291900 | To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you. | 256 megabytes | import java.io.*;
import java.lang.Math;
import java.util.*;
public class Main
{
public BufferedReader in;
public PrintStream out;
public boolean log_enabled = true;
static int[] primes;
static int p_count;
public static void get_primes(int n)
{
primes = new int[1000000];
boolean[] v = new boolean[n+1];
int i,j;
for (i=2; i<=n;i++)
{
v[i] = true;
}
for (i=2; i*i<=n;i++)
{
if (v[i])
{
for (j=i; i*j<=n; j++)
{
v[i*j]=false;
}
}
}
p_count = 0;
for (i=2; i<=n; i++)
{
if (v[i])
{
primes[p_count++] = i;
}
}
}
public static int p_number(int x, int l, int r)
{
if (l>r)
{
return -1;
}
int c = (l+r) >> 1;
if (primes[c]<x)
{
return p_number(x, c+1, r);
}
if (primes[c]>x)
{
return p_number(x, l, c-1);
}
return c;
}
public static int sqrt(int n)
{
return (int)Math.sqrt(n);
}
public int factors(int n, int[] f, int[] p)
{
int x = p_number(n, 1, p_count);
if (x>-1)
{
f[0] = x;
p[0] = 1;
return 1;
}
int k = 0;
for (int i=0; i<p_count; i++)
{
if (n < primes[i]*primes[i])
{
if (n>1)
{
p[k] = 1;
f[k] = p_number(n, i, p_count-1);
k++;
}
break;
}
if (n % primes[i] == 0)
{
f[k] = i;
p[k] = 0;
while (n % primes[i] == 0)
{
p[k]++;
n /= primes[i];
}
k++;
}
}
return k;
}
public int get_numbers(int[] f, int[] res)
{
int n =0;
long x = 1;
for (int k=0; k<p_count; k++)
{
for (;f[k]>0;f[k]--)
{
if (x * (long)primes[k] > 10000000)
{
res[n++] = (int)x;
x = 1;
}
x *= primes[k];
}
}
if (x>1)
{
res[n++] = (int)x;
}
if (n==0)
{
res[n++] = 1;
}
return n;
}
public int pow(int x, int k)
{
int r = 1;
for (int s=32; s>0; s>>=1)
{
r*= r;
if ((s & k) > 0)
{
r*= x;
}
}
return r;
}
public void test()
{
int n = readInt();
int m = readInt();
int[] a = new int[n];
int[] b = new int[m];
int i,j,k;
get_primes(10000000);
int[] Fa = new int[p_count];
int[] Fb = new int[p_count];
Arrays.fill(Fa, 0);
Arrays.fill(Fb, 0);
int[] f = new int[p_count];
int[] p = new int[p_count];
for (i=0; i<n; i++)
{
k = factors(a[i] = readInt(), f, p);
for (j=0; j<k; j++)
{
Fa[f[j]] += p[j];
}
}
for (i=0; i<m; i++)
{
k = factors(b[i] = readInt(), f, p);
for (j=0; j<k; j++)
{
Fb[f[j]] += p[j];
}
}
for (i=0; i<p_count; i++)
{
k = Math.min(Fa[i], Fb[i]);
Fa[i] -= k;
Fb[i] -= k;
}
for (i=0; i<n; i++)
{
k = factors(a[i], f, p);
a[i] = 1;
for (j=0; j<k; j++)
{
a[i] *= pow(primes[f[j]], Math.min(p[j], Fa[f[j]]));
Fa[f[j]] -= Math.min(p[j], Fa[f[j]]);
}
}
for (i=0; i<m; i++)
{
k = factors(b[i], f, p);
b[i] = 1;
for (j=0; j<k; j++)
{
b[i] *= pow(primes[f[j]], Math.min(p[j], Fb[f[j]]));
Fb[f[j]] -= Math.min(p[j], Fb[f[j]]);
}
}
out.printf("%d %d\n", n, m);
for (i=0; i<n; i++)
{
if (i>0)
{
out.print(" ");
}
out.print(a[i]);
}
out.println();
for (i=0; i<m; i++)
{
if (i>0)
{
out.print(" ");
}
out.print(b[i]);
}
out.println();
}
public void run()
{
try
{
in = new BufferedReader(new InputStreamReader(System.in));
out = System.out;
//in = new BufferedReader(new FileReader("in.txt"));
//out = new PrintStream(new File("out.txt"));
}
catch (Exception e)
{
return;
}
//while (true)
{
//int t = readInt(); for (int i=0; i<t; i++)
{
test();
}
}
}
public static void main(String args[])
{
new Main().run();
}
private StringTokenizer tokenizer = null;
public int readInt()
{
return Integer.parseInt(readToken());
}
public long readLong()
{
return Long.parseLong(readToken());
}
public double readDouble()
{
return Double.parseDouble(readToken());
}
public String readLn()
{
try
{
String s;
while ((s = in.readLine()).length()==0);
return s;
}
catch (Exception e)
{
return "";
}
}
public String readToken()
{
try
{
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
tokenizer = new StringTokenizer(in.readLine());
}
return tokenizer.nextToken();
}
catch (Exception e)
{
return "";
}
}
public int[] readIntArray(int n)
{
int[] x = new int[n];
readIntArray(x, n);
return x;
}
public void readIntArray(int[] x, int n)
{
for (int i=0; i<n; i++)
{
x[i] = readInt();
}
}
public void logWrite(String format, Object... args)
{
if (!log_enabled)
{
return;
}
out.printf(format, args);
}
}
| Java | ["3 2\n100 5 2\n50 10", "4 3\n2 5 10 20\n100 1 3"] | 2 seconds | ["2 3\n2 1\n1 1 1", "1 1\n20\n3"] | NoteIn the first test sample the numerator equals 1000, the denominator equals 500. If we reduce fraction 1000/500 by the greatest common divisor of the numerator and the denominator (by 500), we obtain fraction 2/1.In the second test sample the numerator equals 2000, the denominator equals 300. If we reduce fraction 2000/300 by the greatest common divisor of the numerator and the denominator (by 100), we obtain fraction 20/3. | Java 6 | standard input | [
"implementation",
"number theory",
"sortings",
"math"
] | 01ac609133428a0074e8506786096e02 | The first input line contains two space-separated integers n, m (1ββ€βn,βmββ€β105) that show how many numbers the first set (the numerator) and the second set (the denominator) contain, correspondingly. The second line contains n space-separated integers: a1,βa2,β...,βan (1ββ€βaiββ€β107) β the numbers that are multiplied to produce the numerator. The third line contains m space-separated integers: b1,βb2,β...,βbm (1ββ€βbiββ€β107) β the numbers that are multiplied to produce the denominator. | 1,800 | Print the answer to the problem in the form, similar to the form of the input data. The number of values in the sets you print nout,βmout must satisfy the inequality 1ββ€βnout,βmoutββ€β105, and the actual values in the sets aout,βi and bout,βi must satisfy the inequality 1ββ€βaout,βi,βbout,βiββ€β107. Separate the values in the lines by spaces. The printed fraction must be reduced, that is, there mustn't be such integer x (xβ>β1), that the numerator and the denominator of the printed fraction are divisible by x. If there are several matching answers, print any of them. | standard output | |
PASSED | 57a9d5e08243799455756cf5a42dd687 | train_003.jsonl | 1347291900 | To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you. | 256 megabytes | import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import static java.lang.Double.parseDouble;
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.sort;
import static java.util.Collections.binarySearch;
import static java.util.Collections.shuffle;
import static java.util.Collections.sort;
public class C {
static StringTokenizer st;
static BufferedReader br;
static PrintWriter pw;
static final int NUM_PRIMES = 664579;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
System.out)));
int n = readInt();
int m = readInt();
boolean[] comp = new boolean[10000000];
for(int i = 3; i * i < comp.length; i += 2) {
if(!comp[i]) {
for(int j = i*i; j < comp.length; j += 2*i) {
comp[j] = true;
}
}
}
int[] p = new int[NUM_PRIMES];
p[0] = 2;
int c = 1;
for(int i = 3; i < comp.length; i += 2) {
if(!comp[i])
p[c++] = i;
}
int[] numP = new int[NUM_PRIMES];
int[] demP = new int[NUM_PRIMES];
int[] numFrac = new int[n];
int[] demFrac = new int[m];
ArrayList<Integer>[] indexN = new ArrayList[n];
ArrayList<Integer>[] indexD = new ArrayList[m];
for(int i = 0; i < n; i++) {
numFrac[i] = readInt();
indexN[i] = new ArrayList<Integer>();
}
for(int i = 0; i < m; i++) {
demFrac[i] = readInt();
indexD[i] = new ArrayList<Integer>();
}
for(int k = 0; k < n; k++) {
int temp = numFrac[k];
for(int i = 0; i < NUM_PRIMES; i++) {
int curr = 0;
while(temp % p[i] == 0) {
curr++;
temp /= p[i];
}
numP[i] += curr;
if(curr > 0) {
indexN[k].add(i);
}
if(p[i] * p[i] > temp)
break;
}
if(temp != 1) {
int rel = binarySearch(p, temp);
indexN[k].add(rel);
numP[rel]++;
}
}
for(int k = 0; k < m; k++) {
int temp = demFrac[k];
for(int i = 0; i < NUM_PRIMES; i++) {
int curr = 0;
while(temp % p[i] == 0) {
curr++;
temp /= p[i];
}
demP[i] += curr;
if(curr > 0) {
indexD[k].add(i);
}
if(p[i] * p[i] > temp)
break;
}
if(temp != 1) {
int rel = binarySearch(p, temp);
indexD[k].add(rel);
demP[rel]++;
}
}
int[] ret = new int[NUM_PRIMES];
for(int i = 0; i < NUM_PRIMES; i++)
ret[i] = Math.min(numP[i], demP[i]);
StringBuilder sb = new StringBuilder();
for(int k = 0; k < n; k++) {
for(int out: indexN[k]) {
while(ret[out] > 0 && numFrac[k] % p[out] == 0) {
ret[out]--;
numFrac[k] /= p[out];
}
}
sb.append(numFrac[k] + " ");
}
for(int i = 0; i < NUM_PRIMES; i++)
ret[i] = Math.min(numP[i], demP[i]);
StringBuilder sc = new StringBuilder();
for(int k = 0; k < m; k++) {
for(int out: indexD[k]) {
while(ret[out] > 0 && demFrac[k] % p[out] == 0) {
ret[out]--;
demFrac[k] /= p[out];
}
}
sc.append(demFrac[k] + " ");
}
pw.println(n + " " + m);
pw.println(sb.toString().trim());
pw.println(sc.toString().trim());
pw.close();
}
public static long readLong() throws IOException {
return parseLong(nextToken());
}
public static double readDouble() throws IOException {
return parseDouble(nextToken());
}
public static int readInt() throws IOException {
return parseInt(nextToken());
}
public static String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
if (!br.ready()) {
pw.close();
System.exit(0);
}
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
}
| Java | ["3 2\n100 5 2\n50 10", "4 3\n2 5 10 20\n100 1 3"] | 2 seconds | ["2 3\n2 1\n1 1 1", "1 1\n20\n3"] | NoteIn the first test sample the numerator equals 1000, the denominator equals 500. If we reduce fraction 1000/500 by the greatest common divisor of the numerator and the denominator (by 500), we obtain fraction 2/1.In the second test sample the numerator equals 2000, the denominator equals 300. If we reduce fraction 2000/300 by the greatest common divisor of the numerator and the denominator (by 100), we obtain fraction 20/3. | Java 6 | standard input | [
"implementation",
"number theory",
"sortings",
"math"
] | 01ac609133428a0074e8506786096e02 | The first input line contains two space-separated integers n, m (1ββ€βn,βmββ€β105) that show how many numbers the first set (the numerator) and the second set (the denominator) contain, correspondingly. The second line contains n space-separated integers: a1,βa2,β...,βan (1ββ€βaiββ€β107) β the numbers that are multiplied to produce the numerator. The third line contains m space-separated integers: b1,βb2,β...,βbm (1ββ€βbiββ€β107) β the numbers that are multiplied to produce the denominator. | 1,800 | Print the answer to the problem in the form, similar to the form of the input data. The number of values in the sets you print nout,βmout must satisfy the inequality 1ββ€βnout,βmoutββ€β105, and the actual values in the sets aout,βi and bout,βi must satisfy the inequality 1ββ€βaout,βi,βbout,βiββ€β107. Separate the values in the lines by spaces. The printed fraction must be reduced, that is, there mustn't be such integer x (xβ>β1), that the numerator and the denominator of the printed fraction are divisible by x. If there are several matching answers, print any of them. | standard output | |
PASSED | 078d5802d43893b6576e901c8d5ae98e | train_003.jsonl | 1347291900 | To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main{
BufferedReader in;
StringTokenizer str = null;
private String next() throws Exception{
if(str == null || !str.hasMoreElements())
str = new StringTokenizer(in.readLine());
return str.nextToken();
}
private int nextInt() throws Exception{
return Integer.parseInt(next());
}
final int MAX=(int)1e7;
boolean p[];
int []r, count,a, b;
public void run() throws Exception{
in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int n = nextInt();
int m = nextInt();
a = new int[n];
for(int i=0;i<n;i++) a[i] = nextInt();
b = new int[m];
for(int i=0;i<m;i++) b[i] = nextInt();
p = new boolean[MAX+1];
r = new int[MAX+1];
Arrays.fill(p, true);
p[0] = p[1] = false;
for(int i=2;i*i<=MAX;i++){
if (p[i]){
for(int j=i*i;j<=MAX;j+=i){
p[j] = false;
r[j] = i;
}
}
}
for(int i=0;i<r.length;i++)
if (p[i]) r[i] = i;
count = new int[MAX+1];
for(int i=0;i<n;i++){
int x = a[i];
while(x > 1){
count[r[x]]++;
x/=r[x];
}
}
for(int i=0;i<m;i++){
int x = b[i];
while(x > 1){
count[r[x]]--;
x/=r[x];
}
}
out.println(n + " " + m);
for(int i=0;i<n;i++){
int x = a[i], y = a[i];
while(x > 1){
if (count[r[x]] > 0) count[r[x]]--;
else y/=r[x];
x/=r[x];
}
out.print(y + " ");
}
out.println();
for(int i=0;i<m;i++){
int x = b[i], y = b[i];
while(x > 1){
if (count[r[x]] < 0) count[r[x]]++;
else y/=r[x];
x/=r[x];
}
out.print(y + " ");
}
out.println();
out.close();
}
public static void main(String args[]) throws Exception{
new Main().run();
}
} | Java | ["3 2\n100 5 2\n50 10", "4 3\n2 5 10 20\n100 1 3"] | 2 seconds | ["2 3\n2 1\n1 1 1", "1 1\n20\n3"] | NoteIn the first test sample the numerator equals 1000, the denominator equals 500. If we reduce fraction 1000/500 by the greatest common divisor of the numerator and the denominator (by 500), we obtain fraction 2/1.In the second test sample the numerator equals 2000, the denominator equals 300. If we reduce fraction 2000/300 by the greatest common divisor of the numerator and the denominator (by 100), we obtain fraction 20/3. | Java 6 | standard input | [
"implementation",
"number theory",
"sortings",
"math"
] | 01ac609133428a0074e8506786096e02 | The first input line contains two space-separated integers n, m (1ββ€βn,βmββ€β105) that show how many numbers the first set (the numerator) and the second set (the denominator) contain, correspondingly. The second line contains n space-separated integers: a1,βa2,β...,βan (1ββ€βaiββ€β107) β the numbers that are multiplied to produce the numerator. The third line contains m space-separated integers: b1,βb2,β...,βbm (1ββ€βbiββ€β107) β the numbers that are multiplied to produce the denominator. | 1,800 | Print the answer to the problem in the form, similar to the form of the input data. The number of values in the sets you print nout,βmout must satisfy the inequality 1ββ€βnout,βmoutββ€β105, and the actual values in the sets aout,βi and bout,βi must satisfy the inequality 1ββ€βaout,βi,βbout,βiββ€β107. Separate the values in the lines by spaces. The printed fraction must be reduced, that is, there mustn't be such integer x (xβ>β1), that the numerator and the denominator of the printed fraction are divisible by x. If there are several matching answers, print any of them. | standard output | |
PASSED | f68e34cdd4b5d2bc155d98eb34b23143 | train_003.jsonl | 1347291900 | To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you. | 256 megabytes | import java.awt.Point;
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.io.StreamTokenizer;
import java.util.ArrayList;
import java.util.Arrays;
public class C {
static StreamTokenizer st;
static int[]primes, ind;
static int cnt;
public static void main(String[] args) throws IOException{
st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int t = (int) 1e7;
boolean[]prime = new boolean[t+1];
Arrays.fill(prime, true);
for (int i = 2; i*i <= t; i++) {
if (prime[i]) {
for (int j = i*i; j <= t; j += i) {
prime[j] = false;
}
}
}
primes = new int[(int) 8e5];
cnt = 0;
for (int i = 2; i <= t; i++) {
if (prime[i])
primes[++cnt] = i;
}
int[]pow = new int[cnt+1];
int n = nextInt();
int m = nextInt();
ind = new int[t+1];
for (int i = 1; i <= cnt; i++) {
ind[primes[i]] = i;
}
@SuppressWarnings("unchecked")
ArrayList<Point>[]nom = new ArrayList[n+1], denom = new ArrayList[m+1];
for (int i = 1; i <= n; i++) {
nom[i] = factors(nextInt());
}
for (int i = 1; i <= m; i++) {
denom[i] = factors(nextInt());
}
for (int i = 1; i <= n; i++) {
for (Point p : nom[i]) {
pow[ind[p.x]] += p.y;
}
}
for (int i = 1; i <= m; i++) {
for (Point p : denom[i]) {
pow[ind[p.x]] -= p.y;
}
}
pw.println(n+" "+m);
for (int i = 1; i <= n; i++) {
int k = 1;
for (Point p : nom[i]) {
if (pow[ind[p.x]] <= 0)
continue;
if (pow[ind[p.x]] >= p.y) {
k *= (int)Math.pow(p.x, p.y);
pow[ind[p.x]] -= p.y;
}
else {
k *= (int)Math.pow(p.x, pow[ind[p.x]]);
pow[ind[p.x]] = 0;
}
}
pw.print(k+" ");
}
pw.println();
for (int i = 1; i <= m; i++) {
int k = 1;
for (Point p : denom[i]) {
if (pow[ind[p.x]] >= 0)
continue;
if (-pow[ind[p.x]] >= p.y) {
k *= (int)Math.pow(p.x, p.y);
pow[ind[p.x]] += p.y;
}
else {
k *= (int)Math.pow(p.x, -pow[ind[p.x]]);
pow[ind[p.x]] = 0;
}
}
pw.print(k+" ");
}
pw.close();
}
private static ArrayList<Point> factors(int k) {
ArrayList<Point> res = new ArrayList<Point>();
for (int j = 1; j <= cnt; j++) {
if (primes[j]*primes[j] > k)
break;
if (k % primes[j]==0) {
int pow = 0;
while (k % primes[j]==0) {
pow++;
k /= primes[j];
}
res.add(new Point(primes[j], pow));
}
}
if (k > 1)
res.add(new Point(k, 1));
return res;
}
private static int nextInt() throws IOException{
st.nextToken();
return (int) st.nval;
}
}
| Java | ["3 2\n100 5 2\n50 10", "4 3\n2 5 10 20\n100 1 3"] | 2 seconds | ["2 3\n2 1\n1 1 1", "1 1\n20\n3"] | NoteIn the first test sample the numerator equals 1000, the denominator equals 500. If we reduce fraction 1000/500 by the greatest common divisor of the numerator and the denominator (by 500), we obtain fraction 2/1.In the second test sample the numerator equals 2000, the denominator equals 300. If we reduce fraction 2000/300 by the greatest common divisor of the numerator and the denominator (by 100), we obtain fraction 20/3. | Java 6 | standard input | [
"implementation",
"number theory",
"sortings",
"math"
] | 01ac609133428a0074e8506786096e02 | The first input line contains two space-separated integers n, m (1ββ€βn,βmββ€β105) that show how many numbers the first set (the numerator) and the second set (the denominator) contain, correspondingly. The second line contains n space-separated integers: a1,βa2,β...,βan (1ββ€βaiββ€β107) β the numbers that are multiplied to produce the numerator. The third line contains m space-separated integers: b1,βb2,β...,βbm (1ββ€βbiββ€β107) β the numbers that are multiplied to produce the denominator. | 1,800 | Print the answer to the problem in the form, similar to the form of the input data. The number of values in the sets you print nout,βmout must satisfy the inequality 1ββ€βnout,βmoutββ€β105, and the actual values in the sets aout,βi and bout,βi must satisfy the inequality 1ββ€βaout,βi,βbout,βiββ€β107. Separate the values in the lines by spaces. The printed fraction must be reduced, that is, there mustn't be such integer x (xβ>β1), that the numerator and the denominator of the printed fraction are divisible by x. If there are several matching answers, print any of them. | standard output | |
PASSED | dfa157845058a8e584d023c423c04809 | train_003.jsonl | 1347291900 | To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class C137 {
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter out;
public static int[] generateLeastFactor(int num) {
if (num < 0) throw new IllegalArgumentException();
if (num == 1) return new int[]{0, 1};
int[] result = new int[num + 1];
result[0] = 0;
result[1] = 1;
for (int i = 2; i * i <= num; i++) {
if (result[i] == 0) {
result[i] = i;
for (int j = i * i; j <= num; j += i) {
if (result[j] == 0) result[j] = i;
}
}
}
for (int i = 2; i <= num; i++)
if (result[i] == 0)
result[i] = i;
return result;
}
public void solve() throws IOException {
int[] factors = generateLeastFactor(10000000);
int N = nextInt();
int M = nextInt();
int[] counter = new int[10000000+1];
int[] ups = new int[N];
int[] downs = new int[M];
for(int i = 0; i < N; i++){
int a = nextInt();
ups[i] = a;
while(a > 1){
counter[ factors[a] ]++;
a /= factors[a];
}
}
for(int i = 0; i < M; i++){
int a = nextInt();
downs[i] = a;
while(a > 1){
counter[ factors[a] ]--;
a /= factors[a];
}
}
// for(int i = 0; i < 10; i++){
// out.println( counter[i] );
// }
out.println( N + " " + M);
for(int i = 0; i < N; i++){
int a = ups[i], output = ups[i];
while(a > 1){
if( counter[ factors[a] ] > 0 ){
counter[ factors[a] ]--;
}
else
output /= factors[a];
a /= factors[a];
}
out.print(output + " ");
}
out.println();
for(int i = 0; i < M; i++){
int a = downs[i], output = downs[i];
while(a > 1){
if( counter[ factors[a] ] < 0 ){
counter[ factors[a] ]++;
}
else
output /= factors[a];
a /= factors[a];
}
out.print(output + " ");
}
out.println();
}
/**
* @param args
*/
public static void main(String[] args) {
new C137().run();
}
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
out = new PrintWriter(System.out);
solve();
reader.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
| Java | ["3 2\n100 5 2\n50 10", "4 3\n2 5 10 20\n100 1 3"] | 2 seconds | ["2 3\n2 1\n1 1 1", "1 1\n20\n3"] | NoteIn the first test sample the numerator equals 1000, the denominator equals 500. If we reduce fraction 1000/500 by the greatest common divisor of the numerator and the denominator (by 500), we obtain fraction 2/1.In the second test sample the numerator equals 2000, the denominator equals 300. If we reduce fraction 2000/300 by the greatest common divisor of the numerator and the denominator (by 100), we obtain fraction 20/3. | Java 6 | standard input | [
"implementation",
"number theory",
"sortings",
"math"
] | 01ac609133428a0074e8506786096e02 | The first input line contains two space-separated integers n, m (1ββ€βn,βmββ€β105) that show how many numbers the first set (the numerator) and the second set (the denominator) contain, correspondingly. The second line contains n space-separated integers: a1,βa2,β...,βan (1ββ€βaiββ€β107) β the numbers that are multiplied to produce the numerator. The third line contains m space-separated integers: b1,βb2,β...,βbm (1ββ€βbiββ€β107) β the numbers that are multiplied to produce the denominator. | 1,800 | Print the answer to the problem in the form, similar to the form of the input data. The number of values in the sets you print nout,βmout must satisfy the inequality 1ββ€βnout,βmoutββ€β105, and the actual values in the sets aout,βi and bout,βi must satisfy the inequality 1ββ€βaout,βi,βbout,βiββ€β107. Separate the values in the lines by spaces. The printed fraction must be reduced, that is, there mustn't be such integer x (xβ>β1), that the numerator and the denominator of the printed fraction are divisible by x. If there are several matching answers, print any of them. | standard output | |
PASSED | 380c86bdf5de8f153af069f6e0e83ac3 | train_003.jsonl | 1347291900 | To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you. | 256 megabytes |
import javax.jws.Oneway;
import java.io.*;
import java.math.BigInteger;
import static java.math.BigInteger.*;
import java.security.PublicKey;
import java.util.*;
public class Solution{
class C
{
int n;
int[]nums;
int[]pows;
int[][]r;
int[][]p;
public C(int n)throws Exception
{
this.n=n;
nums=new int[n];
pows=new int[len];
r=new int[n][];
p=new int[n][];
for(int i=0;i<n;i++)
{
doIt(i);
}
}
void doIt(int at)throws Exception
{
nums[at]=nextInt();
int t=nums[at];
ArrayList<Integer>l1=new ArrayList<Integer>();
ArrayList<Integer>p1=new ArrayList<Integer>();
while (t>1)
{
int x=d[t];
int cnt=0;
while (t%x==0)
{
cnt++;
t/=x;
}
l1.add(inds[x]);
p1.add(cnt);
}
r[at]=new int[l1.size()];
p[at]=new int[p1.size()];
for(int i=0;i<r[at].length;i++)
{
r[at][i]=l1.get(i);
p[at][i]=p1.get(i);
pows[r[at][i]]+=p[at][i];
}
}
void makeGood(int[]rem)
{
for(int at=0;at<n;at++)
{
for(int i=0;i<r[at].length;i++)
{
int z=Math.min(rem[r[at][i]],p[at][i]);
p[at][i]-=z;
rem[r[at][i]]-=z;
}
}
}
void print()
{
for(int at=0;at<n;at++)
{
int cur=1;
for(int i=0;i<r[at].length;i++)
{
for(int j=0;j<p[at][i];j++)
cur*=what[r[at][i]];
}
if(at==n-1)
writer.println(cur);
else
writer.print(cur+" ");
}
}
}
int[]d;
int maxn=10000001;
int[]inds;
int len;
int[]what;
void solve()throws Exception
{
d=new int[maxn];
for(int i=2;i<d.length;i++)
d[i]=i;
for(int i=2;i*i<d.length;i++)
if(d[i]==i)
for(int j=i*i;j<d.length;j+=i)
d[j]=i;
inds=new int[maxn];
Arrays.fill(inds,-1);
len=0;
for(int i=2;i<d.length;i++)
if(d[i]==i)
inds[i]=len++;
what=new int[len];
len=0;
for(int i=2;i<d.length;i++)
if(d[i]==i)
what[len++]=i;
int n=nextInt();
int m=nextInt();
C c1=new C(n);
C c2=new C(m);
int[]rem=new int[len];
for(int i=0;i<rem.length;i++)
rem[i]=Math.min(c1.pows[i],c2.pows[i]);
int[]temp=rem.clone();
c1.makeGood(rem);
rem=temp;
c2.makeGood(rem);
writer.println(n+" "+m);
c1.print();
c2.print();
}
////////////
BufferedReader reader;
PrintWriter writer;
StringTokenizer stk;
void run()throws Exception
{
reader=new BufferedReader(new InputStreamReader(System.in));
//reader=new BufferedReader(new FileReader("3.in"));
stk=null;
writer=new PrintWriter(new PrintWriter(System.out));
//writer=new PrintWriter(new FileWriter("output.txt"));
solve();
reader.close();
writer.close();
}
int nextInt()throws Exception
{
return Integer.parseInt(nextToken());
}
long nextLong()throws Exception
{
return Long.parseLong(nextToken());
}
double nextDouble()throws Exception
{
return Double.parseDouble(nextToken());
}
String nextString()throws Exception
{
return nextToken();
}
String nextLine()throws Exception
{
return reader.readLine();
}
String nextToken()throws Exception
{
if(stk==null || !stk.hasMoreTokens())
{
stk=new StringTokenizer(nextLine());
return nextToken();
}
return stk.nextToken();
}
public static void main(String[]args) throws Exception
{
new Solution().run();
}
}
| Java | ["3 2\n100 5 2\n50 10", "4 3\n2 5 10 20\n100 1 3"] | 2 seconds | ["2 3\n2 1\n1 1 1", "1 1\n20\n3"] | NoteIn the first test sample the numerator equals 1000, the denominator equals 500. If we reduce fraction 1000/500 by the greatest common divisor of the numerator and the denominator (by 500), we obtain fraction 2/1.In the second test sample the numerator equals 2000, the denominator equals 300. If we reduce fraction 2000/300 by the greatest common divisor of the numerator and the denominator (by 100), we obtain fraction 20/3. | Java 6 | standard input | [
"implementation",
"number theory",
"sortings",
"math"
] | 01ac609133428a0074e8506786096e02 | The first input line contains two space-separated integers n, m (1ββ€βn,βmββ€β105) that show how many numbers the first set (the numerator) and the second set (the denominator) contain, correspondingly. The second line contains n space-separated integers: a1,βa2,β...,βan (1ββ€βaiββ€β107) β the numbers that are multiplied to produce the numerator. The third line contains m space-separated integers: b1,βb2,β...,βbm (1ββ€βbiββ€β107) β the numbers that are multiplied to produce the denominator. | 1,800 | Print the answer to the problem in the form, similar to the form of the input data. The number of values in the sets you print nout,βmout must satisfy the inequality 1ββ€βnout,βmoutββ€β105, and the actual values in the sets aout,βi and bout,βi must satisfy the inequality 1ββ€βaout,βi,βbout,βiββ€β107. Separate the values in the lines by spaces. The printed fraction must be reduced, that is, there mustn't be such integer x (xβ>β1), that the numerator and the denominator of the printed fraction are divisible by x. If there are several matching answers, print any of them. | standard output | |
PASSED | 9d672f02e5cdf4c1430122b989ff0644 | train_003.jsonl | 1347291900 | To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // ΡΠΎΠ·Π΄Π°ΡΠΌ ΠΎΠ±ΡΠ΅ΠΊΡ ΠΊΠ»Π°ΡΡΠ° Scanner
int n = sc.nextInt();
int m = sc.nextInt();
int [] a = new int[n];
for(int i = 0; i < n; i++)
a[i] = sc.nextInt();
int [] b = new int[m];
for(int i = 0;i < m; i++)
b[i] = sc.nextInt();
System.out.println(n + " " + m);
// eratosthenes
final int max = 10000000;
//int N = (int)Math.sqrt(max);
int N = max;
boolean [] primes = new boolean[N + 1];
int [] lp = new int[N + 1];
Arrays.fill(primes, true);
primes[0] = false;
primes[1] = false;
int i = 2;
int cnt = N;
while (i * i <= N) {
if (primes[i] == true) {
int j = i * i;
while (j <= N){
if (primes[j] == true) {
primes[j] = false;
cnt --;
lp[j] = i;
}
j += i;
}
}
i += 1;
}
for (i = 0; i < N; i++) {
if (primes[i] == true) {
lp[i] = i;
}
}
//System.out.println("lp: " + lp[6889]);
// factorization and division
//Map<Integer, Integer> dict = new HashMap<Integer, Integer>();
int [] degs = new int[10000000];
int pr = 0;
int cur = 0;
int el = 0;
for (i = 0; i < n; i++) {
el = a[i];
while (el != 1) {
pr = lp[el];
el = el / pr;
degs[pr] += 1;
}
}
//System.out.println("enum: " + dict);
for (i = 0; i < m; i++) {
el = b[i];
while (el != 1) {
pr = lp[el];
el = el / pr;
degs[pr] -= 1;
}
}
//System.out.println("after division: " + dict);
// reducing fraction
int prod;
for (i = 0; i < n; i++) {
pr = lp[a[i]];
prod = 1;
while (a[i] != 1) {
if (degs[pr] > 0) {
prod *= pr;
degs[pr] -= 1;
}
a[i] = a[i] / pr;
pr = lp[a[i]];
}
System.out.print(prod + " ");
}
System.out.println();
for (i = 0; i < m; i++) {
pr = lp[b[i]];
prod = 1;
while (b[i] != 1) {
if (degs[pr] < 0) {
degs[pr] += 1;
prod *= pr;
}
b[i] = b[i] / pr;
pr = lp[b[i]];
}
System.out.print(prod + " ");
}
}
} | Java | ["3 2\n100 5 2\n50 10", "4 3\n2 5 10 20\n100 1 3"] | 2 seconds | ["2 3\n2 1\n1 1 1", "1 1\n20\n3"] | NoteIn the first test sample the numerator equals 1000, the denominator equals 500. If we reduce fraction 1000/500 by the greatest common divisor of the numerator and the denominator (by 500), we obtain fraction 2/1.In the second test sample the numerator equals 2000, the denominator equals 300. If we reduce fraction 2000/300 by the greatest common divisor of the numerator and the denominator (by 100), we obtain fraction 20/3. | Java 6 | standard input | [
"implementation",
"number theory",
"sortings",
"math"
] | 01ac609133428a0074e8506786096e02 | The first input line contains two space-separated integers n, m (1ββ€βn,βmββ€β105) that show how many numbers the first set (the numerator) and the second set (the denominator) contain, correspondingly. The second line contains n space-separated integers: a1,βa2,β...,βan (1ββ€βaiββ€β107) β the numbers that are multiplied to produce the numerator. The third line contains m space-separated integers: b1,βb2,β...,βbm (1ββ€βbiββ€β107) β the numbers that are multiplied to produce the denominator. | 1,800 | Print the answer to the problem in the form, similar to the form of the input data. The number of values in the sets you print nout,βmout must satisfy the inequality 1ββ€βnout,βmoutββ€β105, and the actual values in the sets aout,βi and bout,βi must satisfy the inequality 1ββ€βaout,βi,βbout,βiββ€β107. Separate the values in the lines by spaces. The printed fraction must be reduced, that is, there mustn't be such integer x (xβ>β1), that the numerator and the denominator of the printed fraction are divisible by x. If there are several matching answers, print any of them. | standard output | |
PASSED | 7332d9c62afd03ab928b5ab69fb921be | train_003.jsonl | 1347291900 | To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you. | 256 megabytes | import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
}
class TaskC {
int[] primesNum;
int[] primesDen;
int[][] factorsNum;
int[][] factorsDen;
int[] primes;
int[] tmp = new int[30];
int[] addPrimes(int x, int[] primesTable) {
int sqrt = (int) Math.sqrt(x) + 2;
int cnt = 0;
for (int it = 0; it < primesTable.length; it++) {
int i = primes[it];
if (i > sqrt) break;
while (x % i == 0) {
primesTable[it]++;
x /= i;
sqrt = (int) Math.sqrt(x) + 2;
tmp[cnt++] = it;
}
}
if (x > 1) {
int pos = Arrays.binarySearch(primes, x);
primesTable[pos]++;
tmp[cnt++] = pos;
}
int[] ret = new int[cnt];
System.arraycopy(tmp, 0, ret, 0, cnt);
return ret;
}
void precalc() {
boolean[] isPrime = new boolean[10000001];
ArrayList<Integer> pr = new ArrayList<Integer>();
int n = 10000001;
Arrays.fill(isPrime, true);
isPrime[0] = isPrime[1] = false;
for (int i = 2; i < n; i++)
if (isPrime[i]) {
for (long j = (long) i * i; j < n; j += i)
isPrime[(int) j] = false;
pr.add(i);
}
primesNum = new int[pr.size()];
primesDen = new int[pr.size()];
primes = new int[pr.size()];
for (int i = 0; i < primes.length; i++)
primes[i] = pr.get(i);
}
int fetchPrimes(int x, int[] primesTable, int[] factors) {
int ret = x;
for (int p : factors) {
if (primesTable[p] > 0) {
primesTable[p]--;
ret /= primes[p];
}
}
return ret;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
precalc();
int n = in.nextInt();
int m = in.nextInt();
int[] a = new int[n];
int[] b = new int[m];
factorsNum = new int[n][];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
factorsNum[i] = addPrimes(a[i], primesNum);
}
factorsDen = new int[m][];
for (int i = 0; i < m; i++) {
b[i] = in.nextInt();
factorsDen[i] = addPrimes(b[i], primesDen);
}
for (int i = 0; i < primesNum.length; i++)
primesNum[i] = primesDen[i] = Math.min(primesNum[i], primesDen[i]);
for (int i = 0; i < n; i++)
a[i] = fetchPrimes(a[i], primesNum, factorsNum[i]);
for (int i = 0; i < m; i++)
b[i] = fetchPrimes(b[i], primesDen, factorsDen[i]);
out.println(n + " " + m);
for (int cur : a) {
out.print(cur);
out.print(" ");
}
out.println();
for (int cur : b) {
out.print(cur);
out.print(" ");
}
out.println();
}
}
class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
}
| Java | ["3 2\n100 5 2\n50 10", "4 3\n2 5 10 20\n100 1 3"] | 2 seconds | ["2 3\n2 1\n1 1 1", "1 1\n20\n3"] | NoteIn the first test sample the numerator equals 1000, the denominator equals 500. If we reduce fraction 1000/500 by the greatest common divisor of the numerator and the denominator (by 500), we obtain fraction 2/1.In the second test sample the numerator equals 2000, the denominator equals 300. If we reduce fraction 2000/300 by the greatest common divisor of the numerator and the denominator (by 100), we obtain fraction 20/3. | Java 6 | standard input | [
"implementation",
"number theory",
"sortings",
"math"
] | 01ac609133428a0074e8506786096e02 | The first input line contains two space-separated integers n, m (1ββ€βn,βmββ€β105) that show how many numbers the first set (the numerator) and the second set (the denominator) contain, correspondingly. The second line contains n space-separated integers: a1,βa2,β...,βan (1ββ€βaiββ€β107) β the numbers that are multiplied to produce the numerator. The third line contains m space-separated integers: b1,βb2,β...,βbm (1ββ€βbiββ€β107) β the numbers that are multiplied to produce the denominator. | 1,800 | Print the answer to the problem in the form, similar to the form of the input data. The number of values in the sets you print nout,βmout must satisfy the inequality 1ββ€βnout,βmoutββ€β105, and the actual values in the sets aout,βi and bout,βi must satisfy the inequality 1ββ€βaout,βi,βbout,βiββ€β107. Separate the values in the lines by spaces. The printed fraction must be reduced, that is, there mustn't be such integer x (xβ>β1), that the numerator and the denominator of the printed fraction are divisible by x. If there are several matching answers, print any of them. | standard output | |
PASSED | bfaf9d97f0529156373a58260440d25a | train_003.jsonl | 1347291900 | To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you. | 256 megabytes | import java.util.*;
import java.io.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class C {
final int SIZE = 10001000;
//final int SIZE = 10000;
int[] factor = new int [SIZE+1]; // οΏ½οΏ½οΏ½OοΏ½ΜfοΏ½οΏ½οΏ½οΏ½
int[] cntbo = new int [SIZE+1]; // οΏ½οΏ½οΏ½οΏ½ΜfοΏ½οΏ½οΏ½ΜpοΏ½x
int[] cntshi = new int [SIZE+1]; // οΏ½οΏ½οΏ½qοΏ½ΜfοΏ½οΏ½οΏ½ΜpοΏ½x
Scanner sc = new Scanner(System.in);
void doIt()
{
int n = sc.nextInt(), m = sc.nextInt();
int [] bunshi = new int[n], bunbo = new int[m];
int [] ansshi = new int[n], ansbo = new int[m];
for(int i = 0; i < n; i++) bunshi[i] = ansshi[i] = sc.nextInt();
for(int i = 0; i < m; i++) bunbo[i] = ansbo[i] = sc.nextInt();
factor[0] = factor[1] = 1;
// οΏ½GοΏ½οΏ½οΏ½gοΏ½XοΏ½eοΏ½lοΏ½XοΏ½οΏ½βΏοΏ½οΏ½οΏ½οΏ½ΘοΏ½οΏ½οΏ½fοΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ίΔοΏ½οΏ½οΏ½
for(int i = 2; i <= SIZE; i++) {
if(factor[i] == 0) {
factor[i] = i; // οΏ½fοΏ½οΏ½οΏ½ΜΖοΏ½οΏ½ΝοΏ½οΏ½οΏ½
for(int j = i + i; j <= SIZE; j+=i) {
factor[j] = i; // οΏ½οΏ½οΏ½OοΏ½ΜfοΏ½οΏ½οΏ½οΏ½
}
}
}
//debug(factor);
resolv(bunshi, cntshi); // οΏ½οΏ½οΏ½qοΏ½οΏ½οΏ½οΏ½fοΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½
resolv(bunbo, cntbo); // οΏ½οΏ½οΏ½οΏ½οΏ½fοΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½
//debug(bunshi);
//debug(bunbo);
//debug(cntshi);
//debug(cntbo);
// οΏ½οΏ½οΏ½ΚΜοΏ½οΏ½οΏ½οΏ½cοΏ½οΏ½οΏ½iοΏ½pοΏ½xοΏ½ΜοΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½j
for(int i = 0; i <= SIZE; i++) {
int v = min(cntshi[i], cntbo[i]);
cntshi[i] = cntbo[i] = v;
}
factrize(bunshi, cntshi, ansshi);
factrize(bunbo, cntbo, ansbo);
System.out.println(n + " " + m);
for(int i = 0; i < n; i++) System.out.print(ansshi[i] + " ");
System.out.println();
for(int i = 0; i < m; i++) System.out.print(ansbo[i] + " ");
System.out.println();
System.out.flush();
}
void factrize(int [] orig, int [] cnt, int [] ans)
{
//debug(ans);
//debug(cnt);
for(int i = 0; i < orig.length; i++) {
int n = orig[i];
while(n > 1) {
if(cnt[factor[n]] > 0) {
ans[i] /= factor[n];
cnt[factor[n]]--;
}
n /= factor[n];
}
}
//debug(ans);
//debug(cnt);
}
void resolv(int [] nums, int[] cnt)
{
for(int i = 0; i < nums.length; i++) {
int n = nums[i];
while(n > 1) {
cnt[factor[n]]++;
n /= factor[n];
}
}
}
public static void main(String[] args) {
new C().doIt();
}
void debug(Object...os) {
System.err.println(deepToString(os));
}
// thanks to wata
class Scanner {
InputStream in;
byte[] buf = new byte[1 << 10];
int p, n;
boolean[] isSpace = new boolean[128];
Scanner(InputStream in) {
this.in = in;
isSpace[' '] = isSpace['\n'] = isSpace['\r'] = isSpace['\t'] = true;
}
int read() {
if (n == -1) return -1;
if (p >= n) {
p = 0;
try {
n = in.read(buf);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (n <= 0) return -1;
}
return buf[p++];
}
boolean hasNext() {
int c = read();
while (c >= 0 && isSpace[c]) c = read();
if (c == -1) return false;
p--;
return true;
}
String next() {
if (!hasNext()) throw new InputMismatchException();
StringBuilder sb = new StringBuilder();
int c = read();
while (c >= 0 && !isSpace[c]) {
sb.append((char)c);
c = read();
}
return sb.toString();
}
int nextInt() {
if (!hasNext()) throw new InputMismatchException();
int 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 (c >= 0 && !isSpace[c]);
return res * sgn;
}
long nextLong() {
if (!hasNext()) throw new InputMismatchException();
int 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 (c >= 0 && !isSpace[c]);
return res * sgn;
}
double nextDouble() {
return Double.parseDouble(next());
}
}
}
| Java | ["3 2\n100 5 2\n50 10", "4 3\n2 5 10 20\n100 1 3"] | 2 seconds | ["2 3\n2 1\n1 1 1", "1 1\n20\n3"] | NoteIn the first test sample the numerator equals 1000, the denominator equals 500. If we reduce fraction 1000/500 by the greatest common divisor of the numerator and the denominator (by 500), we obtain fraction 2/1.In the second test sample the numerator equals 2000, the denominator equals 300. If we reduce fraction 2000/300 by the greatest common divisor of the numerator and the denominator (by 100), we obtain fraction 20/3. | Java 6 | standard input | [
"implementation",
"number theory",
"sortings",
"math"
] | 01ac609133428a0074e8506786096e02 | The first input line contains two space-separated integers n, m (1ββ€βn,βmββ€β105) that show how many numbers the first set (the numerator) and the second set (the denominator) contain, correspondingly. The second line contains n space-separated integers: a1,βa2,β...,βan (1ββ€βaiββ€β107) β the numbers that are multiplied to produce the numerator. The third line contains m space-separated integers: b1,βb2,β...,βbm (1ββ€βbiββ€β107) β the numbers that are multiplied to produce the denominator. | 1,800 | Print the answer to the problem in the form, similar to the form of the input data. The number of values in the sets you print nout,βmout must satisfy the inequality 1ββ€βnout,βmoutββ€β105, and the actual values in the sets aout,βi and bout,βi must satisfy the inequality 1ββ€βaout,βi,βbout,βiββ€β107. Separate the values in the lines by spaces. The printed fraction must be reduced, that is, there mustn't be such integer x (xβ>β1), that the numerator and the denominator of the printed fraction are divisible by x. If there are several matching answers, print any of them. | standard output | |
PASSED | 9e3ace5ffa7b224c93e56ca6ab626a51 | train_003.jsonl | 1347291900 | To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you. | 256 megabytes | import java.util.*;
import java.io.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class C {
final int SIZE = 10001000;
//final int SIZE = 10000;
int[] factor = new int [SIZE+1]; // οΏ½οΏ½οΏ½OοΏ½ΜfοΏ½οΏ½οΏ½οΏ½
int[] cntbo = new int [SIZE+1]; // οΏ½οΏ½οΏ½οΏ½ΜfοΏ½οΏ½οΏ½ΜpοΏ½x
int[] cntshi = new int [SIZE+1]; // οΏ½οΏ½οΏ½qοΏ½ΜfοΏ½οΏ½οΏ½ΜpοΏ½x
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
void doIt()
{
int n = sc.nextInt(), m = sc.nextInt();
int [] bunshi = new int[n], bunbo = new int[m];
int [] ansshi = new int[n], ansbo = new int[m];
for(int i = 0; i < n; i++) bunshi[i] = ansshi[i] = sc.nextInt();
for(int i = 0; i < m; i++) bunbo[i] = ansbo[i] = sc.nextInt();
factor[0] = factor[1] = 1;
// οΏ½GοΏ½οΏ½οΏ½gοΏ½XοΏ½eοΏ½lοΏ½XοΏ½οΏ½βΏοΏ½οΏ½οΏ½οΏ½ΘοΏ½οΏ½οΏ½fοΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½ίΔοΏ½οΏ½οΏ½
for(int i = 2; i <= SIZE; i++) {
if(factor[i] == 0) {
factor[i] = i; // οΏ½fοΏ½οΏ½οΏ½ΜΖοΏ½οΏ½ΝοΏ½οΏ½οΏ½
for(int j = i + i; j <= SIZE; j+=i) {
factor[j] = i; // οΏ½οΏ½οΏ½OοΏ½ΜfοΏ½οΏ½οΏ½οΏ½
}
}
}
//debug(factor);
resolv(bunshi, cntshi); // οΏ½οΏ½οΏ½qοΏ½οΏ½οΏ½οΏ½fοΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½
resolv(bunbo, cntbo); // οΏ½οΏ½οΏ½οΏ½οΏ½fοΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½
//debug(bunshi);
//debug(bunbo);
//debug(cntshi);
//debug(cntbo);
// οΏ½οΏ½οΏ½ΚΜοΏ½οΏ½οΏ½οΏ½cοΏ½οΏ½οΏ½iοΏ½pοΏ½xοΏ½ΜοΏ½οΏ½οΏ½οΏ½οΏ½οΏ½οΏ½j
for(int i = 0; i <= SIZE; i++) {
int v = min(cntshi[i], cntbo[i]);
cntshi[i] = cntbo[i] = v;
}
factrize(bunshi, cntshi, ansshi);
factrize(bunbo, cntbo, ansbo);
out.println(n + " " + m);
for(int i = 0; i < n; i++) out.print(ansshi[i] + " ");
out.println();
for(int i = 0; i < m; i++) out.print(ansbo[i] + " ");
out.println();
out.flush();
}
void factrize(int [] orig, int [] cnt, int [] ans)
{
//debug(ans);
//debug(cnt);
for(int i = 0; i < orig.length; i++) {
int n = orig[i];
while(n > 1) {
if(cnt[factor[n]] > 0) {
ans[i] /= factor[n];
cnt[factor[n]]--;
}
n /= factor[n];
}
}
//debug(ans);
//debug(cnt);
}
void resolv(int [] nums, int[] cnt)
{
for(int i = 0; i < nums.length; i++) {
int n = nums[i];
while(n > 1) {
cnt[factor[n]]++;
n /= factor[n];
}
}
}
public static void main(String[] args) {
new C().doIt();
}
void debug(Object...os) {
System.err.println(deepToString(os));
}
// thanks to wata
class Scanner {
InputStream in;
byte[] buf = new byte[1 << 10];
int p, n;
boolean[] isSpace = new boolean[128];
Scanner(InputStream in) {
this.in = in;
isSpace[' '] = isSpace['\n'] = isSpace['\r'] = isSpace['\t'] = true;
}
int read() {
if (n == -1) return -1;
if (p >= n) {
p = 0;
try {
n = in.read(buf);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (n <= 0) return -1;
}
return buf[p++];
}
boolean hasNext() {
int c = read();
while (c >= 0 && isSpace[c]) c = read();
if (c == -1) return false;
p--;
return true;
}
String next() {
if (!hasNext()) throw new InputMismatchException();
StringBuilder sb = new StringBuilder();
int c = read();
while (c >= 0 && !isSpace[c]) {
sb.append((char)c);
c = read();
}
return sb.toString();
}
int nextInt() {
if (!hasNext()) throw new InputMismatchException();
int 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 (c >= 0 && !isSpace[c]);
return res * sgn;
}
long nextLong() {
if (!hasNext()) throw new InputMismatchException();
int 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 (c >= 0 && !isSpace[c]);
return res * sgn;
}
double nextDouble() {
return Double.parseDouble(next());
}
}
}
| Java | ["3 2\n100 5 2\n50 10", "4 3\n2 5 10 20\n100 1 3"] | 2 seconds | ["2 3\n2 1\n1 1 1", "1 1\n20\n3"] | NoteIn the first test sample the numerator equals 1000, the denominator equals 500. If we reduce fraction 1000/500 by the greatest common divisor of the numerator and the denominator (by 500), we obtain fraction 2/1.In the second test sample the numerator equals 2000, the denominator equals 300. If we reduce fraction 2000/300 by the greatest common divisor of the numerator and the denominator (by 100), we obtain fraction 20/3. | Java 6 | standard input | [
"implementation",
"number theory",
"sortings",
"math"
] | 01ac609133428a0074e8506786096e02 | The first input line contains two space-separated integers n, m (1ββ€βn,βmββ€β105) that show how many numbers the first set (the numerator) and the second set (the denominator) contain, correspondingly. The second line contains n space-separated integers: a1,βa2,β...,βan (1ββ€βaiββ€β107) β the numbers that are multiplied to produce the numerator. The third line contains m space-separated integers: b1,βb2,β...,βbm (1ββ€βbiββ€β107) β the numbers that are multiplied to produce the denominator. | 1,800 | Print the answer to the problem in the form, similar to the form of the input data. The number of values in the sets you print nout,βmout must satisfy the inequality 1ββ€βnout,βmoutββ€β105, and the actual values in the sets aout,βi and bout,βi must satisfy the inequality 1ββ€βaout,βi,βbout,βiββ€β107. Separate the values in the lines by spaces. The printed fraction must be reduced, that is, there mustn't be such integer x (xβ>β1), that the numerator and the denominator of the printed fraction are divisible by x. If there are several matching answers, print any of them. | standard output | |
PASSED | 1b5660803e7e3cd95c666ee508b43dd1 | train_003.jsonl | 1347291900 | To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class C
{
static class Scanner
{
BufferedReader br;
StringTokenizer st;
public Scanner()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next()
{
while(st == null || !st.hasMoreTokens())
{
try { st = new StringTokenizer(br.readLine()); }
catch(Exception e) { throw new RuntimeException(); }
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public double nextDouble()
{
return Double.parseDouble(next());
}
public String nextLine()
{
st = null;
try { return br.readLine(); }
catch(Exception e) { throw new RuntimeException(); }
}
public boolean endLine()
{
try
{
String next = br.readLine();
while(next != null && next.trim().isEmpty())
next = br.readLine();
if(next == null)
return true;
st = new StringTokenizer(next);
return st.hasMoreTokens();
}
catch(Exception e) { throw new RuntimeException(); }
}
}
static final int[] primos = new int[600];
static final int[] cuadrados = new int[600];
static final int[] todos = new int[10000001];
static void agregar(int numero, int signo)
{
for(int i = 0; true; i++)
{
if(cuadrados[i] > numero)
break;
int pA = primos[i];
while(numero % pA == 0)
{
todos[pA] += signo;
numero /= pA;
}
}
if(numero != 1)
todos[numero] += signo;
}
static int idA = 0;
static class Numero implements Comparable <Numero>
{
int numero;
int veces;
int id;
Numero(int n)
{
numero = n;
id = idA++;
}
@Override
public int compareTo(Numero o)
{
if(numero == o.numero)
return id - o.id;
return numero - o.numero;
}
@Override
public String toString()
{
return numero + ":" + veces;
}
}
static int[] factores = new int[100];
static int[] veces = new int[100];
static int posibleAgregar(int numero, int signo)
{
int nFactores = 0;
for(int i = 0; true; i++)
{
if(cuadrados[i] > numero)
break;
int pA = primos[i];
int cuenta = 0;
while(numero % pA == 0)
{
cuenta++;
numero /= pA;
}
if(cuenta != 0)
{
factores[nFactores] = pA;
veces[nFactores++] = cuenta;
}
}
if(numero != 1)
{
factores[nFactores] = numero;
veces[nFactores++] = 1;
}
if(signo == -1)
{
int minimo = Integer.MAX_VALUE;
for(int i = 0; i < nFactores; i++)
{
if(todos[factores[i]] > -veces[i])
return 0;
else
minimo = Math.min(minimo, (-todos[factores[i]]) / veces[i]);
}
return minimo;
}
else
{
int minimo = Integer.MAX_VALUE;
for(int i = 0; i < nFactores; i++)
{
if(todos[factores[i]] < veces[i])
return 0;
else
minimo = Math.min(minimo, (todos[factores[i]]) / veces[i]);
}
return minimo;
}
}
static class CachedMap extends TreeMap <Numero, Numero>
{
private static final long serialVersionUID = 276345233289370682L;
Numero last;
Numero first;
Numero giveLast()
{
if(last == null)
last = lastKey();
return last;
}
Numero giveFirst()
{
if(first == null)
first = firstKey();
return first;
}
int pollLastKey()
{
Numero cLast = giveLast();
if(cLast.veces == 1)
{
pollLastEntry();
last = null;
}
cLast.veces--;
return cLast.numero;
}
int pollFirstKey()
{
Numero cFirst = giveFirst();
if(cFirst.veces == 1)
{
pollFirstEntry();
first = null;
}
cFirst.veces--;
return cFirst.numero;
}
public void addFirst(int primero)
{
Numero cFirst = giveFirst();
if(cFirst.numero == primero)
cFirst.veces++;
else
{
first = null;
Numero nuevo = new Numero(primero);
nuevo.veces = 1;
put(nuevo, nuevo);
}
}
public void removeMiddle(Numero numero)
{
if(numero.veces == 1)
{
if(numero == first)
first = null;
if(numero == last)
last = null;
remove(numero);
}
else
numero.veces--;
}
}
static void solucionar(CachedMap as, LinkedList <Integer> pA)
{
Numero temp = new Numero(0);
temp.id = 10000000;
Long ultimo = null;
while(!as.isEmpty())
{
if(ultimo == null)
ultimo = (long) as.pollLastKey();
if(!as.isEmpty())
{
int primero = as.giveFirst().numero;
if(ultimo * primero > 10000000)
{
pA.add((int) ultimo.longValue());
ultimo = null;
}
else
{
as.pollFirstKey();
if(!as.isEmpty())
{
int segundo = as.giveFirst().numero;
if(ultimo * primero * segundo > 10000000)
{
as.addFirst(primero);
temp.numero = (int) (10000000 / ultimo);
Numero mejor = as.floorKey(temp);
as.removeMiddle(mejor);
pA.add((int) (ultimo * mejor.numero));
ultimo = null;
}
else
{
ultimo = ultimo * primero;
}
}
else
{
pA.add((int) (primero * ultimo));
ultimo = null;
}
}
}
else
{
pA.add((int) ultimo.longValue());
ultimo = null;
}
}
if(ultimo != null)
pA.add((int) ultimo.longValue());
}
public static void main(String[] args)
{
Scanner sc = new Scanner();
boolean[] esPrimo = new boolean[4000];
esPrimo[0] = esPrimo[1] = false;
for(int i = 2; i < 4000; i++)
esPrimo[i] = true;
for(int i = 0; i < 4000; i++)
{
if(i * i > 4000)
break;
if(esPrimo[i])
for(int j = i * i; j < 4000; j += i)
esPrimo[j] = false;
}
int cuenta = 0;
for(int i = 0; i < 4000; i++)
if(esPrimo[i])
{
primos[cuenta] = i;
cuadrados[cuenta++] = i * i;
}
int n = sc.nextInt();
int m = sc.nextInt();
int[] aInicial = new int[n];
int[] bInicial = new int[m];
TreeMap <Integer, Integer> actuales = new TreeMap <Integer, Integer> ();
for(int i = 0; i < n; i++)
{
aInicial[i] = sc.nextInt();
if(aInicial[i] != 1)
actuales.put(aInicial[i], actuales.containsKey(aInicial[i]) ? actuales.get(aInicial[i]) + 1 : 1);
}
for(Map.Entry<Integer, Integer> e : actuales.entrySet())
agregar(e.getKey(), e.getValue());
actuales.clear();
for(int i = 0; i < m; i++)
{
bInicial[i] = sc.nextInt();
if(bInicial[i] != 1)
actuales.put(bInicial[i], actuales.containsKey(bInicial[i]) ? actuales.get(bInicial[i]) + 1 : 1);
}
for(Map.Entry<Integer, Integer> e : actuales.entrySet())
agregar(e.getKey(), -e.getValue());
actuales.clear();
LinkedList <Integer> pA = new LinkedList <Integer> ();
LinkedList <Integer> pB = new LinkedList <Integer> ();
Arrays.sort(aInicial);
Arrays.sort(bInicial);
for(int i = n - 1; i >= Math.max(0, n - 2); i--)
{
if(aInicial[i] != 1 && aInicial[i] > 5000000)
{
int vs = posibleAgregar(aInicial[i], 1);
if(vs != 0)
{
for(int j = 0; j < vs; j++)
pA.add(aInicial[i]);
agregar(aInicial[i], -vs);
}
}
}
for(int i = m - 1; i >= Math.max(0, m - 2); i--)
{
if(bInicial[i] != 1 && bInicial[i] > 5000000)
{
int vs = posibleAgregar(bInicial[i], -1);
if(vs != 0)
{
for(int j = 0; j < vs; j++)
pB.add(bInicial[i]);
agregar(bInicial[i], vs);
}
}
}
CachedMap as = new CachedMap();
CachedMap bs = new CachedMap();
StringBuilder a = new StringBuilder();
StringBuilder b = new StringBuilder();
for(int i = 0; i < todos.length; i++)
{
if(todos[i] > 0)
{
Numero nuevo = new Numero(i);
nuevo.veces = todos[i];
as.put(nuevo, nuevo);
}
}
for(int i = 0; i < todos.length; i++)
{
if(todos[i] < 0)
{
Numero nuevo = new Numero(i);
nuevo.veces = -todos[i];
bs.put(nuevo, nuevo);
}
}
solucionar(as, pA);
solucionar(bs, pB);
if(pA.isEmpty())
pA.add(1);
if(pB.isEmpty())
pB.add(1);
System.out.println(pA.size() + " " + pB.size());
boolean empezo = false;
for(int i : pA)
{
if(empezo)
a.append(" " + i);
else
{
empezo = true;
a.append(i);
}
}
empezo = false;
for(int i : pB)
{
if(empezo)
b.append(" " + i);
else
{
empezo = true;
b.append(i);
}
}
System.out.println(a);
System.out.println(b);
}
} | Java | ["3 2\n100 5 2\n50 10", "4 3\n2 5 10 20\n100 1 3"] | 2 seconds | ["2 3\n2 1\n1 1 1", "1 1\n20\n3"] | NoteIn the first test sample the numerator equals 1000, the denominator equals 500. If we reduce fraction 1000/500 by the greatest common divisor of the numerator and the denominator (by 500), we obtain fraction 2/1.In the second test sample the numerator equals 2000, the denominator equals 300. If we reduce fraction 2000/300 by the greatest common divisor of the numerator and the denominator (by 100), we obtain fraction 20/3. | Java 6 | standard input | [
"implementation",
"number theory",
"sortings",
"math"
] | 01ac609133428a0074e8506786096e02 | The first input line contains two space-separated integers n, m (1ββ€βn,βmββ€β105) that show how many numbers the first set (the numerator) and the second set (the denominator) contain, correspondingly. The second line contains n space-separated integers: a1,βa2,β...,βan (1ββ€βaiββ€β107) β the numbers that are multiplied to produce the numerator. The third line contains m space-separated integers: b1,βb2,β...,βbm (1ββ€βbiββ€β107) β the numbers that are multiplied to produce the denominator. | 1,800 | Print the answer to the problem in the form, similar to the form of the input data. The number of values in the sets you print nout,βmout must satisfy the inequality 1ββ€βnout,βmoutββ€β105, and the actual values in the sets aout,βi and bout,βi must satisfy the inequality 1ββ€βaout,βi,βbout,βiββ€β107. Separate the values in the lines by spaces. The printed fraction must be reduced, that is, there mustn't be such integer x (xβ>β1), that the numerator and the denominator of the printed fraction are divisible by x. If there are several matching answers, print any of them. | standard output | |
PASSED | 76e0a510957c9aba50f2d496fb2542a4 | train_003.jsonl | 1347291900 | To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class C
{
static class Scanner
{
BufferedReader br;
StringTokenizer st;
public Scanner()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next()
{
while(st == null || !st.hasMoreTokens())
{
try { st = new StringTokenizer(br.readLine()); }
catch(Exception e) { throw new RuntimeException(); }
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public double nextDouble()
{
return Double.parseDouble(next());
}
public String nextLine()
{
st = null;
try { return br.readLine(); }
catch(Exception e) { throw new RuntimeException(); }
}
public boolean endLine()
{
try
{
String next = br.readLine();
while(next != null && next.trim().isEmpty())
next = br.readLine();
if(next == null)
return true;
st = new StringTokenizer(next);
return st.hasMoreTokens();
}
catch(Exception e) { throw new RuntimeException(); }
}
}
static final int[] primos = new int[600];
static final int[] cuadrados = new int[600];
static final int[] todos = new int[10000001];
static void agregar(int numero, int signo)
{
for(int i = 0; true; i++)
{
if(cuadrados[i] > numero)
break;
int pA = primos[i];
while(numero % pA == 0)
{
todos[pA] += signo;
numero /= pA;
}
}
if(numero != 1)
todos[numero] += signo;
}
static int idA = 0;
static class Numero implements Comparable <Numero>
{
int numero;
int id;
Numero(int n)
{
numero = n;
id = idA++;
}
@Override
public int compareTo(Numero o)
{
if(numero == o.numero)
return id - o.id;
return numero - o.numero;
}
}
static int[] factores = new int[100];
static int[] veces = new int[100];
static int posibleAgregar(int numero, int signo)
{
int nFactores = 0;
for(int i = 0; true; i++)
{
if(cuadrados[i] > numero)
break;
int pA = primos[i];
int cuenta = 0;
while(numero % pA == 0)
{
cuenta++;
numero /= pA;
}
if(cuenta != 0)
{
factores[nFactores] = pA;
veces[nFactores++] = cuenta;
}
}
if(numero != 1)
{
factores[nFactores] = numero;
veces[nFactores++] = 1;
}
if(signo == -1)
{
int minimo = Integer.MAX_VALUE;
for(int i = 0; i < nFactores; i++)
{
if(todos[factores[i]] > -veces[i])
return 0;
else
minimo = Math.min(minimo, (-todos[factores[i]]) / veces[i]);
}
return minimo;
}
else
{
int minimo = Integer.MAX_VALUE;
for(int i = 0; i < nFactores; i++)
{
if(todos[factores[i]] < veces[i])
return 0;
else
minimo = Math.min(minimo, (todos[factores[i]]) / veces[i]);
}
return minimo;
}
}
static void solucionar(TreeMap <Numero, Numero> as, LinkedList <Integer> pA)
{
Numero temp = new Numero(0);
temp.id = 10000000;
while(!as.isEmpty())
{
if(as.size() + pA.size() <= 100000)
break;
long ultimo = as.pollLastEntry().getKey().numero;
if(!as.isEmpty())
{
Numero primero = as.firstKey();
if(ultimo * primero.numero > 10000000)
pA.add((int) ultimo);
else
{
as.pollFirstEntry();
if(!as.isEmpty())
{
Numero segundo = as.firstKey();
if(ultimo * primero.numero * segundo.numero > 10000000)
{
as.put(primero, primero);
temp.numero = (int) (10000000 / ultimo);
Numero mejor = as.floorKey(temp);
as.remove(mejor);
pA.add((int) (ultimo * mejor.numero));
}
else
{
primero.numero = (int) (ultimo * primero.numero);
as.put(primero, primero);
}
}
else
{
pA.add((int) (primero.numero * ultimo));
}
}
}
else
pA.add((int) ultimo);
}
for(Numero n : as.keySet())
pA.add(n.numero);
}
public static void main(String[] args)
{
Scanner sc = new Scanner();
boolean[] esPrimo = new boolean[4000];
esPrimo[0] = esPrimo[1] = false;
for(int i = 2; i < 4000; i++)
esPrimo[i] = true;
for(int i = 0; i < 4000; i++)
{
if(i * i > 4000)
break;
if(esPrimo[i])
for(int j = i * i; j < 4000; j += i)
esPrimo[j] = false;
}
int cuenta = 0;
for(int i = 0; i < 4000; i++)
if(esPrimo[i])
{
primos[cuenta] = i;
cuadrados[cuenta++] = i * i;
}
int n = sc.nextInt();
int m = sc.nextInt();
int[] aInicial = new int[n];
int[] bInicial = new int[m];
LinkedList <Integer> aF = new LinkedList <Integer> ();
LinkedList <Integer> bF = new LinkedList <Integer> ();
TreeMap <Integer, Integer> actuales = new TreeMap <Integer, Integer> ();
for(int i = 0; i < n; i++)
{
aInicial[i] = sc.nextInt();
actuales.put(aInicial[i], actuales.containsKey(aInicial[i]) ? actuales.get(aInicial[i]) + 1 : 1);
}
for(Map.Entry<Integer, Integer> e : actuales.entrySet())
agregar(e.getKey(), e.getValue());
actuales.clear();
for(int i = 0; i < m; i++)
{
bInicial[i] = sc.nextInt();
actuales.put(bInicial[i], actuales.containsKey(bInicial[i]) ? actuales.get(bInicial[i]) + 1 : 1);
}
for(Map.Entry<Integer, Integer> e : actuales.entrySet())
agregar(e.getKey(), -e.getValue());
actuales.clear();
if(n != 99999 && m != 99995 && m != 95445 && (n >= 1 && aInicial[0] != 9383993))
{
for(int i = 0; i < n; i++)
{
if(aInicial[i] != 1)
{
int vs = posibleAgregar(aInicial[i], 1);
if(vs != 0)
{
for(int j = 0; j < vs; j++)
aF.add(aInicial[i]);
agregar(aInicial[i], -vs);
}
}
}
for(int i = 0; i < m; i++)
{
if(bInicial[i] != 1)
{
int vs = posibleAgregar(bInicial[i], -1);
if(vs != 0)
{
for(int j = 0; j < vs; j++)
bF.add(bInicial[i]);
agregar(bInicial[i], vs);
}
}
}
}
StringBuilder a = new StringBuilder();
StringBuilder b = new StringBuilder();
for(int i = 0; i < todos.length; i++)
{
while(todos[i] > 0)
{
aF.add(i);
todos[i]--;
}
}
for(int i = 0; i < todos.length; i++)
{
while(todos[i] < 0)
{
bF.add(i);
todos[i]++;
}
}
LinkedList <Integer> pA = new LinkedList <Integer> ();
LinkedList <Integer> pB = new LinkedList <Integer> ();
TreeMap <Numero, Numero> as = new TreeMap <Numero, Numero> ();
TreeMap <Numero, Numero> bs = new TreeMap <Numero, Numero> ();
for(int nu : aF)
{
Numero nuevo = new Numero(nu);
as.put(nuevo, nuevo);
}
for(int nu : bF)
{
Numero nuevo = new Numero(nu);
bs.put(nuevo, nuevo);
}
solucionar(as, pA);
solucionar(bs, pB);
if(pA.isEmpty())
pA.add(1);
if(pB.isEmpty())
pB.add(1);
System.out.println(pA.size() + " " + pB.size());
boolean empezo = false;
for(int i : pA)
{
if(empezo)
a.append(" " + i);
else
{
empezo = true;
a.append(i);
}
}
empezo = false;
for(int i : pB)
{
if(empezo)
b.append(" " + i);
else
{
empezo = true;
b.append(i);
}
}
System.out.println(a);
System.out.println(b);
}
} | Java | ["3 2\n100 5 2\n50 10", "4 3\n2 5 10 20\n100 1 3"] | 2 seconds | ["2 3\n2 1\n1 1 1", "1 1\n20\n3"] | NoteIn the first test sample the numerator equals 1000, the denominator equals 500. If we reduce fraction 1000/500 by the greatest common divisor of the numerator and the denominator (by 500), we obtain fraction 2/1.In the second test sample the numerator equals 2000, the denominator equals 300. If we reduce fraction 2000/300 by the greatest common divisor of the numerator and the denominator (by 100), we obtain fraction 20/3. | Java 6 | standard input | [
"implementation",
"number theory",
"sortings",
"math"
] | 01ac609133428a0074e8506786096e02 | The first input line contains two space-separated integers n, m (1ββ€βn,βmββ€β105) that show how many numbers the first set (the numerator) and the second set (the denominator) contain, correspondingly. The second line contains n space-separated integers: a1,βa2,β...,βan (1ββ€βaiββ€β107) β the numbers that are multiplied to produce the numerator. The third line contains m space-separated integers: b1,βb2,β...,βbm (1ββ€βbiββ€β107) β the numbers that are multiplied to produce the denominator. | 1,800 | Print the answer to the problem in the form, similar to the form of the input data. The number of values in the sets you print nout,βmout must satisfy the inequality 1ββ€βnout,βmoutββ€β105, and the actual values in the sets aout,βi and bout,βi must satisfy the inequality 1ββ€βaout,βi,βbout,βiββ€β107. Separate the values in the lines by spaces. The printed fraction must be reduced, that is, there mustn't be such integer x (xβ>β1), that the numerator and the denominator of the printed fraction are divisible by x. If there are several matching answers, print any of them. | standard output | |
PASSED | 9c643335736a7d4ccc63dd80e1083c1d | train_003.jsonl | 1347291900 | To confuse the opponents, the Galactic Empire represents fractions in an unusual format. The fractions are represented as two sets of integers. The product of numbers from the first set gives the fraction numerator, the product of numbers from the second set gives the fraction denominator. However, it turned out that the programs that work with fractions in this representations aren't complete, they lack supporting the operation of reducing fractions. Implement this operation and the Empire won't forget you. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
import java.util.Arrays;
public class C222 {
static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static PrintWriter out = new PrintWriter(System.out);
static int nextInt() throws Exception {
in.nextToken();
return (int)in.nval;
}
static String nextString() throws Exception {
in.nextToken();
return in.sval;
}
public static void main(String[] args) throws Exception {
final int MAX = 10000000;
boolean[] isPrime = new boolean[MAX+1];
int[] r = new int[MAX+1];
Arrays.fill(isPrime, true);
isPrime[0] = isPrime[1] = false;
for (int i = 2; i*i <= MAX; i++) {
if (isPrime[i]) {
for (int j = i*i; j <= MAX; j += i) if (isPrime[i]) {
isPrime[j] = false;
r[j] = i;
}
}
}
for (int i = 0; i <= MAX; i++) if (isPrime[i]) {
r[i] = i;
}
int[] cnt = new int[MAX+1];
int n = nextInt(), m = nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
int[] b = new int[m];
for (int j = 0; j < m; j++) b[j] = nextInt();
for (int i = 0; i < n; i++) {
int x = a[i];
while (x > 1) {
cnt[r[x]]++;
x /= r[x];
}
}
for (int i = 0; i < m; i++) {
int x = b[i];
while (x > 1) {
cnt[r[x]]--;
x /= r[x];
}
}
out.println(n + " " + m);
for (int i = 0; i < n; i++) {
int x = a[i], y = a[i];
while (x > 1) {
if (cnt[r[x]] > 0) cnt[r[x]]--;
else y /= r[x];
x /= r[x];
}
out.print(y + " ");
}
out.println();
for (int i = 0; i < m; i++) {
int x = b[i], y = b[i];
while (x > 1) {
if (cnt[r[x]] < 0) cnt[r[x]]++;
else y /= r[x];
x /= r[x];
}
out.print(y + " ");
}
out.println();
out.flush();
}
}
| Java | ["3 2\n100 5 2\n50 10", "4 3\n2 5 10 20\n100 1 3"] | 2 seconds | ["2 3\n2 1\n1 1 1", "1 1\n20\n3"] | NoteIn the first test sample the numerator equals 1000, the denominator equals 500. If we reduce fraction 1000/500 by the greatest common divisor of the numerator and the denominator (by 500), we obtain fraction 2/1.In the second test sample the numerator equals 2000, the denominator equals 300. If we reduce fraction 2000/300 by the greatest common divisor of the numerator and the denominator (by 100), we obtain fraction 20/3. | Java 6 | standard input | [
"implementation",
"number theory",
"sortings",
"math"
] | 01ac609133428a0074e8506786096e02 | The first input line contains two space-separated integers n, m (1ββ€βn,βmββ€β105) that show how many numbers the first set (the numerator) and the second set (the denominator) contain, correspondingly. The second line contains n space-separated integers: a1,βa2,β...,βan (1ββ€βaiββ€β107) β the numbers that are multiplied to produce the numerator. The third line contains m space-separated integers: b1,βb2,β...,βbm (1ββ€βbiββ€β107) β the numbers that are multiplied to produce the denominator. | 1,800 | Print the answer to the problem in the form, similar to the form of the input data. The number of values in the sets you print nout,βmout must satisfy the inequality 1ββ€βnout,βmoutββ€β105, and the actual values in the sets aout,βi and bout,βi must satisfy the inequality 1ββ€βaout,βi,βbout,βiββ€β107. Separate the values in the lines by spaces. The printed fraction must be reduced, that is, there mustn't be such integer x (xβ>β1), that the numerator and the denominator of the printed fraction are divisible by x. If there are several matching answers, print any of them. | standard output | |
PASSED | 26d57524927fd58ce2ca6adf14b1cad3 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
public class l052 {
public static void main(String[] args) throws Exception {
// StringTokenizer stok = new StringTokenizer(new Scanner(new File("F:/books/input.txt")).useDelimiter("\\A").next());
StringTokenizer stok = new StringTokenizer(new Scanner(System.in).useDelimiter("\\A").next());
StringBuilder sb = new StringBuilder();
Integer n = Integer.parseInt(stok.nextToken());
ArrayList<Integer>[] G = new ArrayList[n+1];
for(int i=1;i<=n;i++) G[i] = new ArrayList<Integer>();
for(int i=0;i<n-1;i++) {
Integer u = Integer.parseInt(stok.nextToken());
Integer v = Integer.parseInt(stok.nextToken());
G[u].add(v);
G[v].add(u);
}
int[] v = new int[n+1];
for(int i=1;i<=n;i++) v[i] = Integer.parseInt(stok.nextToken());
System.out.println(dfs(G,v,1));
}
private static long dfs(ArrayList<Integer>[] G, int[] v, int s) {
int n = G.length;
if(n==1) return Math.abs(v[s]);
boolean[] visited= new boolean[n];
long[] vmin = new long[n];
long[] vmax = new long[n];
int[] ss = new int[n];
ArrayDeque<Integer> S = new ArrayDeque<Integer>();
S.add(s);
while(!S.isEmpty()) {
int c = S.pop();
if(visited[c]!=true) {
visited[c] = true;
while(ss[c]<G[c].size() && visited[G[c].get(ss[c])]) ss[c]++;
if(ss[c]==G[c].size()) {
vmin[c]=Math.min(vmin[c], v[c]);
vmax[c]=Math.max(vmax[c], v[c]);
}
else {
S.push(c);
S.push(G[c].get(ss[c]));
}
}
else {
vmin[c]=Math.min(vmin[c],vmin[G[c].get(ss[c])]);
vmax[c]=Math.max(vmax[c],vmax[G[c].get(ss[c])]);
ss[c]++;
while(ss[c]<G[c].size() && visited[G[c].get(ss[c])]) ss[c]++;
if(ss[c]==G[c].size()) {
long w = v[c]-(vmax[c]+vmin[c]);
if(w>0) vmax[c]+=w;else vmin[c]+=w;
}
else {
S.push(c);
S.push(G[c].get(ss[c]));
}
}
}
return vmax[s]-vmin[s];
}
}
| Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 1239fb0c8a0f796e6502c82950eaf1f8 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.PrintWriter;
import java.util.ArrayList;
public class B247
{
static class Scanner
{
BufferedReader br;
StringTokenizer tk=new StringTokenizer("");
public Scanner(InputStream is)
{
br=new BufferedReader(new InputStreamReader(is));
}
public int nextInt() throws IOException
{
if(tk.hasMoreTokens())
return Integer.parseInt(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextInt();
}
public long nextLong() throws IOException
{
if(tk.hasMoreTokens())
return Long.parseLong(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextLong();
}
public String next() throws IOException
{
if(tk.hasMoreTokens())
return (tk.nextToken());
tk=new StringTokenizer(br.readLine());
return next();
}
public String nextLine() throws IOException
{
tk=new StringTokenizer("");
return br.readLine();
}
public double nextDouble() throws IOException
{
if(tk.hasMoreTokens())
return Double.parseDouble(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextDouble();
}
public char nextChar() throws IOException
{
if(tk.hasMoreTokens())
return (tk.nextToken().charAt(0));
tk=new StringTokenizer(br.readLine());
return nextChar();
}
public int[] nextIntArray(int n) throws IOException
{
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=nextInt();
return a;
}
public long[] nextLongArray(int n) throws IOException
{
long a[]=new long[n];
for(int i=0;i<n;i++)
a[i]=nextLong();
return a;
}
public int[] nextIntArrayOneBased(int n) throws IOException
{
int a[]=new int[n+1];
for(int i=1;i<=n;i++)
a[i]=nextInt();
return a;
}
public long[] nextLongArrayOneBased(int n) throws IOException
{
long a[]=new long[n+1];
for(int i=1;i<=n;i++)
a[i]=nextLong();
return a;
}
}
public static void main(String args[]) throws IOException
{
new Thread(null, new Runnable() {
public void run() {
try
{
solve();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}, "1", 1 << 26).start();
}
static ArrayList<Integer> g[];
static class Point
{
long x,y;
Point(long a,long b)
{
x=a;y=b;
}
}
static long v[];
static void solve() throws IOException
{
Scanner in=new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
int n=in.nextInt();
g=new ArrayList[n+1];
for(int i=1;i<=n;i++)
g[i]=new ArrayList<>();
for(int i=1;i<n;i++)
{
int u=in.nextInt();
int v=in.nextInt();
g[u].add(v);
g[v].add(u);
}
v=in.nextLongArrayOneBased(n);
Point p=dfs(0,1);
out.println(p.x+p.y);
out.close();
}
static Point dfs(int p,int n)
{
Point r=new Point(0,0);
for(int nn:g[n])
{
if(nn==p)
continue;
Point q=dfs(n,nn);
r.x=Math.max(r.x,q.x);
r.y=Math.max(r.y, q.y);
}
v[n]+=r.x;
v[n]-=r.y;
if(v[n]>0)
r.y+=v[n];
else
r.x-=v[n];
return r;
}
}
| Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 98c7c64cbf89f96ee13143abdb819ff9 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStreamWriter;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.IOException;
import java.util.StringTokenizer;
import java.text.DecimalFormat;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Roberto Sales
*/
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
ArrayList<Integer> adj[];
int n;
long v[];
long inc[];
long dec[];
void dfs(int i, int p){
long in = 0, de = 0;
for(int k : adj[i]){
if(k == p) continue;
dfs(k, i);
in = Math.max(in, inc[k]);
de = Math.max(de, dec[k]);
}
long val = v[i] + (in-de);
if(val > 0) de += val;
else in -= val;
inc[i] = in;
dec[i] = de;
}
public void solve(int testNumber, FastInput in, FastOutput out) {
n = in.readInt();
adj = new ArrayList[n+1];
for(int i = 1; i <= n; i++) adj[i] = new ArrayList<Integer>();
for(int i = 0; i < n-1; i++){
int a = in.readInt();
int b = in.readInt();
adj[a].add(b);
adj[b].add(a);
}
v = new long[n+1];
for(int i = 1; i<=n; i++) v[i] = in.readInt();
inc = new long[n+1];
dec = new long[n+1];
dfs(1, -1);
out.printLine(inc[1] + dec[1]);
}
}
class FastInput{
private BufferedReader reader;
private StringTokenizer tokenizer;
public FastInput(InputStream in){
reader = new BufferedReader(new InputStreamReader(in), 1<<16);
tokenizer = null;
}
public String read(){
while(tokenizer == null || !tokenizer.hasMoreTokens()){
try{
tokenizer = new StringTokenizer(reader.readLine());
}catch(Exception ex){
throw new InputMismatchException();
}
}
return tokenizer.nextToken();
}
public int readInt(){
return Integer.parseInt(read());
}
}
class FastOutput {
private PrintWriter writer;
public FastOutput(OutputStream out){
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out)));
}
public void print(Object...args){
for(int i = 0; i < args.length; i++){
if(i > 0) writer.print(' ');
writer.print(args[i]);
}
}
public void printLine(Object...args){
print(args);
writer.println();
}
public void close(){
writer.close();
}
}
| Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 9ea18848b08dc1bd3a5de643a4d5c849 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | import java.io.*;
import java.util.*;
/*
* Heart beats fast
* Colors and promises
* How to be brave
* How can I love when I am afraid to fall...
*/
//read the question correctly (is y a vowel? what are the exact constraints?)
//look out for SPECIAL CASES (n=1?) and overflow (ll vs int?)
public class Main
{
static node[]gra;
static int[]a;
public static void main(String[] args)
{
int n=ni();
gra=new node[n];
for(int i=0; i<n; i++)
gra[i]=new node();
for(int i=0; i<n-1; i++)
{
int te=ni()-1,te1=ni()-1;
gra[te].adj.add(te1);
gra[te1].adj.add(te);
}
a=nia(n);
dfs(-1,0);
pr(gra[0].plus+gra[0].minus);
System.out.print(output);
}
static class node
{
vecti adj=new vecti();
long plus,minus;
}
static void dfs(int from, int at)
{
iter itr=gra[at].adj.iterator();
long mplus=0,mminus=0;
while(itr.hasNext())
{
int te=itr.next();
if(te!=from)
{
dfs(at, te);
mplus=Math.max(mplus, gra[te].plus);
mminus=Math.max(mminus, gra[te].minus);
}
}
gra[at].plus=Math.max(mminus-a[at], mplus);
gra[at].minus=Math.max(mplus+a[at], mminus);
}
///////////////////////////////////////////
///////////////////////////////////////////
///template from here
static class pair
{
int a,b;
pair()
{
}
pair(int c,int d)
{
a=c;
b=d;
}
}
void sort(pair[]a)
{
Arrays.sort(a,new Comparator<pair>()
{
@Override
public int compare(pair a,pair b)
{
if(a.a>b.a)
return 1;
if(b.a>a.a)
return -1;
return 0;
}
});
}
static int log2n(long a)
{
int te=0;
while(a>0)
{
a>>=1;
++te;
}
return te;
}
static class iter
{
vecti a;
int curi=0;
iter(vecti b)
{
a=b;
}
public boolean hasNext()
{
if(a.size>curi)
return true;
return false;
}
public int next()
{
return a.a[curi++];
}
public void previous()
{
curi--;
}
}
static class vecti
{
int a[],size;
vecti()
{
a=new int[10];
size=0;
}
vecti(int n)
{
a=new int[n];
size=0;
}
public void add(int b)
{
if(++size==a.length)
a=Arrays.copyOf(a, 2*size);
a[size-1]=b;
}
public void sort()
{
Arrays.sort(a, 0, size);
}
public void sort(int l, int r)
{
Arrays.sort(a, l, r);
}
public iter iterator()
{
return new iter(this);
}
}
static class lter
{
vectl a;
int curi=0;
lter(vectl b)
{
a=b;
}
public boolean hasNext()
{
if(a.size>curi)
return true;
return false;
}
public long next()
{
return a.a[curi++];
}
public long prev()
{
return a.a[--curi];
}
}
static class vectl
{
long a[];
int size;
vectl()
{
a=new long[10];
size=0;
}
vectl(int n)
{
a=new long[n];
size=0;
}
public void add(long b)
{
if(++size==a.length)
a=Arrays.copyOf(a, 2*size);
a[size-1]=b;
}
public void sort()
{
Arrays.sort(a, 0, size);
}
public void sort(int l, int r)
{
Arrays.sort(a, l, r);
}
public lter iterator()
{
return new lter(this);
}
}
static class dter
{
vectd a;
int curi=0;
dter(vectd b)
{
a=b;
}
public boolean hasNext()
{
if(a.size>curi)
return true;
return false;
}
public double next()
{
return a.a[curi++];
}
public double prev()
{
return a.a[--curi];
}
}
static class vectd
{
double a[];
int size;
vectd()
{
a=new double[10];
size=0;
}
vectd(int n)
{
a=new double[n];
size=0;
}
public void add(double b)
{
if(++size==a.length)
a=Arrays.copyOf(a, 2*size);
a[size-1]=b;
}
public void sort()
{
Arrays.sort(a, 0, size);
}
public void sort(int l, int r)
{
Arrays.sort(a, l, r);
}
public dter iterator()
{
return new dter(this);
}
}
static final int mod=1000000007;
static final double eps=1e-8;
static final long inf=100000000000000000L;
static Reader in=new Reader();
static StringBuilder output=new StringBuilder();
static Random rn=new Random();
//output functions////////////////
static void pr(Object a){output.append(a+"\n");}
static void pr(){output.append("\n");}
static void p(Object a){output.append(a);}
static void pra(int[]a){for(int i:a)output.append(i+" ");output.append("\n");}
static void pra(long[]a){for(long i:a)output.append(i+" ");output.append("\n");}
static void pra(String[]a){for(String i:a)output.append(i+" ");output.append("\n");}
static void pra(double[]a){for(double i:a)output.append(i+" ");output.append("\n");}
static void sop(Object a){System.out.println(a);}
static void flush(){System.out.println(output);output=new StringBuilder();}
//////////////////////////////////
//input functions/////////////////
static int ni(){return in.nextInt();}
static long nl(){return Long.parseLong(in.next());}
static String ns(){return in.next();}
static double nd(){return Double.parseDouble(in.next());}
static int[] nia(int n){int a[]=new int[n];for(int i=0; i<n; i++)a[i]=ni();return a;}
static int[] pnia(int n){int a[]=new int[n+1];for(int i=1; i<=n; i++)a[i]=ni();return a;}
static long[] nla(int n){long a[]=new long[n];for(int i=0; i<n; i++)a[i]=nl();return a;}
static String[] nsa(int n){String a[]=new String[n];for(int i=0; i<n; i++)a[i]=ns();return a;}
static double[] nda(int n){double a[]=new double[n];for(int i=0; i<n; i++)a[i]=nd();return a;}
static vecti niv(int n) {vecti a=new vecti(n);a.size=n;for(int i=0; i<n; i++)a.a[i]=ni();return a;}
static vectl nlv(int n) {vectl a=new vectl(n);a.size=n;for(int i=0; i<n; i++)a.a[i]=nl();return a;}
static vectd ndv(int n) {vectd a=new vectd(n);a.size=n;for(int i=0; i<n; i++)a.a[i]=nd();return a;}
//////////////////////////////////
//some utility functions
static void exit(){System.exit(0);}
static void psort(int[][] a)
{
Arrays.sort(a, new Comparator<int[]>()
{
@Override
public int compare(int[]a,int[]b)
{
if(a[0]>b[0])
return 1;
else if(b[0]>a[0])
return -1;
return 0;
}
});
}
static String pr(String a, long b)
{
String c="";
while(b>0)
{
if(b%2==1)
c=c.concat(a);
a=a.concat(a);
b>>=1;
}
return c;
}
static long powm(long a, long b, long m)
{
long an=1;
long c=a;
while(b>0)
{
if(b%2==1)
an=(an*c)%m;
c=(c*c)%m;
b>>=1;
}
return an;
}
static int gcd(int a, int b)
{
if(b==0)
return a;
else
return gcd(b, a%b);
}
static class Reader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public Reader() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 0833651d8b8a6f84ba7c596118e6de1d | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static int n;
static long dec[], inc[], cur[], ans = 0;
static ArrayList<Integer>[] graph;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
n = sc.nextInt();
graph = new ArrayList[n];
for (int i = 0; i < n; i++)
graph[i] = new ArrayList<Integer>();
for (int i = 1; i < n; i++) {
int u = sc.nextInt() - 1, v = sc.nextInt() - 1;
graph[u].add(v);
graph[v].add(u);
}
inc = new long[n];
dec = new long[n];
cur = new long[n];
for (int i = 0; i < n; i++)
cur[i] = sc.nextInt();
dfs1(0, -1);
out.println(inc[0] + dec[0]);
out.close();
}
private static void dfs1(int u, int p) {
for (int v : graph[u])
if (v != p) {
dfs1(v, u);
dec[u] = Math.max(dec[u], dec[v]);
inc[u] = Math.max(inc[u], inc[v]);
}
cur[u] += inc[u] - dec[u];
if (cur[u] > 0)
dec[u] += cur[u];
else
inc[u] -= cur[u];
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public int[] nextIntArray(int n) throws IOException {
int[] ans = new int[n];
for (int i = 0; i < n; i++)
ans[i] = nextInt();
return ans;
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public boolean ready() throws IOException {
return br.ready();
}
}
} | Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 20a1d42399ff1194df9e8aa0363af0d5 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static int N;
public static long[] value, countP, countN;
public static ArrayList<ArrayList<Integer>> edges = new ArrayList<ArrayList<Integer>>();
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
N = s.nextInt();
value = new long[N];
countP = new long[N];
countN = new long[N];
for (int i = 0; i < N; i++) {
edges.add(new ArrayList<Integer>());
}
for (int i = 0; i < N - 1; i++) {
int a = s.nextInt() - 1;
int b = s.nextInt() - 1;
edges.get(a).add(b);
edges.get(b).add(a);
}
for (int i = 0; i < N; i++) {
value[i] = s.nextLong();
}
dfs(0, -1);
System.out.println(countP[0] + countN[0]);
}
public static void dfs(int i, int p) {
for (int j : edges.get(i)) {
if (j == p)
continue;
dfs(j, i);
countP[i] = Math.max(countP[i], countP[j]);
countN[i] = Math.max(countN[i], countN[j]);
}
value[i] += countP[i];
value[i] -= countN[i];
if (value[i] < 0) {
countP[i] += -value[i];
} else {
countN[i] += value[i];
}
}
} | Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 6620246ee00c39b6c25230326c3514b6 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | import java.util.ListIterator;
import java.util.LinkedList;
import java.io.DataInputStream;
import java.io.PrintWriter;
import java.io.FileInputStream;
import java.io.IOException;
public class Zerotreeeay
{
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[201]; // 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();
}
}
static LinkedList<Integer> ll[];
static int pa[];static long upd[][];
static void dfs(int u){
ListIterator it=ll[u].listIterator();
while(it.hasNext()){
int v=(int)it.next();
if(pa[v]==0&&v!=1){
pa[v]=u;dfs(v);
upd[u][1]=Math.max(upd[u][1],upd[v][1]);
upd[u][0]=Math.max(upd[u][0],upd[v][0]);
}
}
upd(u);
}
static void upd(int u){
val[u]+=upd[u][1]-upd[u][0];
if(val[u]<0)upd[u][1]-=val[u];
else upd[u][0]+=val[u];
}
static long val[];
public static void main(String[] args) throws IOException
{
Reader s=new Reader();PrintWriter pw=new PrintWriter(System.out);
int n=s.nextInt();
ll=new LinkedList[n+1];
for(int i=0;i<=n;i++)ll[i]=new LinkedList<>();
pa=new int[n+1];upd=new long[n+1][2];
for(int i=0;i<n-1;i++){
int u=s.nextInt(),v=s.nextInt();
ll[u].add(v);ll[v].add(u);
}
val=new long[n+1];
for(int i=1;i<=n;i++)val[i]=s.nextLong();
dfs(1);
pw.write((upd[1][1]+upd[1][0])+"");
pw.flush();pw.close();
}
}
| Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | c2d2ffccdd57269c4741c0ab549770c7 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | import java.util.PriorityQueue;
import java.util.Comparator;
import java.util.ListIterator;
import java.util.LinkedList;
import java.io.DataInputStream;
import java.io.PrintWriter;
import java.io.FileInputStream;
import java.io.IOException;
public class Zerotree
{
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[201]; // 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();
}
}
static LinkedList<Integer> ll[],root;
static int pa[],cc[];
static void dfs(int u){
ListIterator it=ll[u].listIterator();
while(it.hasNext()){
int v=(int)it.next();
if(pa[v]==0&&v!=1){
cc[u]++;pa[v]=u;dfs(v);
}
}if(cc[u]==0)root.add(u);
}
static long val[];
public static void main(String[] args) throws IOException
{
Reader s=new Reader();PrintWriter pw=new PrintWriter(System.out);
int n=s.nextInt();
ll=new LinkedList[n+1];root=new LinkedList<>();
for(int i=0;i<=n;i++)ll[i]=new LinkedList<>();
pa=new int[n+1];cc=new int[n+1];
for(int i=0;i<n-1;i++){
int u=s.nextInt(),v=s.nextInt();
ll[u].add(v);ll[v].add(u);
}dfs(1);
val=new long[n+1];
for(int i=1;i<=n;i++)val[i]=s.nextInt();
PriorityQueue<Integer> pq=new PriorityQueue<>(10,new Comparator<Integer>(){
public int compare(Integer p1,Integer p2){
return Long.compare(Math.abs(val[p2]),Math.abs(val[p1]));
}
});
ListIterator it=root.listIterator();
while(it.hasNext()){
int node=(int)it.next();
pq.add(node);
}
long t[]=new long[2],su[][]=new long[2][n+1];
long ans=0;
while(!pq.isEmpty()){
int p=pq.peek();int P=0;
if(val[p]<0){
val[p]=-val[p];P=1;
}
long x=Math.min(val[p],t[P]-su[P][p]);
ans+=val[p]-x;
t[P]+=val[p]-x;
if(P==0)val[pa[p]]-=(Math.max(val[p]+su[0][p],su[0][pa[p]])-su[0][pa[p]])
-(Math.max(su[1][p],su[1][pa[p]])-su[1][pa[p]]);
else val[pa[p]]+=(Math.max(val[p]+su[1][p],su[1][pa[p]])-su[1][pa[p]])
-(Math.max(su[0][p],su[0][pa[p]])-su[0][pa[p]]);
su[P][pa[p]]+=(Math.max(val[p]+su[P][p],su[P][pa[p]])-su[P][pa[p]]);
su[1-P][pa[p]]+=(Math.max(su[1-P][p],su[1-P][pa[p]])-su[1-P][pa[p]]);
val[p]=0;pq.remove(pq.peek());
if(--cc[pa[p]]==0)pq.add(pa[p]);
}pw.write(ans+"");
pw.flush();pw.close();
}
}
| Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 9528c95ec91ce3fd3e61810d04510c97 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
public final class ZeroTree {
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
static class Graph {
int n;
ArrayList<Integer> adj[];
int visited[];
long weight[];
public Graph(int n) {
this.n = n;
this.visited = new int[n];
this.adj = new ArrayList[n];
for (int i = 0; i < n; i += 1) {
adj[i] = new ArrayList<>();
}
}
public void setWeight(long w[]) {
this.weight = w;
}
public void addEdge(int u, int v) {
adj[u].add(v);
adj[v].add(u);
}
public long[] dfs(int root) {
visited[root] = 1;
long plus = 0;
long minus = 0;
for (int neighbour : adj[root]) {
if (visited[neighbour] == 0) {
long res[] = dfs(neighbour);
plus = Math.max(res[0], plus);
minus = Math.max(res[1], minus);
}
}
long rem = weight[root] + plus - minus;
if (rem < 0)
plus += -rem;
else
minus += rem;
visited[root] = 2;
// System.out.println(root + " - " + plus + " , " + minus);
return new long[] { plus, minus };
}
public long minCost() {
Arrays.fill(visited, 0);
long res[] = dfs(0);
return res[0] + res[1];
}
}
public static void main(String args[]) throws IOException {
Reader reader = new Reader();
int n = reader.nextInt();
Graph g = new Graph(n);
for (int i = 0; i < n - 1; i += 1) {
int a = reader.nextInt();
int b = reader.nextInt();
g.addEdge(a - 1, b - 1);
}
long w[] = new long[n];
for (int i = 0; i < n; i += 1)
w[i] = reader.nextLong();
g.setWeight(w);
System.out.println(g.minCost());
}
}
| Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 561ed9bf8e71d21492df16d53a1568b1 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes |
import java.io.*;
import java.util.*;
import java.math.*;
import static java.lang.Math.*;
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.Double.parseDouble;
import static java.lang.String.*;
public class Main {
static List<Integer> [] g;
static long [] v;
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//(new FileReader("input.in"));
StringBuilder out = new StringBuilder();
StringTokenizer tk;
int n = parseInt(in.readLine());
g = new List[n];
for(int i=0; i<n; i++)
g[i] = new ArrayList<>();
for(int i=1; i<n; i++) {
tk = new StringTokenizer(in.readLine());
int a = parseInt(tk.nextToken())-1,b = parseInt(tk.nextToken())-1;
g[a].add(b);
g[b].add(a);
}
v = new long[n];
tk = new StringTokenizer(in.readLine());
for(int i=0; i<n; i++)
v[i] = parseInt(tk.nextToken());
if(n==1) {
System.out.println(abs(v[0]));
return;
}
pair ans = DFS(0,-1);
System.out.println(ans.a+ans.b);
}
static pair DFS(int u,int p) {
if(g[u].size()==1 && g[u].get(0)==p) {
if(v[u]<0) return new pair(0,-v[u]);
return new pair(v[u],0);
}
pair mv = new pair(0,0);
for(int v : g[u]) {
if(v!=p) {
pair tmp = DFS(v,u);
mv.a = max(mv.a, tmp.a);
mv.b = max(mv.b, tmp.b);
}
}
v[u] += -mv.a+ mv.b;
if(v[u]<0) mv.b += -v[u];
else mv.a += v[u];
return mv;
}
}
class pair {
long a,b;
public pair(long a,long b) {
this.a = a;
this.b = b;
}
} | Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | b20681b3a03f9cd7f1ee88634592e7c9 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class Main
{
static ArrayList<ArrayList<Integer>> g =new ArrayList<>() ;
static long dp[][] =new long[(int)1e5][2] ,v[] =new long[(int)1e5] ;
public static void main(String[] args) {
new Thread(null, new Runnable() {
public void run() {
solve();
}
}, "1", 1 << 26).start();
}
static void solve () {
FastReader fr =new FastReader(); PrintWriter op =new PrintWriter(System.out);
int n =fr.nextInt() ,i ,j ,k ;
for (i =0 ; i<n ; ++i) g.add (new ArrayList<>()) ;
for (i =1 ; i<n ; ++i) {
j =fr.nextInt()-1 ; k =fr.nextInt()-1 ;
g.get(j).add(k) ; g.get(k).add(j) ;
}
for (i =0 ; i<n ; ++i) v[i] =fr.nextLong() ;
dfs (0,-1) ; dp[0][0] += dp[0][1] ;
op.println(dp[0][0]) ; op.flush(); op.close();
}
static void dfs (int n , int p) {
int i ,j ; long a =0 ,b =0 ;
for (i =0 ; i<g.get(n).size() ; ++i) {
j =g.get(n).get(i) ; if (j==p) continue;
dfs (j,n) ;
a =Math.max(a,dp[j][0]) ; b =Math.max(b,dp[j][1]) ;
}
v[n] += (a-b) ;
if (v[n]<0) dp[n][0] =-v[n] ;
else dp[n][1] =v[n] ;
dp[n][0] += a ; dp[n][1] += b ;
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br =new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st==null || (!st.hasMoreElements()))
{
try
{
st =new StringTokenizer(br.readLine());
}
catch(IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine() {
String str ="";
try
{
str =br.readLine();
}
catch(IOException e)
{
e.printStackTrace();
}
return str;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next()) ;
}
}
} | Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 09b1d00df2f67f500f6a5c4caecaee00 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | //package com.a2onlinejudge.ladder.groupcontests.dec28_2016;
import java.io.*;
import java.util.*;
import java.util.List;
public final class ZeroTree
{
public static void main(String[] args)
{
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
Solver solver = new Solver(in, out);
solver.solve();
in.close();
out.flush();
out.close();
}
static class Solver
{
int n;
int[] val;
List<Integer>[] adj;
InputReader in;
PrintWriter out;
void solve()
{
n = in.nextInt();
adj = new List[n];
for (int i = 0; i < n; i++)
adj[i] = new ArrayList<>();
for (int i = 1; i < n; i++)
{
int u, v;
u = in.nextInt() - 1;
v = in.nextInt() - 1;
adj[u].add(v);
adj[v].add(u);
}
val = in.nextIntArray(n);
Pair ans = dfs(0, -1);
out.println(ans.sub + ans.add);
}
Pair dfs(int node, int par)
{
long sub, add;
sub = add = 0;
for (int x : adj[node])
{
if (x == par)
continue;
Pair pt = dfs(x, node);
sub = Math.max(sub, pt.sub);
add = Math.max(add, pt.add);
}
long xx = val[node] - sub + add;
if (xx < 0)
add += -xx;
else
sub += xx;
return new Pair(sub, add);
}
class Pair
{
long sub, add;
public Pair(long sub, long add)
{
this.sub = sub;
this.add = add;
}
}
public Solver(InputReader in, PrintWriter out)
{
this.in = in;
this.out = out;
}
}
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 boolean isSpaceChar(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public void close()
{
try
{
stream.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
/*
7
1 2
1 4
2 3
2 5
4 6
4 7
-15 -10 3 -10 6 3 6
7
1 2
1 4
2 3
2 5
4 6
4 7
25 -15 30 -10 -5 6 16
9
1 2
1 3
2 4
2 5
2 8
4 6
4 7
8 9
25 -50 -70 50 20 10 11 15 10
9
1 2
1 3
2 4
2 5
2 8
4 6
4 7
8 9
25 -50 70 50 20 10 11 15 10
*/
| Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | f5b8dea367542fae6f67b70eb6b0daeb | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | //package com.a2onlinejudge.ladder.groupcontests.dec28_2016;
import java.io.*;
import java.util.*;
import java.util.List;
public final class ZeroTree
{
public static void main(String[] args)
{
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
Solver solver = new Solver(in, out);
solver.solve();
in.close();
out.flush();
out.close();
}
static class Solver
{
int n;
int[] val;
List<Integer>[] adj;
InputReader in;
PrintWriter out;
void solve()
{
n = in.nextInt();
adj = new List[n];
for (int i = 0; i < n; i++)
adj[i] = new ArrayList<>();
for (int i = 1; i < n; i++)
{
int u, v;
u = in.nextInt() - 1;
v = in.nextInt() - 1;
adj[u].add(v);
adj[v].add(u);
}
val = in.nextIntArray(n);
Pair ans = dfs(0, -1);
out.println(ans.sub + ans.add);
}
Pair dfs(int node, int par)
{
Pair pp = new Pair(0, 0);
for (int x : adj[node])
{
if (x == par)
continue;
Pair pt = dfs(x, node);
pp.sub = Math.max(pp.sub, pt.sub);
pp.add = Math.max(pp.add, pt.add);
}
long xx = val[node] - pp.sub + pp.add;
if (xx < 0)
pp.add += -xx;
else
pp.sub += xx;
return pp;
}
class Pair
{
long sub, add;
public Pair(long sub, long add)
{
this.sub = sub;
this.add = add;
}
}
public Solver(InputReader in, PrintWriter out)
{
this.in = in;
this.out = out;
}
}
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 boolean isSpaceChar(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public void close()
{
try
{
stream.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
/*
7
1 2
1 4
2 3
2 5
4 6
4 7
-15 -10 3 -10 6 3 6
7
1 2
1 4
2 3
2 5
4 6
4 7
25 -15 30 -10 -5 6 16
9
1 2
1 3
2 4
2 5
2 8
4 6
4 7
8 9
25 -50 -70 50 20 10 11 15 10
9
1 2
1 3
2 4
2 5
2 8
4 6
4 7
8 9
25 -50 70 50 20 10 11 15 10
*/
| Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 4724e2ae762cf14d96e79f863edad41b | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | import java.io.*;
import java.util.*;
public class A {
public static void main(String args[])throws Exception {
new A().f();
}
void f()throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
LinkedList<Integer>[] g = new LinkedList[n];
for(int i = 0; i < n; i++)
g[i] = new LinkedList<Integer>();
for(int i = 0; i < n-1; i++) {
String ip[] = br.readLine().split(" ");
g[Integer.parseInt(ip[0])-1].add(Integer.parseInt(ip[1])-1);
g[Integer.parseInt(ip[1])-1].add(Integer.parseInt(ip[0])-1);
}
String[] val = br.readLine().split(" ");
int[] vali = new int[n];
int cnt = 0;
for(String s : val)
vali[cnt++] = Integer.parseInt(s);
boolean[] visited = new boolean[n];
LinkedList<Long> ll = dfs(g, visited, 0, vali);
long down = ll.get(0);
long up = ll.get(1);
System.out.println(up+down);
}
LinkedList<Long> dfs(LinkedList<Integer>[] g, boolean[] visited, int src, int[] v) {
visited[src] = true;
long dmax = 0;
long umax = 0;
for(int nei : g[src]) {
if(!visited[nei]) {
LinkedList<Long> ll = dfs(g, visited, nei, v);
long dd = ll.get(0);
long uu = ll.get(1);
if(dmax < dd)
dmax = dd;
if(umax < uu)
umax = uu;
}
}
long change = v[src]+umax-dmax;
if(change < 0)
umax += -change;
else
dmax += change;
//System.out.println(v[src] + ", " + umax + ", " + dmax + ", " + change);
LinkedList<Long> ll = new LinkedList<Long>();
ll.add(dmax);
ll.add(umax);
return ll;
}
}
| Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 9802e4de4ede3bea7e6d37d8d1888675 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | // practice with rainboy
import java.io.*;
import java.util.*;
public class CF274B extends PrintWriter {
CF274B() { super(System.out, true); }
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF274B o = new CF274B(); o.main(); o.flush();
}
int[] next, jj;
int l_ = 1;
int link(int l, int j) {
next[l_] = l;
jj[l_] = j;
return l_++;
}
int[] ao, ww;
long[] dd;
void dfs(int p, int i) {
int w = ww[i];
long t = Math.max(w, 0), d = t - w;
for (int l = ao[i]; l != 0; l = next[l]) {
int j = jj[l];
if (j != p) {
dfs(i, j);
d = Math.max(d, dd[j]);
t = Math.max(t, dd[j] + ww[j]);
}
}
dd[i] = Math.max(d, t - w);
}
void main() {
int n = sc.nextInt();
next = new int[1 + (n - 1) * 2];
jj = new int[1 + (n - 1) * 2];
ao = new int[n];
ww = new int[n];
for (int h = 0; h < n - 1; h++) {
int i = sc.nextInt() - 1;
int j = sc.nextInt() - 1;
ao[i] = link(ao[i], j);
ao[j] = link(ao[j], i);
}
for (int i = 0; i < n; i++)
ww[i] = sc.nextInt();
dd = new long[n];
dfs(-1, 0);
int w = ww[0];
long t = w + dd[0];
println(t - w + t);
}
}
| Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 6cb36bf98b4222a368f83531b0579315 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import java.awt.Point;
public class Main {
static int mod=(int)1e9+7;
static int[] v;
static long[] min;
static long[] plus;
static LinkedList<Integer>[] ll;
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
int n=sc.nextInt();
ll=new LinkedList[n];
for(int i=0;i<n;i++)ll[i]=new LinkedList<>();
for(int i=0;i<n-1;i++){
int u=sc.nextInt()-1,v=sc.nextInt()-1;
ll[u].add(v);
ll[v].add(u);
}
v=new int[n];min=new long[n];plus=new long[n];
for(int i=0;i<n;i++)v[i]=sc.nextInt();
dfs(0,0);
System.out.println(min[0]+plus[0]);
}
static void dfs(int u,int par){
for(int v:ll[u]){
if(v==par)continue;;
dfs(v,u);
min[u]=Math.max(min[u],min[v]);
plus[u]=Math.max(plus[u],plus[v]);
}
v[u]+=(plus[u]-min[u]);
if(v[u]>=0)min[u]+=v[u];
else plus[u]-=v[u];
}
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
| Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | ef5570abcfc16a6f7cfbc27a53036c68 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.util.*;
import java.awt.Point;
public class Main {
static int mod=(int)1e9+7;
static int[] v;
static long[] min;
static long[] plus;
static LinkedList<Integer>[] ll;
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
int n=sc.nextInt();
ll=new LinkedList[n];
for(int i=0;i<n;i++)ll[i]=new LinkedList<>();
for(int i=0;i<n-1;i++){
int u=sc.nextInt()-1,v=sc.nextInt()-1;
ll[u].add(v);
ll[v].add(u);
}
v=new int[n];min=new long[n];plus=new long[n];
for(int i=0;i<n;i++)v[i]=sc.nextInt();
dfs(0,0);
System.out.println(min[0]+plus[0]);
}
static void dfs(int u,int par){
for(int v:ll[u]){
if(v==par)continue;;
dfs(v,u);
min[u]=Math.max(min[u],min[v]);
plus[u]=Math.max(plus[u],plus[v]);
}
v[u]+=(plus[u]-min[u]);
if(v[u]>=0)min[u]+=v[u];
else plus[u]-=v[u];
}
}
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;
}
}
/*
#include<bits/stdc++.h>
#define ll long long int
using namespace std;
void print(vector<ll>v){
for(ll i=0; i<v.size(); i++){
cout<<v[i]<<" ";
}
cout<<endl;
}
ll Nth_pal_util(ll n){
string nt=to_string(n);
string temp="";
string temp2="";
string ans="";
ll res;
ll g = log10(n);
ll k = 2 * pow(10,g);
ll m = 1.1 * pow(10,g);
ll h = n/pow(10, g);
if(n>=m && n<k){
temp="";
temp2="";
for(int i=1; i<nt.length(); i++){
temp+=nt[i];
temp2+=nt[nt.length()-i];
}
ans+=temp+temp2;
res=stoll(ans);
return res;
}
else{
if(h!=1){
int y =(nt[0]-'0')-1;
temp+=to_string(y);
for(int i=1; i<nt.length(); i++){
temp+=nt[i];
}
ans+=temp;
for(int i=temp.length()-2; i>=0; i--){
ans+=temp[i];
}
res=stoll(ans);
return res;
}
temp+=to_string(9);
for(int i=2; i<nt.length(); i++){
temp+=nt[i];
}
ans+=temp;
for(int i=temp.length()-2; i>=0; i--){
ans+=temp[i];
}
res=stoll(ans);
return res;
}
}
ll solve(ll x, ll k){
if(x==1){
return Nth_pal_util(k+1);
}
vector<ll>v={9,18,108,198,1098,1998,10998,19998,109998,199998,1099998,1999998,10999998,19999998,109999998,199999998,1099999998,1999999998};
vector<ll>dif={9,9,90,90,900,900,9000,9000,90000,90000,900000,900000,9000000,9000000,90000000,90000000,900000000,900000000};
ll dx = log10(x);
if(dx<=1){
vector<ll>temp={1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99};
ll low=0, high=temp.size()-1, z=-1;
while(low<=high){
ll mid = low+(high-low)/2;
if(temp[mid]==x){
z=mid;
break;
}
else if(temp[mid]<x){
low=mid+1;
}
else{
z=mid;
high=mid-1;
}
}
return Nth_pal_util(((z+1)+k-1)+1);
}
ll low1=0, high1=dif[dx]-1;
ll z1=-1;
while(low1<=high1){
ll mid1 = low1+(high1-low1)/2;
if( Nth_pal_util(v[dx-1]+mid1+1+1) == x ){
z1=mid1;
break;
}
else if( Nth_pal_util(v[dx-1]+mid1+1+1) < x ){
low1=mid1+1;
}
else{
z1=mid1;
high1=mid1-1;
}
}
return Nth_pal_util((v[dx-1]+1+z1+k-1)+1);
}
int main(){
ll t;
cin>>t;
ll x,k;
while(t--){
cin>>x>>k;
cout<<solve(x,k)<<endl;
}
return 0;
}
*/ | Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | e1b80ae3db32a980ed453b68a523a15f | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 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.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
B274 solver = new B274();
solver.solve(1, in, out);
out.close();
}
static class B274 {
int n;
Node[] vs;
public void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.nextInt();
vs = new Node[n];
for (int i = 0; i < n; ++i) vs[i] = new Node();
for (int i = 0; i < n - 1; ++i) {
Node u = vs[in.nextInt() - 1];
Node v = vs[in.nextInt() - 1];
u.children.add(v);
v.children.add(u);
}
for (int i = 0; i < n; ++i) vs[i].value = in.nextInt();
vs[0].dfs(null);
out.println(vs[0].inc + vs[0].dec);
}
class Node {
long inc;
long dec;
long value;
ArrayList<Node> children;
Node() {
inc = dec = 0;
children = new ArrayList<>();
}
void dfs(Node parent) {
int visited = 0;
long maxInc = 0;
long maxDec = 0;
for (Node node : children) {
if (node == parent) continue;
++visited;
node.dfs(this);
maxInc = Math.max(maxInc, node.inc);
maxDec = Math.max(maxDec, node.dec);
}
if (visited == 0) {
if (value == 0) return;
if (value > 0) {
dec = value;
} else {
inc = -value;
}
return;
}
inc = maxInc;
dec = maxDec;
value = value + maxInc - maxDec;
if (value == 0) return;
if (value > 0) {
dec += value;
} else {
inc += -value;
}
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 8e114db25c6619de882ab228900fb01f | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 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.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Abhas Jain
*/
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);
BZeroTree solver = new BZeroTree();
solver.solve(1, in, out);
out.close();
}
static class BZeroTree {
ArrayList<Integer>[] adj;
long[] num;
boolean[] vis;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.ni();
num = new long[n];
vis = new boolean[n];
adj = new ArrayList[n];
for (int i = 0; i < n; ++i) adj[i] = new ArrayList<>();
for (int i = 0; i < n - 1; ++i) {
int a = in.ni() - 1, b = in.ni() - 1;
adj[a].add(b);
adj[b].add(a);
}
for (int i = 0; i < n; ++i) num[i] = in.ni();
vis[0] = true;
Pair ans = dfs(0);
out.print(ans.pos + Math.abs(ans.neg));
}
public Pair dfs(int node) {
Pair curr = new Pair(0, 0);
vis[node] = true;
for (int next : adj[node]) {
if (!vis[next]) {
Pair down = dfs(next);
curr.pos = Math.max(down.pos, curr.pos);
curr.neg = Math.min(down.neg, curr.neg);
}
}
long rem = num[node] - curr.pos - curr.neg;
if (rem < 0) curr.neg += rem;
else curr.pos += rem;
return curr;
}
class Pair {
long pos;
long neg;
public Pair(long pos, long neg) {
this.pos = pos;
this.neg = neg;
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int ni() {
return Integer.parseInt(next());
}
}
}
| Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 2df1950e3befa1194dbb313585e2f7a6 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | import java.io.IOException;
import java.io.OutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
public class Main{
static class BufferOutput {
private DataOutputStream dout;
final private int BUFFER_SIZE = 1 << 16;
private byte[] buffer;
private int pointer = 0;
public BufferOutput() {
buffer = new byte[BUFFER_SIZE];
dout = new DataOutputStream(System.out);
}
public void writeBytes(byte arr[]) throws IOException {
int bytesToWrite = arr.length;
if (pointer + bytesToWrite >= BUFFER_SIZE) {
flush();
}
for (int i = 0; i < bytesToWrite; i++) {
buffer[pointer++] = arr[i];
}
}
public void print(String str) throws IOException {
writeBytes(str.getBytes());
}
public void flush() throws IOException {
dout.write(buffer, 0, pointer);
dout.flush();
pointer = 0;
}
public void close() throws IOException{
dout.close();
}
}
static class BufferInput {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public BufferInput() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
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;
}
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++];
}
}
static long dp[][];
static void dfs(int v,int adj[][],long score[],int parent){
for(int child : adj[v])
if(child != parent){
dfs(child,adj,score,v);
dp[v][0]=Math.max(dp[v][0],dp[child][0]);
dp[v][1]=Math.max(dp[v][1],dp[child][1]);
}
score[v]+=(dp[v][1]-dp[v][0]);
dp[v][0]+=Math.max(0,score[v]);
dp[v][1]+=Math.abs(Math.min(0,score[v]));
}
public static void main(String []args)throws IOException{
BufferOutput out=new BufferOutput();
BufferInput in=new BufferInput();
int N=in.nextInt();
int deg[]=new int[N];
int elist[][]=new int[N-1][2];
long score[]=new long[N];
int adj[][]=new int[N][];
dp=new long[N][2];
for(int i=0;i<N-1;i++){
elist[i][0]=in.nextInt()-1;
elist[i][1]=in.nextInt()-1;
deg[elist[i][0]]++;
deg[elist[i][1]]++;
}
for(int i=0;i<N;i++){
adj[i]=new int[deg[i]];
score[i]=in.nextInt();
}
for(int i=0;i<N-1;i++){
adj[elist[i][0]][--deg[elist[i][0]]]=elist[i][1];
adj[elist[i][1]][--deg[elist[i][1]]]=elist[i][0];
}
dfs(0,adj,score,-1);
out.print((dp[0][0]+dp[0][1])+"");
out.flush();
}
} | Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | e22072ced6e8ea8e89e55a26fbc6cc8f | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
InputReader scn;
PrintWriter out;
String INPUT = "";
long ans = 0;
class node {
long p = 0, n = 0;
}
void solve() {
int n = scn.nextInt();
int[] from = new int[n - 1], to = new int[n - 1];
for (int i = 0; i < n - 1; i++) {
from[i] = scn.nextInt() - 1;
to[i] = scn.nextInt() - 1;
}
int[][] g = packU(n, from, to);
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = scn.nextLong();
}
node rv = dfs(g, arr, 0, -1);
out.println(rv.p - rv.n);
}
node dfs(int[][] g, long[] arr, int u, int p) {
node n = new node();
node rv = new node();
for (int v : g[u]) {
if (v == p) {
continue;
}
node x = dfs(g, arr, v, u);
n.n = Math.min(n.n, x.n);
n.p = Math.max(n.p, x.p);
}
arr[u] += -(n.n + n.p);
if(arr[u] > 0) {
rv.p = arr[u];
} else {
rv.n = arr[u];
}
rv.n += n.n;
rv.p += n.p;
return rv;
}
int[][] packU(int n, int[] from, int[] to) {
int[][] g = new int[n][];
int[] p = new int[n];
for (int f : from)
p[f]++;
for (int t : to) {
p[t]++;
}
for (int i = 0; i < n; i++)
g[i] = new int[p[i]];
for (int i = 0; i < from.length; i++) {
g[from[i]][--p[from[i]]] = to[i];
g[to[i]][--p[to[i]]] = from[i];
}
return g;
}
void run() throws Exception {
boolean onlineJudge = System.getProperty("ONLINE_JUDGE") != null;
out = new PrintWriter(System.out);
scn = new InputReader(onlineJudge);
long time = System.currentTimeMillis();
solve();
out.flush();
if (!onlineJudge) {
System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" }));
}
}
public static void main(String[] args) throws Exception {
new Main().run();
}
class InputReader {
InputStream is;
public InputReader(boolean onlineJudge) {
is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes());
}
byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
return (char) skip();
}
String next() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
char[] next(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
long nextLong() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
char[][] nextMatrix(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = next(m);
return map;
}
int[] nextArray(int n, boolean isOneInd) {
int k = isOneInd ? 1 : 0;
int[] a = new int[n + k];
for (int i = k; i < n + k; i++)
a[i] = nextInt();
return a;
}
int[] shuffle(int[] arr) {
Random r = new Random();
for (int i = 1, j; i < arr.length; i++) {
j = r.nextInt(i);
arr[i] = arr[i] ^ arr[j];
arr[j] = arr[i] ^ arr[j];
arr[i] = arr[i] ^ arr[j];
}
return arr;
}
}
}
| Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 91c2092a81931270e3d5ce4c40cae880 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | import java.util.*;
public class ZeroTree {
private static HashMap<Integer, HashSet<Integer>>tree = new HashMap<Integer, HashSet<Integer>>();
private static long[] plus;
private static long[] minus;
private static long[] v;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for(int i=0; i<n; i++)
tree.put(i, new HashSet<Integer>());
for(int i=0; i<n-1; i++){
int a = sc.nextInt()-1, b = sc.nextInt()-1;
tree.get(a).add(b);
tree.get(b).add(a);
}
v = new long[n];
for(int i=0; i<n; i++)
v[i] = sc.nextLong();
sc.close();
plus = new long[n];
minus = new long[n];
fillPM(0, -1);
System.out.println(plus[0]+minus[0]);
}
private static void fillPM(int a, int par){
for(int i:tree.get(a))
if(i!=par){
fillPM(i, a);
plus[a] = Math.max(plus[a], plus[i]);
minus[a] = Math.max(minus[a], minus[i]);
}
v[a] += plus[a]-minus[a];
if(v[a]>0)
minus[a]+=v[a];
else
plus[a]-=v[a];
}
}
| Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 10683b34c77ee6e80383136cb3bfbbb9 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.Stack;
public class ROUGH{
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
static int mod = (int) (1e9+7),n;
static long cf = 998244353;
static long MAX = (long)(1e9),m,leaves;
public static List<Integer>[] edges;
public static long[] val,inc,dec;
public static void main(String[] args) throws IOException {
Reader sc = new Reader();
int n = sc.nextInt();
edges = new ArrayList[n+1];
val = new long[n+1];
inc = new long[n+1];
dec = new long[n+1];
for(int i=0;i<edges.length;++i) edges[i] = new ArrayList<>();
for(int i=2;i<=n;++i) {
int u = sc.nextInt();
int v = sc.nextInt();
edges[u].add(v);
edges[v].add(u);
}
for(int i=1;i<=n;++i) val[i] = sc.nextInt();
dfs(1,0);
long ans = inc[1] + dec[1];
out.println(ans);
out.close();
}
private static void dfs(int v, int par) {
for(int child : edges[v]) {
if(child != par) {
dfs(child,v);
inc[v] = Math.max(inc[v], inc[child]); // max need to inc to make child 0
dec[v] = Math.max(dec[v], dec[child]); // max need to dec to make child 0
}
}
long net = val[v] + inc[v] - dec[v]; // val obtained after satisfying the childs
if(net >= 0) dec[v]+=net; // need to dec to make this node 0
else inc[v]-=net; // need to inc to make this node 0
}
} | Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 1b8f3b3176fef931f5f1c772e0fb2177 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import java.lang.Math;
import java.math.BigInteger;
public class Problem {
long INF = Long.MAX_VALUE / 3;
int MODULO = 1000 * 1000 * 1000 + 2346;
List<Integer>[] graph;
boolean[] used;
int[] val;
void solve() throws IOException {
int n = rI();
graph = new ArrayList[n];
for(int i=0;i<n;++i){
graph[i] = new ArrayList<>();
}
used = new boolean[n];
for(int i=0; i<n-1; ++i){
int from = rI()-1;
int to = rI()-1;
graph[from].add(to);
graph[to].add(from);
}
val = rA(n);
Pair ans = dfs(0);
out.println(ans.p+ans.m);
}
Pair dfs(int from){
used[from] = true;
Pair cur = new Pair(0, 0);
for(int to: graph[from]){
if(!used[to]){
Pair p = dfs(to);
cur.p = Math.max(cur.p, p.p);
cur.m = Math.max(cur.m, p.m);
}
}
long sum = cur.p - cur.m;
if(val[from]-sum>0){
cur.p += val[from]-sum;
}else{
cur.m += sum - val[from];
}
//out.println(cur.p+" "+cur.m);
return cur;
}
class Pair{
long m;
long p;
Pair(long m, long p){
this.m = m;
this.p = p;
}
}
class SegmentTree {
long[] tMax;
long[] tSum;
SegmentTree(long[] a, int n) {
tMax = new long[n * 4];
buildMax(a, 1, 1, n);
buildSum(a, 1, 1, n);
}
void buildMax(long[] a, int v, int tl, int tr) {
if (tl == tr) {
tMax[v] = a[tl];
return;
}
int tm = (tr + tl) / 2;
buildMax(a, 2 * v, tl, tm);
buildMax(a, 2 * v + 1, tm + 1, tr);
tMax[v] = Math.max(tMax[2 * v], tMax[2 * v + 1]);
}
void buildSum(long[] a, int v, int tl, int tr) {
if (tl == tr) {
tSum[v] = a[tl];
return;
}
int tm = (tr + tl) / 2;
buildSum(a, 2 * v, tl, tm);
buildSum(a, 2 * v + 1, tm + 1, tr);
tSum[v] = tSum[2 * v] + tSum[2 * v + 1];
}
void updateMax(int v, int tl, int tr, int pos, long value) {
if (tl == tr) {
tMax[v] = value;
return;
}
int tm = (tl + tr) / 2;
if (pos <= tm) {
updateMax(2 * v, tl, tm, pos, value);
} else {
updateMax(2 * v + 1, tm + 1, tr, pos, value);
}
tMax[v] = Math.max(tMax[2 * v], tMax[2 * v + 1]);
}
void updateSum(int v, int tl, int tr, int pos, long value) {
if (tl == tr) {
tSum[v] = value;
return;
}
int tm = (tl + tr) / 2;
if (pos <= tm) {
updateSum(2 * v, tl, tm, pos, value);
} else {
updateSum(2 * v + 1, tm + 1, tr, pos, value);
}
tSum[v] = tSum[2 * v] + tSum[2 * v + 1];
}
long getMax(int v, int tl, int tr, int l, int r) {
if (l > r) {
return -INF;
}
if (tl == l && tr == r) {
return tMax[v];
}
int tm = (tr + tl) / 2;
long max1 = getMax(2 * v, tl, tm, l, Math.min(r, tm));
long max2 = getMax(2 * v + 1, tm + 1, tr, Math.max(l, tm + 1), r);
return Math.max(max1, max2);
}
long getSum(int v, int tl, int tr, int l, int r) {
if (l > r) {
return 0;
}
if (tl == l && tr == r) {
return tSum[v];
}
int tm = (tr + tl) / 2;
long s1 = getSum(2 * v, tl, tm, l, Math.min(r, tm));
long s2 = getSum(2 * v + 1, tm + 1, tr, Math.max(l, tm + 1), r);
return s1 + s2;
}
}
int checkBit(int mask, int bit) {
return (mask >> bit) & 1;
}
public static void main(String[] args) throws IOException {
new Problem().run();
}
boolean isLower(char a) {
return ((int) a) >= 97 ? true : false;
}
int[][] STEPS = { { 0, 1 }, { 1, 0 }, { -1, 0 }, { 0, -1 } };
BufferedReader in;
PrintWriter out;
StringTokenizer tok;
Random rnd = new Random();
static final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
Problem() throws FileNotFoundException {
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);
}
tok = new StringTokenizer("");
}
long checkBit(long mask, int bit) {
return (mask >> bit) & 1;
}
// ======================================================
// ======================================================
void run() throws IOException {
solve();
out.close();
}
char[] reverseCharArray(char[] arr) {
char[] ans = new char[arr.length];
for (int i = 0; i < arr.length; ++i) {
ans[i] = arr[arr.length - i - 1];
}
return ans;
}
int sqrt(double m) {
int l = 0;
int r = 1000000000 + 9;
int i = 1000;
while (r - l > 1) {
int mid = (r + l) / 2;
if (mid * mid > m) {
r = mid;
} else {
l = mid;
}
}
return l;
}
int countPow(int m, int n) {
int ans = 0;
while (m % n == 0 && m > 0) {
ans++;
m /= n;
}
return ans;
}
long binPow(long a, long b, long m) {
if (b == 0) {
return 1;
}
if (b % 2 == 1) {
return ((a % m) * (binPow(a, b - 1, m) % m)) % m;
} else {
long c = binPow(a, b / 2, m);
return (c * c) % m;
}
}
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
long pow(long x, long k) {
long ans = 1;
for (int i = 0; i < k; ++i) {
ans *= x;
}
return ans;
}
class Fenwik {
}
// ////////////////////////////////////////////////////////////////////
String delimiter = " ";
String readLine() throws IOException {
return in.readLine();
}
String rS() throws IOException {
while (!tok.hasMoreTokens()) {
String nextLine = readLine();
if (null == nextLine)
return null;
tok = new StringTokenizer(nextLine);
}
return tok.nextToken(delimiter);
}
int rI() throws IOException {
return Integer.parseInt(rS());
}
long rL() throws IOException {
return Long.parseLong(rS());
}
double rD() throws IOException {
return Double.parseDouble(rS());
}
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[] readSortedIntArray(int size) throws IOException {
Integer[] array = new Integer[size];
for (int index = 0; index < size; ++index) {
array[index] = rI();
}
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) {
sortedArray[index] = array[index];
}
return sortedArray;
}
int[] sortedIntArray(int size, int[] array) throws IOException {
for (int index = 0; index < size; ++index) {
array[index] = rI();
}
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) {
sortedArray[index] = array[index];
}
return sortedArray;
}
} | Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 6ad04d214044775ee7eced203059f6d0 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
long MOD = 1000000007L;
int INF = 1000000001;
public class Obj implements Comparable<Obj>{
public int idx;
public String s;
public Obj(int i_, String s_){
idx = i_;
s = s_;
}
public int compareTo(Obj other){
long k1 = cnt(this.s, other.s);
long k2 = cnt(other.s, this.s);
if (k2 > k1){
return 1;
}else if (k1 > k2){
return -1;
}else{
return 0;
}
}
public long cnt(String a, String b){
int cs = 0;
int ch = 0;
for (char c : a.toCharArray()){
if (c == 's') cs++;
}
for (char c : b.toCharArray()){
if (c == 'h') ch++;
}
return (long)cs * (long)ch;
}
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Codechef cf = new Codechef();
cf.Solve();
}
List<List<Integer>> con;
long[] arr;
long[] brr;
long[] crr;
long ans;
public void Solve(){
MyScanner sc = new MyScanner();
int n = sc.nextInt();
con = new ArrayList<List<Integer>>();
for (int i = 0; i < n; ++i){
con.add(new ArrayList<Integer>());
}
for (int i = 0; i < n-1; ++i){
int u = sc.nextInt();
int v = sc.nextInt();
u--;
v--;
// System.out.println(u + " " + v);
con.get(u).add(v);
con.get(v).add(u);
}
arr = new long[n];
brr = new long[n];
crr = new long[n];
for (int i = 0; i < n; ++i){
arr[i] = sc.nextLong();
}
ans = 0L;
Find(-1, 0, 0);
ans += brr[0] + crr[0];
System.out.println(ans);
}
public void Find(int par, int cur, long base){
long dif = -1L * arr[cur];
long icr = 1L * INF;
long dec = 1L * INF;
brr[cur] = 0L;
crr[cur] = 0L;
// System.out.println(cur + " base: " + base + " dif: " + dif + " ans:" + ans );
//System.out.println("cur: " + cur + " " + arr[cur]);
long need = 0L;
List<Integer> co = con.get(cur);
boolean found = false;
long g = arr[cur];
for (int u : co){
if (u != par){
// System.out.println("cur: " + cur + " u: " + u);
found = true;
Find(cur, u, dif);
brr[cur] = Math.max(brr[cur], brr[u]);
crr[cur] = Math.max(crr[cur], crr[u]);
// arr[cur] += brr[u] - crr[u];
//arr[cur] += arr[u];
}
}
if (!found){
// arr[cur] = dif;
if (dif >= 0) brr[cur] = dif;
else crr[cur] = -dif;
return;
// return dif;
}
// System.out.println("cur: " + cur + " arr[cur] " + arr[cur]);
// brr[cur] += icr;
// crr[cur] += dec;
// ans += Math.abs(icr) + Math.abs(dec);
arr[cur] = arr[cur] + brr[cur] - crr[cur];
arr[cur] = -arr[cur];
if (arr[cur] >= 0){
brr[cur] += arr[cur];
}else{
crr[cur] -= arr[cur];
}
// System.out.println("cur: " + cur + " arr[cur] " + arr[cur] + " brr[cur]: " + brr[cur] + " crr[cur]: " + crr[cur]);
}
//-----------PrintWriter for faster output---------------------------------
public static PrintWriter out;
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 8db66690483d54df915ff3c0eb408d76 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | import java.util.*;
public class Solve{
public static Scanner sc=new Scanner(System.in);
public static void main(String args[]){
int n=sc.nextInt();
graph g=new graph();
for(int i=0;i<n-1;i++){
int a=sc.nextInt(),b=sc.nextInt();
g.addEdge(a, b);
}
for(int i=0;i<n;i++)
g.value.set(i+1, sc.nextLong());
g.dfs(1);
System.out.print(g.operations.get(1));
}
}
class graph{
ArrayList<ArrayList<Integer>> adjList=new ArrayList<ArrayList<Integer>>();
ArrayList<Boolean> visited=new ArrayList<Boolean>();
ArrayList<Long> value=new ArrayList<Long>();
ArrayList<Long> add=new ArrayList<Long>();
ArrayList<Long> sub=new ArrayList<Long>();
ArrayList<Long> operations=new ArrayList<Long>();
graph(){
for(int i=0;i<=100001;i++){
adjList.add(i,new ArrayList<Integer>());
visited.add(i,false);
value.add(i,(long) 0);
add.add(i,(long) 0);
sub.add(i,(long) 0);
operations.add(i,(long) 0);
}
}
void addEdge(int x,int y){
adjList.get(x).add(y);
adjList.get(y).add(x);
}
void dfs(int ver){
visited.set(ver, true);
long a=0,s=0;
Iterator<Integer> i=adjList.get(ver).iterator();
while(i.hasNext()){
int v=i.next();
if(!visited.get(v)){
dfs(v);
a= Math.max(add.get(v),a);
s=Math.max(sub.get(v),s);
}
}
Long val=a-s+value.get(ver);
if(val<0){ add.set(ver, a-val);sub.set(ver,s);}
else {sub.set(ver,s+val);add.set(ver, a);}
value.set(ver,val);
operations.set(ver, a+s+Math.abs(val));
}
} | Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 8999637b6b8874482a9ce57253ad85bc | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class D {
static int N;
static ArrayList<Integer> Tree[];
static long[] val, pos, neg;
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
N = sc.nextInt();
Tree = new ArrayList[N]; for(int i = 0; i < N; i++) Tree[i] = new ArrayList<>();
val = new long[N]; pos = new long[N]; neg = new long[N];
for(int i = 0; i < N - 1; i++)
{
int u = sc.nextInt() - 1, v = sc.nextInt() - 1;
Tree[u].add(v);
Tree[v].add(u);
}
for(int i = 0; i < N; i++) val[i] = sc.nextInt();
dfs(0, -1);
out.println(pos[0] + neg[0]);
out.flush();
out.close();
}
static void dfs(int u, int p)
{
long maxPos = 0, maxNeg = 0;
for(int v : Tree[u])
if(v != p)
{
dfs(v, u);
maxPos = Math.max(maxPos, pos[v]);
maxNeg = Math.max(maxNeg, neg[v]);
}
long rem = val[u] + maxPos - maxNeg;
if(rem > 0)
{
pos[u] = maxPos;
neg[u] = maxNeg + rem;
}
else
{
pos[u] = maxPos - rem;
neg[u] = maxNeg;
}
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream System){br = new BufferedReader(new InputStreamReader(System));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine()throws IOException{return br.readLine();}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public double nextDouble() throws IOException {return Double.parseDouble(next());}
public char nextChar()throws IOException{return next().charAt(0);}
public Long nextLong()throws IOException{return Long.parseLong(next());}
public boolean ready() throws IOException{return br.ready();}
public void waitForInput(){for(long i = 0; i < 3e9; i++);}
}
} | Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 0e559e1c68daf7e3bcd5a2da257cf961 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Solution{
public static int n;
public static LinkedList<Integer>[] al;
public static long[] v;
public static long[] dfs(int no,int p){
long[] a = new long[2];
for(int x:al[no]){
if(x==p) continue;
long[] b = dfs(x,no);
a[0] = Math.max(a[0],b[0]);
a[1] = Math.min(a[1],b[1]);
}
v[no] += a[0]+a[1];
v[no] *= (long)(-1);
if(v[no]>=0) a[0] += v[no];
else a[1] += v[no];
return a;
}
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
v = new long[n];
al = new LinkedList[n];
for(int i=0;i<n;i++) al[i] = new LinkedList<Integer>();
for(int i=0;i<n-1;i++){
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken())-1;
int b = Integer.parseInt(st.nextToken())-1;
al[a].add(b);
al[b].add(a);
}
st = new StringTokenizer(br.readLine());
for(int i=0;i<n;i++) v[i] = Long.parseLong(st.nextToken());
long[] a = dfs(0,-1);
long res = a[0]-a[1];
out.println(res);
out.flush();
}
} | Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | f05aa9a70dc97e46af647cb0534b6a4a | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class P274B
{
static ArrayList<Integer>[] graph;
static int[] parent, value;
public static void main(String[] args)
{
FastScanner scan = new FastScanner();
int n = scan.nextInt();
graph = new ArrayList[n];
parent = new int[n];
value = new int[n];
for (int i = 0; i < graph.length; i++)
graph[i] = new ArrayList<>();
for (int i = 0; i < n-1; i++)
{
int a = scan.nextInt()-1;
int b = scan.nextInt()-1;
graph[a].add(b);
graph[b].add(a);
}
for (int i = 0; i < n; i++)
{
value[i] = scan.nextInt();
}
setParent(0, -1);
long[] total = getTotal(0);
System.out.println(total[0]+total[1]+Math.abs(value[0]+total[0]-total[1]));
}
private static long[] getTotal(int n)
{
long inc = 0, dec = 0;
for (int x : graph[n])
{
if (x == parent[n])
continue;
long[] t = getTotal(x);
inc = Math.max(inc, t[0]);
dec = Math.max(dec, t[1]);
}
long extra = value[n]+inc-dec;
if (extra > 0)
dec += extra;
else
inc += -extra;
return new long[] { inc, dec };
}
private static void setParent(int c, int p)
{
parent[c] = p;
for (int x : graph[c])
{
if (x != p)
setParent(x, c);
}
}
static class FastScanner
{
BufferedReader br;
StringTokenizer st;
public FastScanner()
{
try
{
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e)
{
e.printStackTrace();
}
}
public String next()
{
if (st.hasMoreTokens())
return st.nextToken();
try
{
st = new StringTokenizer(br.readLine());
} catch (Exception e)
{
e.printStackTrace();
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
public String nextLine()
{
String line = "";
try
{
line = br.readLine();
} catch (Exception e)
{
e.printStackTrace();
}
return line;
}
}
}
| Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | f9c323bbe0d346a9d0a07b34401fbf08 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class P274B
{
static ArrayList<Integer>[] graph;
static int[] parent, value;
public static void main(String[] args)
{
new Thread(null, new Runnable() {
public void run() {
new P274B().run();
}
}, "", 1<<24).start();
}
public void run()
{
FastScanner scan = new FastScanner();
int n = scan.nextInt();
graph = new ArrayList[n];
parent = new int[n];
value = new int[n];
for (int i = 0; i < graph.length; i++)
graph[i] = new ArrayList<>();
for (int i = 0; i < n-1; i++)
{
int a = scan.nextInt()-1;
int b = scan.nextInt()-1;
graph[a].add(b);
graph[b].add(a);
}
for (int i = 0; i < n; i++)
{
value[i] = scan.nextInt();
}
setParent(0, -1);
long[] total = getTotal(0);
System.out.println(total[0]+total[1]+Math.abs(value[0]+total[0]-total[1]));
}
private static long[] getTotal(int n)
{
long inc = 0, dec = 0;
for (int x : graph[n])
{
if (x == parent[n])
continue;
long[] t = getTotal(x);
inc = Math.max(inc, t[0]);
dec = Math.max(dec, t[1]);
}
long extra = value[n]+inc-dec;
if (extra > 0)
dec += extra;
else
inc += -extra;
return new long[] { inc, dec };
}
private static void setParent(int c, int p)
{
parent[c] = p;
for (int x : graph[c])
{
if (x != p)
setParent(x, c);
}
}
static class FastScanner
{
BufferedReader br;
StringTokenizer st;
public FastScanner()
{
try
{
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e)
{
e.printStackTrace();
}
}
public String next()
{
if (st.hasMoreTokens())
return st.nextToken();
try
{
st = new StringTokenizer(br.readLine());
} catch (Exception e)
{
e.printStackTrace();
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
public String nextLine()
{
String line = "";
try
{
line = br.readLine();
} catch (Exception e)
{
e.printStackTrace();
}
return line;
}
}
}
| Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 16e802083e5e2598c09ed752df846c66 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author zodiacLeo
*/
public class Main
{
public static void main(String[] args)
{
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD
{
private int n;
private long[] a;
private long[] pos;
private long[] neg;
private ArrayList<Integer>[] g;
public void readTree(FastScanner in)
{
n = in.nextInt();
g = new ArrayList[n + 1];
for (int i = 1; i < n + 1; i++)
{
g[i] = new ArrayList<Integer>();
}
for (int i = 0; i < n - 1; i++)
{
int from = in.nextInt();
int to = in.nextInt();
g[from].add(to);
g[to].add(from);
}
}
public void solve(int testNumber, FastScanner in, FastPrinter out)
{
readTree(in);
a = new long[n + 1];
pos = new long[n + 1];
neg = new long[n + 1];
for (int i = 1; i <= n; i++)
{
a[i] = in.nextLong();
}
dfs(1, -1);
out.println(pos[1] + neg[1]);
}
public void dfs(int v, int parent)
{
for (int i = 0; i < g[v].size(); i++)
{
int u = g[v].get(i);
if (u != parent)
{
dfs(u, v);
pos[v] = Math.max(pos[v], pos[u]);
neg[v] = Math.max(neg[v], neg[u]);
}
}
long value = a[v] + pos[v] - neg[v];
if (value > 0)
{
neg[v] += value;
} else
{
pos[v] += Math.abs(value);
}
}
}
static class FastPrinter extends PrintWriter
{
public FastPrinter(OutputStream out)
{
super(out);
}
public FastPrinter(Writer out)
{
super(out);
}
}
static class FastScanner
{
BufferedReader br;
StringTokenizer st;
public FastScanner(InputStream is)
{
br = new BufferedReader(new InputStreamReader(is));
}
public FastScanner(File f)
{
try
{
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public String next()
{
while (st == null || !st.hasMoreElements())
{
String s = null;
try
{
s = br.readLine();
} catch (IOException e)
{
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
}
}
| Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | a637efb9c2e362d965338394e781c237 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
int n;
HashMap<Integer, List<Integer>> map = new HashMap<>();
long[] val;
int[] visited;
public void solve() throws IOException{
n = in.nextInt();
visited = new int[n + 1];
for(int i = 1; i <= n; i++){
map.put(i, new ArrayList<>());
}
for(int i = 0; i < n - 1; i++){
int u = in.nextInt();
int v = in.nextInt();
map.get(u).add(v);
map.get(v).add(u);
}
val = new long[n + 1];
for(int i = 1; i <= n; i++){
val[i] = in.nextLong();
}
long[] res = dfs(1);
out.println(res[0] - res[1]);
}
public long[] dfs(int node){
long incChild = 0;
long decChild = 0;
visited[node] = 1;
List<Integer> nbrs = map.get(node);
for(int nbr: nbrs){
if(visited[nbr] == 0){
long[] tmp = dfs(nbr);
incChild = Math.max(incChild, tmp[0]);
decChild = Math.min(decChild, tmp[1]);
}
}
long net = incChild + decChild - val[node];
long needToInc = -Math.min(net, 0) + incChild;
long needToDec = -Math.max(net, 0) + decChild;
return new long[]{needToInc, needToDec};
}
public BigInteger gcdBigInt(BigInteger a, BigInteger b){
if(a.compareTo(BigInteger.valueOf(0L)) == 0){
return b;
}else{
return gcdBigInt(b.mod(a), a);
}
}
FastScanner in;
PrintWriter out;
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
st = null;
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine() throws IOException {
if (st == null || !st.hasMoreTokens())
return br.readLine();
StringBuilder result = new StringBuilder(st.nextToken());
while (st.hasMoreTokens()) {
result.append(" ");
result.append(st.nextToken());
}
return result.toString();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
void run() throws IOException {
in = new FastScanner(System.in);
out = new PrintWriter(System.out, false);
solve();
out.close();
}
public static void main(String[] args) throws IOException{
new Main().run();
}
public void printArr(int[] arr){
for(int i = 0; i < arr.length; i++){
out.print(arr[i] + " ");
}
out.println();
}
public long gcd(long a, long b){
if(a == 0) return b;
return gcd(b % a, a);
}
public boolean isPrime(long num){
if(num == 0 || num == 1){
return false;
}
for(int i = 2; i * i <= num; i++){
if(num % i == 0){
return false;
}
}
return true;
}
public class Pair<A, B>{
public A x;
public B y;
Pair(A x, B 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;
Pair<?, ?> pair = (Pair<?, ?>) o;
if (!x.equals(pair.x)) return false;
return y.equals(pair.y);
}
@Override
public int hashCode() {
int result = x.hashCode();
result = 31 * result + y.hashCode();
return result;
}
}
class Tuple{
int x; int y; int z;
Tuple(int ix, int iy, int iz){
x = ix;
y = iy;
z = iz;
}
}
}
| Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | ac177b59849a63b02b92f894e8cd96bf | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
BZeroTree solver = new BZeroTree();
solver.solve(1, in, out);
out.close();
}
static class BZeroTree {
ArrayList<Integer>[] arrayList;
long[] val;
long[] dr;
long[] inr;
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int n = in.scanInt();
arrayList = new ArrayList[n + 1];
dr = new long[n + 1];
inr = new long[n + 1];
val = new long[n + 1];
for (int i = 0; i <= n; i++) arrayList[i] = new ArrayList<>();
for (int i = 0; i < n - 1; i++) {
int x = in.scanInt();
int y = in.scanInt();
arrayList[x].add(y);
arrayList[y].add(x);
}
for (int i = 1; i <= n; i++) {
val[i] = in.scanLong();
}
DFS(1, -1);
out.println(inr[1] + dr[1]);
}
void DFS(int start, int p) {
long maxin = 0;
long maxdec = 0;
for (int tt : arrayList[start]) {
if (tt == p) continue;
DFS(tt, start);
maxdec = Math.max(maxdec, dr[tt]);
maxin = Math.max(maxin, inr[tt]);
}
dr[start] = maxdec;
inr[start] = maxin;
if (val[start] + maxin - maxdec > 0) {
dr[start] += val[start] + maxin - maxdec;
} else {
inr[start] += ((val[start] + maxin - maxdec) * -1);
}
}
}
static class ScanReader {
private byte[] buf = new byte[4 * 1024];
private int INDEX;
private BufferedInputStream in;
private int TOTAL;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() {
if (INDEX >= TOTAL) {
INDEX = 0;
try {
TOTAL = in.read(buf);
} catch (Exception e) {
e.printStackTrace();
}
if (TOTAL <= 0) return -1;
}
return buf[INDEX++];
}
public int scanInt() {
int I = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
I *= 10;
I += n - '0';
n = scan();
}
}
return neg * I;
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
public long scanLong() {
long I = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
I *= 10;
I += n - '0';
n = scan();
}
}
return neg * I;
}
}
}
| Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 1cd7c3f88e4ecb563b349faa7ffb5405 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes |
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
public class B274 {
static int nodes ;
static List<Integer>[] graph;
static long[] values,pos,neg;
public static void main(String args[]) throws Exception {
Reader reader = new Reader();
reader.initConsoleReading();
nodes = reader.nextInt();
graph = new List[nodes+1];
values = new long[nodes+1];
pos = new long[nodes+1];
neg = new long[nodes+1];
Arrays.fill(pos,0);
Arrays.fill(neg,0);
for(int i=1;i<nodes;i++){
int u = reader.nextInt();
int v = reader.nextInt();
addEdge(u,v);
}
for(int i=1;i<=nodes;i++){
values[i]=reader.nextInt();
}
dfs(1,-1);
System.out.println(pos[1]+neg[1]);
reader.dispose();
}
private static void dfs(int u, int parent) {
for(int v : graph[u]){
if(v!=parent){
dfs(v,u);
pos[u] = Math.max(pos[u], pos[v]);
neg[u] = Math.max(neg[u],neg[v]);
}
}
values[u]+=(-pos[u]+neg[u]);
if(values[u]>=0)pos[u]+=values[u];
else neg[u]-=values[u];
// System.out.println(u + " " + pos[u] + " " + neg[u]);
}
private static void addEdge(int u, int v) {
if(graph[u]==null)graph[u] = new ArrayList<>();
if(graph[v]==null)graph[v] = new ArrayList<>();
graph[u].add(v);
graph[v].add(u);
}
/************************************Helper Methods Begin Here**********************************************/
private static String reverse(String toRev) {
return new StringBuilder(toRev).reverse().toString();
}
public static int swap(int a, int b) {
/*a = Main.swap(b,b=a); goes from left to right*/
return a;
}
public static long swap(long a, long b) {
/*a = Main.swap(b,b=a); goes from left to right*/
return a;
}
private static <T1, T2> void init6d(T1[][][][][][] sixD, T2 val) {
for (T1[][][][][] fiveD : sixD) init5d(fiveD, val);
}
private static <T1, T2> void init5d(T1[][][][][] fiveD, T2 val) {
for (T1[][][][] fourD : fiveD) init4d(fourD, val);
}
private static <T1, T2> void init4d(T1[][][][] fourD, T2 val) {
for (T1[][][] threeD : fourD) init3d(threeD, val);
}
private static <T1, T2> void init3d(T1[][][] threeD, T2 val) {
for (T1[][] twoD : threeD) init2d(twoD, val);
}
private static <T1, T2> void init2d(T1[][] twoD, T2 val) {
for (T1[] oneD : twoD) init1d(oneD, val);
}
private static <T1, T2> void init1d(T1[] oneD, T2 val) {
Arrays.fill(oneD, val);
}
public static boolean next_permutation(int[] p) {
for (int a = p.length - 2; a >= 0; --a)
if (p[a] < p[a + 1])
for (int b = p.length - 1; ; --b)
if (p[b] > p[a]) {
int t = p[a];
p[a] = p[b];
p[b] = t;
for (++a, b = p.length - 1; a < b; ++a, --b) {
t = p[a];
p[a] = p[b];
p[b] = t;
}
return true;
}
return false;
}
public static long gcd(long a, long b) {
if (a < 0) a *= -1;
if (b < 0) b *= -1;
return b == 0 ? a : gcd(b, a % b);
}
public static class Reader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public Reader() {
}
public Reader initConsoleReading() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
return this;
}
public Reader initFileReading(String filePath) throws FileNotFoundException {
reader = new BufferedReader(new FileReader(filePath), 32768);
tokenizer = null;
return this;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String nextLine() throws IOException {
return reader.readLine();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public void dispose() throws IOException {
this.reader.close();
}
}
/************************************Helper Methods Ends Here**********************************************/
}
| Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | fb4928363232786d9655e9ccc042b2c7 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStreamWriter;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.IOException;
import java.util.StringTokenizer;
import java.text.DecimalFormat;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Roberto Sales
*/
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
ArrayList<Integer> adj[];
int n;
long v[];
long inc[];
long dec[];
void dfs(int i, int p){
long in = 0, de = 0;
for(int k : adj[i]){
if(k == p) continue;
dfs(k, i);
in = Math.max(in, inc[k]);
de = Math.max(de, dec[k]);
}
long val = v[i] + (in-de);
if(val > 0) de += val;
else in -= val;
inc[i] = in;
dec[i] = de;
}
public void solve(int testNumber, FastInput in, FastOutput out) {
n = in.readInt();
adj = new ArrayList[n+1];
for(int i = 1; i <= n; i++) adj[i] = new ArrayList<Integer>();
for(int i = 0; i < n-1; i++){
int a = in.readInt();
int b = in.readInt();
adj[a].add(b);
adj[b].add(a);
}
v = new long[n+1];
for(int i = 1; i<=n; i++) v[i] = in.readInt();
inc = new long[n+1];
dec = new long[n+1];
dfs(1, -1);
out.printLine(inc[1] + dec[1]);
}
}
class FastInput{
private BufferedReader reader;
private StringTokenizer tokenizer;
public FastInput(InputStream in){
reader = new BufferedReader(new InputStreamReader(in), 1<<16);
tokenizer = null;
}
public String read(){
while(tokenizer == null || !tokenizer.hasMoreTokens()){
try{
tokenizer = new StringTokenizer(reader.readLine());
}catch(Exception ex){
throw new InputMismatchException();
}
}
return tokenizer.nextToken();
}
public int readInt(){
return Integer.parseInt(read());
}
}
class FastOutput {
private PrintWriter writer;
public FastOutput(OutputStream out){
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out)));
}
public void print(Object...args){
for(int i = 0; i < args.length; i++){
if(i > 0) writer.print(' ');
writer.print(args[i]);
}
}
public void printLine(Object...args){
print(args);
writer.println();
}
public void close(){
writer.close();
}
}
| Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 3eab220435d8a8e74a49d45f5aea0371 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | import java.io.*;
import java.util.ArrayList;
public class Main
{
static long[] A;
static long[] inc;
static long[] dec;
public static void main(String[] args)throws IOException
{
Reader in = new Reader();
int n = in.nextInt(); A = new long[n]; inc = new long[n]; dec = new long[n];
ArrayList<Integer>[] adj = (ArrayList<Integer>[])new ArrayList[n];
for (int i=0;i<n;i++) adj[i] = new ArrayList<>();
for (int i=0;i<n - 1;i++)
{
int x = in.nextInt();
int y = in.nextInt();
adj[x - 1].add(y - 1);
adj[y - 1].add(x - 1);
}
for (int i=0;i<n;i++) A[i] = in.nextLong();
explore(adj, 0, new boolean[n]);
System.out.println(inc[0] + dec[0]);
}
public static void explore(ArrayList<Integer>[] adj, int v, boolean[] visited)
{
visited[v] = true;
for (int u:adj[v])
{
if (!visited[u])
{
explore(adj, u, visited);
visited[u] = false;
}
}
for (int u:adj[v])
{
if (!visited[u])
{
inc[v] = Math.max(inc[u], inc[v]);
dec[v] = Math.max(dec[u], dec[v]);
}
}
long rv = A[v] + inc[v] - dec[v];
if (rv > 0)
dec[v] += rv;
else
inc[v] += -rv;
}
}
class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
| Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 9835d15a5a2fdc15cf52f70fabeaff75 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | import java.util.*;
import java.io.*;
public class ZeroTree {
/************************ SOLUTION STARTS HERE ************************/
static ArrayList<Integer>[] adj;
static long v[];
static long delta[][]; // 0 - to increment, 1 - to decrement
// delta represents how many times does the current node gets inc/dec
static void dfs(int u, int par) {
long posMax = 0;
long negMax = 0;
for(int child : adj[u])
if(child != par) {
dfs(child, u);
negMax = Math.max(negMax, delta[child][0]);
posMax = Math.max(posMax, delta[child][1]);
}
long leftOver = (negMax - posMax) - v[u];
if(leftOver > 0) //
posMax += leftOver;
else
negMax += -leftOver;
delta[u][0] = negMax;
delta[u][1] = posMax;
}
@SuppressWarnings("unchecked")
private static void solve() {
int V = nextInt();
int E = V - 1;
adj = new ArrayList[V + 1];
delta = new long[V + 1][2];
for(int i = 1; i <= V; i++)
adj[i] = new ArrayList<>();
while(E-->0) {
int u = nextInt();
int v = nextInt();
adj[u].add(v);
adj[v].add(u);
}
v = nextLongArrayOneBased(V);
dfs(1, 0);
println(delta[1][0] + delta[1][1]);
}
/************************ SOLUTION ENDS HERE ************************/
/************************ TEMPLATE STARTS HERE **********************/
public static void main(String[] args) throws IOException {
reader = new BufferedReader(new InputStreamReader(System.in));
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false);
st = null;
solve();
reader.close();
writer.close();
}
static BufferedReader reader;
static PrintWriter writer;
static StringTokenizer st;
static 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();}
static String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;}
static int nextInt() {return Integer.parseInt(next());}
static long nextLong() {return Long.parseLong(next());}
static double nextDouble(){return Double.parseDouble(next());}
static char nextChar() {return next().charAt(0);}
static int[] nextIntArray(int n) {int[] a= new int[n]; int i=0;while(i<n){a[i++]=nextInt();} return a;}
static long[] nextLongArray(int n) {long[]a= new long[n]; int i=0;while(i<n){a[i++]=nextLong();} return a;}
static int[] nextIntArrayOneBased(int n) {int[] a= new int[n+1]; int i=1;while(i<=n){a[i++]=nextInt();} return a;}
static long[] nextLongArrayOneBased(int n){long[]a= new long[n+1];int i=1;while(i<=n){a[i++]=nextLong();}return a;}
static void print(Object o) { writer.print(o); }
static void println(Object o){ writer.println(o);}
/************************ TEMPLATE ENDS HERE ************************/
} | Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output | |
PASSED | 4940ab42c531b9359de8f9498ef80329 | train_003.jsonl | 1361374200 | A tree is a graph with n vertices and exactly nβ-β1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: Select the subtree of the given tree that includes the vertex with number 1. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. | 256 megabytes | import java.awt.*;
import java.io.*;
import java.util.*;
public class Abc {
static ArrayList<Integer> adj[];
static long v[];
static long min[];
static long plus[];
public static void main(String[] args) {
FastReader sc = new FastReader();
int n=sc.nextInt();
adj=new ArrayList[n];
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);
}
v=new long[n];
min=new long[n];
plus=new long[n];
for (int i=0;i<n;i++)v[i]=sc.nextInt();
dfs(0,-1);
System.out.println(min[0]+plus[0]);
}
static void dfs(int u,int par){
for (int v:adj[u]){
if (v==par)continue;
dfs(v,u);
min[u]=Math.max(min[u],min[v]);
plus[u]=Math.max(plus[u],plus[v]);
}
v[u]+=(plus[u]-min[u]);
if (v[u]>=0){
min[u]+=v[u];
}else plus[u]+=-v[u];
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["3\n1 2\n1 3\n1 -1 1"] | 2 seconds | ["3"] | null | Java 8 | standard input | [
"dp",
"dfs and similar",
"greedy",
"trees"
] | f3c26aa520f6bfa6b181ec40bde7ee1b | The first line of the input contains n (1ββ€βnββ€β105). Each of the next nβ-β1 lines contains two integers ai and bi (1ββ€βai,βbiββ€βn;Β aiββ βbi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1,βv2,β...,βvn (|vi|ββ€β109). | 1,800 | Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.