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 | 9c6b5bb050dddd2b9a6796e3c53e76f1 | train_003.jsonl | 1537612500 | After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency.These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of them throughout the years. Unfortunately, when paying something in bitcoin everyone can see how many bitcoins you have in your public address wallet. This worried Alice, so she decided to split her bitcoins among multiple different addresses, so that every address has at most $$$x$$$ satoshi (1 bitcoin = $$$10^8$$$ satoshi). She can create new public address wallets for free and is willing to pay $$$f$$$ fee in satoshi per transaction to ensure acceptable speed of transfer. The fee is deducted from the address the transaction was sent from. Tell Alice how much total fee in satoshi she will need to pay to achieve her goal. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
private FastScanner scanner = new FastScanner();
public static void main(String[] args) {
new Main().solve();
}
List<List<Integer>> gr = new ArrayList<>();
private void solve() {
int n = scanner.nextInt();
long a[] = new long[n];
for (int i = 0; i < n; i ++) {
a[i] = scanner.nextInt();
}
long x = scanner.nextInt(), f = scanner.nextInt();
long ans = 0;
for (int i = 0; i < n; i ++) {
if (a[i] <= x) {
continue;
}
ans += (a[i] - x) % (x + f) == 0? (a[i] - x) / (x + f): (a[i] - x) / (x + f) + 1 ;
}
System.out.print(ans * f);
}
class Pair {
int l, r, i;
public Pair(int l, int r, int i) {
this.l = l;
this.r = r;
this.i = i;
}
}
long gcd(long a, long b) {
if (b != 0) {
return gcd(b, a % b);
}
return a;
}
void initGr(int n, int m) {
for (int i = 0; i < n; i++) {
gr.add(new ArrayList<>());
}
for (int i = 0; i < m; i++) {
int u = scanner.nextInt() - 1, v = scanner.nextInt() - 1;
gr.get(u).add(v);
gr.get(v).add(u);
}
}
class FastScanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastScanner() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
} | Java | ["3\n13 7 6\n6 2"] | 1 second | ["4"] | NoteAlice can make two transactions in a following way:0. 13 7 6 (initial state)1. 6 7 6 5 (create new address and transfer from first public address 5 satoshies)2. 6 4 6 5 1 (create new address and transfer from second address 1 satoshi)Since cost per transaction is 2 satoshies, total fee is 4. | Java 8 | standard input | [
"implementation"
] | 8a3e8a5db6d7d668ffea0f59e2639e87 | First line contains number $$$N$$$ ($$$1 \leq N \leq 200\,000$$$) representing total number of public addresses Alice has. Next line contains $$$N$$$ integer numbers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) separated by a single space, representing how many satoshi Alice has in her public addresses. Last line contains two numbers $$$x$$$, $$$f$$$ ($$$1 \leq f < x \leq 10^9$$$) representing maximum number of satoshies Alice can have in one address, as well as fee in satoshies she is willing to pay per transaction. | 1,400 | Output one integer number representing total fee in satoshi Alice will need to pay to achieve her goal. | standard output | |
PASSED | 3e628c9394dba249a7d13dccf2bc5d61 | train_003.jsonl | 1537612500 | After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency.These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of them throughout the years. Unfortunately, when paying something in bitcoin everyone can see how many bitcoins you have in your public address wallet. This worried Alice, so she decided to split her bitcoins among multiple different addresses, so that every address has at most $$$x$$$ satoshi (1 bitcoin = $$$10^8$$$ satoshi). She can create new public address wallets for free and is willing to pay $$$f$$$ fee in satoshi per transaction to ensure acceptable speed of transfer. The fee is deducted from the address the transaction was sent from. Tell Alice how much total fee in satoshi she will need to pay to achieve her goal. | 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);
int n = sc.nextInt();
if(n==1){
int a = sc.nextInt();
int x = sc.nextInt();
int f = sc.nextInt();
a -=x;
if(a<=0) System.out.println("0");
else{
x = a/(x+f);
if(a%(x+f)!=0) x++;
System.out.println(x*f);
}
}else{
int[] a = new int[n];
for(int i=0;i<n;i++) a[i] = sc.nextInt();
int x = sc.nextInt();
int f = sc.nextInt();
long res = 0;
for(int i=0;i<n;i++){
int k = a[i];
k -= x;
if(k<=0) continue;
res += (long)(k/(x+f));
if(k%(x+f)!=0) res++;
}
System.out.println(res*f);
}
}
} | Java | ["3\n13 7 6\n6 2"] | 1 second | ["4"] | NoteAlice can make two transactions in a following way:0. 13 7 6 (initial state)1. 6 7 6 5 (create new address and transfer from first public address 5 satoshies)2. 6 4 6 5 1 (create new address and transfer from second address 1 satoshi)Since cost per transaction is 2 satoshies, total fee is 4. | Java 8 | standard input | [
"implementation"
] | 8a3e8a5db6d7d668ffea0f59e2639e87 | First line contains number $$$N$$$ ($$$1 \leq N \leq 200\,000$$$) representing total number of public addresses Alice has. Next line contains $$$N$$$ integer numbers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) separated by a single space, representing how many satoshi Alice has in her public addresses. Last line contains two numbers $$$x$$$, $$$f$$$ ($$$1 \leq f < x \leq 10^9$$$) representing maximum number of satoshies Alice can have in one address, as well as fee in satoshies she is willing to pay per transaction. | 1,400 | Output one integer number representing total fee in satoshi Alice will need to pay to achieve her goal. | standard output | |
PASSED | 4feaf130562635d48bb07c22b728b05e | train_003.jsonl | 1537612500 | After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency.These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of them throughout the years. Unfortunately, when paying something in bitcoin everyone can see how many bitcoins you have in your public address wallet. This worried Alice, so she decided to split her bitcoins among multiple different addresses, so that every address has at most $$$x$$$ satoshi (1 bitcoin = $$$10^8$$$ satoshi). She can create new public address wallets for free and is willing to pay $$$f$$$ fee in satoshi per transaction to ensure acceptable speed of transfer. The fee is deducted from the address the transaction was sent from. Tell Alice how much total fee in satoshi she will need to pay to achieve her goal. | 256 megabytes | import java.util.Scanner;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
try {
Scanner sc = new Scanner(System.in);
int i,n,x,f;
long count=0;
n=sc.nextInt();
int a[] = new int[n];
for(i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
x=sc.nextInt();
f=sc.nextInt();
for(i=0;i<n;i++)
{
if((a[i]+f)%(x+f) == 0)
count=(a[i]+f)/(x+f)-1+count;
else
count=(a[i]+f)/(x+f)+count;
}
count=count*f;
System.out.println(count);
} catch(Exception e) {
}
}
}
| Java | ["3\n13 7 6\n6 2"] | 1 second | ["4"] | NoteAlice can make two transactions in a following way:0. 13 7 6 (initial state)1. 6 7 6 5 (create new address and transfer from first public address 5 satoshies)2. 6 4 6 5 1 (create new address and transfer from second address 1 satoshi)Since cost per transaction is 2 satoshies, total fee is 4. | Java 8 | standard input | [
"implementation"
] | 8a3e8a5db6d7d668ffea0f59e2639e87 | First line contains number $$$N$$$ ($$$1 \leq N \leq 200\,000$$$) representing total number of public addresses Alice has. Next line contains $$$N$$$ integer numbers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) separated by a single space, representing how many satoshi Alice has in her public addresses. Last line contains two numbers $$$x$$$, $$$f$$$ ($$$1 \leq f < x \leq 10^9$$$) representing maximum number of satoshies Alice can have in one address, as well as fee in satoshies she is willing to pay per transaction. | 1,400 | Output one integer number representing total fee in satoshi Alice will need to pay to achieve her goal. | standard output | |
PASSED | 1379c4b5701da48d5c76a55cfd25da1e | train_003.jsonl | 1537612500 | After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency.These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of them throughout the years. Unfortunately, when paying something in bitcoin everyone can see how many bitcoins you have in your public address wallet. This worried Alice, so she decided to split her bitcoins among multiple different addresses, so that every address has at most $$$x$$$ satoshi (1 bitcoin = $$$10^8$$$ satoshi). She can create new public address wallets for free and is willing to pay $$$f$$$ fee in satoshi per transaction to ensure acceptable speed of transfer. The fee is deducted from the address the transaction was sent from. Tell Alice how much total fee in satoshi she will need to pay to achieve her goal. | 256 megabytes |
/**
* Date: 22 Sep, 2018
* Link:
*
* @author Prasad-Chaudhari
* @linkedIn: https://www.linkedin.com/in/prasad-chaudhari-841655a6/
* @git: https://github.com/Prasad-Chaudhari
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class newProgram1 {
public static void main(String[] args) throws IOException {
// TODO code application logic here
FastIO in = new FastIO();
int n = in.ni();
int a[] = in.gia(n);
int x = in.ni();
int f = in.ni();
long acc = 0;
for (int i = 0; i < n; i++) {
if (a[i] > x) {
int mul = (a[i] - x) / (x + f);
if ((a[i] - x) % (x + f) != 0) {
mul++;
}
acc += mul;
}
}
System.out.println(acc * f);
}
static class FastIO {
private final BufferedReader br;
private final BufferedWriter bw;
private String s[];
private int index;
private StringBuilder sb;
public FastIO() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out, "UTF-8"));
s = br.readLine().split(" ");
sb = new StringBuilder();
index = 0;
}
public int ni() throws IOException {
return Integer.parseInt(nextToken());
}
public double nd() throws IOException {
return Double.parseDouble(nextToken());
}
public long nl() throws IOException {
return Long.parseLong(nextToken());
}
public String next() throws IOException {
return nextToken();
}
public String nli() throws IOException {
try {
return br.readLine();
} catch (IOException ex) {
}
return null;
}
public int[] gia(int n) throws IOException {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}
public int[] gia(int n, int start, int end) throws IOException {
validate(n, start, end);
int a[] = new int[n];
for (int i = start; i < end; i++) {
a[i] = ni();
}
return a;
}
public double[] gda(int n) throws IOException {
double a[] = new double[n];
for (int i = 0; i < n; i++) {
a[i] = nd();
}
return a;
}
public double[] gda(int n, int start, int end) throws IOException {
validate(n, start, end);
double a[] = new double[n];
for (int i = start; i < end; i++) {
a[i] = nd();
}
return a;
}
public long[] gla(int n) throws IOException {
long a[] = new long[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}
public long[] gla(int n, int start, int end) throws IOException {
validate(n, start, end);
long a[] = new long[n];
for (int i = start; i < end; i++) {
a[i] = ni();
}
return a;
}
public int[][] gg(int n, int m) throws IOException {
int adja[][] = new int[n + 1][];
int from[] = new int[m];
int to[] = new int[m];
int count[] = new int[n + 1];
for (int i = 0; i < m; i++) {
from[i] = ni();
to[i] = ni();
count[from[i]]++;
count[to[i]]++;
}
for (int i = 0; i <= n; i++) {
adja[i] = new int[count[i]];
}
for (int i = 0; i < m; i++) {
adja[from[i]][--count[from[i]]] = to[i];
adja[to[i]][--count[to[i]]] = from[i];
}
return adja;
}
public void print(String s) throws IOException {
bw.write(s);
bw.flush();
}
public void println(String s) throws IOException {
bw.write(s);
bw.newLine();
bw.flush();
}
private String nextToken() throws IndexOutOfBoundsException, IOException {
if (index == s.length) {
s = br.readLine().split(" ");
index = 0;
}
return s[index++];
}
private void validate(int n, int start, int end) {
if (start < 0 || end >= n) {
throw new IllegalArgumentException();
}
}
}
static class Data implements Comparable<Data> {
int a, b;
public Data(int a, int b) {
this.a = a;
this.b = b;
}
@Override
public int compareTo(Data o) {
if (a != o.a) {
return Integer.compare(b, o.b);
}
return Integer.compare(a, o.a);
}
}
}
| Java | ["3\n13 7 6\n6 2"] | 1 second | ["4"] | NoteAlice can make two transactions in a following way:0. 13 7 6 (initial state)1. 6 7 6 5 (create new address and transfer from first public address 5 satoshies)2. 6 4 6 5 1 (create new address and transfer from second address 1 satoshi)Since cost per transaction is 2 satoshies, total fee is 4. | Java 8 | standard input | [
"implementation"
] | 8a3e8a5db6d7d668ffea0f59e2639e87 | First line contains number $$$N$$$ ($$$1 \leq N \leq 200\,000$$$) representing total number of public addresses Alice has. Next line contains $$$N$$$ integer numbers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) separated by a single space, representing how many satoshi Alice has in her public addresses. Last line contains two numbers $$$x$$$, $$$f$$$ ($$$1 \leq f < x \leq 10^9$$$) representing maximum number of satoshies Alice can have in one address, as well as fee in satoshies she is willing to pay per transaction. | 1,400 | Output one integer number representing total fee in satoshi Alice will need to pay to achieve her goal. | standard output | |
PASSED | 52091d2a621c2a3df2498c84c4a1081a | train_003.jsonl | 1537612500 | After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency.These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of them throughout the years. Unfortunately, when paying something in bitcoin everyone can see how many bitcoins you have in your public address wallet. This worried Alice, so she decided to split her bitcoins among multiple different addresses, so that every address has at most $$$x$$$ satoshi (1 bitcoin = $$$10^8$$$ satoshi). She can create new public address wallets for free and is willing to pay $$$f$$$ fee in satoshi per transaction to ensure acceptable speed of transfer. The fee is deducted from the address the transaction was sent from. Tell Alice how much total fee in satoshi she will need to pay to achieve her goal. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Jenish
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
FSplittingMoney solver = new FSplittingMoney();
solver.solve(1, in, out);
out.close();
}
static class FSplittingMoney {
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int n = in.scanInt();
long ans = 0;
long arr[] = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = in.scanInt();
}
int x = in.scanInt();
long f = in.scanInt();
for (int i = 0; i < n; i++) {
if (arr[i] > x) {
while (arr[i] > x) {
long temp = arr[i] / (x + f);
arr[i] = arr[i] - (temp * (x + f));
ans += temp;
if (temp == 0) {
arr[i] = arr[i] - x;
ans++;
}
}
}
}
out.println(ans * f);
}
}
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;
}
}
}
| Java | ["3\n13 7 6\n6 2"] | 1 second | ["4"] | NoteAlice can make two transactions in a following way:0. 13 7 6 (initial state)1. 6 7 6 5 (create new address and transfer from first public address 5 satoshies)2. 6 4 6 5 1 (create new address and transfer from second address 1 satoshi)Since cost per transaction is 2 satoshies, total fee is 4. | Java 8 | standard input | [
"implementation"
] | 8a3e8a5db6d7d668ffea0f59e2639e87 | First line contains number $$$N$$$ ($$$1 \leq N \leq 200\,000$$$) representing total number of public addresses Alice has. Next line contains $$$N$$$ integer numbers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) separated by a single space, representing how many satoshi Alice has in her public addresses. Last line contains two numbers $$$x$$$, $$$f$$$ ($$$1 \leq f < x \leq 10^9$$$) representing maximum number of satoshies Alice can have in one address, as well as fee in satoshies she is willing to pay per transaction. | 1,400 | Output one integer number representing total fee in satoshi Alice will need to pay to achieve her goal. | standard output | |
PASSED | 6761dbbba71078f09171f3b0384d43cf | train_003.jsonl | 1537612500 | After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency.These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of them throughout the years. Unfortunately, when paying something in bitcoin everyone can see how many bitcoins you have in your public address wallet. This worried Alice, so she decided to split her bitcoins among multiple different addresses, so that every address has at most $$$x$$$ satoshi (1 bitcoin = $$$10^8$$$ satoshi). She can create new public address wallets for free and is willing to pay $$$f$$$ fee in satoshi per transaction to ensure acceptable speed of transfer. The fee is deducted from the address the transaction was sent from. Tell Alice how much total fee in satoshi she will need to pay to achieve her goal. | 256 megabytes | import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* #
* @author pttrung
*/
public class F_Bubble11_Div2 {
public static long MOD = 998244353;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int n = in.nextInt();
int[]data = new int[n];
for(int i = 0; i < n; i++){
data[i] = in.nextInt();
}
int x = in.nextInt();
int f = in.nextInt();
long result = 0;
for(int i : data){
if(i > x){
int v = (i + f) / (x + f);
if((i + f) % (x + f) != 0){
v++;
}
//System.out.println(i);
v = Integer.max(2, v);
result += (v - 1)*f;
}
}
out.println(result);
out.close();
}
static int count(int last, int cur){
if(last == cur){
return 0;
}
if(last == 0 && cur != 0){
return 1;
}
if(last == 1 ){
if(cur == 2){
return 2;
}
return 0;
}
if(last == 2){
if(cur == 1){
return 2;
}
return 0;
}
return 1;
}
public static boolean div(int need, String v) {
int cur = 0;
for (int i = 0; i < v.length(); i++) {
cur += v.charAt(i) - '0';
if (cur == need) {
cur = 0;
} else if (cur > need) {
return false;
}
}
return true;
}
public static int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static int digit(long n) {
int result = 0;
while (n > 0) {
n /= 10;
result++;
}
return result;
}
public static double dist(long a, long b, long x, long y) {
double val = (b - a) * (b - a) + (x - y) * (x - y);
val = Math.sqrt(val);
double other = x * x + a * a;
other = Math.sqrt(other);
return val + other;
}
public static class Point implements Comparable<Point> {
int x, y;
public Point(int start, int end) {
this.x = start;
this.y = end;
}
@Override
public int hashCode() {
int hash = 5;
hash = 47 * hash + this.x;
hash = 47 * hash + this.y;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Point other = (Point) obj;
if (this.x != other.x) {
return false;
}
if (this.y != other.y) {
return false;
}
return true;
}
@Override
public int compareTo(Point o) {
return Integer.compare(x, o.x);
}
}
public static class FT {
long[] data;
FT(int n) {
data = new long[n];
}
public void update(int index, long value) {
while (index < data.length) {
data[index] += value;
index += (index & (-index));
}
}
public long get(int index) {
long result = 0;
while (index > 0) {
result += data[index];
index -= (index & (-index));
}
return result;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static long pow(long a, long b, long MOD) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2, MOD);
if (b % 2 == 0) {
return val * val % MOD;
} else {
return val * (val * a % MOD) % MOD;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
} | Java | ["3\n13 7 6\n6 2"] | 1 second | ["4"] | NoteAlice can make two transactions in a following way:0. 13 7 6 (initial state)1. 6 7 6 5 (create new address and transfer from first public address 5 satoshies)2. 6 4 6 5 1 (create new address and transfer from second address 1 satoshi)Since cost per transaction is 2 satoshies, total fee is 4. | Java 8 | standard input | [
"implementation"
] | 8a3e8a5db6d7d668ffea0f59e2639e87 | First line contains number $$$N$$$ ($$$1 \leq N \leq 200\,000$$$) representing total number of public addresses Alice has. Next line contains $$$N$$$ integer numbers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) separated by a single space, representing how many satoshi Alice has in her public addresses. Last line contains two numbers $$$x$$$, $$$f$$$ ($$$1 \leq f < x \leq 10^9$$$) representing maximum number of satoshies Alice can have in one address, as well as fee in satoshies she is willing to pay per transaction. | 1,400 | Output one integer number representing total fee in satoshi Alice will need to pay to achieve her goal. | standard output | |
PASSED | b79f2577c9ce1bbae9afec0ca11fa99e | train_003.jsonl | 1537612500 | After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency.These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of them throughout the years. Unfortunately, when paying something in bitcoin everyone can see how many bitcoins you have in your public address wallet. This worried Alice, so she decided to split her bitcoins among multiple different addresses, so that every address has at most $$$x$$$ satoshi (1 bitcoin = $$$10^8$$$ satoshi). She can create new public address wallets for free and is willing to pay $$$f$$$ fee in satoshi per transaction to ensure acceptable speed of transfer. The fee is deducted from the address the transaction was sent from. Tell Alice how much total fee in satoshi she will need to pay to achieve her goal. | 256 megabytes |
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class SplittingMoney implements Closeable {
private InputReader in = new InputReader(System.in);
private PrintWriter out = new PrintWriter(System.out);
public void solve() {
int n = in.ni();
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = in.nl();
}
long max = in.nl(), fee = in.nl(), result = 0;
for (int i = 0; i < n; i++) {
if (a[i] > max) {
long transactions = a[i] / (max + fee), remaining = a[i] % (max + fee);
result += (transactions * fee);
if (remaining > max) {
result += fee;
}
}
}
out.println(result);
}
@Override
public void close() throws IOException {
in.close();
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int ni() {
return Integer.parseInt(next());
}
public long nl() {
return Long.parseLong(next());
}
public void close() throws IOException {
reader.close();
}
}
public static void main(String[] args) throws IOException {
try (SplittingMoney instance = new SplittingMoney()) {
instance.solve();
}
}
}
| Java | ["3\n13 7 6\n6 2"] | 1 second | ["4"] | NoteAlice can make two transactions in a following way:0. 13 7 6 (initial state)1. 6 7 6 5 (create new address and transfer from first public address 5 satoshies)2. 6 4 6 5 1 (create new address and transfer from second address 1 satoshi)Since cost per transaction is 2 satoshies, total fee is 4. | Java 8 | standard input | [
"implementation"
] | 8a3e8a5db6d7d668ffea0f59e2639e87 | First line contains number $$$N$$$ ($$$1 \leq N \leq 200\,000$$$) representing total number of public addresses Alice has. Next line contains $$$N$$$ integer numbers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) separated by a single space, representing how many satoshi Alice has in her public addresses. Last line contains two numbers $$$x$$$, $$$f$$$ ($$$1 \leq f < x \leq 10^9$$$) representing maximum number of satoshies Alice can have in one address, as well as fee in satoshies she is willing to pay per transaction. | 1,400 | Output one integer number representing total fee in satoshi Alice will need to pay to achieve her goal. | standard output | |
PASSED | d065e50a5c4a4a90aff11ed6b4a08579 | train_003.jsonl | 1537612500 | After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency.These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of them throughout the years. Unfortunately, when paying something in bitcoin everyone can see how many bitcoins you have in your public address wallet. This worried Alice, so she decided to split her bitcoins among multiple different addresses, so that every address has at most $$$x$$$ satoshi (1 bitcoin = $$$10^8$$$ satoshi). She can create new public address wallets for free and is willing to pay $$$f$$$ fee in satoshi per transaction to ensure acceptable speed of transfer. The fee is deducted from the address the transaction was sent from. Tell Alice how much total fee in satoshi she will need to pay to achieve her goal. | 256 megabytes | import java.util.*;
public class Q3 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int N = in.nextInt();
long[] arr = new long[N];
for (int j = 0; j < N; j++)
arr[j] = in.nextInt();
int f=in.nextInt(),k=in.nextInt();
long ans =0;
for (int i = 0; i < N; i++) {
if(arr[i]<=f)
continue;
long diff=arr[i]-f,sum=f+k;
ans +=(diff+sum-1)/sum;
}
System.out.println(ans*k);
}
} | Java | ["3\n13 7 6\n6 2"] | 1 second | ["4"] | NoteAlice can make two transactions in a following way:0. 13 7 6 (initial state)1. 6 7 6 5 (create new address and transfer from first public address 5 satoshies)2. 6 4 6 5 1 (create new address and transfer from second address 1 satoshi)Since cost per transaction is 2 satoshies, total fee is 4. | Java 8 | standard input | [
"implementation"
] | 8a3e8a5db6d7d668ffea0f59e2639e87 | First line contains number $$$N$$$ ($$$1 \leq N \leq 200\,000$$$) representing total number of public addresses Alice has. Next line contains $$$N$$$ integer numbers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) separated by a single space, representing how many satoshi Alice has in her public addresses. Last line contains two numbers $$$x$$$, $$$f$$$ ($$$1 \leq f < x \leq 10^9$$$) representing maximum number of satoshies Alice can have in one address, as well as fee in satoshies she is willing to pay per transaction. | 1,400 | Output one integer number representing total fee in satoshi Alice will need to pay to achieve her goal. | standard output | |
PASSED | 521e3a5c1783772e207d496f8568b4f8 | train_003.jsonl | 1537612500 | After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency.These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of them throughout the years. Unfortunately, when paying something in bitcoin everyone can see how many bitcoins you have in your public address wallet. This worried Alice, so she decided to split her bitcoins among multiple different addresses, so that every address has at most $$$x$$$ satoshi (1 bitcoin = $$$10^8$$$ satoshi). She can create new public address wallets for free and is willing to pay $$$f$$$ fee in satoshi per transaction to ensure acceptable speed of transfer. The fee is deducted from the address the transaction was sent from. Tell Alice how much total fee in satoshi she will need to pay to achieve her goal. | 256 megabytes | import java.util.*;
public class algo_102
{
public static void main(String args[])
{
Scanner ex=new Scanner(System.in);
int n=ex.nextInt();
long ans=0;
long coin[]=new long[n];
for(int i=0;i<n;i++)
coin[i]=ex.nextLong();
long x=ex.nextLong();
long f=ex.nextLong();
long sum=x+f;
for(int i=0;i<n;i++)
{
long num=coin[i];
long count=num/sum;
long rem=num%sum;
if(rem>x)
count++;
ans=ans+f*count;
}
System.out.println(ans);
}
} | Java | ["3\n13 7 6\n6 2"] | 1 second | ["4"] | NoteAlice can make two transactions in a following way:0. 13 7 6 (initial state)1. 6 7 6 5 (create new address and transfer from first public address 5 satoshies)2. 6 4 6 5 1 (create new address and transfer from second address 1 satoshi)Since cost per transaction is 2 satoshies, total fee is 4. | Java 8 | standard input | [
"implementation"
] | 8a3e8a5db6d7d668ffea0f59e2639e87 | First line contains number $$$N$$$ ($$$1 \leq N \leq 200\,000$$$) representing total number of public addresses Alice has. Next line contains $$$N$$$ integer numbers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) separated by a single space, representing how many satoshi Alice has in her public addresses. Last line contains two numbers $$$x$$$, $$$f$$$ ($$$1 \leq f < x \leq 10^9$$$) representing maximum number of satoshies Alice can have in one address, as well as fee in satoshies she is willing to pay per transaction. | 1,400 | Output one integer number representing total fee in satoshi Alice will need to pay to achieve her goal. | standard output | |
PASSED | 206f98a47fb4cc3cca686c81644196ae | train_003.jsonl | 1537612500 | After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency.These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of them throughout the years. Unfortunately, when paying something in bitcoin everyone can see how many bitcoins you have in your public address wallet. This worried Alice, so she decided to split her bitcoins among multiple different addresses, so that every address has at most $$$x$$$ satoshi (1 bitcoin = $$$10^8$$$ satoshi). She can create new public address wallets for free and is willing to pay $$$f$$$ fee in satoshi per transaction to ensure acceptable speed of transfer. The fee is deducted from the address the transaction was sent from. Tell Alice how much total fee in satoshi she will need to pay to achieve her goal. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static int gcd(int a, int b) {
return b > 0 ? gcd(b, a % b) : a;
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] m = new int[n];
for(int i = 0; i < n;i++){
m[i] = sc.nextInt();
}
int a = sc.nextInt();
int b = sc.nextInt();
long ans = 0;
for(int i = 0; i < n; i++){
int h = m[i];
if(h <= a)
continue;
int c = (int)Math.ceil((double)(h-a) /(a + b));
ans += b * c;
}
System.out.println(ans);
}
static int binSearch(int[] a, int key) {
int l = 0;
int r = a.length ;
while (l < r - 1) {
int m = (l + r) / 2;
if (a[m] < key)
l = m + 1;
else
r = m;
}
return r;
}
// static double dst(int a, int b, int c, int d) {
// return (Math.sqrt((a - c) * (a - c) + (b - d) * (b - d)));
// }
}
| Java | ["3\n13 7 6\n6 2"] | 1 second | ["4"] | NoteAlice can make two transactions in a following way:0. 13 7 6 (initial state)1. 6 7 6 5 (create new address and transfer from first public address 5 satoshies)2. 6 4 6 5 1 (create new address and transfer from second address 1 satoshi)Since cost per transaction is 2 satoshies, total fee is 4. | Java 8 | standard input | [
"implementation"
] | 8a3e8a5db6d7d668ffea0f59e2639e87 | First line contains number $$$N$$$ ($$$1 \leq N \leq 200\,000$$$) representing total number of public addresses Alice has. Next line contains $$$N$$$ integer numbers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) separated by a single space, representing how many satoshi Alice has in her public addresses. Last line contains two numbers $$$x$$$, $$$f$$$ ($$$1 \leq f < x \leq 10^9$$$) representing maximum number of satoshies Alice can have in one address, as well as fee in satoshies she is willing to pay per transaction. | 1,400 | Output one integer number representing total fee in satoshi Alice will need to pay to achieve her goal. | standard output | |
PASSED | 514619196f3ac597ff09ccc88f901829 | train_003.jsonl | 1537612500 | After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency.These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of them throughout the years. Unfortunately, when paying something in bitcoin everyone can see how many bitcoins you have in your public address wallet. This worried Alice, so she decided to split her bitcoins among multiple different addresses, so that every address has at most $$$x$$$ satoshi (1 bitcoin = $$$10^8$$$ satoshi). She can create new public address wallets for free and is willing to pay $$$f$$$ fee in satoshi per transaction to ensure acceptable speed of transfer. The fee is deducted from the address the transaction was sent from. Tell Alice how much total fee in satoshi she will need to pay to achieve her goal. | 256 megabytes | /**
* BaZ :D
*/
import java.util.*;
import java.io.*;
import static java.lang.Math.*;
public class Chu
{
static Reader scan;
static PrintWriter pw;
public static void main(String[] args) {
new Thread(null,null,"BaZ",1<<25)
{
public void run()
{
try
{
solve();
}
catch(Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
}.start();
}
static void solve() throws IOException
{
scan = new Reader();
pw = new PrintWriter(System.out,true);
StringBuilder sb = new StringBuilder();
int n = ni();
long arr[] = new long[n];
for(int i=0;i<n;++i) {
arr[i] = nl();
}
long x = nl(),f = nl();
long total = 0;
for(int i=0;i<n;++i) {
if(arr[i]>x) {
long mc = (x+f);
long mu = arr[i]/mc;
total+=f*mu;
arr[i]-=mc*mu;
if(arr[i]>x)
total+=f;
}
}
pl(total);
pw.flush();
pw.close();
}
static int ni() throws IOException
{
return scan.nextInt();
}
static long nl() throws IOException
{
return scan.nextLong();
}
static double nd() throws IOException
{
return scan.nextDouble();
}
static void pl()
{
pw.println();
}
static void p(Object o)
{
pw.print(o+" ");
}
static void pl(Object o)
{
pw.println(o);
}
static void psb(StringBuilder sb)
{
pw.print(sb);
}
static void pa(String arrayName, Object arr[])
{
pl(arrayName+" : ");
for(Object o : arr)
p(o);
pl();
}
static void pa(String arrayName, int arr[])
{
pl(arrayName+" : ");
for(int o : arr)
p(o);
pl();
}
static void pa(String arrayName, long arr[])
{
pl(arrayName+" : ");
for(long o : arr)
p(o);
pl();
}
static void pa(String arrayName, double arr[])
{
pl(arrayName+" : ");
for(double o : arr)
p(o);
pl();
}
static void pa(String arrayName, char arr[])
{
pl(arrayName+" : ");
for(char o : arr)
p(o);
pl();
}
static void pa(String listName, List list)
{
pl(listName+" : ");
for(Object o : list)
p(o);
pl();
}
static void pa(String arrayName, Object[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(Object o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, int[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(int o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, long[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(long o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, char[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(char o : arr[i])
p(o);
pl();
}
}
static void pa(String arrayName, double[][] arr) {
pl(arrayName+" : ");
for(int i=0;i<arr.length;++i) {
for(double o : arr[i])
p(o);
pl();
}
}
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];
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\n13 7 6\n6 2"] | 1 second | ["4"] | NoteAlice can make two transactions in a following way:0. 13 7 6 (initial state)1. 6 7 6 5 (create new address and transfer from first public address 5 satoshies)2. 6 4 6 5 1 (create new address and transfer from second address 1 satoshi)Since cost per transaction is 2 satoshies, total fee is 4. | Java 8 | standard input | [
"implementation"
] | 8a3e8a5db6d7d668ffea0f59e2639e87 | First line contains number $$$N$$$ ($$$1 \leq N \leq 200\,000$$$) representing total number of public addresses Alice has. Next line contains $$$N$$$ integer numbers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) separated by a single space, representing how many satoshi Alice has in her public addresses. Last line contains two numbers $$$x$$$, $$$f$$$ ($$$1 \leq f < x \leq 10^9$$$) representing maximum number of satoshies Alice can have in one address, as well as fee in satoshies she is willing to pay per transaction. | 1,400 | Output one integer number representing total fee in satoshi Alice will need to pay to achieve her goal. | standard output | |
PASSED | ff311c6544a163a9a058d46cba1a0326 | train_003.jsonl | 1537612500 | After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency.These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of them throughout the years. Unfortunately, when paying something in bitcoin everyone can see how many bitcoins you have in your public address wallet. This worried Alice, so she decided to split her bitcoins among multiple different addresses, so that every address has at most $$$x$$$ satoshi (1 bitcoin = $$$10^8$$$ satoshi). She can create new public address wallets for free and is willing to pay $$$f$$$ fee in satoshi per transaction to ensure acceptable speed of transfer. The fee is deducted from the address the transaction was sent from. Tell Alice how much total fee in satoshi she will need to pay to achieve her goal. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] Args) {
Scanner in = new Scanner(System.in);
//HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
int n = in.nextInt();
long[] a = new long[n];
for(int i=0;i<n;i++) {
a[i] = in.nextLong();
}
long x = in.nextLong();
long f = in.nextLong();
long c=0;
for(int i=0;i<n;i++) {
c+=a[i]/(x+f);
if(a[i]%(x+f)>x) {
c++;
}
}
System.out.println(c*f);
in.close();
}
}
| Java | ["3\n13 7 6\n6 2"] | 1 second | ["4"] | NoteAlice can make two transactions in a following way:0. 13 7 6 (initial state)1. 6 7 6 5 (create new address and transfer from first public address 5 satoshies)2. 6 4 6 5 1 (create new address and transfer from second address 1 satoshi)Since cost per transaction is 2 satoshies, total fee is 4. | Java 8 | standard input | [
"implementation"
] | 8a3e8a5db6d7d668ffea0f59e2639e87 | First line contains number $$$N$$$ ($$$1 \leq N \leq 200\,000$$$) representing total number of public addresses Alice has. Next line contains $$$N$$$ integer numbers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) separated by a single space, representing how many satoshi Alice has in her public addresses. Last line contains two numbers $$$x$$$, $$$f$$$ ($$$1 \leq f < x \leq 10^9$$$) representing maximum number of satoshies Alice can have in one address, as well as fee in satoshies she is willing to pay per transaction. | 1,400 | Output one integer number representing total fee in satoshi Alice will need to pay to achieve her goal. | standard output | |
PASSED | ecc2c93fc063e325be3e67386f870d13 | train_003.jsonl | 1537612500 | After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency.These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of them throughout the years. Unfortunately, when paying something in bitcoin everyone can see how many bitcoins you have in your public address wallet. This worried Alice, so she decided to split her bitcoins among multiple different addresses, so that every address has at most $$$x$$$ satoshi (1 bitcoin = $$$10^8$$$ satoshi). She can create new public address wallets for free and is willing to pay $$$f$$$ fee in satoshi per transaction to ensure acceptable speed of transfer. The fee is deducted from the address the transaction was sent from. Tell Alice how much total fee in satoshi she will need to pay to achieve her goal. | 256 megabytes | import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution
{
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
public static void main(String[] args) throws Exception
{
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String[] str = (br.readLine()).trim().split(" ");
long[] arr = new long[n];
for(int i=0;i<n;i++)
arr[i] = Long.parseLong(str[i]);
str = (br.readLine()).trim().split(" ");
long x = Long.parseLong(str[0]);
long f = Long.parseLong(str[1]);
long count = 0;
for(int i=0;i<n;i++)
{
if(arr[i] > x)
{
count = count + (arr[i] - x)/(f + x);
if((arr[i] - x) % (f + x) != 0)
count++;
}
}
out.println(count*f);
out.close();
}
}
| Java | ["3\n13 7 6\n6 2"] | 1 second | ["4"] | NoteAlice can make two transactions in a following way:0. 13 7 6 (initial state)1. 6 7 6 5 (create new address and transfer from first public address 5 satoshies)2. 6 4 6 5 1 (create new address and transfer from second address 1 satoshi)Since cost per transaction is 2 satoshies, total fee is 4. | Java 8 | standard input | [
"implementation"
] | 8a3e8a5db6d7d668ffea0f59e2639e87 | First line contains number $$$N$$$ ($$$1 \leq N \leq 200\,000$$$) representing total number of public addresses Alice has. Next line contains $$$N$$$ integer numbers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) separated by a single space, representing how many satoshi Alice has in her public addresses. Last line contains two numbers $$$x$$$, $$$f$$$ ($$$1 \leq f < x \leq 10^9$$$) representing maximum number of satoshies Alice can have in one address, as well as fee in satoshies she is willing to pay per transaction. | 1,400 | Output one integer number representing total fee in satoshi Alice will need to pay to achieve her goal. | standard output | |
PASSED | 00db0e96a248c6e7d5053bb1b21627bf | train_003.jsonl | 1537612500 | After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency.These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of them throughout the years. Unfortunately, when paying something in bitcoin everyone can see how many bitcoins you have in your public address wallet. This worried Alice, so she decided to split her bitcoins among multiple different addresses, so that every address has at most $$$x$$$ satoshi (1 bitcoin = $$$10^8$$$ satoshi). She can create new public address wallets for free and is willing to pay $$$f$$$ fee in satoshi per transaction to ensure acceptable speed of transfer. The fee is deducted from the address the transaction was sent from. Tell Alice how much total fee in satoshi she will need to pay to achieve her goal. | 256 megabytes | import java.util.*;
import java.io.*;
/**
*
* @author alanl
*/
public class Main {
/**
* @param args the command line arguments
*/
static BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
public static void main(String[] args) throws IOException{
int n = readInt();
ArrayList<Integer>arr = new ArrayList();
for(int i = 0; i<n; i++)arr.add(readInt());
Collections.sort(arr, Collections.reverseOrder());
int x = readInt(), f = readInt();
long ans = 0;
for(int i = 0; i<arr.size(); i++){
if(arr.get(i)>f){
ans+=Math.ceil((double)(arr.get(i)-x)/(f+x))*f;
}
}
System.out.println(ans);
}
static String next () throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(input.readLine().trim());
return st.nextToken();
}
static long readLong () throws IOException {
return Long.parseLong(next());
}
static int readInt () throws IOException {
return Integer.parseInt(next());
}
static double readDouble () throws IOException {
return Double.parseDouble(next());
}
static char readChar () throws IOException {
return next().charAt(0);
}
static String readLine () throws IOException {
return input.readLine().trim();
}
}
| Java | ["3\n13 7 6\n6 2"] | 1 second | ["4"] | NoteAlice can make two transactions in a following way:0. 13 7 6 (initial state)1. 6 7 6 5 (create new address and transfer from first public address 5 satoshies)2. 6 4 6 5 1 (create new address and transfer from second address 1 satoshi)Since cost per transaction is 2 satoshies, total fee is 4. | Java 8 | standard input | [
"implementation"
] | 8a3e8a5db6d7d668ffea0f59e2639e87 | First line contains number $$$N$$$ ($$$1 \leq N \leq 200\,000$$$) representing total number of public addresses Alice has. Next line contains $$$N$$$ integer numbers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) separated by a single space, representing how many satoshi Alice has in her public addresses. Last line contains two numbers $$$x$$$, $$$f$$$ ($$$1 \leq f < x \leq 10^9$$$) representing maximum number of satoshies Alice can have in one address, as well as fee in satoshies she is willing to pay per transaction. | 1,400 | Output one integer number representing total fee in satoshi Alice will need to pay to achieve her goal. | standard output | |
PASSED | 4d1456a4e6c667c460893b2de88e6ad2 | train_003.jsonl | 1537612500 | After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency.These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of them throughout the years. Unfortunately, when paying something in bitcoin everyone can see how many bitcoins you have in your public address wallet. This worried Alice, so she decided to split her bitcoins among multiple different addresses, so that every address has at most $$$x$$$ satoshi (1 bitcoin = $$$10^8$$$ satoshi). She can create new public address wallets for free and is willing to pay $$$f$$$ fee in satoshi per transaction to ensure acceptable speed of transfer. The fee is deducted from the address the transaction was sent from. Tell Alice how much total fee in satoshi she will need to pay to achieve her goal. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author NMouad21
*/
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);
FSplittingMoney solver = new FSplittingMoney();
solver.solve(1, in, out);
out.close();
}
static class FSplittingMoney {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = in.readIntArray(n);
int x = in.nextInt(), f = in.nextInt();
long ans = 0;
for (int v : a) {
if (v > x) {
ans += (v - 1L + f) / (x + f) * f;
}
}
out.print(ans);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024 << 2];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int[] readIntArray(int tokens) {
int[] ret = new int[tokens];
for (int i = 0; i < tokens; ++i) {
ret[i] = nextInt();
}
return ret;
}
public int read() {
if (this.numChars == -1) {
throw new InputMismatchException();
} else {
if (this.curChar >= this.numChars) {
this.curChar = 0;
try {
this.numChars = this.stream.read(this.buf);
} catch (IOException ex) {
throw new InputMismatchException();
}
if (this.numChars <= 0) {
return -1;
}
}
return this.buf[this.curChar++];
}
}
public int nextInt() {
int c;
for (c = this.read(); isSpaceChar(c); c = this.read()) {
}
byte sgn = 1;
if (c == 45) {
sgn = -1;
c = this.read();
}
int res = 0;
while (c >= 48 && c <= 57) {
res *= 10;
res += c - 48;
c = this.read();
if (isSpaceChar(c)) {
return res * sgn;
}
}
throw new InputMismatchException();
}
public static boolean isSpaceChar(int c) {
return c == 32 || c == 10 || c == 13 || c == 9 || c == -1;
}
}
}
| Java | ["3\n13 7 6\n6 2"] | 1 second | ["4"] | NoteAlice can make two transactions in a following way:0. 13 7 6 (initial state)1. 6 7 6 5 (create new address and transfer from first public address 5 satoshies)2. 6 4 6 5 1 (create new address and transfer from second address 1 satoshi)Since cost per transaction is 2 satoshies, total fee is 4. | Java 8 | standard input | [
"implementation"
] | 8a3e8a5db6d7d668ffea0f59e2639e87 | First line contains number $$$N$$$ ($$$1 \leq N \leq 200\,000$$$) representing total number of public addresses Alice has. Next line contains $$$N$$$ integer numbers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) separated by a single space, representing how many satoshi Alice has in her public addresses. Last line contains two numbers $$$x$$$, $$$f$$$ ($$$1 \leq f < x \leq 10^9$$$) representing maximum number of satoshies Alice can have in one address, as well as fee in satoshies she is willing to pay per transaction. | 1,400 | Output one integer number representing total fee in satoshi Alice will need to pay to achieve her goal. | standard output | |
PASSED | 29e9af43c391bddd68753e8a07dd595e | train_003.jsonl | 1537612500 | After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency.These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of them throughout the years. Unfortunately, when paying something in bitcoin everyone can see how many bitcoins you have in your public address wallet. This worried Alice, so she decided to split her bitcoins among multiple different addresses, so that every address has at most $$$x$$$ satoshi (1 bitcoin = $$$10^8$$$ satoshi). She can create new public address wallets for free and is willing to pay $$$f$$$ fee in satoshi per transaction to ensure acceptable speed of transfer. The fee is deducted from the address the transaction was sent from. Tell Alice how much total fee in satoshi she will need to pay to achieve her goal. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static BufferedReader br;
static StringTokenizer st;
static int n;
static int[] vals;
static int x;
static int f;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
vals = new int[n];
st = new StringTokenizer(br.readLine());
for (int i = 0; i<n; i++) {
vals[i] = Integer.parseInt(st.nextToken());
}
st = new StringTokenizer(br.readLine());
x = Integer.parseInt(st.nextToken());
f = Integer.parseInt(st.nextToken());
solve();
}
public static void solve() {
long res = 0;
int cur;
for (int i = 0; i<n; i++) {
cur = vals[i];
if (cur<=x) continue;
if (cur<=(x+f)) {
res++;
continue;
}
res+=cur/(x+f);
cur%=(x+f);
if (cur>x) res++;
}
System.out.println(res*f);
}
} | Java | ["3\n13 7 6\n6 2"] | 1 second | ["4"] | NoteAlice can make two transactions in a following way:0. 13 7 6 (initial state)1. 6 7 6 5 (create new address and transfer from first public address 5 satoshies)2. 6 4 6 5 1 (create new address and transfer from second address 1 satoshi)Since cost per transaction is 2 satoshies, total fee is 4. | Java 8 | standard input | [
"implementation"
] | 8a3e8a5db6d7d668ffea0f59e2639e87 | First line contains number $$$N$$$ ($$$1 \leq N \leq 200\,000$$$) representing total number of public addresses Alice has. Next line contains $$$N$$$ integer numbers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) separated by a single space, representing how many satoshi Alice has in her public addresses. Last line contains two numbers $$$x$$$, $$$f$$$ ($$$1 \leq f < x \leq 10^9$$$) representing maximum number of satoshies Alice can have in one address, as well as fee in satoshies she is willing to pay per transaction. | 1,400 | Output one integer number representing total fee in satoshi Alice will need to pay to achieve her goal. | standard output | |
PASSED | 52ab4aef55905bdcf8df3918de9eaccf | train_003.jsonl | 1537612500 | After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency.These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of them throughout the years. Unfortunately, when paying something in bitcoin everyone can see how many bitcoins you have in your public address wallet. This worried Alice, so she decided to split her bitcoins among multiple different addresses, so that every address has at most $$$x$$$ satoshi (1 bitcoin = $$$10^8$$$ satoshi). She can create new public address wallets for free and is willing to pay $$$f$$$ fee in satoshi per transaction to ensure acceptable speed of transfer. The fee is deducted from the address the transaction was sent from. Tell Alice how much total fee in satoshi she will need to pay to achieve her goal. | 256 megabytes | import java.util.Scanner;
public class SplittingMoney {
private static long splitNum(long i,long x,long f) {
return (i+f-1)/(f+x);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n=scanner.nextInt();
long x,f,ans=0;
long[] a = new long[n];
for (int i=0;i<n;i++) {
a[i] = scanner.nextInt();
}
x=scanner.nextInt();
f=scanner.nextInt();
for (long i : a) {
if (i>x) {
ans += f * splitNum(i, x, f);
}
}
System.out.print(ans);
}
}
| Java | ["3\n13 7 6\n6 2"] | 1 second | ["4"] | NoteAlice can make two transactions in a following way:0. 13 7 6 (initial state)1. 6 7 6 5 (create new address and transfer from first public address 5 satoshies)2. 6 4 6 5 1 (create new address and transfer from second address 1 satoshi)Since cost per transaction is 2 satoshies, total fee is 4. | Java 8 | standard input | [
"implementation"
] | 8a3e8a5db6d7d668ffea0f59e2639e87 | First line contains number $$$N$$$ ($$$1 \leq N \leq 200\,000$$$) representing total number of public addresses Alice has. Next line contains $$$N$$$ integer numbers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) separated by a single space, representing how many satoshi Alice has in her public addresses. Last line contains two numbers $$$x$$$, $$$f$$$ ($$$1 \leq f < x \leq 10^9$$$) representing maximum number of satoshies Alice can have in one address, as well as fee in satoshies she is willing to pay per transaction. | 1,400 | Output one integer number representing total fee in satoshi Alice will need to pay to achieve her goal. | standard output | |
PASSED | ec2c5b00b56dbe75f396d2d734504369 | train_003.jsonl | 1537612500 | After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency.These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of them throughout the years. Unfortunately, when paying something in bitcoin everyone can see how many bitcoins you have in your public address wallet. This worried Alice, so she decided to split her bitcoins among multiple different addresses, so that every address has at most $$$x$$$ satoshi (1 bitcoin = $$$10^8$$$ satoshi). She can create new public address wallets for free and is willing to pay $$$f$$$ fee in satoshi per transaction to ensure acceptable speed of transfer. The fee is deducted from the address the transaction was sent from. Tell Alice how much total fee in satoshi she will need to pay to achieve her goal. | 256 megabytes | /*
Keep solving problems.
*/
import java.util.*;
import java.io.*;
public class CFA {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
private static final long MOD = 1000L * 1000L * 1000L + 7;
private static final int[] dx = {0, -1, 0, 1};
private static final int[] dy = {1, 0, -1, 0};
private static final String yes = "Yes";
private static final String no = "No";
int n;
int[] arr;
int x;
int f;
void solve() throws IOException {
n = nextInt();
arr = nextIntArr(n);
x = nextInt();
f = nextInt();
long res = 0;
for (int i = 0; i < n; i++) {
res += howmany(arr[i]) * f;
}
outln(res);
}
int howmany(int start) {
int res = start / (f + x);
start %= f + x;
if (start > x) {
res++;
}
return res;
}
void shuffle(int[] a) {
int n = a.length;
for(int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
}
long gcd(long a, long b) {
while(a != 0 && b != 0) {
long c = b;
b = a % b;
a = c;
}
return a + b;
}
private void outln(Object o) {
out.println(o);
}
private void out(Object o) {
out.print(o);
}
private void formatPrint(double val) {
outln(String.format("%.9f%n", val));
}
public CFA() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new CFA();
}
public long[] nextLongArr(int n) throws IOException{
long[] res = new long[n];
for(int i = 0; i < n; i++)
res[i] = nextLong();
return res;
}
public int[] nextIntArr(int n) throws IOException {
int[] res = new int[n];
for(int i = 0; i < n; i++)
res[i] = nextInt();
return res;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return null;
}
}
return st.nextToken();
}
public String nextString() {
try {
return br.readLine();
} catch (IOException e) {
eof = true;
return null;
}
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
} | Java | ["3\n13 7 6\n6 2"] | 1 second | ["4"] | NoteAlice can make two transactions in a following way:0. 13 7 6 (initial state)1. 6 7 6 5 (create new address and transfer from first public address 5 satoshies)2. 6 4 6 5 1 (create new address and transfer from second address 1 satoshi)Since cost per transaction is 2 satoshies, total fee is 4. | Java 8 | standard input | [
"implementation"
] | 8a3e8a5db6d7d668ffea0f59e2639e87 | First line contains number $$$N$$$ ($$$1 \leq N \leq 200\,000$$$) representing total number of public addresses Alice has. Next line contains $$$N$$$ integer numbers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) separated by a single space, representing how many satoshi Alice has in her public addresses. Last line contains two numbers $$$x$$$, $$$f$$$ ($$$1 \leq f < x \leq 10^9$$$) representing maximum number of satoshies Alice can have in one address, as well as fee in satoshies she is willing to pay per transaction. | 1,400 | Output one integer number representing total fee in satoshi Alice will need to pay to achieve her goal. | standard output | |
PASSED | 2c4ed0838187698d72c5f08d909be93d | train_003.jsonl | 1537612500 | After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency.These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of them throughout the years. Unfortunately, when paying something in bitcoin everyone can see how many bitcoins you have in your public address wallet. This worried Alice, so she decided to split her bitcoins among multiple different addresses, so that every address has at most $$$x$$$ satoshi (1 bitcoin = $$$10^8$$$ satoshi). She can create new public address wallets for free and is willing to pay $$$f$$$ fee in satoshi per transaction to ensure acceptable speed of transfer. The fee is deducted from the address the transaction was sent from. Tell Alice how much total fee in satoshi she will need to pay to achieve her goal. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main1
{
static class Reader
{
private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;}
public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];}
public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;}
public String s(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();}
public long l(){int c = read();while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read();}while(!isSpaceChar(c));return res * sgn;}
public int i(){int c = read() ;while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }int res = 0;do{if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read() ;}while(!isSpaceChar(c));return res * sgn;}
public double d() throws IOException {return Double.parseDouble(s()) ;}
public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; }
public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; }
public int[] arr(int n){int[] ret = new int[n];for (int i = 0; i < n; i++) {ret[i] = i();}return ret;}
}
// |----| /\ | | ----- |
// | / / \ | | | |
// |--/ /----\ |----| | |
// | \ / \ | | | |
// | \ / \ | | ----- -------
public static void main(String[] args)throws IOException
{
PrintWriter out= new PrintWriter(System.out);
Reader sc=new Reader();
int n=sc.i();
long arr[]=new long[n];
for(int i=0;i<n;i++)
arr[i]=sc.l();
long x=sc.l();long f=sc.l();
long counter=0;
for(int i=0;i<n;i++)
{
if(arr[i]>x)
{
long low=0;
long high=1000000000;
while(low<high)
{
long mid=(low+high)/2;
if(arr[i]-mid*(x+f)<=x)
high=mid;
else
low=mid+1;
}
counter+=low;
}
}
out.println(counter*(long)f);
out.flush();
}
} | Java | ["3\n13 7 6\n6 2"] | 1 second | ["4"] | NoteAlice can make two transactions in a following way:0. 13 7 6 (initial state)1. 6 7 6 5 (create new address and transfer from first public address 5 satoshies)2. 6 4 6 5 1 (create new address and transfer from second address 1 satoshi)Since cost per transaction is 2 satoshies, total fee is 4. | Java 8 | standard input | [
"implementation"
] | 8a3e8a5db6d7d668ffea0f59e2639e87 | First line contains number $$$N$$$ ($$$1 \leq N \leq 200\,000$$$) representing total number of public addresses Alice has. Next line contains $$$N$$$ integer numbers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) separated by a single space, representing how many satoshi Alice has in her public addresses. Last line contains two numbers $$$x$$$, $$$f$$$ ($$$1 \leq f < x \leq 10^9$$$) representing maximum number of satoshies Alice can have in one address, as well as fee in satoshies she is willing to pay per transaction. | 1,400 | Output one integer number representing total fee in satoshi Alice will need to pay to achieve her goal. | standard output | |
PASSED | beb7e41d3d018eedf6553d11a9cfe68a | train_003.jsonl | 1537612500 | After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency.These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of them throughout the years. Unfortunately, when paying something in bitcoin everyone can see how many bitcoins you have in your public address wallet. This worried Alice, so she decided to split her bitcoins among multiple different addresses, so that every address has at most $$$x$$$ satoshi (1 bitcoin = $$$10^8$$$ satoshi). She can create new public address wallets for free and is willing to pay $$$f$$$ fee in satoshi per transaction to ensure acceptable speed of transfer. The fee is deducted from the address the transaction was sent from. Tell Alice how much total fee in satoshi she will need to pay to achieve her goal. | 256 megabytes | //package que_b;
import java.io.*;
import java.util.*;
import java.math.*;
public class utkarsh {
InputStream is;
PrintWriter out;
long mod = (long) (1e9 + 7);
boolean SHOW_TIME;
void solve() {
//Enter code here utkarsh
//SHOW_TIME = true;
int n = ni();
long a[] = new long[n];
for(int i = 0; i < n; i++) a[i] = nl();
long x = nl(), f = nl();
long ans = 0;
for(long t : a) {
if(t <= x) continue;
long d = t - x;
ans += f * ((d+x+f-1) / (x+f));
}
out.println(ans);
}
//---------- I/O Template ----------
public static void main(String[] args) { new utkarsh().run(); }
void run() {
is = System.in;
out = new PrintWriter(System.out);
long start = System.currentTimeMillis();
solve();
long end = System.currentTimeMillis();
if(SHOW_TIME) out.println("\n" + (end - start) + " ms");
out.flush();
}
byte input[] = new byte[1024];
int len = 0, ptr = 0;
int readByte() {
if(ptr >= len) { ptr = 0;
try { len = is.read(input); }
catch(IOException e) { throw new InputMismatchException(); }
if(len <= 0) { return -1; }
} return input[ptr++];
}
boolean isSpaceChar(int c) { return !( c >= 33 && c <= 126 ); }
int skip() {
int b = readByte();
while(b != -1 && isSpaceChar(b)) { b = readByte(); }
return b;
}
char nc() { return (char)skip(); }
String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while(!isSpaceChar(b)) { sb.appendCodePoint(b); b = readByte(); }
return sb.toString();
}
String nLine() {
int b = skip();
StringBuilder sb = new StringBuilder();
while( !(isSpaceChar(b) && b != ' ') ) { sb.appendCodePoint(b); b = readByte(); }
return sb.toString();
}
int ni() {
int n = 0, b = readByte();
boolean minus = false;
while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); }
if(b == '-') { minus = true; b = readByte(); }
if(b == -1) { return -1; } //no input
while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); }
return minus ? -n : n;
}
long nl() {
long n = 0L; int b = readByte();
boolean minus = false;
while(b != -1 && !( (b >= '0' && b <= '9') || b == '-')) { b = readByte(); }
if(b == '-') { minus = true; b = readByte(); }
while(b >= '0' && b <= '9') { n = n * 10 + (b - '0'); b = readByte(); }
return minus ? -n : n;
}
double nd() { return Double.parseDouble(ns()); }
float nf() { return Float.parseFloat(ns()); }
int[] na(int n) {
int a[] = new int[n];
for(int i = 0; i < n; i++) { a[i] = ni(); }
return a;
}
char[] ns(int n) {
char c[] = new char[n];
int i, b = skip();
for(i = 0; i < n; i++) {
if(isSpaceChar(b)) { break; }
c[i] = (char)b; b = readByte();
} return i == n ? c : Arrays.copyOf(c,i);
}
} | Java | ["3\n13 7 6\n6 2"] | 1 second | ["4"] | NoteAlice can make two transactions in a following way:0. 13 7 6 (initial state)1. 6 7 6 5 (create new address and transfer from first public address 5 satoshies)2. 6 4 6 5 1 (create new address and transfer from second address 1 satoshi)Since cost per transaction is 2 satoshies, total fee is 4. | Java 8 | standard input | [
"implementation"
] | 8a3e8a5db6d7d668ffea0f59e2639e87 | First line contains number $$$N$$$ ($$$1 \leq N \leq 200\,000$$$) representing total number of public addresses Alice has. Next line contains $$$N$$$ integer numbers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) separated by a single space, representing how many satoshi Alice has in her public addresses. Last line contains two numbers $$$x$$$, $$$f$$$ ($$$1 \leq f < x \leq 10^9$$$) representing maximum number of satoshies Alice can have in one address, as well as fee in satoshies she is willing to pay per transaction. | 1,400 | Output one integer number representing total fee in satoshi Alice will need to pay to achieve her goal. | standard output | |
PASSED | 7b2fad3b9851b8a74535e1e3bac5ccd7 | train_003.jsonl | 1537612500 | After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency.These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of them throughout the years. Unfortunately, when paying something in bitcoin everyone can see how many bitcoins you have in your public address wallet. This worried Alice, so she decided to split her bitcoins among multiple different addresses, so that every address has at most $$$x$$$ satoshi (1 bitcoin = $$$10^8$$$ satoshi). She can create new public address wallets for free and is willing to pay $$$f$$$ fee in satoshi per transaction to ensure acceptable speed of transfer. The fee is deducted from the address the transaction was sent from. Tell Alice how much total fee in satoshi she will need to pay to achieve her goal. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long cnt = 0;
long n = scanner.nextLong();
long[] a = new long[200001];
for (int i=1;i<=n;i++) {
a[i] = scanner.nextLong();
}
long x = scanner.nextLong();
long f = scanner.nextLong();
for (int i=1;i<=n;i++) {
cnt += a[i] / (x + f);
a[i] %= x + f;
if (a[i] > x)
cnt++;
}
System.out.println(cnt * f);
}
} | Java | ["3\n13 7 6\n6 2"] | 1 second | ["4"] | NoteAlice can make two transactions in a following way:0. 13 7 6 (initial state)1. 6 7 6 5 (create new address and transfer from first public address 5 satoshies)2. 6 4 6 5 1 (create new address and transfer from second address 1 satoshi)Since cost per transaction is 2 satoshies, total fee is 4. | Java 8 | standard input | [
"implementation"
] | 8a3e8a5db6d7d668ffea0f59e2639e87 | First line contains number $$$N$$$ ($$$1 \leq N \leq 200\,000$$$) representing total number of public addresses Alice has. Next line contains $$$N$$$ integer numbers $$$a_i$$$ ($$$1 \leq a_i \leq 10^9$$$) separated by a single space, representing how many satoshi Alice has in her public addresses. Last line contains two numbers $$$x$$$, $$$f$$$ ($$$1 \leq f < x \leq 10^9$$$) representing maximum number of satoshies Alice can have in one address, as well as fee in satoshies she is willing to pay per transaction. | 1,400 | Output one integer number representing total fee in satoshi Alice will need to pay to achieve her goal. | standard output | |
PASSED | a5468e3ed66d21d79a26523c181ce5e4 | train_003.jsonl | 1389972600 | Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers a1, a2, ..., an of length n, that the following condition fulfills: a2 - a1 = a3 - a2 = a4 - a3 = ... = ai + 1 - ai = ... = an - an - 1.For example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, 2], [1, 2, 4] are not.Alexander has n cards containing integers. Arthur wants to give Alexander exactly one more card with a number so that he could use the resulting n + 1 cards to make an arithmetic progression (Alexander has to use all of his cards).Arthur has already bought a card but he hasn't written a number on it. Help him, print all integers that you can write on a card so that the described condition fulfilled. | 256 megabytes | import java.util.*;
import java.io.*;
public class jk
{
public static void main(String[] args) throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
int num = Integer.parseInt(in.readLine());
int[] array = new int[num];
String[] p = in.readLine().split(" ");
for(int u=0; u<p.length; u++)
array[u]=Integer.parseInt(p[u]);
Arrays.sort(array);
Map<Integer,Integer> diff = new HashMap<Integer,Integer>();
if(array.length==1)
{
out.write("-1");
out.flush();
out.close();
return;
}
//int[] ind = new int[2];
for(int u=1; u<array.length; u++)
{
int tof=array[u]-array[u-1];
if(diff.get(tof)==null)
{
diff.put(tof,1);
}
else
{
diff.put(tof, diff.get(tof)+1);
}
}
if(array.length==2)
{
if(array[1]==array[0])
{
out.write("1");
out.write("\n");
out.write(Integer.toString(array[0]));
}
else if((array[1]-array[0])%2==0)
{
out.write("3");
out.write("\n");
out.write(Integer.toString(array[0]-(array[1]-array[0])) + " ");
out.write(Integer.toString(array[0]+(array[1]-array[0])/2)+ " ");
out.write(Integer.toString(array[1]+(array[1]-array[0])));
}
else
{
out.write("2");
out.write("\n");
out.write(Integer.toString(array[0]-(array[1]-array[0])) + " ");
out.write(Integer.toString(array[1]+(array[1]-array[0])));
}
}
else if(diff.size()==1)
{
//all in ap
if(diff.get(0)!=null)
{
out.write("1");
out.write("\n");
out.write(Integer.toString(array[0]));
}
else
{
out.write("2");
out.write("\n");
out.write(Integer.toString(array[0]-(array[1]-array[0])) + " ");
out.write(Integer.toString(array[array.length-1]+(array[1]-array[0])));
}
}
else if(diff.size()>2 )
{
out.write("0");//return with 0
}
else
{
int coun=0;
int[] m1 = new int[2];
int m=0;
int k=-1;
for(int key: diff.keySet())
{
if(diff.get(key)>1)
{
k=key;
coun++;
}
//k[m]=ke
m1[m]=key;
m++;
}
if(coun==2)
{
out.write("0");//return with 0
}
else if(coun==0)
{
int max = Math.max(m1[0],m1[1]);
if(max%2 !=0 || (max/2)!= (max==m1[0]?m1[1]:m1[0]))
{
out.write("0");
}
else
{
for(int u=1; u<array.length; u++)
{
if(array[u]-array[u-1]==(max))
{
out.write("1");
out.write("\n");
out.write(Integer.toString(array[u]-(max/2)));
break;
}
}
}
}
else
{
if((k==m1[0]?m1[1]:m1[0])<k ||(k==m1[0]?m1[1]:m1[0])%2 !=0 || ((k==m1[0]?m1[1]:m1[0])/2)!=k)
{
out.write("0");//return 0
}
else
{
for(int u=1; u<array.length; u++)
{
if(array[u]-array[u-1]==(k==m1[0]?m1[1]:m1[0]))
{
out.write("1");
out.write("\n");
out.write(Integer.toString(array[u]-k));
break;
}
}
}
}
}
out.flush();
out.close();
}
} | Java | ["3\n4 1 7", "1\n10", "4\n1 3 5 9", "4\n4 3 4 5", "2\n2 4"] | 1 second | ["2\n-2 10", "-1", "1\n7", "0", "3\n0 3 6"] | null | Java 8 | standard input | [
"implementation",
"sortings"
] | e3ca8338beb8852c201be72650e9aabd | The first line contains integer n (1 ≤ n ≤ 105) — the number of cards. The next line contains the sequence of integers — the numbers on Alexander's cards. The numbers are positive integers, each of them doesn't exceed 108. | 1,700 | If Arthur can write infinitely many distinct integers on the card, print on a single line -1. Otherwise, print on the first line the number of integers that suit you. In the second line, print the numbers in the increasing order. Note that the numbers in the answer can exceed 108 or even be negative (see test samples). | standard output | |
PASSED | 432cf00c625348060bbb167119545761 | train_003.jsonl | 1389972600 | Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers a1, a2, ..., an of length n, that the following condition fulfills: a2 - a1 = a3 - a2 = a4 - a3 = ... = ai + 1 - ai = ... = an - an - 1.For example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, 2], [1, 2, 4] are not.Alexander has n cards containing integers. Arthur wants to give Alexander exactly one more card with a number so that he could use the resulting n + 1 cards to make an arithmetic progression (Alexander has to use all of his cards).Arthur has already bought a card but he hasn't written a number on it. Help him, print all integers that you can write on a card so that the described condition fulfilled. | 256 megabytes | import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
public class ArithmeticProgression {
static int mod = 1000000007;
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 in = new Reader();
int i, n;
n = in.nextInt();
long arr[] = new long[n];
for (i = 0; i < n; i++)
arr[i] = in.nextLong();
if (n == 1) {
System.out.println("-1");
return;
}
Arrays.sort(arr);
if (arr[0] == arr[n - 1]) {
System.out.println("1\n" + arr[0]);
return;
}
long diff[] = new long[n - 1];
for (i = 0; i < n - 1; i++)
diff[i] = arr[i + 1] - arr[i];
if (n == 2) {
if ((diff[0] & 1) == 0) {
System.out
.println("3\n" + (arr[0] - diff[0]) + " " + (arr[0] + diff[0] / 2) + " " + (arr[1] + diff[0]));
return;
} else {
System.out.println("2\n" + (arr[0] - diff[0]) + " " + (arr[1] + diff[0]));
return;
}
}
long dif1, dif2, cnt1 = 0, cnt2 = 0;
dif1 = dif2 = diff[0];
for (i = 0; i < n - 1; i++) {
if (diff[i] == dif1) {
cnt1++;
} else if (dif1 == dif2) {
dif2 = diff[i];
cnt2++;
} else if (diff[i] == dif2) {
cnt2++;
} else {
System.out.println("0");
return;
}
}
if (dif1 == dif2) {
// if ((dif1 & 1) == 0) {
// StringBuilder ans = new StringBuilder();
// ans.append((n + 1) + "\n");
// for (i = 0; i < n; i++)
// ans.append(arr[i] - (dif1 / 2) + " ");
// ans.append(arr[n - 1] + dif1 / 2);
// System.out.println(ans);
// return;
// } else
System.out.println("2\n" + (arr[0] - dif1) + " " + (arr[n - 1] + diff[0]));
return;
}
long max, c1, min, c2;
if (dif1 > dif2) {
max = dif1;
c1 = cnt1;
min = dif2;
c2 = cnt2;
} else {
max = dif2;
c1 = cnt2;
min = dif1;
c2 = cnt1;
}
if (min == 0) {
System.out.println("0");
return;
}
if (c1 == 1 && (max & 1) == 0 && (max / 2) == min) {
for (i = 0; i < n - 1; i++) {
if (diff[i] == max) {
System.out.println("1\n" + (arr[i] + max / 2));
return;
}
}
} else {
System.out.println("0");
}
}
}
| Java | ["3\n4 1 7", "1\n10", "4\n1 3 5 9", "4\n4 3 4 5", "2\n2 4"] | 1 second | ["2\n-2 10", "-1", "1\n7", "0", "3\n0 3 6"] | null | Java 8 | standard input | [
"implementation",
"sortings"
] | e3ca8338beb8852c201be72650e9aabd | The first line contains integer n (1 ≤ n ≤ 105) — the number of cards. The next line contains the sequence of integers — the numbers on Alexander's cards. The numbers are positive integers, each of them doesn't exceed 108. | 1,700 | If Arthur can write infinitely many distinct integers on the card, print on a single line -1. Otherwise, print on the first line the number of integers that suit you. In the second line, print the numbers in the increasing order. Note that the numbers in the answer can exceed 108 or even be negative (see test samples). | standard output | |
PASSED | 82a3d2c7167b1253cddfb4351a38b6dd | train_003.jsonl | 1389972600 | Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers a1, a2, ..., an of length n, that the following condition fulfills: a2 - a1 = a3 - a2 = a4 - a3 = ... = ai + 1 - ai = ... = an - an - 1.For example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, 2], [1, 2, 4] are not.Alexander has n cards containing integers. Arthur wants to give Alexander exactly one more card with a number so that he could use the resulting n + 1 cards to make an arithmetic progression (Alexander has to use all of his cards).Arthur has already bought a card but he hasn't written a number on it. Help him, print all integers that you can write on a card so that the described condition fulfilled. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
//
public static void main(String[] args)throws IOException, URISyntaxException {
Reader.init(System.in);
StringBuilder s=new StringBuilder();
int n = Reader.nextInt();
if(n == 1) {
System.out.println("-1");
return;
}
int[] arr = new int[n];
int i;
for(i = 0; i < n; i++)
arr[i] = Reader.nextInt();
Arrays.sort(arr);
if(n == 2) {
int d = arr[1] - arr[0], cnt = 2;
if(d == 0) {
System.out.println("1\n" + arr[0]);
return;
}
if(d > 1 && d % 2 == 0)
cnt++;
s.append(cnt).append('\n').append(arr[0] - d).append(' ');
if(cnt == 3)
s.append((arr[0] + arr[1]) / 2).append(' ');
s.append(arr[1] + d).append('\n');
} else {
int d = arr[1] - arr[0], cnt = 0;
for(i = 2; i < n; i++)
d = Math.min(d, arr[i] - arr[i - 1]);
for(i = 1; i < n; i++)
if(arr[i] - arr[i - 1] != d) {
if(cnt == 1 || (arr[i] - arr[i - 1]) % 2 == 1 || (arr[i] + arr[i - 1]) / 2 - arr[i - 1] != d) {
System.out.println('0');
return;
}
cnt++;
s.append('1').append('\n').append((arr[i] + arr[i - 1]) / 2).append('\n');
}
if(cnt == 0) {
if(d == 0) {
System.out.println("1\n" + arr[0]);
return;
}
s.append('2').append('\n').append(arr[0] - d).append(' ').append(arr[n - 1] + d).append('\n');
}
}
System.out.print(s);
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) throws UnsupportedEncodingException {
reader = new BufferedReader(
new InputStreamReader(input, "UTF-8") );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static String nextLine() throws IOException {
return reader.readLine();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
static long nextLong() throws IOException {
return Long.parseLong( next() );
}
} | Java | ["3\n4 1 7", "1\n10", "4\n1 3 5 9", "4\n4 3 4 5", "2\n2 4"] | 1 second | ["2\n-2 10", "-1", "1\n7", "0", "3\n0 3 6"] | null | Java 8 | standard input | [
"implementation",
"sortings"
] | e3ca8338beb8852c201be72650e9aabd | The first line contains integer n (1 ≤ n ≤ 105) — the number of cards. The next line contains the sequence of integers — the numbers on Alexander's cards. The numbers are positive integers, each of them doesn't exceed 108. | 1,700 | If Arthur can write infinitely many distinct integers on the card, print on a single line -1. Otherwise, print on the first line the number of integers that suit you. In the second line, print the numbers in the increasing order. Note that the numbers in the answer can exceed 108 or even be negative (see test samples). | standard output | |
PASSED | 0a0213fa07f7ae91da12aea69ec88aba | train_003.jsonl | 1389972600 | Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers a1, a2, ..., an of length n, that the following condition fulfills: a2 - a1 = a3 - a2 = a4 - a3 = ... = ai + 1 - ai = ... = an - an - 1.For example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, 2], [1, 2, 4] are not.Alexander has n cards containing integers. Arthur wants to give Alexander exactly one more card with a number so that he could use the resulting n + 1 cards to make an arithmetic progression (Alexander has to use all of his cards).Arthur has already bought a card but he hasn't written a number on it. Help him, print all integers that you can write on a card so that the described condition fulfilled. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args)throws IOException, URISyntaxException {
Reader.init(System.in);
StringBuilder s=new StringBuilder();
int n = Reader.nextInt();
if(n == 1) {
System.out.println("-1");
return;
}
int[] arr = new int[n];
int i;
for(i = 0; i < n; i++)
arr[i] = Reader.nextInt();
Arrays.sort(arr);
if(n == 2) {
int d = arr[1] - arr[0], cnt = 2;
if(d == 0) {
System.out.println("1\n" + arr[0]);
return;
}
if(d > 1 && d % 2 == 0)
cnt++;
s.append(cnt).append('\n').append(arr[0] - d).append(' ');
if(cnt == 3)
s.append((arr[0] + arr[1]) / 2).append(' ');
s.append(arr[1] + d).append('\n');
} else {
int d = arr[1] - arr[0], cnt = 0;
for(i = 2; i < n; i++)
d = Math.min(d, arr[i] - arr[i - 1]);
for(i = 1; i < n; i++)
if(arr[i] - arr[i - 1] != d) {
if(cnt == 1 || (arr[i] - arr[i - 1]) % 2 == 1 || (arr[i] + arr[i - 1]) / 2 - arr[i - 1] != d) {
System.out.println('0');
return;
}
cnt++;
s.append('1').append('\n').append((arr[i] + arr[i - 1]) / 2).append('\n');
}
if(cnt == 0) {
if(d == 0) {
System.out.println("1\n" + arr[0]);
return;
}
s.append('2').append('\n').append(arr[0] - d).append(' ').append(arr[n - 1] + d).append('\n');
}
}
System.out.print(s);
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) throws UnsupportedEncodingException {
reader = new BufferedReader(
new InputStreamReader(input, "UTF-8") );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static String nextLine() throws IOException {
return reader.readLine();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
static long nextLong() throws IOException {
return Long.parseLong( next() );
}
} | Java | ["3\n4 1 7", "1\n10", "4\n1 3 5 9", "4\n4 3 4 5", "2\n2 4"] | 1 second | ["2\n-2 10", "-1", "1\n7", "0", "3\n0 3 6"] | null | Java 8 | standard input | [
"implementation",
"sortings"
] | e3ca8338beb8852c201be72650e9aabd | The first line contains integer n (1 ≤ n ≤ 105) — the number of cards. The next line contains the sequence of integers — the numbers on Alexander's cards. The numbers are positive integers, each of them doesn't exceed 108. | 1,700 | If Arthur can write infinitely many distinct integers on the card, print on a single line -1. Otherwise, print on the first line the number of integers that suit you. In the second line, print the numbers in the increasing order. Note that the numbers in the answer can exceed 108 or even be negative (see test samples). | standard output | |
PASSED | db5281895b6cf9e162beb31816e26384 | train_003.jsonl | 1389972600 | Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers a1, a2, ..., an of length n, that the following condition fulfills: a2 - a1 = a3 - a2 = a4 - a3 = ... = ai + 1 - ai = ... = an - an - 1.For example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, 2], [1, 2, 4] are not.Alexander has n cards containing integers. Arthur wants to give Alexander exactly one more card with a number so that he could use the resulting n + 1 cards to make an arithmetic progression (Alexander has to use all of his cards).Arthur has already bought a card but he hasn't written a number on it. Help him, print all integers that you can write on a card so that the described condition fulfilled. | 256 megabytes | /**
* ******* Created on 10/12/19 12:37 AM*******
*/
import java.io.*;
import java.util.*;
public class C382 implements Runnable {
private static final int MAX = (int) (1E5 + 5);
private static final int MOD = (int) (1E9 + 7);
private static final int Inf = (int) (1E9 + 10);
List<Integer> res = new ArrayList<>();
private void solve() throws IOException {
int n = reader.nextInt();
int[] a = new int[n];
for(int i = 0;i<n;i++)
a[i] = reader.nextInt();
Arrays.sort(a);
int ans = -1,diff;
if( n == 1) {
writer.println("-1");
return;
}
else if(n ==2){
int temp = a[1] -a[0];
if(temp == 0){
ans =1;
res.add(a[0]);
}
else if(temp%2 == 0){
ans =3;
res.add(a[0] - temp);
res.add(a[1] - temp/2);
res.add(a[1] + temp);
}else{
ans = 2;
res.add(a[0] - temp);
res.add(a[1] + temp);
}
}else{
diff = a[1] -a[0];
int diff2 =MOD;
boolean possible =true;
boolean flag = false;
int cnt = 0, cnt2=0, pos =-1;
for(int i =1;i < n;i++) {
int val = a[i] -a[i-1];
if( (!flag && val !=diff) || (val == diff2 )){
pos =i;
diff2 = a[i] - a[i-1];
flag = true;
cnt2++;
}
else if(val == diff) cnt++;
else possible = false;
}
if(!possible)
ans =0;
else if(cnt == n-1 && a[0] != a[n-1]){ {
ans = 2;
res.add(a[0]-diff);
res.add(a[n-1]+diff);
}
}else if(cnt == n-1 && a[0] == a[n-1]) {
ans =1;
res.add(a[0]);
}
else{
if(cnt2 == 1){
if(( a[pos] - a[pos-1] ) %2 == 0 && a[pos]-a[pos-1] == 2*diff && cnt == n-2){
res.add(a[pos-1]+diff);
ans =1;
}else if(cnt ==1 && (a[1] - a[0]) %2 == 0 && a[1]-a[0] == 2*diff2 && cnt == n-2){
res.add(a[0] + diff2);
ans =1;
}else{
ans =0;
}
}else if(cnt == 1&& (a[1] - a[0]) %2 == 0 && a[1]-a[0] == 2*diff2 && cnt2 == n-2){
res.add(a[0] + diff2);
ans =1;
}else{
ans =0;
}
}
}
writer.println(ans);
for(int i=0;i< ans;i++)writer.print(res.get(i)+" ");
}
public static void main(String[] args) throws IOException {
try (Input reader = new StandardInput(); PrintWriter writer = new PrintWriter(System.out)) {
new C382().run();
}
}
StandardInput reader;
PrintWriter writer;
@Override
public void run() {
try {
reader = new StandardInput();
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
interface Input extends Closeable {
String next() throws IOException;
default int nextInt() throws IOException {
return Integer.parseInt(next());
}
default long nextLong() throws IOException {
return Long.parseLong(next());
}
default double nextDouble() throws IOException {
return Double.parseDouble(next());
}
default int[] readIntArray() throws IOException {
return readIntArray(nextInt());
}
default int[] readIntArray(int size) throws IOException {
int[] array = new int[size];
for (int i = 0; i < array.length; i++) {
array[i] = nextInt();
}
return array;
}
default long[] readLongArray(int size) throws IOException {
long[] array = new long[size];
for (int i = 0; i < array.length; i++) {
array[i] = nextLong();
}
return array;
}
}
private static class StandardInput implements Input {
private final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
private StringTokenizer stringTokenizer;
@Override
public void close() throws IOException {
reader.close();
}
@Override
public String next() throws IOException {
if (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
stringTokenizer = new StringTokenizer(reader.readLine());
}
return stringTokenizer.nextToken();
}
}
}
| Java | ["3\n4 1 7", "1\n10", "4\n1 3 5 9", "4\n4 3 4 5", "2\n2 4"] | 1 second | ["2\n-2 10", "-1", "1\n7", "0", "3\n0 3 6"] | null | Java 8 | standard input | [
"implementation",
"sortings"
] | e3ca8338beb8852c201be72650e9aabd | The first line contains integer n (1 ≤ n ≤ 105) — the number of cards. The next line contains the sequence of integers — the numbers on Alexander's cards. The numbers are positive integers, each of them doesn't exceed 108. | 1,700 | If Arthur can write infinitely many distinct integers on the card, print on a single line -1. Otherwise, print on the first line the number of integers that suit you. In the second line, print the numbers in the increasing order. Note that the numbers in the answer can exceed 108 or even be negative (see test samples). | standard output | |
PASSED | 8ce7c5571eba8090c06daf446356b4f4 | train_003.jsonl | 1389972600 | Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers a1, a2, ..., an of length n, that the following condition fulfills: a2 - a1 = a3 - a2 = a4 - a3 = ... = ai + 1 - ai = ... = an - an - 1.For example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, 2], [1, 2, 4] are not.Alexander has n cards containing integers. Arthur wants to give Alexander exactly one more card with a number so that he could use the resulting n + 1 cards to make an arithmetic progression (Alexander has to use all of his cards).Arthur has already bought a card but he hasn't written a number on it. Help him, print all integers that you can write on a card so that the described condition fulfilled. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class C {
public static void main(String[] args) throws IOException {
FastScanner scan = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
int n = scan.nextInt();
int[] a = scan.nextArray(n);
Arrays.sort(a);
if(n == 1) out.println(-1);
else {
TreeSet<Integer> diffs = new TreeSet<>();
for(int i = 1; i < n; i++) diffs.add(a[i]-a[i-1]);
if(diffs.size() == 1){
int d = diffs.pollFirst();
if(d == 0) out.println(1+"\n"+a[0]);
else out.print((n == 2 && d%2==0?3:2)+"\n"+Math.min(d-a[0], a[0]-d)+" "+(n == 2 && d%2==0?a[0]+(d/2)+" ":"")+(a[n-1]+d)+" ");
}
else if(diffs.size() == 2){
int d1 = diffs.pollFirst(), d2 = diffs.pollFirst();
int dd1 = 0, dd2 = 0;
for(int i = 1; i < n; i++) {
if(a[i]-a[i-1] == d1) dd1++;
else dd2++;
}
if((double)d2/2.0 != (double)d1)out.println(0);
else if(dd1 == 1 && dd2 == 1){
out.println(1);
if(a[2]-a[1] == d2) out.println(a[2]-d1);
else out.println(a[1]-d1);
}
else if(dd1 == 1)out.println(0);
else if(dd2 == 1){
for(int i = 1; i < n; i++){
if(a[i]-a[i-1] == d2) {
out.println(1);
out.println(a[i]-d1);
break;
}
}
}
else out.println(0);
}
else out.println(0);
}
out.close();
}
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 double nextDouble() {return Double.parseDouble(next());}
public String nextLine() {
String line = "";
try {line = br.readLine();}
catch (Exception e) {e.printStackTrace();}
return line;
}
public int[] nextArray(int n) {
int[] a = new int[n];
for(int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
}
}
| Java | ["3\n4 1 7", "1\n10", "4\n1 3 5 9", "4\n4 3 4 5", "2\n2 4"] | 1 second | ["2\n-2 10", "-1", "1\n7", "0", "3\n0 3 6"] | null | Java 8 | standard input | [
"implementation",
"sortings"
] | e3ca8338beb8852c201be72650e9aabd | The first line contains integer n (1 ≤ n ≤ 105) — the number of cards. The next line contains the sequence of integers — the numbers on Alexander's cards. The numbers are positive integers, each of them doesn't exceed 108. | 1,700 | If Arthur can write infinitely many distinct integers on the card, print on a single line -1. Otherwise, print on the first line the number of integers that suit you. In the second line, print the numbers in the increasing order. Note that the numbers in the answer can exceed 108 or even be negative (see test samples). | standard output | |
PASSED | a02ef1c439498f5b8aa6358320db6480 | train_003.jsonl | 1389972600 | Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers a1, a2, ..., an of length n, that the following condition fulfills: a2 - a1 = a3 - a2 = a4 - a3 = ... = ai + 1 - ai = ... = an - an - 1.For example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, 2], [1, 2, 4] are not.Alexander has n cards containing integers. Arthur wants to give Alexander exactly one more card with a number so that he could use the resulting n + 1 cards to make an arithmetic progression (Alexander has to use all of his cards).Arthur has already bought a card but he hasn't written a number on it. Help him, print all integers that you can write on a card so that the described condition fulfilled. | 256 megabytes | /**
* DA-IICT
* Author : PARTH PATEL
*/
import java.io.*;
import java.math.*;
import java.util.*;
import static java.util.Arrays.fill;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;
public class C382
{
public static long mod = 1000000007;
public static long INF = (1L << 60);
static FastScanner2 in = new FastScanner2();
static OutputWriter out = new OutputWriter(System.out);
public static void main(String[] args)
{
int n=in.nextInt();
int[] arr=new int[n];
for(int i=0;i<n;i++)
arr[i]=in.nextInt();
sort(arr);
TreeSet<Integer> treeset=new TreeSet<>();
for(int i=1;i<n;i++)
treeset.add(arr[i]-arr[i-1]);
if(treeset.size()==1 && treeset.contains(0))
{
System.out.println(1);
System.out.println(arr[0]);
return;
}
if(n==1)
{
System.out.println(-1);
return;
}
if(treeset.size()>2)
{
System.out.println(0);
return;
}
if(treeset.size()==1)
{
int x=0;
for(int i:treeset)
x=i;
//already in AP
ArrayList<Integer> list=new ArrayList<>();
list.add(arr[0]-x);
list.add(arr[n-1]+x);
if(n==2 && (arr[1]-arr[0])%2==0)
list.add(arr[0]+(arr[1]-arr[0])/2);
Collections.sort(list);
out.println(list.size());
for(int i : list)
out.print(i+" ");
out.flush();
return;
}
if(treeset.size()==2)
{
int[] diff=new int[2];
int x=0;
for(int i : treeset)
diff[x++]=i;
int d1=diff[0];
int d2=diff[1];
if(d2!=2*d1)
{
System.out.println(0);
return;
}
boolean ispso=true;
int count1=0,count2=0;
int a1=0,a2=0;
for(int i=1;i<n;i++)
{
if(arr[i]-arr[i-1]==d2)
{
count2++;
a1=arr[i-1]+(arr[i]-arr[i-1])/2;
}
}
if(count2==1)
{
System.out.println(1);
System.out.println(a1);
return;
}
else
{
System.out.println(0);
return;
}
}
out.close();
}
public static long pow(long x, long n)
{
long res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p))
{
if ((n & 1) != 0)
{
res = (res * p);
}
}
return res;
}
public static long pow(long x, long n, long mod)
{
long res = 1;
for (long p = x; n > 0; n >>= 1, p = (p * p) % mod)
{
if ((n & 1) != 0)
{
res = (res * p % mod);
}
}
return res;
}
public static long gcd(long n1, long n2)
{
long r;
while (n2 != 0)
{
r = n1 % n2;
n1 = n2;
n2 = r;
}
return n1;
}
public static long lcm(long n1, long n2)
{
long answer = (n1 * n2) / (gcd(n1, n2));
return answer;
}
static class FastScanner2
{
private byte[] buf = new byte[1024];
private int curChar;
private int snumChars;
public int read()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = System.in.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isEndOfLine(c));
return res.toString();
}
public String nextString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n)
{
long[] arr = new long[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
}
static class InputReader
{
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream inputstream)
{
reader = new BufferedReader(new InputStreamReader(inputstream));
tokenizer = null;
}
public String nextLine()
{
String fullLine = null;
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try
{
fullLine = reader.readLine();
} catch (IOException e)
{
throw new RuntimeException(e);
}
return fullLine;
}
return fullLine;
}
public String next()
{
while (tokenizer == null || !tokenizer.hasMoreTokens())
{
try
{
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e)
{
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public long nextLong()
{
return Long.parseLong(next());
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n)
{
long a[] = new long[n];
for (int i = 0; i < n; i++)
{
a[i] = nextLong();
}
return a;
}
public int nextInt()
{
return Integer.parseInt(next());
}
}
static class OutputWriter
{
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream)
{
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer)
{
this.writer = new PrintWriter(writer);
}
public void print(Object... objects)
{
for (int i = 0; i < objects.length; i++)
{
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void println(Object... objects)
{
print(objects);
writer.println();
}
public void close()
{
writer.close();
}
public void flush()
{
writer.flush();
}
}
} | Java | ["3\n4 1 7", "1\n10", "4\n1 3 5 9", "4\n4 3 4 5", "2\n2 4"] | 1 second | ["2\n-2 10", "-1", "1\n7", "0", "3\n0 3 6"] | null | Java 8 | standard input | [
"implementation",
"sortings"
] | e3ca8338beb8852c201be72650e9aabd | The first line contains integer n (1 ≤ n ≤ 105) — the number of cards. The next line contains the sequence of integers — the numbers on Alexander's cards. The numbers are positive integers, each of them doesn't exceed 108. | 1,700 | If Arthur can write infinitely many distinct integers on the card, print on a single line -1. Otherwise, print on the first line the number of integers that suit you. In the second line, print the numbers in the increasing order. Note that the numbers in the answer can exceed 108 or even be negative (see test samples). | standard output | |
PASSED | e63a16d4838f5cb22c84b75c54248590 | train_003.jsonl | 1389972600 | Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers a1, a2, ..., an of length n, that the following condition fulfills: a2 - a1 = a3 - a2 = a4 - a3 = ... = ai + 1 - ai = ... = an - an - 1.For example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, 2], [1, 2, 4] are not.Alexander has n cards containing integers. Arthur wants to give Alexander exactly one more card with a number so that he could use the resulting n + 1 cards to make an arithmetic progression (Alexander has to use all of his cards).Arthur has already bought a card but he hasn't written a number on it. Help him, print all integers that you can write on a card so that the described condition fulfilled. | 256 megabytes | /*
*created by Kraken on 08-05-2020 at 10:40
*/
//package com.kraken.cf.practice;
import java.util.*;
import java.io.*;
public class C382 {
private static final long INF = (long) 1e12;
public static void main(String[] args) {
FastReader sc = new FastReader();
int n = sc.nextInt();
Long[] x = new Long[n];
for (int i = 0; i < n; i++) x[i] = sc.nextLong();
if (n == 1) {
System.out.println(-1);
return;
}
Arrays.sort(x);
Map<Long, Integer> cnt = new HashMap<>();
for (int i = 1; i < n; i++) {
long diff = x[i] - x[i - 1];
if (cnt.containsKey(diff)) cnt.put(diff, cnt.get(diff) + 1);
else cnt.put(diff, 1);
}
if (cnt.size() > 2) {
System.out.println(0);
return;
}
if (cnt.size() == 1) {
long diff = -1;
for (Map.Entry<Long, Integer> i : cnt.entrySet()) diff = i.getKey();
TreeSet<Long> set = new TreeSet<>();
set.add(x[0] - diff);
set.add(x[n - 1] + diff);
if (n == 2 && diff % 2 == 0) {
set.add(x[0] + diff / 2);
}
System.out.println(set.size());
for (long i : set)
System.out.print(i + " ");
System.out.println();
} else {
long diff = Long.MAX_VALUE;
for (Map.Entry<Long, Integer> i : cnt.entrySet()) {
diff = Math.min(i.getKey(), diff);
}
int bads = 0;
long ans = -INF;
for (int i = 1; i < n; i++) {
if (x[i] != x[i - 1] + diff) {
if (bads > 0 || x[i] != x[i - 1] + 2 * diff) {
System.out.println(0);
return;
}
bads++;
ans = x[i - 1] + diff;
}
}
System.out.printf("1\n%d\n", ans);
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["3\n4 1 7", "1\n10", "4\n1 3 5 9", "4\n4 3 4 5", "2\n2 4"] | 1 second | ["2\n-2 10", "-1", "1\n7", "0", "3\n0 3 6"] | null | Java 8 | standard input | [
"implementation",
"sortings"
] | e3ca8338beb8852c201be72650e9aabd | The first line contains integer n (1 ≤ n ≤ 105) — the number of cards. The next line contains the sequence of integers — the numbers on Alexander's cards. The numbers are positive integers, each of them doesn't exceed 108. | 1,700 | If Arthur can write infinitely many distinct integers on the card, print on a single line -1. Otherwise, print on the first line the number of integers that suit you. In the second line, print the numbers in the increasing order. Note that the numbers in the answer can exceed 108 or even be negative (see test samples). | standard output | |
PASSED | 9258fbcde5d138d09399b8ca2a528d25 | train_003.jsonl | 1389972600 | Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers a1, a2, ..., an of length n, that the following condition fulfills: a2 - a1 = a3 - a2 = a4 - a3 = ... = ai + 1 - ai = ... = an - an - 1.For example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, 2], [1, 2, 4] are not.Alexander has n cards containing integers. Arthur wants to give Alexander exactly one more card with a number so that he could use the resulting n + 1 cards to make an arithmetic progression (Alexander has to use all of his cards).Arthur has already bought a card but he hasn't written a number on it. Help him, print all integers that you can write on a card so that the described condition fulfilled. | 256 megabytes | import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class ArithmeticProgression {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
int n = inp.nextInt();
AP arr[] = new AP[n];
List<Integer> pos = new ArrayList<Integer>();
for(int i=0;i<n;i++) {
arr[i]= new AP();
arr[i].n = inp.nextLong();
}
Arrays.sort(arr);
if(n==1) {
System.out.println("-1");
return;
}
else if(n==2) {
if(arr[0].n == arr[1].n) {
System.out.println("1");
System.out.println(arr[0].n);
return;
}
long d=arr[1].n-arr[0].n;
if( (arr[0].n+arr[1].n)%2==0) {
System.out.println("3");
System.out.print((arr[0].n-d)+" ");
System.out.print(((arr[0].n+arr[1].n)/2)+" ");
System.out.print((arr[1].n+d));
}
else {
System.out.println("2");
System.out.print((arr[0].n-d)+" ");
System.out.print((arr[1].n+d));
}
return;
}
if(n==3) {
if( (arr[0].n==arr[1].n) && arr[1].n==arr[2].n) {
System.out.println("1");
System.out.println(arr[0].n);
return ;
}
if( (arr[1].n-arr[0].n)== (arr[2].n-arr[1].n) ) {
long d = arr[1].n-arr[0].n;
System.out.println("2");
System.out.println( (arr[0].n-d)+" "+(arr[n-1].n+d));
return;
}
if( (arr[1].n-arr[0].n) == (2* (arr[2].n-arr[1].n))) {
System.out.println("1");
System.out.println(arr[0].n+arr[2].n-arr[1].n);
return;
}
if( (arr[2].n-arr[1].n) == 2*(arr[1].n - arr[0].n)) {
System.out.println("1");
System.out.println((2*arr[1].n -arr[0].n));
}
else
System.out.println("0");
}else { //assert n>=4
long d1 = arr[1].n-arr[0].n;
long d2 = arr[2].n-arr[1].n;
long d3 = arr[3].n-arr[2].n;
long d;
if(d1==d3)
d=d1;
else
d=d2;
for(int i=1;i<n;i++) {
if(d != (arr[i].n - arr[i-1].n)) {
pos.add(i);
}
}
if(pos.size()>1){
System.out.println("0");
return;
}
if(pos.size()==1) {
if( (arr[pos.get(0)].n-arr[pos.get(0)-1].n)==(2*d)) {
System.out.println("1");
System.out.println(arr[pos.get(0)].n-d);
return;
}
else {
System.out.println("0");
return;
}
}
if(d==0) {
System.out.println("1");
System.out.println(arr[0].n);
return;
}
System.out.println("2");
System.out.println((arr[0].n-d)+" "+(arr[n-1].n+d) );
}
}
}
class AP implements Comparable<AP> {
long n;
@Override
public int compareTo(AP o) {
if(this.n >o.n )
return 1;
return -1;
}
} | Java | ["3\n4 1 7", "1\n10", "4\n1 3 5 9", "4\n4 3 4 5", "2\n2 4"] | 1 second | ["2\n-2 10", "-1", "1\n7", "0", "3\n0 3 6"] | null | Java 8 | standard input | [
"implementation",
"sortings"
] | e3ca8338beb8852c201be72650e9aabd | The first line contains integer n (1 ≤ n ≤ 105) — the number of cards. The next line contains the sequence of integers — the numbers on Alexander's cards. The numbers are positive integers, each of them doesn't exceed 108. | 1,700 | If Arthur can write infinitely many distinct integers on the card, print on a single line -1. Otherwise, print on the first line the number of integers that suit you. In the second line, print the numbers in the increasing order. Note that the numbers in the answer can exceed 108 or even be negative (see test samples). | standard output | |
PASSED | f5bd89f5f1ef240ccc7383de4c88e008 | train_003.jsonl | 1389972600 | Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers a1, a2, ..., an of length n, that the following condition fulfills: a2 - a1 = a3 - a2 = a4 - a3 = ... = ai + 1 - ai = ... = an - an - 1.For example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, 2], [1, 2, 4] are not.Alexander has n cards containing integers. Arthur wants to give Alexander exactly one more card with a number so that he could use the resulting n + 1 cards to make an arithmetic progression (Alexander has to use all of his cards).Arthur has already bought a card but he hasn't written a number on it. Help him, print all integers that you can write on a card so that the described condition fulfilled. | 256 megabytes | import java.io.*;
import java.util.*;
public class C1
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = Integer.parseInt(br.readLine());
int[] nums = new int[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for(int i = 0; i < n; i++)
nums[i] = Integer.parseInt(st.nextToken());
Arrays.sort(nums);
if(nums.length == 1)
pw.println(-1);
else if(nums.length == 2)
{
int d = nums[1] - nums[0];
if(d == 0)
pw.println(1 + "\n" + nums[0]);
else if(d%2 == 0)
pw.println(3 + "\n" + (nums[0] - d) + " " + (nums[0] + d/2) + " " + (nums[1] + d));
else
pw.println(2 + "\n" + (nums[0] - d) + " " + (nums[1] + d));
}
else
{
HashSet<Integer> dif = new HashSet<Integer>();
for(int i = 1; i < n; i++)
dif.add(nums[i] - nums[i-1]);
if(dif.size() == 1)
{
int d = nums[1]- nums[0];
if(d == 0)
pw.println(1 + "\n" + nums[0]);
else
pw.println(2 + "\n" + (nums[0] - d) + " " + (nums[nums.length-1] + d));
}
else if(dif.size() == 2)
{
Iterator<Integer> it = dif.iterator();
ArrayList<Integer> dif2 = new ArrayList<Integer>();
while(it.hasNext())
dif2.add(it.next());
int d1 = Math.max(dif2.get(0), dif2.get(1)), d2 = Math.min(dif2.get(0), dif2.get(1));
if(d1 == 2*d2)
{
boolean fake = false;
int index = -1;
for(int i = 1; i < n; i++)
if(nums[i] - nums[i-1] == d1)
{
if(index == -1)
index = i-1;
else
fake = true;
}
if(fake)
pw.println(0);
else
pw.println(1 + "\n" + (nums[index] + d2));
}
else
pw.println(0);
}
else
pw.println(0);
}
br.close(); pw.close(); System.exit(0);
}
} | Java | ["3\n4 1 7", "1\n10", "4\n1 3 5 9", "4\n4 3 4 5", "2\n2 4"] | 1 second | ["2\n-2 10", "-1", "1\n7", "0", "3\n0 3 6"] | null | Java 8 | standard input | [
"implementation",
"sortings"
] | e3ca8338beb8852c201be72650e9aabd | The first line contains integer n (1 ≤ n ≤ 105) — the number of cards. The next line contains the sequence of integers — the numbers on Alexander's cards. The numbers are positive integers, each of them doesn't exceed 108. | 1,700 | If Arthur can write infinitely many distinct integers on the card, print on a single line -1. Otherwise, print on the first line the number of integers that suit you. In the second line, print the numbers in the increasing order. Note that the numbers in the answer can exceed 108 or even be negative (see test samples). | standard output | |
PASSED | bc4822ec01a7171fd01c2e8a57002237 | train_003.jsonl | 1389972600 | Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers a1, a2, ..., an of length n, that the following condition fulfills: a2 - a1 = a3 - a2 = a4 - a3 = ... = ai + 1 - ai = ... = an - an - 1.For example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, 2], [1, 2, 4] are not.Alexander has n cards containing integers. Arthur wants to give Alexander exactly one more card with a number so that he could use the resulting n + 1 cards to make an arithmetic progression (Alexander has to use all of his cards).Arthur has already bought a card but he hasn't written a number on it. Help him, print all integers that you can write on a card so that the described condition fulfilled. | 256 megabytes |
import java.io.*;
import java.util.*;
public class C
{
static StringBuilder st = new StringBuilder();
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
if(n == 1)
{
out.println(-1);
out.flush();
return ;
}
int [] a = new int [n];
for(int i = 0 ; i< n ;i ++ )a[i] = sc.nextInt();
shuffle(a);
Arrays.sort(a);
TreeMap<Integer,Integer> mapDiff = new TreeMap<>();
for(int i = 1 ; i < n ; i++)
mapDiff.put(a[i] - a[i-1], mapDiff.getOrDefault(a[i] - a[i-1], 0) + 1);
TreeSet<Integer> sol = new TreeSet<>();
if(mapDiff.size() == 1)
{
sol.add(a[0] - mapDiff.firstKey());
sol.add(a[n-1] + mapDiff.lastKey());
if(n == 2 && ((a[0] + a[n - 1]) & 1) == 0)
sol.add((a[0] + a[n-1]) >> 1);
}
else if(mapDiff.size() == 2)
{
int first = mapDiff.firstKey();
int last = mapDiff.lastKey();
if(mapDiff.get(first).intValue() == 1)
{
for(int i = 1 ; i < n ;i++)
if(a[i] - a[i-1] == first)
{
if(a[i] - last == a[i - 1] + last)
{
sol.add(a[i] - last);
}
}
}
if(mapDiff.get(last).intValue() == 1)
{
for(int i = 1 ; i < n ;i++)
if(a[i] - a[i-1] == last)
{
if(a[i] - first == a[i - 1] + first)
{
sol.add(a[i] - first);
}
}
}
}
out.println(sol.size());
for(int x : sol)
out.print(x+" ");
out.flush();
out.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String path) throws Exception {
br = new BufferedReader(new FileReader(path));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
static void shuffle(int[] a) {
int n = a.length;
for (int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
}
}
| Java | ["3\n4 1 7", "1\n10", "4\n1 3 5 9", "4\n4 3 4 5", "2\n2 4"] | 1 second | ["2\n-2 10", "-1", "1\n7", "0", "3\n0 3 6"] | null | Java 8 | standard input | [
"implementation",
"sortings"
] | e3ca8338beb8852c201be72650e9aabd | The first line contains integer n (1 ≤ n ≤ 105) — the number of cards. The next line contains the sequence of integers — the numbers on Alexander's cards. The numbers are positive integers, each of them doesn't exceed 108. | 1,700 | If Arthur can write infinitely many distinct integers on the card, print on a single line -1. Otherwise, print on the first line the number of integers that suit you. In the second line, print the numbers in the increasing order. Note that the numbers in the answer can exceed 108 or even be negative (see test samples). | standard output | |
PASSED | 1a2d3bc9de0e2df453af7a78404a2ae0 | train_003.jsonl | 1389972600 | Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers a1, a2, ..., an of length n, that the following condition fulfills: a2 - a1 = a3 - a2 = a4 - a3 = ... = ai + 1 - ai = ... = an - an - 1.For example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, 2], [1, 2, 4] are not.Alexander has n cards containing integers. Arthur wants to give Alexander exactly one more card with a number so that he could use the resulting n + 1 cards to make an arithmetic progression (Alexander has to use all of his cards).Arthur has already bought a card but he hasn't written a number on it. Help him, print all integers that you can write on a card so that the described condition fulfilled. | 256 megabytes |
import java.io.*;
import java.util.*;
public class C {
static StringBuilder st = new StringBuilder();
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
if(n == 1)
{
out.println(-1);
out.flush();
return ;
}
int [] a = new int [n];
for(int i = 0 ; i< n ;i ++ )a[i] = sc.nextInt();
shuffle(a);
Arrays.sort(a);
TreeMap<Integer,Integer> mapDiff = new TreeMap<>();
for(int i = 1 ; i < n ; i++)
mapDiff.put(a[i] - a[i-1], mapDiff.getOrDefault(a[i] - a[i-1], 0) + 1);
TreeSet<Integer> sol = new TreeSet<>();
if(mapDiff.size() == 1)
{
sol.add(a[0] - mapDiff.firstKey());
sol.add(a[n-1] + mapDiff.lastKey());
if(n == 2)
{
for(int diff = 0 ; diff <= 1e8 ; diff++ )
if(a[0] + diff == a[n-1] - diff)
sol.add(a[0] + diff);
}
}
else if(mapDiff.size() == 2)
{
int first = mapDiff.firstKey();
int last = mapDiff.lastKey();
if(mapDiff.get(first).intValue() == 1)
{
for(int i = 1 ; i < n ;i++)
if(a[i] - a[i-1] == first)
{
if(a[i] - last == a[i - 1] + last)
{
sol.add(a[i] - last);
}
}
}
if(mapDiff.get(last).intValue() == 1)
{
for(int i = 1 ; i < n ;i++)
if(a[i] - a[i-1] == last)
{
if(a[i] - first == a[i - 1] + first)
{
sol.add(a[i] - first);
}
}
}
}
out.println(sol.size());
for(int x : sol)
out.print(x+" ");
out.flush();
out.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String path) throws Exception {
br = new BufferedReader(new FileReader(path));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
static void shuffle(int[] a) {
int n = a.length;
for (int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
}
}
| Java | ["3\n4 1 7", "1\n10", "4\n1 3 5 9", "4\n4 3 4 5", "2\n2 4"] | 1 second | ["2\n-2 10", "-1", "1\n7", "0", "3\n0 3 6"] | null | Java 8 | standard input | [
"implementation",
"sortings"
] | e3ca8338beb8852c201be72650e9aabd | The first line contains integer n (1 ≤ n ≤ 105) — the number of cards. The next line contains the sequence of integers — the numbers on Alexander's cards. The numbers are positive integers, each of them doesn't exceed 108. | 1,700 | If Arthur can write infinitely many distinct integers on the card, print on a single line -1. Otherwise, print on the first line the number of integers that suit you. In the second line, print the numbers in the increasing order. Note that the numbers in the answer can exceed 108 or even be negative (see test samples). | standard output | |
PASSED | 8a6fdb194ed444360d29dc4b4cfe3f0b | train_003.jsonl | 1389972600 | Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers a1, a2, ..., an of length n, that the following condition fulfills: a2 - a1 = a3 - a2 = a4 - a3 = ... = ai + 1 - ai = ... = an - an - 1.For example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, 2], [1, 2, 4] are not.Alexander has n cards containing integers. Arthur wants to give Alexander exactly one more card with a number so that he could use the resulting n + 1 cards to make an arithmetic progression (Alexander has to use all of his cards).Arthur has already bought a card but he hasn't written a number on it. Help him, print all integers that you can write on a card so that the described condition fulfilled. | 256 megabytes |
import java.io.*;
import java.util.*;
public class C {
static StringBuilder st = new StringBuilder();
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
if(n == 1)
{
out.println(-1);
out.flush();
return ;
}
int [] a = new int [n];
for(int i = 0 ; i< n ;i ++ )a[i] = sc.nextInt();
shuffle(a);
Arrays.sort(a);
TreeMap<Integer,Integer> mapDiff = new TreeMap<>();
for(int i = 1 ; i < n ; i++)
mapDiff.put(a[i] - a[i-1], mapDiff.getOrDefault(a[i] - a[i-1], 0) + 1);
TreeSet<Integer> sol = new TreeSet<>();
if(mapDiff.size() == 1)
{
sol.add(a[0] - mapDiff.firstKey());
sol.add(a[n-1] + mapDiff.lastKey());
if(n == 2 && ((a[0] + a[n - 1]) & 1) == 0)
sol.add((a[0] + a[n-1]) >> 1);
}
else if(mapDiff.size() == 2)
{
int first = mapDiff.firstKey();
int last = mapDiff.lastKey();
if(mapDiff.get(first).intValue() == 1)
{
for(int i = 1 ; i < n ;i++)
if(a[i] - a[i-1] == first)
{
if(a[i] - last == a[i - 1] + last)
{
sol.add(a[i] - last);
}
}
}
if(mapDiff.get(last).intValue() == 1)
{
for(int i = 1 ; i < n ;i++)
if(a[i] - a[i-1] == last)
{
if(a[i] - first == a[i - 1] + first)
{
sol.add(a[i] - first);
}
}
}
}
out.println(sol.size());
for(int x : sol)
out.print(x+" ");
out.flush();
out.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String path) throws Exception {
br = new BufferedReader(new FileReader(path));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
static void shuffle(int[] a) {
int n = a.length;
for (int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
}
}
| Java | ["3\n4 1 7", "1\n10", "4\n1 3 5 9", "4\n4 3 4 5", "2\n2 4"] | 1 second | ["2\n-2 10", "-1", "1\n7", "0", "3\n0 3 6"] | null | Java 8 | standard input | [
"implementation",
"sortings"
] | e3ca8338beb8852c201be72650e9aabd | The first line contains integer n (1 ≤ n ≤ 105) — the number of cards. The next line contains the sequence of integers — the numbers on Alexander's cards. The numbers are positive integers, each of them doesn't exceed 108. | 1,700 | If Arthur can write infinitely many distinct integers on the card, print on a single line -1. Otherwise, print on the first line the number of integers that suit you. In the second line, print the numbers in the increasing order. Note that the numbers in the answer can exceed 108 or even be negative (see test samples). | standard output | |
PASSED | 0d68f49311d4e2fd165a002544f3f6fb | train_003.jsonl | 1389972600 | Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers a1, a2, ..., an of length n, that the following condition fulfills: a2 - a1 = a3 - a2 = a4 - a3 = ... = ai + 1 - ai = ... = an - an - 1.For example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, 2], [1, 2, 4] are not.Alexander has n cards containing integers. Arthur wants to give Alexander exactly one more card with a number so that he could use the resulting n + 1 cards to make an arithmetic progression (Alexander has to use all of his cards).Arthur has already bought a card but he hasn't written a number on it. Help him, print all integers that you can write on a card so that the described condition fulfilled. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main {
static final int INF = (int) 1e9 + 7;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
Integer arr[] = new Integer[n];
for(int i = 0; i < n; ++i) arr[i] = sc.nextInt();
Arrays.sort(arr);
if(n == 1) out.println(-1);
else if(n == 2) {
if(arr[1] - arr[0] == 0) { System.out.println(1); System.out.println(arr[0]); return; }
int count = 2;
if((arr[1] - arr[0]) % 2 == 0 && (arr[1] - arr[0]) != 0)
count++;
out.println(count);
int diff = (arr[1] - arr[0]);
out.print((arr[0] - diff) + " ");
if((arr[0] + arr[1]) % 2 == 0 && diff != 0)
out.print((arr[0] + arr[1]) / 2 + " ");
out.println(arr[1] + diff);
}
else {
int diff1 = -INF, diff2 = -INF, c1 = 0, c2 = 0, p1 = -1, p2 = -1;
for(int i = 1; i < n; ++i) {
int diff = arr[i] - arr[i - 1];
if(c1 == 0) {
diff1 = diff;
p1 = i;
c1++;
}
else if(c2 == 0 && diff != diff1) {
diff2 = diff;
p2 = i;
c2++;
}
else {
if(diff == diff1) c1++;
else if(diff == diff2) c2++;
else {
System.out.println(0);
return;
}
}
}
if(c1 > 1 && c2 > 1) { System.out.println(0); return; }
else if(c1 == 0 && c2 > 0 || c1 > 0 && c2 == 0) {
if(diff1 == 0 || diff2 == 0) { System.out.println(1); System.out.println(arr[0]); return; }
out.println(2);
out.println(arr[0] - diff1 + " " + (arr[n - 1] + diff1));
}
else {
if(diff1 == 0 && diff2 != 0 || diff2 == 0 && diff1 != 0) {
System.out.println(0);
return;
}
if(c1 == 1 && c2 == 1) {
int res = 0;
if(diff1 % 2 == 0 && diff1 / 2 == diff2 && diff1 != 0) res++;
if(diff2 % 2 == 0 && diff2 / 2 == diff1 && diff2 != 0) res++;
out.println(res);
if(diff1 % 2 == 0 && diff1 / 2 == diff2 && diff1 != 0)
out.print((arr[p1] + arr[p1 - 1]) / 2);
if(diff2 % 2 == 0 && diff2 / 2 == diff1 && diff2 != 0)
out.println(" " + ((arr[p2] + arr[p2 - 1]) / 2));
}
else {
out.println(1);
if(!(diff1 % 2 == 0 && diff1 / 2 == diff2 && c1 == 1 || diff2 % 2 == 0 && diff2 / 2 == diff1 && c2 == 1)) {
System.out.println(0);
return;
}
if(c1 == 1)
out.println((arr[p1] + arr[p1 - 1]) / 2 + " ");
else
out.println(((arr[p2] + arr[p2 - 1]) / 2));
}
}
}
out.flush();
out.close();
}
static class Pair implements Comparable<Pair> {
int a, b;
public Pair(int x, int y) {
a = x;
b = y;
}
@Override
public int compareTo(Pair p) {
return Integer.compare(Math.min(2 * p.a, p.b), Math.min(2 * a, b));
}
@Override
public String toString() {
return a + " " + b;
}
}
static class Scanner{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public Scanner(FileReader r){ br = new BufferedReader(r);}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException { return Double.parseDouble(next()); }
public boolean ready() throws IOException {return br.ready();}
}
} | Java | ["3\n4 1 7", "1\n10", "4\n1 3 5 9", "4\n4 3 4 5", "2\n2 4"] | 1 second | ["2\n-2 10", "-1", "1\n7", "0", "3\n0 3 6"] | null | Java 8 | standard input | [
"implementation",
"sortings"
] | e3ca8338beb8852c201be72650e9aabd | The first line contains integer n (1 ≤ n ≤ 105) — the number of cards. The next line contains the sequence of integers — the numbers on Alexander's cards. The numbers are positive integers, each of them doesn't exceed 108. | 1,700 | If Arthur can write infinitely many distinct integers on the card, print on a single line -1. Otherwise, print on the first line the number of integers that suit you. In the second line, print the numbers in the increasing order. Note that the numbers in the answer can exceed 108 or even be negative (see test samples). | standard output | |
PASSED | 7135fb888256c4e5f7ac1f8570e5ba5b | train_003.jsonl | 1389972600 | Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers a1, a2, ..., an of length n, that the following condition fulfills: a2 - a1 = a3 - a2 = a4 - a3 = ... = ai + 1 - ai = ... = an - an - 1.For example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, 2], [1, 2, 4] are not.Alexander has n cards containing integers. Arthur wants to give Alexander exactly one more card with a number so that he could use the resulting n + 1 cards to make an arithmetic progression (Alexander has to use all of his cards).Arthur has already bought a card but he hasn't written a number on it. Help him, print all integers that you can write on a card so that the described condition fulfilled. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class B {
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt(), a[] = new int[n], x[] = new int[n-1], d1 = -1, d2 = -1, d3 = -1;
int f1 = 1, f2 = 1;
for(int i = 0; i < n; ++i)
a[i] = sc.nextInt();
shuffle(a);
Arrays.sort(a);
for(int i = 0; i < n - 1; ++i)
{
int y = x[i] = a[i+1] - a[i];
if(d1 == -1)
d1 = y;
else if(d1 == y)
f1++;
else if(d2 == -1)
d2 = y;
else if(d2 == y)
f2++;
else
d3 = y;
}
if(n == 1)
out.println(-1);
else if(d3 != -1 || f1 > 1 && f2 > 1)
out.println(0);
else
{
ArrayList<Integer> sol = new ArrayList<Integer>();
if(d2 != -1)
{
for(int i = 0; i < n - 1; ++i)
if((x[i] == d1 && f1 == 1 && d1 == d2 * 2|| x[i] == d2 && f2 == 1 && d2 == d1 * 2) && x[i] % 2 == 0 && x[i] != 0)
sol.add(a[i] + x[i] / 2);
}
else if(n == 2 && d1 % 2 == 0)
{
sol.add(a[0] - d1);
if(d1 != 0)
{
sol.add(a[0] + d1 / 2);
sol.add(a[1] + d1);
}
}
else
{
sol.add(a[0] - d1);
if(d1 != 0)
sol.add(a[n - 1] + d1);
}
out.println(sol.size());
for(int s: sol)
out.print(s + " ");
}
out.flush();
out.close();
}
static void shuffle(int[] a)
{
int n = a.length;
for(int i = 0; i < n; ++i)
{
int r = i + (int)(Math.random() * (n - i));
int tmp = a[r];
a[r] = a[i];
a[i] = tmp;
}
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public Scanner(FileReader r){ br = new BufferedReader(r);}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException { return Double.parseDouble(next()); }
public boolean ready() throws IOException {return br.ready();}
}
} | Java | ["3\n4 1 7", "1\n10", "4\n1 3 5 9", "4\n4 3 4 5", "2\n2 4"] | 1 second | ["2\n-2 10", "-1", "1\n7", "0", "3\n0 3 6"] | null | Java 8 | standard input | [
"implementation",
"sortings"
] | e3ca8338beb8852c201be72650e9aabd | The first line contains integer n (1 ≤ n ≤ 105) — the number of cards. The next line contains the sequence of integers — the numbers on Alexander's cards. The numbers are positive integers, each of them doesn't exceed 108. | 1,700 | If Arthur can write infinitely many distinct integers on the card, print on a single line -1. Otherwise, print on the first line the number of integers that suit you. In the second line, print the numbers in the increasing order. Note that the numbers in the answer can exceed 108 or even be negative (see test samples). | standard output | |
PASSED | 360b46467c13d765519aee4be05f1499 | train_003.jsonl | 1389972600 | Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers a1, a2, ..., an of length n, that the following condition fulfills: a2 - a1 = a3 - a2 = a4 - a3 = ... = ai + 1 - ai = ... = an - an - 1.For example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, 2], [1, 2, 4] are not.Alexander has n cards containing integers. Arthur wants to give Alexander exactly one more card with a number so that he could use the resulting n + 1 cards to make an arithmetic progression (Alexander has to use all of his cards).Arthur has already bought a card but he hasn't written a number on it. Help him, print all integers that you can write on a card so that the described condition fulfilled. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
int n = in.nextInt();
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = in.nextInt();
}
// 无数解情况
if (n == 1) {
System.out.println(-1);
continue;
}
// 排序
Arrays.sort(nums);
// 寻找公差,最多出现两个不同的值
Map<Integer, Integer> map = new HashMap<>();
for (int i = 1; i < n; i++) {
int dif = nums[i] - nums[i - 1];
map.put(dif, map.getOrDefault(dif, 0) + 1);
}
// 无解
if (map.size() > 2) {
System.out.println(0);
continue;
}
// 原本即为等差数列,公差为dif
if (map.size() == 1) {
int dif = nums[1] - nums[0];
if (dif == 0) {
System.out.println(1);
System.out.println(nums[0]);
continue;
}
// 3 6
// 2 4 6 8
if (dif % 2 == 1 || map.get(dif) > 1) {
System.out.println(2);
System.out.println(nums[0] - dif + " " + (nums[nums.length - 1] + dif));
continue;
}
// 3 5
System.out.println(3);
System.out.println(nums[0] - dif + " " + (nums[0] + dif / 2) + " " + (nums[nums.length - 1] + dif));
continue;
}
// 需要新增一个数成为等差数列
int[] difs = new int[2];
int[] cnts = new int[2];
int j = 0;
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
difs[j] = entry.getKey();
cnts[j++] = entry.getValue();
}
int[] diffs = new int[2];
int[] cntts = new int[2];
if (difs[0] > difs[1]) {
diffs[0] = difs[1];
diffs[1] = difs[0];
cntts[1] = cnts[0];
cntts[0] = cnts[1];
} else {
diffs[0] = difs[0];
diffs[1] = difs[1];
cntts[1] = cnts[1];
cntts[0] = cnts[0];
}
// 公差大的出现不止一次,无解
// 1 3 5 8 10
if (cntts[1] != 1) {
System.out.println(0);
continue;
}
// 1 3 5 7 10
if (diffs[1] != diffs[0] * 2) {
System.out.println(0);
continue;
}
for (int i = 1; i < n; i++) {
if (nums[i] - nums[i - 1] == diffs[1]) {
System.out.println(1);
System.out.println(nums[i - 1] + diffs[0]);
break;
}
}
}
}
}
| Java | ["3\n4 1 7", "1\n10", "4\n1 3 5 9", "4\n4 3 4 5", "2\n2 4"] | 1 second | ["2\n-2 10", "-1", "1\n7", "0", "3\n0 3 6"] | null | Java 8 | standard input | [
"implementation",
"sortings"
] | e3ca8338beb8852c201be72650e9aabd | The first line contains integer n (1 ≤ n ≤ 105) — the number of cards. The next line contains the sequence of integers — the numbers on Alexander's cards. The numbers are positive integers, each of them doesn't exceed 108. | 1,700 | If Arthur can write infinitely many distinct integers on the card, print on a single line -1. Otherwise, print on the first line the number of integers that suit you. In the second line, print the numbers in the increasing order. Note that the numbers in the answer can exceed 108 or even be negative (see test samples). | standard output | |
PASSED | 68baf1a65e4c4fcdab074e91be10ba08 | train_003.jsonl | 1389972600 | Everybody knows what an arithmetic progression is. Let us remind you just in case that an arithmetic progression is such sequence of numbers a1, a2, ..., an of length n, that the following condition fulfills: a2 - a1 = a3 - a2 = a4 - a3 = ... = ai + 1 - ai = ... = an - an - 1.For example, sequences [1, 5], [10], [5, 4, 3] are arithmetic progressions and sequences [1, 3, 2], [1, 2, 4] are not.Alexander has n cards containing integers. Arthur wants to give Alexander exactly one more card with a number so that he could use the resulting n + 1 cards to make an arithmetic progression (Alexander has to use all of his cards).Arthur has already bought a card but he hasn't written a number on it. Help him, print all integers that you can write on a card so that the described condition fulfilled. | 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...
*/
public class Main
{
public static void main(String[] args) throws IOException
{
int n=ni();
int a[]=nia(n);
Arrays.sort(a);
if(n==1)
pr(-1);
else if(n==2)
{
if(a[0]!=a[1])
{
if((a[1]+a[0])%2==0)
{
pr(3);
pr(2*a[0]-a[1]+" "+(a[0]+a[1])/2+" "+(2*a[1]-a[0]));
}
else
{
pr(2);
pr((2*a[0]-a[1])+" "+(2*a[1]-a[0]));
}
}
else
pr("1\n"+a[0]);
}
else
{
int d=a[1]-a[0];
int mis=0;
for(int i=2; i<n; i++)
if(d!=a[i]-a[i-1])
mis++;
if(mis==n-2)
{
d=a[2]-a[1];
mis=0;
for(int i=1; i<n; i++)
if(d!=a[i]-a[i-1])
mis++;
}
if(d==0&&mis==0)
pr("1\n"+a[0]);
else if(n==3&&mis==1)
{
if(2*(a[1]-a[0])==a[2]-a[1])
{
pr(1);
pr(2*a[1]-a[0]);
}
else if((a[1]-a[0])==2*(a[2]-a[1]))
{
pr(1);
pr(a[0]+a[2]-a[1]);
}
else
pr(0);
}
else if(mis>1)
{
pr(0);
}
else if(mis==1)
{
for(int i=1; i<n; i++)
{
if(d!=a[i]-a[i-1])
{
if(2*d==a[i]-a[i-1])
pr(1+"\n"+(a[i]+a[i-1])/2);
else
pr(0);
}
}
}
else
{
pr(2);
pr(2*a[0]-a[1]+" "+(a[n-1]+a[1]-a[0]));
}
}
System.out.println(ans);
}
static final int mod=1000000007;
static final double eps=1e-8;
static final long inf=100000000000000000L;
static final boolean debug=true;
static Reader in=new Reader();
static StringBuilder ans=new StringBuilder();
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 Random rn=new Random();
static void pd(){if(debug)ans.append("hola");}
static void pd(Object a){if(debug)ans.append(a+"\n");}
static void pr(Object a){ans.append(a+"\n");}
static void pr(){ans.append("\n");}
static void p(Object a){ans.append(a);}
static void sop(Object a){System.out.println(a);}
static int ni(){return in.nextInt();}
static int[] nia(int n){int a[]=new int[n];for(int i=0; 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 long nl(){return in.nextLong();}
static String ns(){return in.next();}
static double nd(){return in.nextDouble();}
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 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());
}
}
static class dyns
{
dyns(long le,long ri)
{
lb=le;
rb=ri;
}
dyns l,r;
long val,lb,rb;
void set(long te)
{
val++;
if(lb!=te||rb!=te)
{
if((lb+rb)/2>=te)
{
if(l==null)
l=new dyns(lb, (lb+rb)/2);
l.set(te);
}
else
{
if(r==null)
r=new dyns(((lb+rb)/2)+1,rb);
r.set(te);
}
}
}
void reset(long a)
{
val--;
if(val==0)
{
l=null;
r=null;
return;
}
if(lb!=a||rb!=a)
{
if((lb+rb)/2>=a)
l.reset(a);
else
r.reset(a);
}
}
long count(long le, long ri)
{
if(le<=lb&&ri>=rb)
return val;
if(le>rb)
return 0;
if(ri<lb)
return 0;
int a=0;
if(l!=null)
a+=l.count(le,ri);
if(r!=null)
a+=r.count(le,ri);
return a;
}
}
} | Java | ["3\n4 1 7", "1\n10", "4\n1 3 5 9", "4\n4 3 4 5", "2\n2 4"] | 1 second | ["2\n-2 10", "-1", "1\n7", "0", "3\n0 3 6"] | null | Java 8 | standard input | [
"implementation",
"sortings"
] | e3ca8338beb8852c201be72650e9aabd | The first line contains integer n (1 ≤ n ≤ 105) — the number of cards. The next line contains the sequence of integers — the numbers on Alexander's cards. The numbers are positive integers, each of them doesn't exceed 108. | 1,700 | If Arthur can write infinitely many distinct integers on the card, print on a single line -1. Otherwise, print on the first line the number of integers that suit you. In the second line, print the numbers in the increasing order. Note that the numbers in the answer can exceed 108 or even be negative (see test samples). | standard output | |
PASSED | 203f1797543f5243d7d7f898aecf747b | train_003.jsonl | 1479918900 | Gosha is hunting. His goal is to catch as many Pokemons as possible. Gosha has a Poke Balls and b Ultra Balls. There are n Pokemons. They are numbered 1 through n. Gosha knows that if he throws a Poke Ball at the i-th Pokemon he catches it with probability pi. If he throws an Ultra Ball at the i-th Pokemon he catches it with probability ui. He can throw at most one Ball of each type at any Pokemon.The hunting proceeds as follows: at first, Gosha chooses no more than a Pokemons at which he will throw Poke Balls and no more than b Pokemons at which he will throw Ultra Balls. After that, he throws the chosen Balls at the chosen Pokemons. If he throws both Ultra Ball and Poke Ball at some Pokemon, he is caught if and only if he is caught by any of these Balls. The outcome of a throw doesn't depend on the other throws.Gosha would like to know what is the expected number of the Pokemons he catches if he acts in an optimal way. In other words, he would like to know the maximum possible expected number of Pokemons can catch. | 256 megabytes | //package com.company;
import java.io.*;
import java.util.*;
public class Main {
public static class Task {
int n, a, b;
double[] pa, pb, pab;
int maxChoice(double[] expect) {
int bestC = 0;
for (int i = 1; i < expect.length; i++) {
if (expect[i] > expect[bestC]) bestC = i;
}
return bestC;
}
int useA, useB;
double bestVal = 0.0;
double check(double lambda1, double lambda2) {
useA = 0;
useB = 0;
double realVal = 0.0;
for (int i = 0; i < n; i++) {
double[] expect = new double[]{0.0, -lambda1 + pa[i], -lambda2 + pb[i], -lambda1 + -lambda2 + pab[i]};
int choice = maxChoice(expect);
if (choice == 1) {
useA++;
realVal += pa[i];
} else if (choice == 2) {
useB++;
realVal += pb[i];
} else if (choice == 3) {
useA++;
useB++;
realVal += pab[i];
}
}
return realVal + (a - useA) * lambda1 + (b - useB) * lambda2;
}
public void solve(Scanner sc, PrintWriter pw) throws IOException {
n = sc.nextInt();
a = sc.nextInt();
b = sc.nextInt();
pa = new double[n];
pb = new double[n];
pab = new double[n];
for (int i = 0; i < n; i++) {
pa[i] = sc.nextDouble();
}
for (int i = 0; i < n; i++) {
pb[i] = sc.nextDouble();
}
for (int i = 0; i < n; i++) {
pab[i] = 1 - (1 - pa[i]) * (1 - pb[i]);
}
double loA = 0.0, hiA = 1.0;
double EPS = 1e-10;
while (loA < hiA - EPS) {
double midA = (loA + hiA) / 2;
double loB = 0.0, hiB = 1.0;
while (loB < hiB - EPS) {
double midB = (loB + hiB) / 2;
check(midA, midB);
if (useB <= b) {
hiB = midB;
} else {
loB = midB;
}
}
check(midA, hiB);
if (useB > b) throw new RuntimeException();
if (useA <= a) {
hiA = midA;
} else {
loA = midA;
}
}
double loB = 0.0, hiB = 1.0;
while (loB < hiB - EPS) {
double midB = (loB + hiB) / 2;
check(hiA, midB);
if (useB <= b) {
hiB = midB;
} else {
loB = midB;
}
}
bestVal = check(hiA, hiB);
System.err.println(hiA + " " + hiB);
if (useA > a || useB > b) {
throw new RuntimeException();
}
pw.println(bestVal);
}
}
static long TIME_START, TIME_END;
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
// Scanner sc = new Scanner(new FileInputStream("input"));
PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out));
// PrintWriter pw = new PrintWriter(new FileOutputStream("input"));
Runtime runtime = Runtime.getRuntime();
long usedMemoryBefore = runtime.totalMemory() - runtime.freeMemory();
TIME_START = System.currentTimeMillis();
Task t = new Task();
t.solve(sc, pw);
TIME_END = System.currentTimeMillis();
long usedMemoryAfter = runtime.totalMemory() - runtime.freeMemory();
pw.close();
System.err.println("Memory increased: " + (usedMemoryAfter - usedMemoryBefore) / 1000000);
System.err.println("Time used: " + (TIME_END - TIME_START) + ".");
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader s) throws FileNotFoundException {
br = new BufferedReader(s);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public boolean ready() throws IOException {
return br.ready();
}
}
} | Java | ["3 2 2\n1.000 0.000 0.500\n0.000 1.000 0.500", "4 1 3\n0.100 0.500 0.500 0.600\n0.100 0.500 0.900 0.400", "3 2 0\n0.412 0.198 0.599\n0.612 0.987 0.443"] | 5 seconds | ["2.75", "2.16", "1.011"] | null | Java 11 | standard input | [
"dp",
"flows",
"probabilities",
"math",
"sortings",
"data structures",
"brute force"
] | ea7643c3b7ed02d9c41a4b3441e53935 | The first line contains three integers n, a and b (2 ≤ n ≤ 2000, 0 ≤ a, b ≤ n) — the number of Pokemons, the number of Poke Balls and the number of Ultra Balls. The second line contains n real values p1, p2, ..., pn (0 ≤ pi ≤ 1), where pi is the probability of catching the i-th Pokemon if Gosha throws a Poke Ball to it. The third line contains n real values u1, u2, ..., un (0 ≤ ui ≤ 1), where ui is the probability of catching the i-th Pokemon if Gosha throws an Ultra Ball to it. All the probabilities are given with exactly three digits after the decimal separator. | 3,000 | Print the maximum possible expected number of Pokemons Gosha can catch. The answer is considered correct if it's absolute or relative error doesn't exceed 10 - 4. | standard output | |
PASSED | fc631566f006b91c258e00956fadc886 | train_003.jsonl | 1300809600 | A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces. | 256 megabytes | import java.util.Scanner;
/**
* Created by Usandy on 18.03.15.
*/
public class ACM {
public static void main(String[] args){
Scanner scanner=new Scanner(System.in);
int n=scanner.nextInt();
long[] mas=new long[3];
long kol=0;
for(int i=0;i<n;i++)
for(int j=0;j<3;j++)
mas[j]+=scanner.nextInt();
System.out.print(mas[0]==0&& mas[1]==0 && mas[2]==0?"YES":"NO");
}
}
| Java | ["3\n4 1 7\n-2 4 -1\n1 -5 -3", "3\n3 -1 7\n-5 2 -4\n2 -1 -3"] | 2 seconds | ["NO", "YES"] | null | Java 7 | standard input | [
"implementation",
"math"
] | 8ea24f3339b2ec67a769243dc68a47b2 | The first line contains a positive integer n (1 ≤ n ≤ 100), then follow n lines containing three integers each: the xi coordinate, the yi coordinate and the zi coordinate of the force vector, applied to the body ( - 100 ≤ xi, yi, zi ≤ 100). | 1,000 | Print the word "YES" if the body is in equilibrium, or the word "NO" if it is not. | standard output | |
PASSED | 6d890d7fe8a996b2f53b29b6d98717fa | train_003.jsonl | 1300809600 | A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces. | 256 megabytes |
import java.util.Scanner;
public class Area {
public static void main(String[] args) {
Scanner bucky = new Scanner(System.in);
int lines = bucky.nextInt()*3;
int[] coords = new int[lines];
for(int i = 0 ; i < lines ; i++){
coords[i] = bucky.nextInt();
}
int sumx = 0;
int sumy = 0;
int sumz = 0;
for(int i = 0; i< lines ; i += 3){
sumx += coords[i];
}
for(int i = 0; i< lines ; i += 3){
sumy += coords[i];
}
for(int i = 0; i< lines ; i += 3){
sumz += coords[i];
}
if(sumx == 0 && sumy == 0 && sumz ==0){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
}
| Java | ["3\n4 1 7\n-2 4 -1\n1 -5 -3", "3\n3 -1 7\n-5 2 -4\n2 -1 -3"] | 2 seconds | ["NO", "YES"] | null | Java 7 | standard input | [
"implementation",
"math"
] | 8ea24f3339b2ec67a769243dc68a47b2 | The first line contains a positive integer n (1 ≤ n ≤ 100), then follow n lines containing three integers each: the xi coordinate, the yi coordinate and the zi coordinate of the force vector, applied to the body ( - 100 ≤ xi, yi, zi ≤ 100). | 1,000 | Print the word "YES" if the body is in equilibrium, or the word "NO" if it is not. | standard output | |
PASSED | fbeca05a3898b4746e61d3d0bd17fa80 | train_003.jsonl | 1300809600 | A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces. | 256 megabytes | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.*;
/**
*
* @author student
*/
public class youngphy
{
public static void main(String args[])throws IOException
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(in.readLine());
int a=0,b=0,c=0;
for(int i=0;i<n;i++)
{
String s[]=in.readLine().split(" ");
a+=Integer.parseInt(s[0]);
b+=Integer.parseInt(s[1]);
c+=Integer.parseInt(s[2]);
}
System.out.println((a==0&&b==0&&c==0)?"YES":"NO");
}
}
| Java | ["3\n4 1 7\n-2 4 -1\n1 -5 -3", "3\n3 -1 7\n-5 2 -4\n2 -1 -3"] | 2 seconds | ["NO", "YES"] | null | Java 7 | standard input | [
"implementation",
"math"
] | 8ea24f3339b2ec67a769243dc68a47b2 | The first line contains a positive integer n (1 ≤ n ≤ 100), then follow n lines containing three integers each: the xi coordinate, the yi coordinate and the zi coordinate of the force vector, applied to the body ( - 100 ≤ xi, yi, zi ≤ 100). | 1,000 | Print the word "YES" if the body is in equilibrium, or the word "NO" if it is not. | standard output | |
PASSED | 4ca9d290b53f21be97c383c9c1e403a1 | train_003.jsonl | 1300809600 | A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces. | 256 megabytes | import java.util.*;
public class YoungPhysicist {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int n=in.nextInt();int x=0,y=0,z=0;
int a[][]=new int[n][3];
for(int row=0;row<a.length;row++)
for(int col=0;col<a[row].length;col++)
{
a[row][col]=in.nextInt();
}
for(int row=0;row<n;row++)
{
x+=a[row][0];
y+=a[row][1];
z+=a[row][2];
}
if(x==0&&y==0&&z==0)
System.out.println("YES");
else
System.out.println("NO");
}
}
| Java | ["3\n4 1 7\n-2 4 -1\n1 -5 -3", "3\n3 -1 7\n-5 2 -4\n2 -1 -3"] | 2 seconds | ["NO", "YES"] | null | Java 7 | standard input | [
"implementation",
"math"
] | 8ea24f3339b2ec67a769243dc68a47b2 | The first line contains a positive integer n (1 ≤ n ≤ 100), then follow n lines containing three integers each: the xi coordinate, the yi coordinate and the zi coordinate of the force vector, applied to the body ( - 100 ≤ xi, yi, zi ≤ 100). | 1,000 | Print the word "YES" if the body is in equilibrium, or the word "NO" if it is not. | standard output | |
PASSED | 773b9bff6f4fd3707e298891a999d697 | train_003.jsonl | 1300809600 | A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main
{
static Scanner in = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
//Scanner scanner = new Scanner(new BufferedReader(new FileReader("input.txt")));
//PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
/*static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
static int nextInt() throws IOException
{
in.nextToken();
return (int) in.nval;
}
static double nextDouble() throws IOException
{
in.nextToken();
return (double) in.nval;
}
*/
public static void main(String[] args) throws IOException
{
long sum1 = 0, sum2 = 0, sum3 = 0;
long n = in.nextLong();
for(long i = 0; i < n; i++)
{
long x = in.nextLong();
sum1 += x;
long y = in.nextLong();
sum2 += y;
long z = in.nextLong();
sum3 += z;
}
if(sum1 != 0 || sum2 != 0 || sum3 != 0)
out.println("NO");
else
out.println("YES");
out.flush();
}
}
/*
3
4 1 7
-2 4 -1
1 -5 -3
NO
3
3 -1 7
-5 2 -4
2 -1 -3
YES
*/
| Java | ["3\n4 1 7\n-2 4 -1\n1 -5 -3", "3\n3 -1 7\n-5 2 -4\n2 -1 -3"] | 2 seconds | ["NO", "YES"] | null | Java 7 | standard input | [
"implementation",
"math"
] | 8ea24f3339b2ec67a769243dc68a47b2 | The first line contains a positive integer n (1 ≤ n ≤ 100), then follow n lines containing three integers each: the xi coordinate, the yi coordinate and the zi coordinate of the force vector, applied to the body ( - 100 ≤ xi, yi, zi ≤ 100). | 1,000 | Print the word "YES" if the body is in equilibrium, or the word "NO" if it is not. | standard output | |
PASSED | 169697094f720ca377d2915b706a36dd | train_003.jsonl | 1300809600 | A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces. | 256 megabytes | import java.util.*;
public class Phys {
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
byte vectors=sc.nextByte();
byte x=0;
byte y=0;
byte z=0;
for(byte i=0;i<vectors;i++){
byte inputx=sc.nextByte();
x+=inputx;
byte inputy=sc.nextByte();
y+=inputy;
byte inputz=sc.nextByte();
z+=inputz;
System.out.println();
}
if((x==0)&&(y==0)&&(z==0)){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
} | Java | ["3\n4 1 7\n-2 4 -1\n1 -5 -3", "3\n3 -1 7\n-5 2 -4\n2 -1 -3"] | 2 seconds | ["NO", "YES"] | null | Java 7 | standard input | [
"implementation",
"math"
] | 8ea24f3339b2ec67a769243dc68a47b2 | The first line contains a positive integer n (1 ≤ n ≤ 100), then follow n lines containing three integers each: the xi coordinate, the yi coordinate and the zi coordinate of the force vector, applied to the body ( - 100 ≤ xi, yi, zi ≤ 100). | 1,000 | Print the word "YES" if the body is in equilibrium, or the word "NO" if it is not. | standard output | |
PASSED | a6aec3f62a961b907983afced509d3fe | train_003.jsonl | 1421586000 | Mr. Kitayuta's garden is planted with n bamboos. (Bamboos are tall, fast-growing tropical plants with hollow stems.) At the moment, the height of the i-th bamboo is hi meters, and it grows ai meters at the end of each day. Actually, Mr. Kitayuta hates these bamboos. He once attempted to cut them down, but failed because their stems are too hard. Mr. Kitayuta have not given up, however. He has crafted Magical Hammer with his intelligence to drive them into the ground.He can use Magical Hammer at most k times during each day, due to his limited Magic Power. Each time he beat a bamboo with Magical Hammer, its height decreases by p meters. If the height would become negative by this change, it will become 0 meters instead (it does not disappear). In other words, if a bamboo whose height is h meters is beaten with Magical Hammer, its new height will be max(0, h - p) meters. It is possible to beat the same bamboo more than once in a day.Mr. Kitayuta will fight the bamboos for m days, starting today. His purpose is to minimize the height of the tallest bamboo after m days (that is, m iterations of "Mr. Kitayuta beats the bamboos and then they grow"). Find the lowest possible height of the tallest bamboo after m days. | 256 megabytes | import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author ilyakor
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
}
class TaskC {
int n, m, k, p;
int[] h;
int[] a;
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.nextInt();
m = in.nextInt();
k = in.nextInt();
p = in.nextInt();
h = new int[n];
a = new int[n];
for (int i = 0; i < n; ++i) {
h[i] = in.nextInt();
a[i] = in.nextInt();
}
long down = 0, up = (long)(1E18);
while (up - down > 1) {
long t = (up + down) / 2L;
if (check(t))
up = t;
else
down = t;
}
long res = check(down) ? down : up;
out.printLine(res);
}
private boolean check(long maxH) {
ArrayList<Integer> touched = new ArrayList<>();
long minHits = 0;
for (int i = 0; i < n; ++i) {
if (maxH < a[i]) return false;
long finalH = (long) h[i] + (long) a[i] * (long) m;
if (finalH <= maxH) continue;
touched.add(i);
long hits = finalH - maxH;
hits = hits / p + (hits % p > 0 ? 1 : 0);
minHits += hits;
}
if (minHits > k * m) return false;
// Now it is theoretically possible to achieve maxH, if zeroes don't stop us.
int[] events = new int[m + 1];
for (int i : touched) {
long inc = 0;
for (int j = m - 1; j >= 0; ) {
for (int step = (1 << 12); step >= 1; step /= 2) {
if (j - step < -1) continue;
if (inc + (long) a[i] * (long) step > maxH) continue;
inc += (long) a[i] * (long) step;
j -= step;
}
long next = a[i];
if (j == -1) next = h[i];
while (inc + next > maxH) {
events[j + 1] += 1;
inc -= p;
}
}
}
int active = 0;
for (int i = 0; i < m; ++i) {
active += events[i];
active -= k;
if (active < 0) active = 0;
}
if (active > 0) return false;
return true;
}
}
class InputReader {
private InputStream stream;
private byte[] buffer = new byte[10000];
private int cur;
private int count;
public InputReader(InputStream stream) {
this.stream = stream;
}
public static boolean isSpace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int read() {
if (count == -1) {
throw new InputMismatchException();
}
try {
if (cur >= count) {
cur = 0;
count = stream.read(buffer);
if (count <= 0)
return -1;
}
} catch (IOException e) {
throw new InputMismatchException();
}
return buffer[cur++];
}
public int readSkipSpace() {
int c;
do {
c = read();
} while (isSpace(c));
return c;
}
public int nextInt() {
int sgn = 1;
int c = readSkipSpace();
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res = res * 10 + c - '0';
c = read();
} while (!isSpace(c));
res *= sgn;
return res;
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void printLine(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
| Java | ["3 1 2 5\n10 10\n10 10\n15 2", "2 10 10 1000000000\n0 10\n0 10", "5 3 3 10\n9 5\n9 2\n4 7\n9 10\n3 8"] | 2 seconds | ["17", "10", "14"] | null | Java 8 | standard input | [
"binary search",
"greedy"
] | 608b152c0c15bf0a41465bfa7fa41866 | The first line of the input contains four space-separated integers n, m, k and p (1 ≤ n ≤ 105, 1 ≤ m ≤ 5000, 1 ≤ k ≤ 10, 1 ≤ p ≤ 109). They represent the number of the bamboos in Mr. Kitayuta's garden, the duration of Mr. Kitayuta's fight in days, the maximum number of times that Mr. Kitayuta beat the bamboos during each day, and the power of Magic Hammer, respectively. The following n lines describe the properties of the bamboos. The i-th of them (1 ≤ i ≤ n) contains two space-separated integers hi and ai (0 ≤ hi ≤ 109, 1 ≤ ai ≤ 109), denoting the initial height and the growth rate of the i-th bamboo, respectively. | 2,900 | Print the lowest possible height of the tallest bamboo after m days. | standard output | |
PASSED | cee1a66946ff935ae842d69f8c406f40 | train_003.jsonl | 1421586000 | Mr. Kitayuta's garden is planted with n bamboos. (Bamboos are tall, fast-growing tropical plants with hollow stems.) At the moment, the height of the i-th bamboo is hi meters, and it grows ai meters at the end of each day. Actually, Mr. Kitayuta hates these bamboos. He once attempted to cut them down, but failed because their stems are too hard. Mr. Kitayuta have not given up, however. He has crafted Magical Hammer with his intelligence to drive them into the ground.He can use Magical Hammer at most k times during each day, due to his limited Magic Power. Each time he beat a bamboo with Magical Hammer, its height decreases by p meters. If the height would become negative by this change, it will become 0 meters instead (it does not disappear). In other words, if a bamboo whose height is h meters is beaten with Magical Hammer, its new height will be max(0, h - p) meters. It is possible to beat the same bamboo more than once in a day.Mr. Kitayuta will fight the bamboos for m days, starting today. His purpose is to minimize the height of the tallest bamboo after m days (that is, m iterations of "Mr. Kitayuta beats the bamboos and then they grow"). Find the lowest possible height of the tallest bamboo after m days. | 256 megabytes | //package round286;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class C {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni(), m = ni(), K = ni(), P = ni();
long[] s = new long[n];
long[] a = new long[n];
for(int i = 0;i < n;i++){
s[i] = ni();
a[i] = ni();
}
long low = -1, high = 1000000000000000L;
while(high-low > 1){
long h = high+low>>1;
if(ok(h, m, K, P, s, a)){
high = h;
}else{
low = h;
}
}
out.println(high);
}
boolean ok(long h, int m, int K, long P, long[] s, long[] a)
{
long num = 0;
int n = s.length;
for(int i = 0;i < n;i++){
if(h < a[i])return false;
long dh = s[i]+a[i]*m-h;
if(dh >= 0){
num += (dh+P-1)/P;
if(num > m*K)return false;
}
}
if(num > m*K)return false;
long[] need = new long[m];
for(int i = 0;i < n;i++){
long cur = h;
int day = m;
while(true){
long spent = Math.min(day, cur/a[i]);
cur -= spent*a[i];
day -= spent;
if(day == 0)break;
long lneed = (a[i]-cur+P-1)/P;
need[(int)day] += lneed;
cur += lneed * P;
}
if(s[i] > cur)need[0] += (s[i]-cur+P-1)/P;
}
for(int i = m-1;i >= 0;i--){
if(need[i] > K)return false;
if(i-1 >= 0)need[i-1] -= K-need[i];
}
return true;
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new C().run(); }
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| Java | ["3 1 2 5\n10 10\n10 10\n15 2", "2 10 10 1000000000\n0 10\n0 10", "5 3 3 10\n9 5\n9 2\n4 7\n9 10\n3 8"] | 2 seconds | ["17", "10", "14"] | null | Java 8 | standard input | [
"binary search",
"greedy"
] | 608b152c0c15bf0a41465bfa7fa41866 | The first line of the input contains four space-separated integers n, m, k and p (1 ≤ n ≤ 105, 1 ≤ m ≤ 5000, 1 ≤ k ≤ 10, 1 ≤ p ≤ 109). They represent the number of the bamboos in Mr. Kitayuta's garden, the duration of Mr. Kitayuta's fight in days, the maximum number of times that Mr. Kitayuta beat the bamboos during each day, and the power of Magic Hammer, respectively. The following n lines describe the properties of the bamboos. The i-th of them (1 ≤ i ≤ n) contains two space-separated integers hi and ai (0 ≤ hi ≤ 109, 1 ≤ ai ≤ 109), denoting the initial height and the growth rate of the i-th bamboo, respectively. | 2,900 | Print the lowest possible height of the tallest bamboo after m days. | standard output | |
PASSED | ec9d25af7d1093cc0c5a88ff209c3282 | train_003.jsonl | 1564497300 | You are given an array of $$$n$$$ integers. You need to split all integers into two groups so that the GCD of all integers in the first group is equal to one and the GCD of all integers in the second group is equal to one.The GCD of a group of integers is the largest non-negative integer that divides all the integers in the group.Both groups have to be non-empty. | 256 megabytes | import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.*;
public class Test {
static PrintWriter writer =
new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n;
int[] a;
static int readInt() {
int ans = 0;
boolean neg = false;
try {
boolean start = false;
for (int c = 0; (c = System.in.read()) != -1; ) {
if (c == '-') {
start = true;
neg = true;
continue;
} else if (c >= '0' && c <= '9') {
start = true;
ans = ans * 10 + c - '0';
} else if (start) break;
}
} catch (IOException e) {
}
return neg ? -ans : ans;
}
static long readLong() {
long ans = 0;
boolean neg = false;
try {
boolean start = false;
for (int c = 0; (c = System.in.read()) != -1; ) {
if (c == '-') {
start = true;
neg = true;
continue;
} else if (c >= '0' && c <= '9') {
start = true;
ans = ans * 10 + c - '0';
} else if (start) break;
}
} catch (IOException e) {
}
return neg ? -ans : ans;
}
static String readLine() {
StringBuilder b = new StringBuilder();
try {
boolean start = false;
for (int c = 0; (c = System.in.read()) != -1; ) {
if (Character.isLetterOrDigit(c)) {
start = true;
b.append((char) c);
} else if (start) break;
}
} catch (IOException e) {
}
return b.toString();
}
public static void main(String[] args) {
Test te = new Test();
te.start();
writer.flush();
}
void brute() {
for (int m = 1; m < (1<< n); m++) {
int g0 = -1, g1 = -1;
for (int j = 0; j < n; j++) {
if (((m >> j) & 1) != 0) {
if (g0 == -1) g0 = a[j];
else g0 = gcd(g0, a[j]);
} else {
if (g1 == -1) g1 = a[j];
else g1 = gcd(g1, a[j]);
}
}
if (g0 == 1 && g1 == 1) {
writer.println("YES");
for (int j = 0; j < n; j++)
if (((m >> j) & 1) != 0) writer.print(1 + " ");
else writer.print(2 + " ");
return;
}
}
writer.println("NO");
}
int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
void start() {
n = readInt();
a = new int[n];
for (int i = 0; i < n; i++) a[i] = readInt();
if (n < 21) {
brute();
return;
}
long start = System.nanoTime();
int[] grp = new int[n];
List<Integer> al = new ArrayList<>();
for (int i = 0; i < n; i++) al.add(i);
while (System.nanoTime() - start < 333_000_000) {
Collections.shuffle(al);
Arrays.fill(grp, 1);
int x = 0, y = 0;
for (int i = 0; i < n; i++) {
int j = al.get(i);
if (x != 1) {
int g = x == 0 ? a[j] : gcd(x, a[j]);
if (g != x) {
x = g;
grp[j] = 1;
} else if (y != 1) {
y = gcd(y, a[j]);
grp[j] = 2;
}
} else if (y != 1) {
y = gcd(y, a[j]);
grp[j] = 2;
} else {
writer.println("YES");
for (int k = 0; k < n; k++) writer.print(grp[k] + " ");
return;
}
}
}
writer.println("NO");
}
}
| Java | ["4\n2 3 6 7", "5\n6 15 35 77 22", "5\n6 10 15 1000 75"] | 0.5 seconds | ["YES\n2 2 1 1", "YES\n2 1 2 1 1", "NO"] | null | Java 11 | standard input | [
"greedy",
"number theory",
"probabilities"
] | 973ef4e00b0489261fce852af11aa569 | The first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$). The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the elements of the array. | 2,900 | In the first line print "YES" (without quotes), if it is possible to split the integers into two groups as required, and "NO" (without quotes) otherwise. If it is possible to split the integers, in the second line print $$$n$$$ integers, where the $$$i$$$-th integer is equal to $$$1$$$ if the integer $$$a_i$$$ should be in the first group, and $$$2$$$ otherwise. If there are multiple solutions, print any. | standard output | |
PASSED | e6fd21b22de1882df1867c2e214fe085 | train_003.jsonl | 1564497300 | You are given an array of $$$n$$$ integers. You need to split all integers into two groups so that the GCD of all integers in the first group is equal to one and the GCD of all integers in the second group is equal to one.The GCD of a group of integers is the largest non-negative integer that divides all the integers in the group.Both groups have to be non-empty. | 256 megabytes | import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Test {
static PrintWriter writer =
new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n;
int[] a;
List<Integer>[] st;
int[][] nxt;
int[] pre;
int[] at;
int[] nf;
int[] ans;
static int readInt() {
int ans = 0;
boolean neg = false;
try {
boolean start = false;
for (int c = 0; (c = System.in.read()) != -1; ) {
if (c == '-') {
start = true;
neg = true;
continue;
} else if (c >= '0' && c <= '9') {
start = true;
ans = ans * 10 + c - '0';
} else if (start) break;
}
} catch (IOException e) {
}
return neg ? -ans : ans;
}
static long readLong() {
long ans = 0;
boolean neg = false;
try {
boolean start = false;
for (int c = 0; (c = System.in.read()) != -1; ) {
if (c == '-') {
start = true;
neg = true;
continue;
} else if (c >= '0' && c <= '9') {
start = true;
ans = ans * 10 + c - '0';
} else if (start) break;
}
} catch (IOException e) {
}
return neg ? -ans : ans;
}
static String readLine() {
StringBuilder b = new StringBuilder();
try {
boolean start = false;
for (int c = 0; (c = System.in.read()) != -1; ) {
if (Character.isLetterOrDigit(c)) {
start = true;
b.append((char) c);
} else if (start) break;
}
} catch (IOException e) {
}
return b.toString();
}
public static void main(String[] args) {
Test te = new Test();
te.start();
writer.flush();
}
int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
int clean(int x) {
int t = 1;
for (int i = 2; i * i <= x; i++)
if (x % i == 0) {
t *= i;
x /= i;
while (x % i == 0) x /= i;
}
return t * x;
}
List<Integer> fact(int x) {
List<Integer> fs = new ArrayList<>();
for (int i = 2; i * i <= x; i++)
if (x % i == 0) {
fs.add(i);
x /= i;
while (x % i == 0) x /= i;
}
if (x > 1) fs.add(x);
return fs;
}
void dp(int start, int x, int y) {
if (start == n && x == 1 && y == 1) {
writer.println("YES");
for (int i = 0; i < n; i++) writer.print(ans[i] + " ");
writer.flush();
System.exit(0);
}
List<Integer> fx = fact(x), fy = fact(y);
Arrays.fill(nxt[n], n);
Arrays.fill(at, n + 1);
nf[n] = 0;
Arrays.fill(ans, start, ans.length, 1);
for (int i = start; i < n; i++) st[i].clear();
for (int i = n - 1; i >= start; i--) {
int v = a[i], m = 0;
for (int j = 0; j < fx.size(); j++) {
int f = fx.get(j);
if (v % f != 0) {
nxt[i][j] = i;
m |= 1 << j;
} else nxt[i][j] = nxt[i + 1][j];
}
for (int j = 0; j < fy.size(); j++) {
int f = fy.get(j);
if (v % f != 0) {
nxt[i][fx.size() + j] = i;
m |= 1 << (j + fx.size());
} else nxt[i][j + fx.size()] = nxt[i + 1][fx.size() + j];
}
nf[i] = m;
}
int init = ((1 << fx.size()) - 1) | (((1 << fy.size()) - 1) << fx.size());
st[start].add(init);
at[init] = start;
pre[init] = Integer.MIN_VALUE;
for (int i = start; i < n; i++) {
for (int s : st[i]) {
if (at[s] != i) continue;
for (int j = 0; j < fx.size(); j++) {
if (((s >> j) & 1) == 0) continue;
int to = nxt[i][j];
if (to >= n) continue;
int ns = s ^ (s & (((1 << fx.size()) - 1) & nf[to]));
if (to + 1 < at[ns]) {
at[ns] = to + 1;
pre[ns] = s;
st[to + 1].add(ns);
}
}
for (int j = 0; j < fy.size(); j++) {
if (((s >> (j + fx.size())) & 1) == 0) continue;
int to = nxt[i][j + fx.size()];
if (to >= n) continue;
int ns = s ^ (s & ((((1 << fy.size()) - 1) << fx.size()) & nf[to]));
if (to + 1 < at[ns]) {
at[ns] = to + 1;
pre[ns] = -s;
st[to + 1].add(ns);
}
}
}
if (at[0] <= n) {
int s = 0;
while (s != Integer.MIN_VALUE) {
if (s < 0) s = -s;
if (pre[s] < 0) {
int to = at[s] - 1;
ans[to] = 2;
}
s = pre[s];
}
writer.println("YES");
for (int j = 0; j < n; j++) writer.print(ans[j] + " ");
writer.flush();
System.exit(0);
}
}
}
void start() {
n = readInt();
a = new int[n];
ans = new int[n];
Arrays.fill(ans, 1);
nxt = new int[n + 1][18];
st = new List[n + 1];
for (int i = 0; i < st.length; i++) st[i] = new ArrayList<>();
at = new int[1 << 18];
pre = new int[1 << 18];
nf = new int[n + 1];
for (int i = 0; i < n; i++) a[i] = readInt();
int x = clean(a[0]);
for (int i = 1; i < n; i++) {
ans[i] = 2;
a[i] = clean(a[i]);
dp(i + 1, x, a[i]);
ans[i] = 1;
if (a[i] % x == 0) break;
x = gcd(x, a[i]);
}
writer.println("NO");
}
}
| Java | ["4\n2 3 6 7", "5\n6 15 35 77 22", "5\n6 10 15 1000 75"] | 0.5 seconds | ["YES\n2 2 1 1", "YES\n2 1 2 1 1", "NO"] | null | Java 11 | standard input | [
"greedy",
"number theory",
"probabilities"
] | 973ef4e00b0489261fce852af11aa569 | The first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$). The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the elements of the array. | 2,900 | In the first line print "YES" (without quotes), if it is possible to split the integers into two groups as required, and "NO" (without quotes) otherwise. If it is possible to split the integers, in the second line print $$$n$$$ integers, where the $$$i$$$-th integer is equal to $$$1$$$ if the integer $$$a_i$$$ should be in the first group, and $$$2$$$ otherwise. If there are multiple solutions, print any. | standard output | |
PASSED | ee70214ac3c47348c46b35e2407d85ff | train_003.jsonl | 1564497300 | You are given an array of $$$n$$$ integers. You need to split all integers into two groups so that the GCD of all integers in the first group is equal to one and the GCD of all integers in the second group is equal to one.The GCD of a group of integers is the largest non-negative integer that divides all the integers in the group.Both groups have to be non-empty. | 256 megabytes | import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.*;
public class Test {
static PrintWriter writer =
new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n;
int[] a;
static int readInt() {
int ans = 0;
boolean neg = false;
try {
boolean start = false;
for (int c = 0; (c = System.in.read()) != -1; ) {
if (c == '-') {
start = true;
neg = true;
continue;
} else if (c >= '0' && c <= '9') {
start = true;
ans = ans * 10 + c - '0';
} else if (start) break;
}
} catch (IOException e) {
}
return neg ? -ans : ans;
}
static long readLong() {
long ans = 0;
boolean neg = false;
try {
boolean start = false;
for (int c = 0; (c = System.in.read()) != -1; ) {
if (c == '-') {
start = true;
neg = true;
continue;
} else if (c >= '0' && c <= '9') {
start = true;
ans = ans * 10 + c - '0';
} else if (start) break;
}
} catch (IOException e) {
}
return neg ? -ans : ans;
}
static String readLine() {
StringBuilder b = new StringBuilder();
try {
boolean start = false;
for (int c = 0; (c = System.in.read()) != -1; ) {
if (Character.isLetterOrDigit(c)) {
start = true;
b.append((char) c);
} else if (start) break;
}
} catch (IOException e) {
}
return b.toString();
}
public static void main(String[] args) {
Test te = new Test();
te.start();
writer.flush();
}
void brute() {
for (int m = 1; m < (1<< n); m++) {
int g0 = -1, g1 = -1;
for (int j = 0; j < n; j++) {
if (((m >> j) & 1) != 0) {
if (g0 == -1) g0 = a[j];
else g0 = gcd(g0, a[j]);
} else {
if (g1 == -1) g1 = a[j];
else g1 = gcd(g1, a[j]);
}
}
if (g0 == 1 && g1 == 1) {
writer.println("YES");
for (int j = 0; j < n; j++)
if (((m >> j) & 1) != 0) writer.print(1 + " ");
else writer.print(2 + " ");
return;
}
}
writer.println("NO");
}
int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
void start() {
n = readInt();
a = new int[n];
for (int i = 0; i < n; i++) a[i] = readInt();
if (n < 21) {
brute();
return;
}
long start = System.nanoTime();
int[] grp = new int[n];
List<Integer> al = new ArrayList<>();
for (int i = 0; i < n; i++) al.add(i);
while (System.nanoTime() - start < 330_000_000) {
Collections.shuffle(al);
Arrays.fill(grp, 1);
int x = 0, y = 0;
for (int i = 0; i < n; i++) {
int j = al.get(i);
if (x != 1) {
int g = x == 0 ? a[j] : gcd(x, a[j]);
if (g != x) {
x = g;
grp[j] = 1;
} else if (y != 1) {
y = gcd(y, a[j]);
grp[j] = 2;
}
} else if (y != 1) {
y = gcd(y, a[j]);
grp[j] = 2;
} else {
writer.println("YES");
for (int k = 0; k < n; k++) writer.print(grp[k] + " ");
return;
}
}
}
writer.println("NO");
}
}
| Java | ["4\n2 3 6 7", "5\n6 15 35 77 22", "5\n6 10 15 1000 75"] | 0.5 seconds | ["YES\n2 2 1 1", "YES\n2 1 2 1 1", "NO"] | null | Java 11 | standard input | [
"greedy",
"number theory",
"probabilities"
] | 973ef4e00b0489261fce852af11aa569 | The first line contains a single integer $$$n$$$ ($$$2 \leq n \leq 10^5$$$). The second line contains $$$n$$$ integers $$$a_1$$$, $$$a_2$$$, $$$\ldots$$$, $$$a_n$$$ ($$$1 \leq a_i \leq 10^9$$$) — the elements of the array. | 2,900 | In the first line print "YES" (without quotes), if it is possible to split the integers into two groups as required, and "NO" (without quotes) otherwise. If it is possible to split the integers, in the second line print $$$n$$$ integers, where the $$$i$$$-th integer is equal to $$$1$$$ if the integer $$$a_i$$$ should be in the first group, and $$$2$$$ otherwise. If there are multiple solutions, print any. | standard output | |
PASSED | 3dc33a7fff1455c29831f18f5d8526ea | train_003.jsonl | 1383379200 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. | 256 megabytes | //package geometry;
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.awt.Point;
/**
*
* @author prabhat // use stringbuilder,TreeSet, priorityQueue
*/
public class point4{
public static long[] BIT;
public static Pair[] tree;
public static long[] sum;
public static int mod=1000000007;
public static int[][] dp;
public static boolean[][] isPalin;
public static int max1=100005;
public static int[][] g;
public static LinkedList<Pair> l[];
public static Query[] query;
public static int n,m,q,k,t,x,y,a[],b[],arr[],chosen[],pos[],val[],blocksize,count=0,size[],tin[],len,
tout[],discover[],cnt[],pre[],cnty[],cntZ[];
public static long V[],low,high,min=Long.MAX_VALUE,cap[],has[],max,ans;
public static ArrayList<Integer> adj[],al[];
public static TreeSet<Integer> ts;
public static char s[][];
public static int depth[],mini,maxi;
public static boolean visit[][],isPrime[],used[];
public static int[][] dist;
public static ArrayList<Integer>prime;
public static int[] x1={0,1};
public static int[] y1={-1,0};
public static ArrayList<Integer> divisor[]=new ArrayList[1000005];
public static int[][] subtree,parent,mat;
public static TreeMap<Integer,Integer> tm;
public static LongPoint[] p;
public static int[][] grid,memo;
public static ArrayList<Pair> list[];
public static TrieNode root,node[];
public static LinkedHashMap<String,Integer> map;
public static ArrayList<String> al1;
public static int upper=(int)(1e7);
public static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws Exception
{
InputReader in = new InputReader(System.in);
PrintWriter pw=new PrintWriter(System.out);
n=in.ii();
a=in.iia(n);
int[] left=new int[n];
int[] right=new int[n];
Stack<Integer> st=new Stack<>(); // for left array
for(int i=0;i<n;i++)
{
while(!st.isEmpty()&&a[st.peek()]%a[i]==0)st.pop();
left[i]=st.isEmpty()?0:st.peek()+1;
st.push(i);
}
st.clear();
for(int i=n-1;i>=0;i--)
{
while(!st.isEmpty()&&a[st.peek()]%a[i]==0)st.pop();
right[i]=st.isEmpty()?n-1:st.peek()-1;
st.push(i);
}
int max=0;
for(int i=0;i<n;i++)
{
max=Math.max(right[i]-left[i],max);
}
TreeSet<Integer> ts=new TreeSet<>();
for(int i=0;i<n;i++)
{
if(right[i]-left[i]==max)
{
ts.add(left[i]+1); // for 1 based index added 1
}
}
pw.println(ts.size()+" "+max);
for(int i:ts)pw.print(i+" ");
pw.close();
}
static class Node{
int gcd,cnt;
public Node(int gcd,int cnt)
{
this.gcd=gcd;
this.cnt=cnt;
}
}
static class SegmentTree
{
Node[] sTree;
int N;
SegmentTree(int n)
{
N=n;
sTree=new Node[4*N+5];
build(1, 0, N-1);
}
Node build(int node, int b, int e)
{
if(b == e)
return sTree[node] = new Node( arr[b] , 1);
int mid = b + e >> 1;
Node left = build(node<<1, b, mid);
Node right = build(node<<1|1, mid + 1, e);
return sTree[node] = combine(left, right);
}
Node combine(Node a, Node b)
{
int g = gcd(a.gcd, b.gcd);
return new Node(g, (g == a.gcd ? a.cnt : 0) + (g == b.gcd ? b.cnt : 0));
}
Node query(int l, int r) { return query(1, 0, N-1, l, r); }
Node query(int node, int b, int e, int l, int r)
{
if(r < b || e < l)
return new Node(0, 0);
if(l <= b && e <= r)
return sTree[node];
int mid = b + e >> 1;
Node q1 = query(node<<1, b, mid, l, r);
Node q2 = query(node<<1|1, mid + 1, e, l, r);
return combine(q1, q2);
}
}
static int get(int u, int d){
for(int i = len - 1; i >= 0; i--){
if(d >= 1 << i){
d -= 1 << i;
u = parent[i][u];
}
}
return u;
}
static void dfs(int u, int p) {
tin[u] = count++;
parent[0][u] = p;
size[u]++;
for (int i = 1; i < len; i++)
parent[i][u] = parent[i - 1][parent[i - 1][u]];
for (int v :adj[u])
if (v != p)
{
depth[v] = depth[u] + 1;
dfs( v, u);
size[u] += size[v];
}
tout[u] = count++;
}
static boolean isParent(int parent, int child) {
return tin[parent] <= tin[child] && tout[child] <= tout[parent];
}
static int lca(int a, int b) {
if (isParent(a, b))
return a;
if (isParent(b, a))
return b;
for (int i = len - 1; i >= 0; i--)
if (!isParent(parent[i][a], b))
a = parent[i][a];
return parent[0][a];
}
static class TrieNode
{
int value; // Only used in leaf nodes
int freq;
TrieNode[] arr = new TrieNode[2];
public TrieNode() {
value = Integer.MAX_VALUE;
freq=0;
arr[0] = null;
arr[1] = null;
}
}
static void insert(int n,int num)
{
TrieNode temp = node[n];
temp.value=Math.min(temp.value,num);
// Start from the msb, insert all bits of
// pre_xor into Trie
for (int i=19; i>=0; i--)
{
// Find current bit in given prefix
int val = (num & (1<<i)) >=1 ? 1 : 0;
// Create a new node if needed
if (temp.arr[val] == null)
temp.arr[val] = new TrieNode();
temp = temp.arr[val];
temp.value=Math.min(temp.value,num);
}
// System.out.println(temp.value);
// Store value at leaf node
//temp.value = pre_xor;
}
static long query(int x,int k,int s)
{
TrieNode temp = node[k];
long ans=0;
if(x%k!=0||temp.value+x>s)return -1;
for (int i=19; i>=0; i--)
{
// Find current bit in given prefix
int val = (x & (1<<i)) >= 1 ? 1 : 0;
if(temp.arr[1^val]!=null&&temp.arr[1^val].value+x<=s)
{
ans+=(1^val)<<i;
temp=temp.arr[1^val];
}
else if(temp.arr[val]!=null){
ans+=val<<i;
temp=temp.arr[val];
if(temp==null||temp.value+x>s)
{
return -1;
}
}
}
return ans;
}
static void update(int indx,long val)
{
while(indx<max1)
{
BIT[indx]=Math.max(BIT[indx],val);
indx+=(indx&(-indx));
}
}
static long query1(int indx)
{
long sum=0;
while(indx>=1)
{
sum=Math.max(BIT[indx],sum);
indx-=(indx&(-indx));
}
return sum;
}
static void Seive()
{
isPrime=new boolean[max1];
Arrays.fill(isPrime,true);
for(int i=1;i<max1;i++)divisor[i]=new ArrayList<Integer>();
isPrime[0]=isPrime[1]=false;
for(int i=1;i<(max1);i++)
{
for(int j=i;j<max1;j+=i)
{
divisor[j].add(i);
}
}
}
static int orient(Point a,Point b,Point c)
{
//return (int)(c.x-a.x)*(int)(b.y-a.y)-(int)(c.y-a.y)*(int)(b.x-a.x);
Point p1=c.minus(a);
Point p2=b.minus(a);
return (int)(p1.cross(p2));
}
public static class Polygon {
static final double EPS = 1e-15;
public int n;
public Point p[];
Polygon(int n, Point x[]) {
this.n = n;
p = Arrays.copyOf(x, n);
}
long area(){ //returns 2 * area
long ans = 0;
for(int i = 1; i + 1 < n; i++)
ans += p[i].minus(p[0]).cross(p[i + 1].minus(p[0]));
return ans;
}
boolean PointInPolygon(Point q) {
boolean c = false;
for (int i = 0; i < n; i++){
int j = (i+1)%n;
if ((p[i].y <= q.y && q.y < p[j].y ||
p[j].y <= q.y && q.y < p[i].y) &&
q.x < p[i].x + (p[j].x - p[i].x) * (q.y - p[i].y) / (p[j].y - p[i].y))
c = !c;
}
return c;
}
// determine if point is on the boundary of a polygon
boolean PointOnPolygon(Point q) {
for (int i = 0; i < n; i++)
if (ProjectPointSegment(p[i], p[(i+1)%n], q).dist(q) < EPS)
return true;
return false;
}
// project point c onto line segment through a and b
Point ProjectPointSegment(Point a, Point b, Point c) {
double r = b.minus(a).dot(b.minus(a));
if (Math.abs(r) < EPS) return a;
r = c.minus(a).dot(b.minus(a))/r;
if (r < 0) return a;
if (r > 1) return b;
return a.plus(b.minus(a).mul(r));
}
}
public static class Point {
public double x, y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public Point minus(Point b) {
return new Point(x - b.x, y - b.y);
}
public Point plus(Point a){
return new Point(x + a.x, y + a.y);
}
public double cross(Point b) {
return (double)x * b.y - (double)y * b.x;
}
public double dot(Point b) {
return (double)x * b.x + (double)y * b.y;
}
public Point mul(double r){
return new Point(x * r, y * r);
}
public double dist(Point p){
return Math.sqrt(fastHypt( x - p.x , y - p.y));
}
public double fastHypt(double x, double y){
return x * x + y * y;
}
}
static class Query implements Comparable<Query>{
int index,k;
int L;
int R;
public Query(){}
public Query(int a,int b,int index)
{
this.L=a;
this.R=b;
this.index=index;
}
public int compareTo(Query o)
{
if(L/blocksize!=o.L/blocksize)return L/blocksize-o.L/blocksize;
else return R-o.R;
}
}
static double dist(Point p1,Point p2)
{
return Math.sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));
}
static class coder {
int indx;
String name;
coder(int indx,String name)
{
this.indx=indx;
this.name=name;
}
}
static int gcd(int a, int b)
{
int res=0;
while(a!=0)
{
res=a;
a=b%a;
b=res;
}
return b;
}
static slope getSlope(Point p, Point q)
{
int dx = (int)(q.x - p.x), dy = (int)(q.y - p.y);
int g = gcd(dx, dy);
return new slope(dy / g, dx / g);
}
static class slope implements Comparable<slope>
{
int x,y;
public slope(int y,int x)
{
this.x=x;
this.y=y;
}
public int compareTo(slope s)
{
if(s.y!=y)return y-s.y;
return x-s.x;
}
}
static class Ball implements Comparable
{
int r;
int occ;
public Ball(int r,int occ)
{
this.r = r;
this.occ = occ;
}
@Override
public int compareTo(Object o) {
Ball b = (Ball) o;
return b.occ-this.occ;
}
}
static class E implements Comparable<E>{
int x,y;
char c;
E(int x,int y,char c)
{
this.x=x;
this.y=y;
this.c=c;
}
public int compareTo(E o)
{
if(x!=o.x)return o.x-x;
else return y-o.y;
}
}
public static ListNode removeNthFromEnd(ListNode a, int b) {
int cnt=0;
ListNode ra1=a;
ListNode ra2=a;
while(ra1!=null){ra1=ra1.next; cnt++;}
if(b>cnt)return a.next;
else if(b==1&&cnt==1)return null;
else{
int y=cnt-b+1;
int u=0;
ListNode prev=null;
while(a!=null)
{
u++;
if(u==y)
{
if(a.next==null)prev.next=null;
else
{
if(prev==null)return ra2.next;
prev.next=a.next;
a.next=null;
}
break;
}
prev=a;
a=a.next;
}
}
return ra2;
}
static ListNode rev(ListNode a)
{
ListNode prev=null;
ListNode cur=a;
ListNode next=null;
while(cur!=null)
{
next=cur.next;
cur.next=prev;
prev=cur;
cur=next;
}
return prev;
}
static class ListNode {
public int val;
public ListNode next;
ListNode(int x) { val = x; next = null; }
}
public static String add(String s1,String s2)
{
int n=s1.length()-1;
int m=s2.length()-1;
int rem=0;
int carry=0;
int i=n;
int j=m;
String ans="";
while(i>=0&&j>=0)
{
int c1=(int)(s1.charAt(i)-'0');
int c2=(int)(s2.charAt(j)-'0');
int sum=c1+c2;
sum+=carry;
rem=sum%10;
carry=sum/10;
ans=rem+ans;
i--; j--;
}
while(i>=0)
{
int c1=(int)(s1.charAt(i)-'0');
int sum=c1;
sum+=carry;
rem=sum%10;
carry=sum/10;
ans=rem+ans;
i--;
}
while(j>=0)
{
int c2=(int)(s2.charAt(j)-'0');
int sum=c2;
sum+=carry;
rem=sum%10;
carry=sum/10;
ans=rem+ans;
j--;
}
if(carry>0)ans=carry+ans;
return ans;
}
public static String[] multiply(String A, String B) {
int lb=B.length();
char[] a=A.toCharArray();
char[] b=B.toCharArray();
String[] s=new String[lb];
int cnt=0;
int y=0;
String s1="";
q=0;
for(int i=b.length-1;i>=0;i--)
{
int rem=0;
int carry=0;
for(int j=a.length-1;j>=0;j--)
{
int mul=(int)(b[i]-'0')*(int)(a[j]-'0');
mul+=carry;
rem=mul%10;
carry=mul/10;
s1=rem+s1;
}
s1=carry+s1;
s[y++]=s1;
q=Math.max(q,s1.length());
s1="";
for(int i1=0;i1<y;i1++)s1+='0';
}
return s;
}
public static long nCr(long total, long choose)
{
if(total < choose)
return 0;
if(choose == 0 || choose == total)
return 1;
return nCr(total-1,choose-1)+nCr(total-1,choose);
}
static int get(long s)
{
int ans=0;
for(int i=0;i<n;i++)
{
if(p[i].x<=s&&s<=p[i].y)ans++;
}
return ans;
}
static class LongPoint {
public long x;
public long y;
public LongPoint(long x, long y) {
this.x = x;
this.y = y;
}
public LongPoint subtract(LongPoint o) {
return new LongPoint(x - o.x, y - o.y);
}
public long cross(LongPoint o) {
return x * o.y - y * o.x;
}
}
static int CountPs(String s,int n)
{
boolean b=false;
char[] S=s.toCharArray();
int[][] dp=new int[n][n];
boolean[][] p=new boolean[n][n];
for(int i=0;i<n;i++)p[i][i]=true;
for(int i=0;i<n-1;i++)
{
if(S[i]==S[i+1])
{
p[i][i+1]=true;
dp[i][i+1]=0;
b=true;
}
}
for(int gap=2;gap<n;gap++)
{
for(int i=0;i<n-gap;i++)
{
int j=gap+i;
if(S[i]==S[j]&&p[i+1][j-1]){p[i][j]=true;}
if(p[i][j])
dp[i][j]=dp[i][j-1]+dp[i+1][j]+1-dp[i+1][j-1];
else if(!p[i][j]) dp[i][j]=dp[i][j-1]+dp[i+1][j]-dp[i+1][j-1];
//if(dp[i][j]>=1)
// return true;
}
}
// return b;
return dp[0][n-1];
}
static long divCeil(long a,long b)
{
return (a+b-1)/b;
}
static long root(int pow, long x) {
long candidate = (long)Math.exp(Math.log(x)/pow);
candidate = Math.max(1, candidate);
while (pow(candidate, pow) <= x) {
candidate++;
}
return candidate-1;
}
static long pow(long x, int pow)
{
long result = 1;
long p = x;
while (pow > 0) {
if ((pow&1) == 1) {
if (result > Long.MAX_VALUE/p) return Long.MAX_VALUE;
result *= p;
}
pow >>>= 1;
if (pow > 0 && p >= 4294967296L) return Long.MAX_VALUE;
p *= p;
}
return result;
}
static boolean valid(int i,int j)
{
if(i>=0&&i<n&&j>=0&&j<m)return true;
return false;
}
private static class DSU{
int[] parent;
int[] rank;
int cnt;
public DSU(int n){
parent=new int[n];
rank=new int[n];
for(int i=0;i<n;i++){
parent[i]=i;
rank[i]=1;
}
cnt=n;
}
int find(int i){
while(parent[i] !=i){
parent[i]=parent[parent[i]];
i=parent[i];
}
return i;
}
int Union(int x, int y){
int xset = find(x);
int yset = find(y);
if(xset!=yset)
cnt--;
if(rank[xset]<rank[yset]){
parent[xset] = yset;
rank[yset]+=rank[xset];
rank[xset]=0;
return yset;
}else{
parent[yset]=xset;
rank[xset]+=rank[yset];
rank[yset]=0;
return xset;
}
}
}
public static int[][] packU(int n, int[] from, int[] to, int max) {
int[][] g = new int[n][];
int[] p = new int[n];
for (int i = 0; i < max; i++) p[from[i]]++;
for (int i = 0; i < max; i++) p[to[i]]++;
for (int i = 0; i < n; i++) g[i] = new int[p[i]];
for (int i = 0; i < max; i++) {
g[from[i]][--p[from[i]]] = to[i];
g[to[i]][--p[to[i]]] = from[i];
}
return g;
}
public static int[][] parents3(int[][] g, int root) {
int n = g.length;
int[] par = new int[n];
Arrays.fill(par, -1);
int[] depth = new int[n];
depth[0] = 0;
int[] q = new int[n];
q[0] = root;
for (int p = 0, r = 1; p < r; p++) {
int cur = q[p];
for (int nex : g[cur]) {
if (par[cur] != nex) {
q[r++] = nex;
par[nex] = cur;
depth[nex] = depth[cur] + 1;
}
}
}
return new int[][]{par, q, depth};
}
public static int lower_bound(int[] nums, int target) {
int low = 0, high = nums.length - 1;
while (low < high) {
int mid = low + (high - low) / 2;
if (nums[mid] < target)
low = mid + 1;
else
high = mid;
}
return nums[low] == target ? low : -1;
}
public static int upper_bound(int[] nums, int target) {
int low = 0, high = nums.length - 1;
while (low < high) {
int mid = low + (high + 1 - low) / 2;
if (nums[mid] > target)
high = mid - 1;
else
low = mid;
}
return nums[low] == target ? low : -1;
}
public static boolean palin(String s)
{
int i=0;
int j=s.length()-1;
while(i<j)
{
if(s.charAt(i)==s.charAt(j))
{
i++;
j--;
}
else return false;
}
return true;
}
static int lcm(int a,int b)
{
return (a*b)/(gcd(a,b));
}
public static long pow(long n,long p,long m)
{
long result = 1;
if(p==0)
return 1;
while(p!=0)
{
if(p%2==1)
result *= n;
if(result>=m)
result%=m;
p >>=1;
n*=n;
if(n>=m)
n%=m;
}
return result;
}
/**
*
* @param n
* @param p
* @return
*/
public static long pow(long n,long p)
{
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
static class Edge implements Comparator<Edge> {
private int u;
private int v;
private long w;
public Edge() {
}
public Edge(int u, int v, long w) {
this.u=u;
this.v=v;
this.w=w;
}
public int getU() {
return u;
}
public void setU(int u) {
this.u = u;
}
public int getV() {
return v;
}
public void setV(int v) {
this.v = v;
}
public long getW() {
return w;
}
public void setW(int w) {
this.w = w;
}
public long compareTo(Edge e)
{
return (this.getW() - e.getW());
}
@Override
public int compare(Edge o1, Edge o2) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
static class Pair implements Comparable<Pair>
{
int x,y;
Pair (int a,int b)
{
this.x=a;
this.y=b;
}
public int compareTo(Pair o) {
// TODO Auto-generated method stub
if(this.x!=o.x)
return -Integer.compare(this.x,o.x);
else
return -Integer.compare(this.y, o.y);
//return 0;
}
public boolean equals(Object o) {
if (o instanceof Pair) {
Pair p = (Pair)o;
return p.x == x && p.y == y;
}
return false;
}
public int hashCode() {
return new Integer(x).hashCode() * 31 + new Integer(y).hashCode();
}
}
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private SpaceCharFilter filter;
byte inbuffer[] = new byte[1024];
int lenbuffer = 0, ptrbuffer = 0;
final int M = (int) 1e9 + 7;
int md=(int)(1e7+1);
int[] SMP=new int[md];
final double eps = 1e-6;
final double pi = Math.PI;
PrintWriter out;
String check = "";
InputStream obj = check.isEmpty() ? System.in : new ByteArrayInputStream(check.getBytes());
public InputReader(InputStream stream)
{
this.stream = stream;
}
int readByte() {
if (lenbuffer == -1) throw new InputMismatchException();
if (ptrbuffer >= lenbuffer) {
ptrbuffer = 0;
try {
lenbuffer = obj.read(inbuffer);
} catch (IOException e) {
throw new InputMismatchException();
}
}
if (lenbuffer <= 0) return -1;
return inbuffer[ptrbuffer++];
}
public int read()
{
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;
}
String is() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) // when nextLine, (isSpaceChar(b) && b!=' ')
{
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public int ii() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public long il() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
boolean isSpaceChar(int c) {
return (!(c >= 33 && c <= 126));
}
int skip()
{
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
float nf() {
return Float.parseFloat(is());
}
double id() {
return Double.parseDouble(is());
}
char ic() {
return (char) skip();
}
int[] iia(int n) {
int a[] = new int[n];
for (int i = 0; i<n; i++) a[i] = ii();
return a;
}
long[] ila(int n) {
long a[] = new long[n];
for (int i = 0; i <n; i++) a[i] = il();
return a;
}
String[] isa(int n) {
String a[] = new String[n];
for (int i = 0; i < n; i++) a[i] = is();
return a;
}
long mul(long a, long b) { return a * b % M; }
long div(long a, long b)
{
return mul(a, pow(b, M - 2));
}
double[][] idm(int n, int m) {
double a[][] = new double[n][m];
for (int i = 0; i < n; i++) for (int j = 0; j < m; j++) a[i][j] = id();
return a;
}
int[][] iim(int n, int m) {
int a[][] = new int[n][m];
for (int i = 0; i < n; i++) for (int j = 0; j <m; j++) a[i][j] = ii();
return a;
}
public String readLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
}
| Java | ["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"] | 2 seconds | ["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"] | NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | Java 8 | standard input | [
"two pointers",
"math",
"data structures",
"binary search",
"brute force"
] | da517ae908ba466da8ded87cec12a9fa | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). | 2,000 | Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. | standard output | |
PASSED | a1c75405e7c8e26865585e642fe1b07f | train_003.jsonl | 1383379200 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. | 256 megabytes |
// Problem : D. Pair of Numbers
// Contest : Codeforces Round #209 (Div. 2)
// URL : https://codeforces.com/contest/359/problem/D
// Memory Limit : 256 MB
// Time Limit : 2000 ms
// Powered by CP Editor (https://github.com/cpeditor/cpeditor)
import java.io.*;
import java.util.*;
public class a {
public static void main(String[] args) {
FastReader scan = new FastReader();
PrintWriter out = new PrintWriter(System.out);
Task solver = new Task();
//int t = scan.nextInt();
int t = 1;
for(int i = 1; i <= t; i++) solver.solve(i, scan, out);
out.close();
}
static class Task {
public void solve(int testNumber, FastReader sc, PrintWriter pw) {
int n = sc.nextInt();
tup[] arr= new tup[n];
int[] arrs = new int[n];
for(int i=0;i<n;i++){
arr[i]=new tup(sc.nextInt(),i);
arrs[i]=arr[i].a;
}
Arrays.sort(arr);
int[] ans= new int[n];
ArrayList<tup> ch = new ArrayList<tup>();
int max = 0;
for(int i=0;i<n;i++){
if(ans[arr[i].b]>0){
continue;
}
else{
int ctr = 0;
int t = arr[i].b;
while(t<n&&arrs[t]%arrs[arr[i].b]==0){
//pw.println(arrs[t]+" "+arrs[arr[i].b]);
ans[t++]=i+1;
ctr++;
}
t = arr[i].b-1;
while(t>=0&&arrs[t]%arrs[arr[i].b]==0){
//pw.println(arrs[t]+" "+arrs[arr[i].b]);
ans[t--]=i+1;
ctr++;
}
max= Math.max(ctr,max);
ch.add(new tup(ctr,t+1));
}
}
//pw.println(Arrays.toString(ans));
ArrayList<Integer> out = new ArrayList<Integer>();
int out2 = 0;
for(tup check : ch){
if(check.a==max){
out.add(check.b+1);
out2++;
}
}
Collections.sort(out);
pw.println(out2 + " "+ (max-1));
for(int x: out){
pw.print(x+" ");
}
}
}
static class tup implements Comparable<tup> {
int a, b;
tup(int a, int b){
this.a=a;
this.b=b;
}
@Override
public int compareTo(tup o2){
return Integer.compare(a,o2.a);
}
}
static void shuffle(int[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
static void shuffle(long[] a) {
Random get = new Random();
for (int i = 0; i < a.length; i++) {
int r = get.nextInt(a.length);
long temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastReader(String s) throws FileNotFoundException {
br = new BufferedReader(new FileReader(new File(s)));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"] | 2 seconds | ["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"] | NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | Java 8 | standard input | [
"two pointers",
"math",
"data structures",
"binary search",
"brute force"
] | da517ae908ba466da8ded87cec12a9fa | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). | 2,000 | Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. | standard output | |
PASSED | 49bee22671b9947bbb5ded2a41e44a84 | train_003.jsonl | 1383379200 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. | 256 megabytes | import java.util.*;
import java.io.*;
public class _0359_D_PairOfNumbers {
static int org[], tbl[][], N, logN, pow2[];
public static void build() {
for(int i = 1; i<=N; i++) tbl[i][0] = org[i];
for(int i = 1; i<=logN; i++) for(int j = 1; j<=N-(1<<i)+1; j++) tbl[j][i] = gcd(tbl[j][i-1], tbl[j+(1<<(i-1))][i-1]);
}
public static int query(int l, int r) {
int k = Integer.numberOfTrailingZeros(Integer.highestOneBit(r-l+1));
return gcd(tbl[l][k], tbl[r-(1<<k)+1][k]);
}
public static int gcd(int a, int b) {
return a*b == 0 ? a+b: gcd(b, a%b);
}
public static void main(String[] args) throws IOException {
N = readInt(); logN = 20; org = new int[N+1]; tbl = new int[N+1][logN+1];
for(int i = 1; i<=N; i++) org[i] = readInt(); build();
int max = -1; int ans[] = new int[N+1], idx = 0;
for(int i = 1; i<=N; i++) {
int l = 1, r = i; int lb = i, ub = i;
while(l <= r) {
int mid = (l+r)>>1;
if(query(mid, i) == org[i]) {lb = mid; r = mid - 1;}
else l = mid + 1;
}
l = i; r = N;
while(l <= r) {
int mid = (l+r)>>1;
if(query(i, mid) == org[i]) {ub = mid; l = mid + 1;}
else r = mid - 1;
}
if(ub-lb > max) {
idx = 0; max = ub-lb;
ans[++idx] = lb;
}
else if(ub-lb == max) {
if(ans[idx] != lb) ans[++idx] = lb;
}
}
println(idx + " " + max); for(int i = 1; i<=idx; i++) print(ans[i] + " ");
exit();
}
final private static int BUFFER_SIZE = 1 << 16;
private static DataInputStream din = new DataInputStream(System.in);
private static byte[] buffer = new byte[BUFFER_SIZE];
private static int bufferPointer = 0, bytesRead = 0;
static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
public static int readInt() throws IOException {
int ret = 0;
byte c = Read();
while (c <= ' ')
c = Read();
do {
ret = ret * 10 + c - '0';
} while ((c = Read()) >= '0' && c <= '9');
return ret;
}
private static void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private static byte Read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
static void print(Object o) {
pr.print(o);
}
static void println(Object o) {
pr.println(o);
}
static void flush() {
pr.flush();
}
static void println() {
pr.println();
}
static void exit() throws IOException {
din.close();
pr.close();
System.exit(0);
}
}
| Java | ["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"] | 2 seconds | ["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"] | NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | Java 8 | standard input | [
"two pointers",
"math",
"data structures",
"binary search",
"brute force"
] | da517ae908ba466da8ded87cec12a9fa | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). | 2,000 | Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. | standard output | |
PASSED | 44cc0340f42244e0fcd9c191c9ba37a7 | train_003.jsonl | 1383379200 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. | 256 megabytes |
import java.io.*;
import java.math.*;
import java.util.*;
import static java.util.Arrays.fill;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;
public class D359_ST
{
public static int mod = 1000000007;
public static long INF = (1L << 60);
static FastScanner2 in = new FastScanner2();
static OutputWriter out = new OutputWriter(System.out);
public static int gcd(int a,int b)
{
if(b==0)
return a;
else
return gcd(b, a%b);
}
public static int ceillog(int a)
{
int mul=1;
int ans=0;
while(mul<=a)
{
mul*=2;
ans++;
}
return (ans-1);
}
static int[][] sparse_table;
static int[][] mintable;
static int n;
public static int querysparcetable(int l,int r)
{
int len=r-l+1;
int log=ceillog(len);
int ans=gcd(sparse_table[l][log], sparse_table[r-(1<<log)+1][log]);
return ans;
}
public static int querymintable(int l,int r)
{
int len=r-l+1;
int log=ceillog(len);
int ans=min(mintable[l][log], mintable[r-(1<<log)+1][log]);
return ans;
}
public static void main(String[] args)
{
n=in.nextInt();
int[] a=new int[n];
for(int i=0;i<n;i++)
{
a[i]=in.nextInt();
}
sparse_table=new int[n][20];
mintable=new int[n][20];
for(int i=0;i<n;i++)
{
sparse_table[i][0]=a[i];
mintable[i][0]=a[i];
}
for(int j=1;j<20;j++)
{
for(int i=0;i<n;i++)
{
if((i+(1<<(j-1)))<n)
{
sparse_table[i][j]=gcd(sparse_table[i][j-1], sparse_table[i+(1<<(j-1))][j-1]);
mintable[i][j]=min(mintable[i][j-1], mintable[i+(1<<(j-1))][j-1]);
}
}
}
int left=1;
int right=n;
int ans=0;
while(left<=right)
{
int mid=(left+right)/2;
boolean ok=false;
for(int i=0;i+mid-1<n && !ok;i++)
{
int squery=querysparcetable(i, i+mid-1);
int mquery=querymintable(i, i+mid-1);
if(squery==mquery)
ok=true;
}
if(ok)
{
ans=mid;
left=mid+1;
}
else
{
right=mid-1;
}
}
ArrayList<Integer> list=new ArrayList<>();
for(int i=0;i<n;i++)
{
if(i+ans-1>=n)
continue;
if(querysparcetable(i, i+ans-1)==querymintable(i, i+ans-1))
list.add(i+1);
}
out.print(list.size()+" "+(ans-1));
out.println();
for(int i : list)
out.print(i+" ");
out.close();
}
static class FastScanner2
{
private byte[] buf = new byte[1024];
private int curChar;
private int snumChars;
public int read()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = System.in.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isEndOfLine(c));
return res.toString();
}
public String nextString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n)
{
long[] arr = new long[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
}
static class OutputWriter
{
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream)
{
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer)
{
this.writer = new PrintWriter(writer);
}
public void print(Object... objects)
{
for (int i = 0; i < objects.length; i++)
{
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void println(Object... objects)
{
print(objects);
writer.println();
}
public void close()
{
writer.close();
}
public void flush()
{
writer.flush();
}
}
private static boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private static void debug(Object... o)
{
if (!oj)
System.out.println(Arrays.deepToString(o));
}
private static void tr(Object... o)
{
if (!oj)
System.out.println(Arrays.deepToString(o));
}
} | Java | ["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"] | 2 seconds | ["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"] | NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | Java 8 | standard input | [
"two pointers",
"math",
"data structures",
"binary search",
"brute force"
] | da517ae908ba466da8ded87cec12a9fa | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). | 2,000 | Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. | standard output | |
PASSED | 87c45b906639810d3851ca5008cb4c5b | train_003.jsonl | 1383379200 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. | 256 megabytes |
import java.io.*;
import java.math.*;
import java.util.*;
import static java.util.Arrays.fill;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;
public class D359
{
public static int mod = 1000000007;
public static long INF = (1L << 60);
static FastScanner2 in = new FastScanner2();
static OutputWriter out = new OutputWriter(System.out);
public static void main(String[] args)
{
int n=in.nextInt();
int[] a=new int[n+1];
for(int i=1;i<=n;i++)
{
a[i]=in.nextInt();
}
Stack<Integer> stack=new Stack<>();
int[] l=new int[n+1];
int[] r=new int[n+1];
for(int i=1;i<=n;i++)
{
while(!stack.isEmpty() && a[stack.peek()]%a[i]==0)
stack.pop();
l[i]=(stack.isEmpty())?1:(stack.peek()+1);
stack.push(i);
}
//tr(l);
stack=new Stack<>();
for(int i=n;i>=1;i--)
{
while(!stack.isEmpty() && a[stack.peek()]%a[i]==0)
stack.pop();
r[i]=(stack.isEmpty())?n:(stack.peek()-1);
stack.push(i);
}
//tr(r);
int len=0;
for(int i=1;i<=n;i++)
{
len=max(len, r[i]-l[i]);
}
TreeSet<Integer> ans=new TreeSet<>();
for(int i=1;i<=n;i++)
{
if(r[i]-l[i]==len)
{
ans.add(l[i]);
}
}
out.println(ans.size()+" "+len);
for(int i : ans)
out.print(i+" ");
out.close();
}
static class FastScanner2
{
private byte[] buf = new byte[1024];
private int curChar;
private int snumChars;
public int read()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = System.in.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isEndOfLine(c));
return res.toString();
}
public String nextString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int[] arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n)
{
long[] arr = new long[n];
for (int i = 0; i < n; i++)
{
arr[i] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
}
static class OutputWriter
{
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream)
{
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer)
{
this.writer = new PrintWriter(writer);
}
public void print(Object... objects)
{
for (int i = 0; i < objects.length; i++)
{
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void println(Object... objects)
{
print(objects);
writer.println();
}
public void close()
{
writer.close();
}
public void flush()
{
writer.flush();
}
}
private static boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private static void debug(Object... o)
{
if (!oj)
System.out.println(Arrays.deepToString(o));
}
private static void tr(Object... o)
{
if (!oj)
System.out.println(Arrays.deepToString(o));
}
} | Java | ["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"] | 2 seconds | ["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"] | NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | Java 8 | standard input | [
"two pointers",
"math",
"data structures",
"binary search",
"brute force"
] | da517ae908ba466da8ded87cec12a9fa | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). | 2,000 | Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. | standard output | |
PASSED | de3f7443a7e7e586a6398f7fbdeb884a | train_003.jsonl | 1383379200 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class CodeChef implements Runnable {
static final double time = 1e9;
static final int MOD = (int) 1e9 + 7;
static final long mh = Long.MAX_VALUE;
static final Reader in = new Reader();
static final PrintWriter out = new PrintWriter(System.out);
StringBuilder answer = new StringBuilder();
long start = System.nanoTime();
public static void main(String[] args) {
new Thread(null, new CodeChef(), "persefone", 1 << 28).start();
}
@Override
public void run() {
solve();
printf();
long elapsed = System.nanoTime() - start;
// out.println("stamp : " + elapsed / time);
// out.println("stamp : " + TimeUnit.SECONDS.convert(elapsed, TimeUnit.NANOSECONDS));
close();
// out.flush();
}
void solve() {
int n = in.nextInt();
int[] a = in.nextIntArray(n);
SparseTable_Gcd sparseTableGcd = new SparseTable_Gcd(a, n);
int[] ans = new int[n];
int m = 0, k = 0;
for (int i = 0; i < n; i++) {
int left = sparseTableGcd.findLeft(0, i, a[i]);
int right = sparseTableGcd.findRight(i, n, a[i]);
int cur = right - left;
if (cur == m && (k == 0 || ans[k - 1] != left + 1)) ans[k++] = left + 1;
else if (cur > m) {
k = 0;
ans[k++] = left + 1;
m = cur;
}
}
printf(k + " " + m);
for (int i = 0; i < k; i++) add(ans[i], ' ');
}
interface SparseTable {
int function(int a, int b);
void build();
int get(int l, int r);
}
static class SparseTable_Gcd implements SparseTable {
private int n, MAX_LENGTH;
private int[] log;
private int[][] gcd;
public SparseTable_Gcd(int[] a, int n) {
this.n = n;
this.log = new int[n + 1];
for (int i = 2; i <= n; i++) log[i] = log[i >> 1] + 1;
this.MAX_LENGTH = log[n];
this.gcd = new int[n + 1][MAX_LENGTH + 1];
for (int i = 0; i < n; i++) gcd[i][0] = a[i];
build();
}
@Override
public int function(int a, int b) {
return b == 0 ? a : function(b, a % b);
}
@Override
public void build() {
for (int j = 1; j <= MAX_LENGTH; j++)
for (int i = 0; i <= n - (1 << j); i++)
gcd[i][j] = function(gcd[i][j - 1], gcd[i + (1 << j - 1)][j - 1]);
}
@Override
public int get(int l, int r) {
int k = log[r - l + 1];
return function(gcd[l][k], gcd[r - (1 << k) + 1][k]);
}
int findLeft(int l, int r, int k) {
int m = 0, R = r, ans = 0, g = 0, t = 0;
while (l < r) {
m = l + r >> 1;
if ((t = get(m, R)) >= k) { ans = r = m; g = t; } else l = m + 1;
}
return g == k ? ans : R;
}
int findRight(int l, int r, int k) {
int m = 0, L = l, ans = 0, g = 0, t = 0;
while (l < r) {
m = l + r >> 1;
if ((t = get(L, m)) >= k) { ans = m; l = m + 1; g = t; } else r = m;
}
return g == k ? ans : L;
}
int find(int cur, int k) {
return findRight(cur, n, k) - findLeft(0, cur, k) + 1;
}
}
static class Fenwick {
private int n;
private long[] sum;
public Fenwick(int n) {
this.n = n + 10;
this.sum = new long[this.n];
}
void update(int i, int val) {
for (; i < n; i += i & -i) sum[i] += val;
}
long get(int i) {
long s = 0;
for (; i > 0; i -= i & -i) s += sum[i];
return s;
}
}
static class SegmentTreeMin {
private int n;
private int[] min, a;
public SegmentTreeMin(int[] a, int n) {
this.n = n;
this.a = a;
this.min = new int[4 * n + 4];
build(1, 0, n - 1);
}
private void build(int currentVertex, int currentLeft, int currentRight) {
if (currentLeft == currentRight) min[currentVertex] = a[currentLeft];
else {
int middle = currentLeft + currentRight >> 1, doubleVex = currentVertex << 1;
build(doubleVex, currentLeft, middle);
build(doubleVex + 1, middle + 1, currentRight);
min[currentVertex] = Math.min(min[doubleVex], min[doubleVex + 1]);
}
}
private void update(int currentVertex, int currentLeft, int currentRight, int pos, int value) {
if (currentLeft == currentRight) min[currentVertex] = a[pos] = value;
else {
int middle = currentLeft + currentRight >> 1, doubleVex = currentVertex << 1;
if (pos <= middle && pos >= currentLeft)
update(doubleVex, currentLeft, middle, pos, value);
else
update(doubleVex + 1, middle + 1, currentRight, pos, value);
min[currentVertex] = Math.min(min[doubleVex], min[doubleVex + 1]);
}
}
public void update(int pos, int value) {
update(1, 0, n - 1, pos, value);
}
private int getMin(int currentVertex, int currentLeft, int currentRight, int left, int right) {
if (left > currentRight || right < currentLeft) return Integer.MAX_VALUE;
if (currentLeft >= left && currentRight <= right) return min[currentVertex];
int middle = currentLeft + currentRight >> 1, doubleVex = currentVertex << 1;
return Math.min(getMin(doubleVex, currentLeft, middle, left, right),
getMin(doubleVex + 1, middle + 1, currentRight, left, right));
}
public int getMin(int left, int right) {
return getMin(1, 0, n - 1, left, right);
}
}
static class ArrayUtils {
static void compressed(int[] a, int n) {
int[] b = a.clone();
Arrays.sort(b, 0, n);
for (int i = 0; i < n; i++) a[i] = lw(b, 0, n, a[i]) + 1;
}
static int lw(int[] b, int l, int r, int k) {
int R = r, m = 0;
while (l <= r) {
m = l + r >> 1;
if (m == R) return m;
if (b[m] >= k) r = m - 1;
else l = m + 1;
}
return l;
}
static void compressed(long[] a, int n) {
long[] b = a.clone();
Arrays.sort(b, 0, n);
for (int i = 0; i < n; i++) a[i] = lw(b, 0, n, a[i]) + 1;
}
static int lw(long[] b, int l, int r, long k) {
int R = r, m = 0;
while (l <= r) {
m = l + r >> 1;
if (m == R) return m;
if (b[m] >= k) r = m - 1;
else l = m + 1;
}
return l;
}
static int up(int[] b, int l, int r, int k) {
int R = r, m = 0;
while (l <= r) {
m = l + r >> 1;
if (m == R) return m;
if (b[m] > k) r = m - 1;
else l = m + 1;
}
return l;
}
}
static class ListUtils {
static <T extends Comparable<T>> int upperBound(List<T> list, int l, int r, T t) {
int R = r, m = 0;
while (l <= r) {
m = l + r >> 1;
if (R == m) return m;
if (list.get(m).compareTo(t) > 0)
r = m - 1;
else
l = m + 1;
}
return l;
}
static <T extends Comparable<T>> int lowerBound(List<T> list, int l, int r, T t) {
int R = r, m = 0;
while (l <= r) {
m = l + r >> 1;
if (R == m) return m;
if (list.get(m).compareTo(t) >= 0)
r = m - 1;
else
l = m + 1;
}
return l;
}
}
void printf() {
out.print(answer);
}
void close() {
out.close();
}
void printf(Stream<?> str) {
str.forEach(o -> add(o, " "));
add("\n");
}
void printf(Object... obj) {
printf(false, obj);
}
void printfWithDescription(Object... obj) {
printf(true, obj);
}
private void printf(boolean b, Object... obj) {
if (obj.length > 1) {
for (int i = 0; i < obj.length; i++) {
if (b) add(obj[i].getClass().getSimpleName(), " - ");
if (obj[i] instanceof Collection<?>) {
printf((Collection<?>) obj[i]);
} else if (obj[i] instanceof int[][]) {
printf((int[][]) obj[i]);
} else if (obj[i] instanceof long[][]) {
printf((long[][]) obj[i]);
} else if (obj[i] instanceof double[][]) {
printf((double[][]) obj[i]);
} else printf(obj[i]);
}
return;
}
if (b) add(obj[0].getClass().getSimpleName(), " - ");
printf(obj[0]);
}
void printf(Object o) {
if (o instanceof int[])
printf(Arrays.stream((int[]) o).boxed());
else if (o instanceof char[])
printf(new String((char[]) o));
else if (o instanceof long[])
printf(Arrays.stream((long[]) o).boxed());
else if (o instanceof double[])
printf(Arrays.stream((double[]) o).boxed());
else if (o instanceof boolean[]) {
for (boolean b : (boolean[]) o) add(b, " ");
add("\n");
} else
add(o, "\n");
}
void printf(int[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(long[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(double[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(boolean[]... obj) {
for (int i = 0; i < obj.length; i++) printf(obj[i]);
}
void printf(Collection<?> col) {
printf(col.stream());
}
<T, K> void add(T t, K k) {
if (t instanceof Collection<?>) {
((Collection<?>) t).forEach(i -> add(i, " "));
} else if (t instanceof Object[]) {
Arrays.stream((Object[]) t).forEach(i -> add(i, " "));
} else
add(t);
add(k);
}
<T> void add(T t) {
answer.append(t);
}
@SuppressWarnings("unchecked")
<T extends Comparable<? super T>> T min(T... t) {
if (t.length == 0)
return null;
T m = t[0];
for (int i = 1; i < t.length; i++)
if (t[i].compareTo(m) < 0)
m = t[i];
return m;
}
@SuppressWarnings("unchecked")
<T extends Comparable<? super T>> T max(T... t) {
if (t.length == 0)
return null;
T m = t[0];
for (int i = 1; i < t.length; i++)
if (t[i].compareTo(m) > 0)
m = t[i];
return m;
}
int gcd(int a, int b) {
return (b == 0) ? a : gcd(b, a % b);
}
long gcd(long a, long b) {
return (b == 0) ? a : gcd(b, a % b);
}
// c = gcd(a, b) -> extends gcd method: ax + by = c <----> (b % a)p + q = c;
int[] ext_gcd(int a, int b) {
if (b == 0) return new int[]{a, 1, 0};
int[] vals = ext_gcd(b, a % b);
int d = vals[0]; // gcd
int p = vals[2]; //
int q = vals[1] - (a / b) * vals[2];
return new int[]{d, p, q};
}
// find any solution of the equation: ax + by = c using extends gcd
boolean find_any_solution(int a, int b, int c, int[] root) {
int[] vals = ext_gcd(Math.abs(a), Math.abs(b));
if (c % vals[0] != 0) return false;
printf(vals);
root[0] = c * vals[1] / vals[0];
root[1] = c * vals[2] / vals[0];
if (a < 0) root[0] *= -1;
if (b < 0) root[1] *= -1;
return true;
}
int mod(int x) {
return x % MOD;
}
int mod(int x, int y) {
return mod(mod(x) + mod(y));
}
long mod(long x) {
return x % MOD;
}
long mod(long x, long y) {
return mod(mod(x) + mod(y));
}
int lw(long[] f, int l, int r, long k) {
int R = r, m = 0;
while (l <= r) {
m = l + r >> 1;
if (m == R) return m;
if (f[m] >= k) r = m - 1;
else l = m + 1;
}
return l;
}
int up(long[] f, int l, int r, long k) {
int R = r, m = 0;
while (l <= r) {
m = l + r >> 1;
if (m == R) return m;
if (f[m] > k) r = m - 1;
else l = m + 1;
}
return l;
}
int lw(int[] f, int l, int r, int k) {
int R = r, m = 0;
while (l <= r) {
m = l + r >> 1;
if (m == R) return m;
if (f[m] >= k) r = m - 1;
else l = m + 1;
}
return l;
}
int up(int[] f, int l, int r, int k) {
int R = r, m = 0;
while (l <= r) {
m = l + r >> 1;
if (m == R) return m;
if (f[m] > k) r = m - 1;
else l = m + 1;
}
return l;
}
<K extends Comparable<K>> int lw(List<K> li, int l, int r, K k) {
int R = r, m = 0;
while (l <= r) {
m = l + r >> 1;
if (m == R) return m;
if (li.get(m).compareTo(k) >= 0)
r = m - 1;
else
l = m + 1;
}
return l;
}
<K extends Comparable<K>> int up(List<K> li, int l, int r, K k) {
int R = r, m = 0;
while (l <= r) {
m = l + r >> 1;
if (m == R) return m;
if (li.get(m).compareTo(k) > 0)
r = m - 1;
else
l = m + 1;
}
return l;
}
<K extends Comparable<K>> int bs(List<K> li, int l, int r, K k) {
while (l <= r) {
int m = l + r >> 1;
if (li.get(m) == k) return m;
else if (li.get(m).compareTo(k) < 0)
l = m + 1;
else
r = m - 1;
}
return -1;
}
long calc(int base, int exponent) {
if (exponent == 0) return 1;
if (exponent == 1) return base % MOD;
long m = calc(base, exponent / 2);
if (exponent % 2 == 0) return (m * m) % MOD;
return (base * ((m * m) % MOD)) % MOD;
}
long calc(int base, long exponent) {
if (exponent == 0) return 1;
if (exponent == 1) return base % MOD;
long m = calc(base, exponent / 2);
if (exponent % 2 == 0) return (m * m) % MOD;
return (base * ((m * m) % MOD)) % MOD;
}
long calc(long base, long exponent) {
if (exponent == 0) return 1;
if (exponent == 1) return base % MOD;
long m = calc(base, exponent / 2);
if (exponent % 2 == 0) return (m * m) % MOD;
return (base * (m * m % MOD)) % MOD;
}
long power(int base, int exponent) {
if (exponent == 0) return 1;
long m = power(base, exponent / 2);
if (exponent % 2 == 0) return m * m;
return base * m * m;
}
void swap(int[] a, int i, int j) {
a[i] ^= a[j];
a[j] ^= a[i];
a[i] ^= a[j];
}
void swap(long[] a, int i, int j) {
long tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static class Pair<K extends Comparable<? super K>, V extends Comparable<? super V>>
implements Comparable<Pair<K, V>> {
private K k;
private V v;
Pair() {
}
Pair(K k, V v) {
this.k = k;
this.v = v;
}
K getK() {
return k;
}
V getV() {
return v;
}
void setK(K k) {
this.k = k;
}
void setV(V v) {
this.v = v;
}
void setKV(K k, V v) {
this.k = k;
this.v = v;
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || !(o instanceof Pair)) return false;
Pair<K, V> p = (Pair<K, V>) o;
return k.compareTo(p.k) == 0 && v.compareTo(p.v) == 0;
}
@Override
public int hashCode() {
int hash = 31;
hash = hash * 89 + k.hashCode();
hash = hash * 89 + v.hashCode();
return hash;
}
@Override
public int compareTo(Pair<K, V> pair) {
return k.compareTo(pair.k) == 0 ? v.compareTo(pair.v) : k.compareTo(pair.k);
}
@Override
public Pair<K, V> clone() {
return new Pair<K, V>(this.k, this.v);
}
@Override
public String toString() {
return String.valueOf(k).concat(" ").concat(String.valueOf(v)).concat("\n");
}
}
static class Reader {
private BufferedReader br;
private StringTokenizer st;
Reader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
try {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String s = "";
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
}
} | Java | ["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"] | 2 seconds | ["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"] | NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | Java 8 | standard input | [
"two pointers",
"math",
"data structures",
"binary search",
"brute force"
] | da517ae908ba466da8ded87cec12a9fa | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). | 2,000 | Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. | standard output | |
PASSED | e50f6f440ff97d33e80a9be2e14241c0 | train_003.jsonl | 1383379200 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. | 256 megabytes |
import java.io.*;
import java.util.*;
public class D {
static StringBuilder st = new StringBuilder();
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt() ;
int [] a = new int [n] ;
Stack<int []> stack = new Stack<>();
for(int i = 0 ; i < n;i++) a[i] = sc.nextInt();
int [] l = new int [n] , r = new int [n];
for(int i = 0 ; i < n ; i++)
{
while(!stack.isEmpty() && stack.peek()[1] % a[i] == 0)
stack.pop();
int left = 0 ;
if(!stack.isEmpty())
left = stack.peek()[0] + 1 ;
stack.push(new int [] {i , a[i]});
l[i] = left ;
}
stack = new Stack<>();
for(int i = n - 1 ; i >= 0 ; i--)
{
while(!stack.isEmpty() && stack.peek()[1] % a[i] == 0)
stack.pop();
int right = n - 1 ;
if(!stack.isEmpty())
right = stack.peek()[0] - 1;
r[i] = right ;
stack.push(new int [] {i , a[i]});
}
int max = 0 ;
TreeSet<Integer> ans = new TreeSet<>();
for(int i = 0 ; i < n ;i++)
{
if(max < r[i] - l[i])
{
max = r[i] - l[i];
ans = new TreeSet<>();
ans.add(l[i] + 1);
}
else if(max == r[i] - l[i])
ans.add(l[i] + 1);
}
out.println(ans.size()+" "+max);
for(int x : ans)
out.print(x+" ");
out.flush();
out.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(String path) throws Exception {
br = new BufferedReader(new FileReader(path));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
static void shuffle(int[] a) {
int n = a.length;
for (int i = 0; i < n; i++) {
int r = i + (int) (Math.random() * (n - i));
int tmp = a[i];
a[i] = a[r];
a[r] = tmp;
}
}
} | Java | ["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"] | 2 seconds | ["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"] | NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | Java 8 | standard input | [
"two pointers",
"math",
"data structures",
"binary search",
"brute force"
] | da517ae908ba466da8ded87cec12a9fa | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). | 2,000 | Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. | standard output | |
PASSED | 7b40d41a4bc1bc3013bf382cc5ff6e37 | train_003.jsonl | 1383379200 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. | 256 megabytes | import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
import java.util.StringTokenizer;
public class l073 {
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());
int[] a = new int[n];
for(int i=0;i<n;i++) a[i] = Integer.parseInt(stok.nextToken());
HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>();
int[] le = new int[n];
int[] ri = new int[n];
boolean[] vis = new boolean[n];
for(int i=0;i<n-1;i++) {
int c = a[i];
ArrayList<Integer> list = new ArrayList<Integer>();
for(Integer k : mp.keySet()) {
Integer v = mp.get(k);
if(c%k!=0) {
le[v]=i-v-1;
list.add(k);
}
}
for(int v : list) mp.remove(v);
if(mp.get(c)==null) mp.put(c, i);
else vis[i]=true;
}
doStuff(le,a,mp,n-1);
for(int i=n-1;i>0;i--) {
int c = a[i];
ArrayList<Integer> list = new ArrayList<Integer>();
for(Integer k : mp.keySet()) {
Integer v = mp.get(k);
if(c%k!=0) {
ri[v]=v-i-1;
list.add(k);
}
}
for(int v : list) mp.remove(v);
if(!vis[i])
if(mp.get(c)==null) mp.put(c, i);
}
doStuff(ri,a,mp,0);
int[] c = new int[n];
for(int i=0;i<n;i++) {
int v = le[i]+ri[i];
c[i-ri[i]] = Math.max(c[i-ri[i]], v);
}
int max = Arrays.stream(c).max().getAsInt();
int cnt = 0;
for(int i=0;i<n;i++) if(c[i]==max) {
cnt++;
sb.append((i+1)+" ");
}
System.out.println(cnt+" "+max);
System.out.print(sb);
}
private static void doStuff(int[] b, int[] a, HashMap<Integer, Integer> mp, int id) {
int c = a[id];
for(Integer k : mp.keySet()) {
Integer p = mp.get(k);
b[p] = Math.abs(id-p)-((c%k!=0)?1:0);
}
mp.clear();
}
}
| Java | ["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"] | 2 seconds | ["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"] | NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | Java 8 | standard input | [
"two pointers",
"math",
"data structures",
"binary search",
"brute force"
] | da517ae908ba466da8ded87cec12a9fa | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). | 2,000 | Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. | standard output | |
PASSED | 8798d36f3e52c7db2b7457a188e9b331 | train_003.jsonl | 1383379200 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. | 256 megabytes |
import java.io.*;
import java.util.*;
public class B {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt(), a[] = new int[n];
for(int i = 0; i < n; ++i)
a[i] = sc.nextInt();
int[] L = new int[n], R = new int[n];
// compute left bound
Stack<Integer> s = new Stack<>();
for(int i = 0; i < n; ++i)
{
while(!s.isEmpty() && a[s.peek()] % a[i] == 0)
s.pop();
L[i] = s.isEmpty() ? 0 : s.peek() + 1;
s.push(i);
}
// compute right bound
s = new Stack<>();
for(int i = n - 1; i >= 0; --i)
{
while(!s.isEmpty() && a[s.peek()] % a[i] == 0)
s.pop();
R[i] = s.isEmpty() ? n - 1 : s.peek() - 1;
s.push(i);
}
int maxLen = 0;
for(int i = 0; i < n; ++i)
maxLen = Math.max(maxLen, R[i] - L[i]);
TreeSet<Integer> sol = new TreeSet<>();
for(int i = 0; i < n; ++i)
if(R[i] - L[i] == maxLen)
sol.add(L[i] + 1);
out.println(sol.size() + " " + maxLen);
for(int x: sol)
out.print(x + " ");
out.close();
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public Scanner(FileReader s) throws FileNotFoundException { br = new BufferedReader(s);}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException { return Double.parseDouble(next()); }
public boolean ready() throws IOException {return br.ready();}
}
} | Java | ["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"] | 2 seconds | ["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"] | NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | Java 8 | standard input | [
"two pointers",
"math",
"data structures",
"binary search",
"brute force"
] | da517ae908ba466da8ded87cec12a9fa | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). | 2,000 | Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. | standard output | |
PASSED | f3c97fe0eea788e5f9012206928f30a3 | train_003.jsonl | 1383379200 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. | 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;
public class D359
{
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;
}
}
static abstract class SparseTable
{
int n,lg,t[][],dfv;
SparseTable(int a[],int log,int dv)
{
dfv=dv;
n=a.length-1;
t=new int[n+1][log];
lg=log;
for(int i=1;i<=n;i++)
t[i][0]=a[i];
int p2=2;
for(int i=1;i<log;i++)
{
for(int j=1;j+p2-1<=n;j++)
{
t[j][i]=f(t[j][i-1],t[j+(p2>>1)][i-1]);
}
p2*=2;
}
}
abstract int f(int a,int b);
int query(int l,int r)
{
int ans=dfv;
for(int i=lg-1;i>=0;i--)
{
if(l+(1<<i)-1<=r)
{
ans=f(ans,t[l][i]);
l=l+(1<<i);
}
}
if(l==r)
ans=f(ans,t[l][0]);
return ans;
}
}
public static void main(String args[]) throws IOException
{
Scanner in=new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
int n=in.nextInt();
int a[]=in.nextIntArrayOneBased(n);
SparseTable min=new SparseTable(a,19,Integer.MAX_VALUE) {
@Override
int f(int a, int b)
{
return Math.min(a,b);
}
};
SparseTable gcd=new SparseTable(a,19,0) {
@Override
int f(int a, int b)
{
if(b==0)
return a;
return f(b,a%b);
}
};
int ans[]=new int[n+1];
int lo=0,hi=n-1;
while(lo<=hi)
{
int mid=(lo+hi)/2;
boolean d=false;
for(int i=1;i+mid<=n;i++)
{
if(min.query(i, i+mid)==gcd.query(i, i+mid))
{
d=true;
ans[i]=mid;
}
}
if(d)
{
lo=mid+1;
}
else
hi=mid-1;
}
int max=0,cnt=0;
for(int i=1;i<=n;i++)
{
if(ans[i]>max)
{
max=ans[i];
cnt=1;
}
else if(max==ans[i])
cnt++;
}
out.println(cnt+" "+max);
for(int i=1;i<=n;i++)
if(ans[i]==max)
out.print(i+" ");
out.println();
out.close();
}
}
| Java | ["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"] | 2 seconds | ["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"] | NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | Java 8 | standard input | [
"two pointers",
"math",
"data structures",
"binary search",
"brute force"
] | da517ae908ba466da8ded87cec12a9fa | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). | 2,000 | Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. | standard output | |
PASSED | 3e76fd607eb07eb243216370917682e6 | train_003.jsonl | 1383379200 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. | 256 megabytes | import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
public class CODEFORCES_359_D {
public static void main (String[] t) throws IOException {
INPUT in = new INPUT (System.in);
PrintWriter out = new PrintWriter (System.out);
int N = in.iscan ();
int[] arr = new int[N];
PriorityQueue<Pair> q = new PriorityQueue<Pair> ();
for (int n = 0; n < N; ++n) {
arr[n] = in.iscan ();
q.offer (new Pair (n, arr[n]));
}
int cnt = 0, maxlen = 0;
boolean[] done = new boolean[N];
NavigableSet<Integer> idx = new TreeSet<Integer> ();
while (!q.isEmpty ()) {
Pair cur = q.poll ();
if (done[cur.i])
continue;
done[cur.i] = true;
int left = 0, right = 0;
// go left
for (int i = cur.i - 1; i >= 0 && arr[i] % cur.v == 0; --i) {
done[i] = true;
++left;
}
// go right
for (int i = cur.i + 1; i < N && arr[i] % cur.v == 0; ++i) {
done[i] = true;
++right;
}
int curlen = left + 1 + right;
if (curlen > maxlen) {
maxlen = curlen;
cnt = 1;
idx.clear ();
idx.add (cur.i - left + 1);
}
else if (curlen == maxlen) {
++cnt;
idx.add (cur.i - left + 1);
}
}
out.println (cnt + " " + (maxlen - 1));
for (int i : idx)
out.print (i + " ");
out.close ();
}
private static class Pair implements Comparable<Pair> {
int i, v;
public int compareTo (Pair p) {
if (Integer.compare (this.v, p.v) != 0)
return Integer.compare (this.v, p.v);
return Integer.compare (this.i, p.i);
}
public Pair (int i, int v) {
this.i = i;
this.v = v;
}
}
private static class INPUT {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public INPUT (InputStream stream) {
this.stream = stream;
}
public INPUT (String file) throws IOException {
this.stream = new FileInputStream (file);
}
public int cscan () throws IOException {
if (curChar >= numChars) {
curChar = 0;
numChars = stream.read (buf);
}
if (numChars == -1)
return numChars;
return buf[curChar++];
}
public int iscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
int res = 0;
do {
res = (res << 1) + (res << 3);
res += c - '0';
c = cscan ();
}
while (!space (c));
return res * sgn;
}
public String sscan () throws IOException {
int c = cscan ();
while (space (c))
c = cscan ();
StringBuilder res = new StringBuilder ();
do {
res.appendCodePoint (c);
c = cscan ();
}
while (!space (c));
return res.toString ();
}
public double dscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
double res = 0;
while (!space (c) && c != '.') {
if (c == 'e' || c == 'E')
return res * UTILITIES.fast_pow (10, iscan ());
res *= 10;
res += c - '0';
c = cscan ();
}
if (c == '.') {
c = cscan ();
double m = 1;
while (!space (c)) {
if (c == 'e' || c == 'E')
return res * UTILITIES.fast_pow (10, iscan ());
m /= 10;
res += (c - '0') * m;
c = cscan ();
}
}
return res * sgn;
}
public long lscan () throws IOException {
int c = cscan (), sgn = 1;
while (space (c))
c = cscan ();
if (c == '-') {
sgn = -1;
c = cscan ();
}
long res = 0;
do {
res = (res << 1) + (res << 3);
res += c - '0';
c = cscan ();
}
while (!space (c));
return res * sgn;
}
public boolean space (int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
public static class UTILITIES {
static final double EPS = 10e-6;
public static int lower_bound (int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] >= x)
high = mid;
else
low = mid + 1;
}
return low;
}
public static int upper_bound (int[] arr, int x) {
int low = 0, high = arr.length, mid = -1;
while (low < high) {
mid = (low + high) / 2;
if (arr[mid] > x)
high = mid;
else
low = mid + 1;
}
return low;
}
public static int gcd (int a, int b) {
return b == 0 ? a : gcd (b, a % b);
}
public static int lcm (int a, int b) {
return a * b / gcd (a, b);
}
public static int fast_pow_mod (int b, int x, int mod) {
if (x == 0) return 1;
if (x == 1) return b;
if (x % 2 == 0) return fast_pow_mod (b * b % mod, x / 2, mod) % mod;
return b * fast_pow_mod (b * b % mod, x / 2, mod) % mod;
}
public static int fast_pow (int b, int x) {
if (x == 0) return 1;
if (x == 1) return b;
if (x % 2 == 0) return fast_pow (b * b, x / 2);
return b * fast_pow (b * b, x / 2);
}
public static long choose (long n, long k) {
k = Math.min (k, n - k);
long val = 1;
for (int i = 0; i < k; ++i)
val = val * (n - i) / (i + 1);
return val;
}
public static long permute (int n, int k) {
if (n < k) return 0;
long val = 1;
for (int i = 0; i < k; ++i)
val = (val * (n - i));
return val;
}
}
} | Java | ["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"] | 2 seconds | ["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"] | NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | Java 8 | standard input | [
"two pointers",
"math",
"data structures",
"binary search",
"brute force"
] | da517ae908ba466da8ded87cec12a9fa | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). | 2,000 | Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. | standard output | |
PASSED | e47d06e2d29d980530c15cd88a581ea3 | train_003.jsonl | 1383379200 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. | 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 class sparse
{
int n;
int[][] table;
int lgn;
Combiner ho;
sparse(int[]a, Combiner c)
{
ho=c;
build(a);
}
void build(int[]a)
{
int te=a.length;
n=a.length;
while(te>0)
{
lgn++;
te>>=1;
}
table=new int[1+lgn][n];
for(int i=0; i<n; i++)
table[0][i]=a[i];
for(int j=1; j<=lgn; j++)
for(int i=0; i+(1<<(j-1))<n; i++)
table[j][i]=ho.combine(table[j-1][i], table[j-1][i+(1<<(j-1))]);
}
int query(int l, int r)
{
int len=r-l+1;
int te=len;
int k=0;
while(te>0)
{
te>>=1;
k++;
}
k--;
return ho.combine(table[k][l],table[k][r+1-(1<<k)]);
}
}
public static void main(String[] args)
{
int n=ni();
int[]a=nia(n);
sparse gcd=new sparse(a, new Combiner()
{
public int combine(int a,int b)
{
return gcd(a,b);
}
});
int max=0;
SortedSet<Integer> ans=new TreeSet<Integer>();
for(int i=0; i<n; i++)
{
int low=i,high=n-1,mid=(low+high+1)/2;
while(low<high)
{
if(gcd.query(i,mid)!=a[i])
high=mid-1;
else
low=mid;
mid=(low+high+1)/2;
}
low=0;
high=i;
int mid1=(low+high)/2;
while(low<high)
{
if(gcd.query(mid1,i)!=a[i])
low=mid1+1;
else
high=mid1;
mid1=(low+high)/2;
}
if((mid-mid1)>max)
{
max=mid-mid1;
ans.clear();;
ans.add(mid1);
}
else if(mid-mid1==max)
ans.add(mid1);
}
pr(ans.size()+" "+(max));
for(int i:ans)
pr(i+1);
System.out.print(output);
}
///////////////////////////////////////////
///////////////////////////////////////////
///template from here
static interface Combiner
{
public int combine(int a, int b);
}
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();
public static void sort(int[]a)
{
int te;
for(int i=0; i<a.length; i++)
{
te=rn.nextInt(a.length);
if(i!=te)
{
a[i]^=a[te];
a[te]^=a[i];
a[i]^=a[te];
}
}
Arrays.sort(a);
}
public static void sort(long[]a)
{
int te;
for(int i=0; i<a.length; i++)
{
te=rn.nextInt(a.length);
if(i!=te)
{
a[i]^=a[te];
a[te]^=a[i];
a[i]^=a[te];
}
}
Arrays.sort(a);
}public static void sort(double[]a)
{
int te;
double te1;
for(int i=0; i<a.length; i++)
{
te=rn.nextInt(a.length);
if(i!=te)
{
te1=a[te];
a[te]=a[i];
a[i]=te1;
}
}
Arrays.sort(a);
}
public static void sort(int[][]a)
{
Arrays.sort(a, new Comparator<int[]>()
{
public int compare(int[]a,int[]b)
{
if(a[0]>b[0])
return 1;
if(b[0]>a[0])
return -1;
return 0;
}
});
}
static int lowerbound(int[]a, int key)
{
/*
* returns index of smallest element larger than equal to given element between indices l and r inclusive
*/
int low=0,high=a.length-1,mid=(low+high)/2;
while(low<high)
{
if(a[mid] >= key)
high=mid;
else
low=mid+1;
mid=(low+high)/2;
}
return mid;
}
static int upperbound(int[]a, int key)
{
/*
* returns index of largest element smaller than equal to given element
*/
int low=0,high=a.length-1,mid=(low+high+1)/2;
while(low<high)
{
if(a[mid] <= key)
low=mid;
else
high=mid-1;
mid=(low+high+1)/2;
}
return mid;
}
static int lowerbound(int[]a, int l, int r, int key)
{
/*
* returns index of smallest element larger than equal to given element between indices l and r inclusive
*/
int low=l,high=r,mid=(low+high)/2;
while(low<high)
{
if(a[mid] >= key)
high=mid;
else
low=mid+1;
mid=(low+high)/2;
}
return mid;
}
static int upperbound(int[]a, int l, int r, int key)
{
/*
* returns index of largest element smaller than equal to given element
*/
int low=l,high=r,mid=(low+high+1)/2;
while(low<high)
{
if(a[mid] <= key)
low=mid;
else
high=mid-1;
mid=(low+high+1)/2;
}
return mid;
}
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 zin=0;
iter(vecti b)
{
a=b;
}
public boolean hasNext()
{
if(a.size>zin)
return true;
return false;
}
public int next()
{
return a.a[zin++];
}
public void previous()
{
zin--;
}
}
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);
}
}
//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 | ["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"] | 2 seconds | ["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"] | NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | Java 8 | standard input | [
"two pointers",
"math",
"data structures",
"binary search",
"brute force"
] | da517ae908ba466da8ded87cec12a9fa | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). | 2,000 | Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. | standard output | |
PASSED | 6a1e1b2965b8f1de92a1647a572bdfcc | train_003.jsonl | 1383379200 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. | 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.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Comparator;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author MottoX
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(1, in, out);
out.close();
}
static class Task {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
SparseTable<Integer> minTable = new SparseTable<>(a);
SparseTable gcdTable = new SparseTable(a) {
protected Comparable pick(Comparable a, Comparable b) {
return MathUtils.gcd((int) a, (int) b);
}
};
int l = 0, r = n - 1, length = 0;
while (l <= r) {
int mid = l + r >>> 1;
boolean okay = false;
for (int i = 0; i + mid < n && !okay; i++) {
int x = minTable.query(i, i + mid);
int y = (int) gcdTable.query(i, i + mid);
if (x == y) {
okay = true;
}
}
if (okay) {
length = mid;
l = mid + 1;
} else {
r = mid - 1;
}
}
List<Integer> indices = new ArrayList<>();
for (int i = 0; i + length < n; i++) {
int x = minTable.query(i, i + length);
int y = (int) gcdTable.query(i, i + length);
if (x == y) {
indices.add(i + 1);
}
}
out.println(indices.size() + " " + length);
indices.forEach(out::println);
}
}
static class InputReader {
private final 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 {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
static class SparseTable<E extends Comparable<? super E>> {
private final Comparator<? super E> comparator;
private final E[] data;
private final Object[][] dp;
private final int[] logTable;
public SparseTable(E[] data) {
this(data, Comparator.naturalOrder());
}
public SparseTable(E[] data, Comparator<? super E> comparator) {
this.data = data;
this.comparator = comparator;
int n = data.length;
logTable = new int[n + 1];
for (int i = 2; i <= n; i++) {
logTable[i] = logTable[i >>> 1] + 1;
}
dp = new Object[n][logTable[n] + 1];
calc(n);
}
protected E pick(E a, E b) {
return comparator.compare(a, b) <= 0 ? a : b;
}
@SuppressWarnings("unchecked")
private void calc(int n) {
for (int i = 0; i < n; i++) {
dp[i][0] = data[i];
}
for (int i = n - 1; i >= 0; i--) {
dp[i][0] = data[i];
for (int j = 1; i + (1 << j) <= n; j++) {
dp[i][j] = pick((E) dp[i][j - 1], (E) dp[i + (1 << j - 1)][j - 1]);
}
}
}
@SuppressWarnings("unchecked")
public E query(int l, int r) {
if (l > r) {
int t = r;
r = l;
l = t;
}
int k = logTable[r - l + 1];
return pick((E) dp[l][k], (E) dp[r - (1 << k) + 1][k]);
}
}
static final class MathUtils {
private MathUtils() {
}
public static int gcd(int x, int y) {
return y == 0 ? x : gcd(y, x % y);
}
}
}
| Java | ["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"] | 2 seconds | ["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"] | NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | Java 8 | standard input | [
"two pointers",
"math",
"data structures",
"binary search",
"brute force"
] | da517ae908ba466da8ded87cec12a9fa | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). | 2,000 | Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. | standard output | |
PASSED | 6c07064b69617dbf09da880fe70ee23e | train_003.jsonl | 1383379200 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. | 256 megabytes | //package pairofno;
import java.util.*;
import java.io.*;
public class Pairofno
{
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 class pair{
int m,id;pair(int a,int b){m=a;id=b;}
}
public static void main(String[] args) throws IOException
{
Reader in=new Reader();PrintWriter out=new PrintWriter(System.out);
int n=in.nextInt();int b[]=new int[n];
pair a[]=new pair[n];for(int i=0;i<n;i++)a[i]=new pair(b[i]=in.nextInt(),i);
Arrays.sort(a,new Comparator<pair>(){
public int compare(pair p1,pair p2){
return p1.m-p2.m;
}
});
ArrayList<Integer> al=new ArrayList<>();int max=0,cnt=0;
boolean inc[]=new boolean[n];
for(int i=0;i<n;i++){
if(inc[a[i].id])continue;
int l=a[i].id,r=a[i].id,j=0;
for(j=a[i].id;j>=0;j--){if(b[j]%a[i].m!=0)break;inc[j]=true;}
l=j+1;
for(j=a[i].id;j<n;j++){if(b[j]%a[i].m!=0)break;inc[j]=true;}
r=j-1;
if(r-l>max){
max=r-l;cnt=1;al.clear();al.add(l+1);
}else if(r-l==max){cnt++;al.add(l+1);}
}
out.println(cnt+" "+max);Collections.sort(al);
for(int i=0;i<al.size();i++)out.print(al.get(i)+" ");
out.flush();out.close();
}
} | Java | ["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"] | 2 seconds | ["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"] | NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | Java 8 | standard input | [
"two pointers",
"math",
"data structures",
"binary search",
"brute force"
] | da517ae908ba466da8ded87cec12a9fa | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). | 2,000 | Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. | standard output | |
PASSED | 7826916b1a97e9a1497e1039dc020307 | train_003.jsonl | 1383379200 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. | 256 megabytes | //package CF;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class A {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt(), a[] = new int[n], res[] = new int[n];
for (int i = 0; i < a.length; i++) {
a[i] = sc.nextInt();
}
int ans = 0, cnt = 0;
for (int i = 0; i < a.length; i++) {
int l = i-1, r = i+1;
while(l >= 0 && a[l] % a[i] == 0) l--;
while(r < n && a[r] % a[i] == 0) r++;
l++;
r--;
if(l < 0) l = 0;
if(r >= n) r = n-1;
int len = r - l;
if (ans < len) {
ans = len;
cnt = 0;
}
if (ans == len) {
res[cnt++] = l;
}
i = r;
}
out.println(cnt + " " + ans);
for (int j = 0; j < cnt; j++) {
out.print(res[j] + 1 + " ");
}
out.flush();
out.close();
}
static class Scanner {
BufferedReader bf;
StringTokenizer st;
public Scanner(InputStream i) {
bf = new BufferedReader(new InputStreamReader(i));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(bf.readLine());
return st.nextToken();
}
public int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(next());
}
public long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
}
} | Java | ["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"] | 2 seconds | ["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"] | NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | Java 8 | standard input | [
"two pointers",
"math",
"data structures",
"binary search",
"brute force"
] | da517ae908ba466da8ded87cec12a9fa | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). | 2,000 | Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. | standard output | |
PASSED | 841e3e4d6a8caa77df5fd3376a2e4188 | train_003.jsonl | 1383379200 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. | 256 megabytes | //package CF;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class A {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt(), a[] = new int[n], l[] = new int[n];
Stack<Integer> st = new Stack<>();
for (int i = 0; i < a.length; i++) {
a[i] = sc.nextInt();
while (!st.isEmpty() && a[st.peek()] % a[i] == 0)
st.pop();
l[i] = st.isEmpty() ? -1 : st.peek();
l[i]++;
st.push(i);
}
int ans = 0;
TreeSet<Integer> set = new TreeSet<>();
st = new Stack<>();
for (int i = n - 1; i >= 0; i--) {
while (!st.isEmpty() && a[st.peek()] % a[i] == 0)
st.pop();
int r = st.isEmpty() ? n : st.peek();
r--;
st.push(i);
int len = r - l[i];
if (ans < len) {
ans = len;
set = new TreeSet<>();
}
if (ans == len) {
set.add(l[i]);
}
}
out.println(set.size() + " " + ans);
for (int i:set) {
out.print(i+1 + " ");
}
out.flush();
out.close();
}
static class Scanner {
BufferedReader bf;
StringTokenizer st;
public Scanner(InputStream i) {
bf = new BufferedReader(new InputStreamReader(i));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(bf.readLine());
return st.nextToken();
}
public int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(next());
}
public long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
}
} | Java | ["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"] | 2 seconds | ["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"] | NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | Java 8 | standard input | [
"two pointers",
"math",
"data structures",
"binary search",
"brute force"
] | da517ae908ba466da8ded87cec12a9fa | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). | 2,000 | Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. | standard output | |
PASSED | 15db9e1b9f78d10f2cd9eb573c4a761a | train_003.jsonl | 1383379200 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. | 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.InputMismatchException;
import java.util.PriorityQueue;
import java.util.TreeMap;
import java.util.TreeSet;
public class Solution1 implements Runnable
{
static final long MAX = 464897L;
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception
{
new Thread(null, new Solution1(),"Solution",1<<26).start();
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
long MOD = 1000000007;
ArrayList<Integer> adj[];
public void run()
{
//InputReader sc= new InputReader(new FileInputStream("input.txt"));
//PrintWriter w= new PrintWriter(new FileWriter("output.txt"));
InputReader sc = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n = sc.nextInt();
int[] arr= new int[n];
for(int i = 0;i < n;i++) {
arr[i] = sc.nextInt();
}
sparse = new Pair[n][32];
build(arr,n);
int l = 0;
int r = n-1;
int ans = -1;
while(l <= r) {
int mid = (l + r)/2;
if(fun(mid,n,arr)) {
ans = mid;
l = mid + 1;
}else {
r = mid - 1;
}
}
add(ans,n);
w.println(ar.size() + " " + ans);
for(int i = 0;i < ar.size();i++) {
w.print((ar.get(i)+1) + " ");
}
w.close();
}
void add(int mid,int n) {
ar = new ArrayList();
for(int i = 0;i < n;i++) {
if(i + mid == n) {
break;
}else {
Pair both = query(i,i+mid);
if(both.a == both.b) {
ar.add(i);
}
}
}
}
boolean fun(int mid,int n,int[] arr) {
//int count = 0;
//temp = new ArrayList();
for(int i = 0;i < n;i++) {
if(i + mid == n) {
break;
}else {
Pair both = query(i,i+mid);
if(both.a == both.b) {
return true;
}
}
}
return false;
}
ArrayList<Integer> ar = new ArrayList();
//ArrayList<Integer> temp = new ArrayList();
Pair sparse[][];
void build(int arr[],int n) {
for(int i = 0;i < n;i++) {
sparse[i][0] = new Pair(arr[i],arr[i]);
}
for(int j = 1;(1 << j) <= n;j++) {
for(int i = 0;(i + (1 << j) - 1) < n;i++) {
Pair p1 = sparse[i][j-1];
Pair p2 = sparse[i + (1 << (j-1))][j-1];
sparse[i][j] = merge(p1,p2);
}
}
}
Pair query(int l,int r) {
int j = 31 - Integer.numberOfLeadingZeros(r-l+1);
Pair p1 = sparse[l][j];
Pair p2 = sparse[r - (1 << j ) + 1][j];
return merge(p1,p2);
}
Pair merge(Pair p1,Pair p2) {
return new Pair(gcd(p1.a,p2.a),Math.min(p1.b,p2.b));
}
class Pair implements Comparable<Pair>{
int a;
int b;
//int c;
Pair(int a,int b){
this.b = b;
this.a = a;
}
public boolean equals(Object o) {
Pair p = (Pair)o;
return this.a == p.a;
}
public int hashCode(){
return Long.hashCode(a)*27 + Long.hashCode(b)* 31;
}
public int compareTo(Pair p) {
if(this.b == p.b) {
return Integer.compare(this.a,p.a);
}
return Integer.compare(p.b,this.b);
}
}
} | Java | ["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"] | 2 seconds | ["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"] | NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | Java 8 | standard input | [
"two pointers",
"math",
"data structures",
"binary search",
"brute force"
] | da517ae908ba466da8ded87cec12a9fa | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). | 2,000 | Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. | standard output | |
PASSED | 5cd3ff2c993dd1e0d5f8d41c8fae6f53 | train_003.jsonl | 1383379200 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
FastScanner in;
PrintWriter out;
static final String FILE = "";
int gcd(int a, int b) {
int c;
while (a != 0) {
c = a;
a = b % a;
b = c;
}
return b;
}
public class RmqSparseTable {
int[] logTable;
int[][] rmq;
int[] a;
public RmqSparseTable(int[] a) {
this.a = a;
int n = a.length;
logTable = new int[n + 1];
for (int i = 2; i <= n; i++)
logTable[i] = logTable[i >> 1] + 1;
rmq = new int[logTable[n] + 1][n];
for (int i = 0; i < n; ++i)
rmq[0][i] = a[i];
for (int k = 1; (1 << k) < n; ++k) {
for (int i = 0; i + (1 << k) <= n; i++) {
int x = rmq[k - 1][i];
int y = rmq[k - 1][i + (1 << k - 1)];
rmq[k][i] = gcd(x, y);
}
}
}
public int query(int i, int j) {
int k = logTable[j - i];
int x = rmq[k][i];
int y = rmq[k][j - (1 << k) + 1];
return gcd(x, y);
}
}
int n;
int ms[];
int left[], right[];
RmqSparseTable table;
void calcLeft(int v) {
int a = 0, b = v;
while (a != b) {
int la = a, lb = b;
int mid = (a + b) / 2;
if(table.query(mid, v) == ms[v])
b = mid;
else
a = mid;
if(la == a && lb == b) {
if(table.query(a, v) == ms[v])
b = a;
else
a = b;
}
}
left[v] = a;
}
void calcRight(int v) {
int a = v, b = n - 1;
while (a != b) {
int la = a, lb = b;
int mid = (a + b) / 2;
if(table.query(v, mid) == ms[v])
a = mid;
else
b = mid;
if(la == a && lb == b) {
if(table.query(v, b) == ms[v])
a = b;
else
b = a;
}
}
right[v] = a;
}
public void solve() {
n = in.nextInt();
ms = new int[n];
left = new int[n];
right = new int[n];
for (int i = 0; i < n; i++)
ms[i] = in.nextInt();
table = new RmqSparseTable(ms);
for (int i = 0; i < n; i++)
calcLeft(i);
for (int i = 0; i < n; i++)
calcRight(i);
TreeSet<Integer> set = new TreeSet<Integer>();
int max = 0;
for(int i = 0; i < n; i++) {
int curr = right[i] - left[i];
if(curr > max) {
set.clear();
set.add(left[i]);
max = curr;
} else if(curr == max) {
set.add(left[i]);
}
}
out.println(set.size() + " " + max);
for (Integer it : set)
out.print((it + 1) + " ");
}
public void run() {
try {
if(FILE.isEmpty()) {
in = new FastScanner(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
} else {
in = new FastScanner(new File(FILE + ".in"));
out = new PrintWriter(new File(FILE + ".out"));
}
solve();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (Exception e) {
e.printStackTrace();
}
}
FastScanner(InputStreamReader rd) {
br = new BufferedReader(rd);
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
class Pair<U extends Comparable<U>, V extends Comparable<V>> implements Comparable<Pair<U, V>> {
U u;
V v;
public Pair(U u, V v) {
this.u = u;
this.v = v;
}
public int hashCode() {
return (u == null ? 0 : u.hashCode() * 31) + (v == null ? 0 : v.hashCode());
}
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Pair<U, V> p = (Pair<U, V>) o;
return (u == null ? p.u == null : u.equals(p.u)) && (v == null ? p.v == null : v.equals(p.v));
}
public int compareTo(Pair<U, V> b) {
int cmpU = u.compareTo(b.u);
return cmpU != 0 ? cmpU : v.compareTo(b.v);
}
}
public static void main(String[] args) {
new Main().run();
}
}
| Java | ["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"] | 2 seconds | ["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"] | NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | Java 8 | standard input | [
"two pointers",
"math",
"data structures",
"binary search",
"brute force"
] | da517ae908ba466da8ded87cec12a9fa | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). | 2,000 | Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. | standard output | |
PASSED | 5199aae5500c42044ae3108e849a76e9 | train_003.jsonl | 1383379200 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.TreeSet;
public final class _209D_PairofNumbers {
public static int left(int arr[], int idx) {
int count = 0;
for (int i = idx; i >= 0 && arr[i] % arr[idx] == 0; i -= 1) {
count += 1;
}
return count;
}
public static int right(int arr[], int idx) {
int count = 0;
for (int i = idx + 1; i < arr.length && arr[i] % arr[idx] == 0; i += 1) {
count += 1;
}
return count;
}
public static void main(String ar[]) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(input.readLine());
StringTokenizer a = new StringTokenizer(input.readLine());
int arr[] = new int[n];
for (int i = 0; i < n; i += 1) {
arr[i] = Integer.parseInt(a.nextToken());
}
int l[] = new int[n];
int r[] = new int[n];
int max = Integer.MIN_VALUE;
for (int i = 0; i < n; i += 1) {
l[i] = left(arr, i);
r[i] = right(arr, i);
max = Math.max(max, l[i] + r[i]);
i = i + r[i];
}
TreeSet<Integer> idx = new TreeSet<>();
for (int i = 0; i < n; i += 1) {
if (l[i] + r[i] == max) {
idx.add(i - l[i] + 2);
}
}
max -= 1;
System.out.println(idx.size() + " " + max);
for (int val : idx) {
System.out.print(val + " ");
}
System.out.println();
}
}
| Java | ["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"] | 2 seconds | ["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"] | NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | Java 8 | standard input | [
"two pointers",
"math",
"data structures",
"binary search",
"brute force"
] | da517ae908ba466da8ded87cec12a9fa | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). | 2,000 | Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. | standard output | |
PASSED | 36cfc1be9d31d56ce1a95efeb6229245 | train_003.jsonl | 1383379200 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Arthur Gazizov - Kazan FU #4.3 [2oo7]
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
TaskD.sparseTable sparseTable;
int[] a;
int n;
boolean f(int length) {
for (int left = 0; left < a.length - length; left++) {
int right = left + length + 1;
int min = sparseTable.getMin(left, right);
int gcd = sparseTable.getGCD(left, right);
if (min == gcd) {
return true;
}
}
return false;
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.nextInt();
a = IOUtils.readIntArray(in, n);
sparseTable = new TaskD.sparseTable(a);
int left = 1;
int right = a.length;
while (right - left > 1) {
int middle = (right + left) / 2;
if (f(middle)) {
left = middle;
} else {
right = middle;
}
}
while (!f(right)) right--;
int length = right;
int count = 0;
StringBuilder builder = new StringBuilder();
for (int i = 0; i < a.length - length; i++) {
int min = sparseTable.getMin(i, i + length + 1);
int gcd = sparseTable.getGCD(i, i + length + 1);
if (min == gcd) {
count++;
builder.append(i + 1)
.append(' ');
}
}
out.prints(count)
.printLine(length);
out.print(builder.toString());
}
static class sparseTable {
private int[][] a;
private int[][] b;
private int[] deg;
public sparseTable(int[] array) {
int n = array.length;
int log = 1;
while ((1 << (log - 1)) < n) {
log++;
}
a = new int[log][];
b = new int[log][];
a[0] = array.clone();
b[0] = array.clone();
for (int i = 1; i < log; i++) {
int halfLen = 1 << (i - 1);
a[i] = new int[n];
b[i] = new int[n];
for (int j = 0; j + halfLen < a[i].length; j++) {
a[i][j] = Math.min(a[i - 1][j], a[i - 1][j + halfLen]);
b[i][j] = IntegerUtils.gcd(b[i - 1][j], b[i - 1][j + halfLen]);
}
}
deg = new int[n + 1];
for (int i = 2; i <= n; i++) {
deg[i] = 1 + deg[i >> 1];
}
}
public int getMin(int left, int right) {
int i = deg[right - left];
return Math.min(a[i][left], a[i][right - (1 << i)]);
}
public int getGCD(int left, int right) {
int i = deg[right - left];
return IntegerUtils.gcd(b[i][left], b[i][right - (1 << i)]);
}
}
}
static class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++) {
array[i] = in.nextInt();
}
return array;
}
}
static class IntegerUtils {
public static int gcd(int a, int b) {
a = Math.abs(a);
b = Math.abs(b);
while (b != 0) {
int temp = a % b;
a = b;
b = temp;
}
return a;
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(objects[i]);
}
}
public void close() {
writer.close();
}
public OutputWriter prints(int i) {
writer.print(i);
writer.print(' ');
return this;
}
public void printLine(int i) {
writer.println(i);
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"] | 2 seconds | ["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"] | NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | Java 8 | standard input | [
"two pointers",
"math",
"data structures",
"binary search",
"brute force"
] | da517ae908ba466da8ded87cec12a9fa | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). | 2,000 | Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. | standard output | |
PASSED | 0d51c0f544546f1bcaabc4fa0f47a2f3 | train_003.jsonl | 1383379200 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. | 256 megabytes | import java.util.*;
public class HelloWorld {
static class Pair{
int v;
int indx;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
int[] ind = new int[n];
HashMap<Integer, ArrayList<Integer>> resultMap = new HashMap<Integer, ArrayList<Integer>>();
ArrayList<Pair> pairs = new ArrayList<>();
ArrayList<Integer> temp = new ArrayList<>();
for(int i = 0; i<n;i++)
{
arr[i] = sc.nextInt();
Pair p = new Pair();
pairs.add(p);
p.v = arr[i];
p.indx = i;
}
Collections.sort(pairs, new Comparator<Pair>() {
@Override
public int compare(Pair o1, Pair o2) {
return Integer.compare(o1.v, o2.v);
}
});
int maxLen = 0;
for(Pair p: pairs){
int j = p.indx;
if(ind[j] == 1)
continue;
int l = j-1;
int r = j+1;
ind[j] = 1;
while(r<n){
if(arr[r]%arr[j] == 0){
ind[r] = 1;
} else {
break;
}
r++;
}
while(l>=0){
if(arr[l]%arr[j] == 0){
ind[l] = 1;
} else {
break;
}
l--;
}
l++;
r--;
int len = r-l;
temp = resultMap.get(len);
if(temp == null){
temp = new ArrayList<>();
resultMap.put(len,temp);
}
temp.add(l);
maxLen = Math.max(maxLen,len);
}
temp = resultMap.get(maxLen);
Collections.sort(temp);
System.out.println(temp.size()+" "+ maxLen);
for(int i: temp){
System.out.print(i+1+" ");
}
System.out.println();
}
}
| Java | ["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"] | 2 seconds | ["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"] | NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | Java 8 | standard input | [
"two pointers",
"math",
"data structures",
"binary search",
"brute force"
] | da517ae908ba466da8ded87cec12a9fa | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). | 2,000 | Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. | standard output | |
PASSED | fe1c6b081a4408558a99266bab2a98e8 | train_003.jsonl | 1383379200 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static int mod=(int)1e9+7;
public static void main(String[] args) throws Exception {
FastReader sc = new FastReader();
StringBuilder sb=new StringBuilder();
int n = sc.nextInt();
int[] arr = new int[n + 1];
for (int i = 1; i <= n; i++)arr[i] = sc.nextInt();
int l, r, p = 0, max = -1;
int[] ans = new int[n];
for(int i = 1; i <= n;) {
l = r = i;
while(l > 1 && arr[l - 1] % arr[i] == 0) l--;
while(r < n && arr[r + 1] % arr[i] == 0) r++;
i = r + 1;
r -= l;
if(r > max) {
p = 0;
max = r;
}
if(r == max) {
ans[p++] = l;
}
}
sb.append(p+" "+max+"\n");
for(int i=0;i<p;i++)sb.append(ans[i]+" ");
System.out.println(sb);
}
}
class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
| Java | ["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"] | 2 seconds | ["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"] | NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | Java 8 | standard input | [
"two pointers",
"math",
"data structures",
"binary search",
"brute force"
] | da517ae908ba466da8ded87cec12a9fa | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). | 2,000 | Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. | standard output | |
PASSED | 17142690fb274735df60945ffca61791 | train_003.jsonl | 1383379200 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. | 256 megabytes | import java.util.*;
import java.io.*;
/*NO RESPECT*/
public class Main implements Runnable {
static boolean showTime = false;
public int gcd(int m, int n){
if(n == 0)
return m;
else
return gcd(n, m % n);
}
private int getGcd(int[][] gcd, int l, int r){
int size = r - l + 1;
int x = 1;
int k = 0;
while(x * 2 <= size){
x = x * 2; k++;
}
return gcd(gcd[k][l], gcd[k][r - x + 1]);
}
public void solve() throws IOException {
int n = nextInt();
int[] a = new int[n];
for(int i = 0; i < n; i++) a[i] = nextInt();
final int MAX = 20;
int[][] gcd = new int[MAX][n] ;
for(int i = 0; i < n; i++) gcd[0][i] = a[i];
//sparse table
for(int i = 1; i < MAX; i++){
for(int j = 0; j < n; j++){
int next = j + (1 << (i-1));
if(next >= n){
gcd[i][j] = gcd[i-1][j];
}
else{
gcd[i][j] = gcd(gcd[i-1][j], gcd[i-1][next]);
}
}
}
ArrayList<Integer> answer = new ArrayList<>();
int best = -1;
int[] left = new int[n];
int[] right = new int[n];
for(int i = 0; i < n; i++){
left[i] = i;
right[i] = i;
int l = i, r = n - 1;
while(l <= r){
int m = (l + r) >> 1;
if(getGcd(gcd, i, m) == a[i]){
right[i] = m;
l = m + 1;
}
else{
r = m - 1;
}
}
l = 0;
r = i;
while(l <= r){
int m = (l + r) >> 1;
if(getGcd(gcd, m, i) == a[i]){
left[i] = m;
r = m - 1;
}
else{
l = m + 1;
}
}
if(right[i] - left[i] > best){
best = right[i] - left[i];
answer.clear();
answer.add(left[i] + 1);
}
else if(right[i] - left[i] == best){
answer.add(left[i] + 1);
}
}
Set<Integer> set = new TreeSet<>();
for(int i : answer) set.add(i);
answer.clear();
for(int i : set) answer.add(i);
out.println(answer.size() + " " + best);
for(int i = 0; i < answer.size(); i++){
if(i > 0) out.print(" ");
out.print(answer.get(i));
}
out.println();
}
//-----------------------------------------------------------
public static void main(String[] args) {
new Main().run();
}
public void debug(Object... arr){
System.out.println(Arrays.deepToString(arr));
}
public void print1Int(int[] a){
for(int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
System.out.println();
}
public void print2Int(int[][] a){
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[0].length; j++){
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
tok = null;
long start = System.currentTimeMillis();
solve();
long end = System.currentTimeMillis();
if(showTime)System.err.println( (end - start) / 1000.0);
in.close();
out.close();
} catch (IOException e) {
System.exit(0);
}
}
public String nextToken() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
PrintWriter out;
BufferedReader in;
StringTokenizer tok;
} | Java | ["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"] | 2 seconds | ["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"] | NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | Java 8 | standard input | [
"two pointers",
"math",
"data structures",
"binary search",
"brute force"
] | da517ae908ba466da8ded87cec12a9fa | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). | 2,000 | Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. | standard output | |
PASSED | a1c36fd343c659c71318ef76b48ab645 | train_003.jsonl | 1383379200 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class main_java {
public static void main(String[] args) {
InputStream inputStream = System.in;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(System.out);
int k = 20;
int n = in.readInt();
int a[] = new int[n];
for(int i = 0; i < n; i ++)
a[i] = in.readInt();
int lf = 1;
int rg = n + 1;
int tg[][] = new int [n][k];
int tm[][] = new int [n][k];
for(int i = 0; i < n; i++){
Arrays.fill(tg[i], -1);
Arrays.fill(tm[i], Integer.MAX_VALUE);
}
for(int j = 0; j < k; j++) {
if (j == 0){
for(int i = 0; i < n; i++) {
tm[i][j] = a[i];
tg[i][j] = a[i];
}
continue;
}
for(int i = 0; i < n; i++) {
if (tg[i][j - 1] == -1) continue;
int tv = i + (1 << (j - 1));
if (tv >= n) continue;
if (tg[tv][j - 1] == -1) continue;
tg[i][j] = gcd(tg[i][j - 1], tg[tv][j - 1]);
tm[i][j] = Math.min(tm[i][j - 1], tm[tv][j - 1]);
}
}
while (rg - lf > 1){
int mid = (lf + rg) >> 1;
boolean ok = false;
int power = 0;
while ((1 << power) <= mid)
power++;
power--;
for(int i = 0; (i <= n - mid) && !ok; i++){
int g = tg[i][power];
int b = i + mid - 1;
g = gcd(tg[b - (1 << power) + 1][power], g);
g -= Math.min(tm[i][power], tm[b - (1 << power) + 1][power]);
if (g == 0)
ok = true;
}
if (ok)
lf = mid;
else
rg = mid;
}
int power = 0;
while ((1 << power) <= lf)
power++;
power--;
int anscnt = 0;
for(int i = 0; (i <= n - lf); i++){
int g = tg[i][power];
int b = i + lf - 1;
g = gcd(tg[b - (1 << power) + 1][power], g);
g -= Math.min(tm[i][power], tm[b - (1 << power) + 1][power]);
if (g == 0) {
anscnt ++;
}
}
out.println(anscnt + " " + (lf - 1));
for(int i = 0; (i <= n - lf); i++){
int g = tg[i][power];
int b = i + lf - 1;
g = gcd(tg[b - (1 << power) + 1][power], g);
g -= Math.min(tm[i][power], tm[b - (1 << power) + 1][power]);
if (g == 0) {
out.print(i + 1 + " ");
}
}
out.close();
}
static int gcd(int a, int b){
if (a == 0)
return b;
return gcd(b % a, a);
}
}
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);
}
} | Java | ["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"] | 2 seconds | ["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"] | NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | Java 8 | standard input | [
"two pointers",
"math",
"data structures",
"binary search",
"brute force"
] | da517ae908ba466da8ded87cec12a9fa | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). | 2,000 | Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. | standard output | |
PASSED | 0ed609f64a6b226d0fd341a57f71af0a | train_003.jsonl | 1383379200 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution{
InputStream is;
static PrintWriter out;
String INPUT = "";
static int mod = (int)1e9+7;
public void solve(){
int n = ni();
double[] a = new double[n+2];
a[0] = mod + 0.13; a[n+1] = mod+0.13;
for(int i = 1; i <= n; i++)a[i] = nd();
//System.out.println(Arrays.toString(a));
int[] left = new int[n+2];
int[] right = new int[n+2];
Arrays.fill(left, 1);
Arrays.fill(right, 1);
for(int i = 1; i <= n; i++){
int j = i-1;
while(j >= 0 && a[j] % a[i] == 0)j = j - left[j];
left[i] = i-j;
}
for(int i = n; i > 0; i--){
int j = i+1;
while(j < n+1 && a[j] % a[i] == 0)j = j + right[j];
right[i] = j-i;
}
int[] ans = new int[n+1];
int max = 1, ct = 0;
for(int i = 1; i <= n; i++){
ans[i] = left[i] + right[i] - 1;
if(max < ans[i]){
ct = 1;
max = ans[i];
}
else if(max == ans[i]){
ct+=1;
}
}
TreeSet<Integer> set = new TreeSet<Integer>();
for(int i = 0; i <= n; i++){
if(ans[i] == max)set.add(i-left[i]+1);
}
out.println(set.size() +" "+(max-1));
for(Integer i : set){
out.print(i+" ");
}
}
void run(){
is = new DataInputStream(System.in);
out = new PrintWriter(System.out);
int t=1;while(t-->0)solve();
out.flush();
}
public static void main(String[] args)throws Exception{new Solution().run();}
long mod(long v, long m){if(v<0){long q=(Math.abs(v)+m-1L)/m;v=v+q*m;}return v%m;}
long mod(long v){if(v<0){long q=(Math.abs(v)+mod-1L)/mod;v=v+q*mod;}return v%mod;}
//Fast I/O code is copied from uwi code.
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte(){
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns(){
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n){
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m){
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n){
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni(){
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl(){
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
static int i(long x){return (int)Math.round(x);}
static int i(double x){return (int)Math.round(x);}
static class Pair implements Comparable<Pair>{
long fs,sc;
Pair(long a,long b){
fs=a;sc=b;
}
public int compareTo(Pair p){
if(this.fs>p.fs)return 1;
else if(this.fs<p.fs)return -1;
else{
return i(this.sc-p.sc);
}
//return i(this.sc-p.sc);
}
public String toString(){
return "("+fs+","+sc+")";
}
}
} | Java | ["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"] | 2 seconds | ["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"] | NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | Java 8 | standard input | [
"two pointers",
"math",
"data structures",
"binary search",
"brute force"
] | da517ae908ba466da8ded87cec12a9fa | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). | 2,000 | Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. | standard output | |
PASSED | 1f2058b25df8a13c1e5e5b5323fb2dbe | train_003.jsonl | 1383379200 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. | 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);
ProblemDPairOfNumbers solver = new ProblemDPairOfNumbers();
solver.solve(1, in, out);
out.close();
}
static class ProblemDPairOfNumbers {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[n + 1];
for (int i = 1; i <= n; ++i) a[i] = in.nextInt();
ProblemDPairOfNumbers.RMQ table = new ProblemDPairOfNumbers.RMQ(n, a);
int low = 0;
int high = n - 1;
while (low <= high) {
int mid = low + high >> 1;
boolean possible = false;
for (int i = mid + 1; i <= n; ++i) {
// int min = tree.queryMin(1, i - mid, i);
int min = table.queryMin(i - mid, i);
int gcd = table.queryGcd(i - mid, i);
if (min == gcd) {
possible = true;
break;
}
}
if (possible) {
low = mid + 1;
} else {
high = mid - 1;
}
}
int mid = high;
ArrayList<Integer> occ = new ArrayList<>(n);
for (int i = mid + 1; i <= n; ++i) {
int min = table.queryMin(i - mid, i);
int gcd = table.queryGcd(i - mid, i);
if (min == gcd) {
occ.add(i - mid);
}
}
out.println(occ.size() + " " + mid);
for (int i : occ) out.print(i + " ");
}
static class RMQ {
int[] vs;
int[][] minLift;
int[][] gcdLift;
int gcd(int x, int y) {
return y == 0 ? x : gcd(y, x % y);
}
public RMQ(int n, int[] vs) {
this.vs = vs;
int maxlog = Integer.numberOfTrailingZeros(Integer.highestOneBit(n)) + 2;
minLift = new int[maxlog][n + 1];
gcdLift = new int[maxlog][n + 1];
for (int i = 1; i <= n; i++)
minLift[0][i] = gcdLift[0][i] = vs[i];
int lastRange = 1;
for (int lg = 1; lg < maxlog; lg++) {
for (int i = 1; i <= n; i++) {
minLift[lg][i] = Math.min(minLift[lg - 1][i], minLift[lg - 1][Math.min(i + lastRange, n)]);
gcdLift[lg][i] = gcd(gcdLift[lg - 1][i], gcdLift[lg - 1][Math.min(i + lastRange, n)]);
}
lastRange *= 2;
}
}
public int queryMin(int low, int hi) {
int range = hi - low + 1;
int exp = Integer.highestOneBit(range);
int lg = Integer.numberOfTrailingZeros(exp);
return Math.min(minLift[lg][low], minLift[lg][hi - exp + 1]);
}
public int queryGcd(int low, int hi) {
int range = hi - low + 1;
int exp = Integer.highestOneBit(range);
int lg = Integer.numberOfTrailingZeros(exp);
return gcd(gcdLift[lg][low], gcdLift[lg][hi - exp + 1]);
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"] | 2 seconds | ["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"] | NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | Java 8 | standard input | [
"two pointers",
"math",
"data structures",
"binary search",
"brute force"
] | da517ae908ba466da8ded87cec12a9fa | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). | 2,000 | Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. | standard output | |
PASSED | e99770559eaab3fc6ea058f31cb17060 | train_003.jsonl | 1383379200 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class code5 {
InputStream is;
PrintWriter out;
static long mod=pow(10,9)+7;
void solve()
{
int n=ni();
int a[]=na(n);
Stack<Integer> s=new Stack<Integer>();
int right[]=new int[n];
Arrays.fill(right,-1);
for(int i=0;i<n;i++)
{
if(s.isEmpty())
s.push(i);
else
{
int index=s.peek();
while(a[i]%a[index]!=0)
{
right[index]=i;
s.pop();
if(s.isEmpty())
break;
index=s.peek();
}
s.push(i);
}
}
int left[]=new int[n];
Arrays.fill(left,-1);
for(int i=n-1;i>=0;i--)
{
if(s.isEmpty())
s.push(i);
else
{
int index=s.peek();
while(a[i]%a[index]!=0)
{
left[index]=i;
s.pop();
if(s.isEmpty())
break;
index=s.peek();
}
s.push(i);
}
}
ArrayList<Integer> ans=new ArrayList<Integer>();
int max=0;
for(int i=0;i<n;i++)
{
int l=left[i];
int r=right[i];
if(l==-1)
l=-1;
if(r==-1)
r=n;
r--;
l++;
if(r-l+1>max)
{
ans=new ArrayList<Integer>();
max=r-l+1;
}
if(r-l+1==max)
ans.add(l+1);
}
Collections.sort(ans);
int count=1;
for(int i=1;i<ans.size();i++)
{
if(ans.get(i).compareTo(ans.get(i-1))!=0)
{
count++;
}
}
System.out.println(count+" "+(max-1));
out.print(ans.get(0)+" ");
for(int i=1;i<ans.size();i++)
{
if(ans.get(i).compareTo(ans.get(i-1))!=0)
{
count++;
out.print(ans.get(i)+" ");
}
}
}
static long d, x, y;
void extendedEuclid(long A, long B) {
if(B == 0) {
d = A;
x = 1;
y = 0;
}
else {
extendedEuclid(B, A%B);
long temp = x;
x = y;
y = temp - (A/B)*y;
}
}
long modInverse(long A,long M) //A and M are coprime
{
extendedEuclid(A,M);
return (x%M+M)%M; //x may be negative
}
public static void mergeSort(int[] arr, int l ,int r){
if((r-l)>=1){
int mid = (l+r)/2;
mergeSort(arr,l,mid);
mergeSort(arr,mid+1,r);
merge(arr,l,r,mid);
}
}
public static void merge(int arr[], int l, int r, int mid){
int n1 = (mid-l+1), n2 = (r-mid);
int left[] = new int[n1];
int right[] = new int[n2];
for(int i =0 ;i<n1;i++) left[i] = arr[l+i];
for(int i =0 ;i<n2;i++) right[i] = arr[mid+1+i];
int i =0, j =0, k = l;
while(i<n1 && j<n2){
if(left[i]>right[j]){
arr[k++] = right[j++];
}
else{
arr[k++] = left[i++];
}
}
while(i<n1) arr[k++] = left[i++];
while(j<n2) arr[k++] = right[j++];
}
public static void mergeSort(long[] arr, int l ,int r){
if((r-l)>=1){
int mid = (l+r)/2;
mergeSort(arr,l,mid);
mergeSort(arr,mid+1,r);
merge(arr,l,r,mid);
}
}
public static void merge(long arr[], int l, int r, int mid){
int n1 = (mid-l+1), n2 = (r-mid);
long left[] = new long[n1];
long right[] = new long[n2];
for(int i =0 ;i<n1;i++) left[i] = arr[l+i];
for(int i =0 ;i<n2;i++) right[i] = arr[mid+1+i];
int i =0, j =0, k = l;
while(i<n1 && j<n2){
if(left[i]>right[j]){
arr[k++] = right[j++];
}
else{
arr[k++] = left[i++];
}
}
while(i<n1) arr[k++] = left[i++];
while(j<n2) arr[k++] = right[j++];
}
static class Pair implements Comparable<Pair>{
int x;
long y,k,i;
Pair (int x,long y){
this.x=x;
this.y=y;
}
public int compareTo(Pair o) {
return Long.compare(this.y,o.y);
}
public boolean equals(Object o) {
if (o instanceof Pair) {
Pair p = (Pair)o;
return p.x == x && p.y == y && p.k==k;
}
return false;
}
@Override
public String toString() {
return "("+x + " " + y +" "+k+" "+i+" )";
}
}
public static boolean isPal(String s){
for(int i=0, j=s.length()-1;i<=j;i++,j--){
if(s.charAt(i)!=s.charAt(j)) return false;
}
return true;
}
public static String rev(String s){
StringBuilder sb=new StringBuilder(s);
sb.reverse();
return sb.toString();
}
public static long gcd(long x,long y){
if(x%y==0)
return y;
else
return gcd(y,x%y);
}
public static int gcd(int x,int y){
if(x%y==0)
return y;
else
return gcd(y,x%y);
}
public static long gcdExtended(long a,long b,long[] x){
if(a==0){
x[0]=0;
x[1]=1;
return b;
}
long[] y=new long[2];
long gcd=gcdExtended(b%a, a, y);
x[0]=y[1]-(b/a)*y[0];
x[1]=y[0];
return gcd;
}
public static int abs(int a,int b){
return (int)Math.abs(a-b);
}
public static long abs(long a,long b){
return (long)Math.abs(a-b);
}
public static int max(int a,int b){
if(a>b)
return a;
else
return b;
}
public static int min(int a,int b){
if(a>b)
return b;
else
return a;
}
public static long max(long a,long b){
if(a>b)
return a;
else
return b;
}
public static long min(long a,long b){
if(a>b)
return b;
else
return a;
}
public static long pow(long n,long p,long m){
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
if(result>=m)
result%=m;
p >>=1;
n*=n;
if(n>=m)
n%=m;
}
return result;
}
public static long pow(long n,long p){
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
public static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
void run() throws Exception {
is = System.in;
out = new PrintWriter(System.out);
solve();
out.flush();
}
public static void main(String[] args) throws Exception {
new Thread(null, new Runnable() {
public void run() {
try {
new code5().run();
} catch (Exception e) {
e.printStackTrace();
}
}
}, "1", 1 << 26).start();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b));
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
} | Java | ["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"] | 2 seconds | ["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"] | NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | Java 8 | standard input | [
"two pointers",
"math",
"data structures",
"binary search",
"brute force"
] | da517ae908ba466da8ded87cec12a9fa | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). | 2,000 | Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. | standard output | |
PASSED | 6685829a75abaa6f8794e771a4f482be | train_003.jsonl | 1383379200 | Simon has an array a1, a2, ..., an, consisting of n positive integers. Today Simon asked you to find a pair of integers l, r (1 ≤ l ≤ r ≤ n), such that the following conditions hold: there is integer j (l ≤ j ≤ r), such that all integers al, al + 1, ..., ar are divisible by aj; value r - l takes the maximum value among all pairs for which condition 1 is true; Help Simon, find the required pair of numbers (l, r). If there are multiple required pairs find all of them. | 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);
DPairOfNumbers solver = new DPairOfNumbers();
solver.solve(1, in, out);
out.close();
}
static class DPairOfNumbers {
int[][] st_min;
int[][] st_gcd;
int n;
int[] log;
public void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.ni();
int[] ar = new int[n];
log = new int[n + 2];
log[1] = 0;
for (int i = 2; i <= n + 1; ++i) {
log[i] = log[i / 2] + 1;
}
for (int i = 0; i < n; ++i) ar[i] = in.ni();
st_min = new int[n][30];
st_gcd = new int[n][30];
for (int i = 0; i < n; ++i) {
st_min[i][0] = ar[i];
st_gcd[i][0] = ar[i];
}
for (int j = 1; j < 30; ++j) {
for (int i = 0; i + (1 << j) <= n; ++i) {
st_min[i][j] = Math.min(st_min[i][j - 1], st_min[i + (1 << (j - 1))][j - 1]);
st_gcd[i][j] = maths.gcd(st_gcd[i][j - 1], st_gcd[i + (1 << (j - 1))][j - 1]);
}
}
int lo = 1;
int hi = n;
//out.println(check(5));
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (check(mid)) lo = mid + 1;
else hi = mid - 1;
}
int len = lo - 1;
ArrayList<Integer> arr = new ArrayList<>();
int min = -1, gcd = -1;
int j = log[len];
for (int i = 0; i + len - 1 < n; ++i) {
int l = i;
int r = i + len - 1;
gcd = maths.gcd(st_gcd[l][j], st_gcd[r - (1 << (j)) + 1][j]);
min = Math.min(st_min[l][j], st_min[r - (1 << (j)) + 1][j]);
if (gcd == min) arr.add(i);
}
out.println(arr.size() + " " + (len - 1));
for (int jj : arr) out.print((jj + 1) + " ");
}
public boolean check(int len) {
int gcd = -1;
int min = -1;
int j = log[len];
for (int i = 0; i + len - 1 < n; ++i) {
int l = i;
int r = i + len - 1;
gcd = maths.gcd(st_gcd[l][j], st_gcd[r - (1 << (j)) + 1][j]);
min = Math.min(st_min[l][j], st_min[r - (1 << (j)) + 1][j]);
if (gcd == min) return true;
}
return false;
}
}
static class maths {
public static int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
}
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 | ["5\n4 6 9 3 6", "5\n1 3 5 7 9", "5\n2 3 5 7 11"] | 2 seconds | ["1 3\n2", "1 4\n1", "5 0\n1 2 3 4 5"] | NoteIn the first sample the pair of numbers is right, as numbers 6, 9, 3 are divisible by 3.In the second sample all numbers are divisible by number 1.In the third sample all numbers are prime, so conditions 1 and 2 are true only for pairs of numbers (1, 1), (2, 2), (3, 3), (4, 4), (5, 5). | Java 8 | standard input | [
"two pointers",
"math",
"data structures",
"binary search",
"brute force"
] | da517ae908ba466da8ded87cec12a9fa | The first line contains integer n (1 ≤ n ≤ 3·105). The second line contains n space-separated integers a1, a2, ..., an (1 ≤ ai ≤ 106). | 2,000 | Print two integers in the first line — the number of required pairs and the maximum value of r - l. On the following line print all l values from optimal pairs in increasing order. | standard output | |
PASSED | 2fc786b32a3aacfff0cfc50776ab6093 | train_003.jsonl | 1584018300 | You are given a tree consisting of $$$n$$$ vertices. A tree is a connected undirected graph with $$$n-1$$$ edges. Each vertex $$$v$$$ of this tree has a color assigned to it ($$$a_v = 1$$$ if the vertex $$$v$$$ is white and $$$0$$$ if the vertex $$$v$$$ is black).You have to solve the following problem for each vertex $$$v$$$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex $$$v$$$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $$$cnt_w$$$ white vertices and $$$cnt_b$$$ black vertices, you have to maximize $$$cnt_w - cnt_b$$$. | 256 megabytes |
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.InputMismatchException;
public class F {
private static int n;
private static HashMap<Integer, ArrayList<Integer>> g;
private static int[] color;
private static int[] ans;
private static int[] ans2;
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
n = in.nextInt();
color = new int[n];
for(int i=0; i<n; i++) color[i] = in.nextInt();
g = new HashMap<>();
for(int i=0; i<n; i++) {
g.put(i, new ArrayList<>());
}
ans = new int[n];
ans2 = new int[n];
for(int i=0; i<n-1; i++) {
int p = in.nextInt()-1;
int q = in.nextInt()-1;
g.get(p).add(q);
g.get(q).add(p);
}
dfs(0, -1);
dfs2(0, -1);
for(int x: ans2) {
w.write(x+" ");
}
w.write("\n");
w.close();
}
private static void dfs2(int u, int p) {
ans2[u] = ans[u];
for(int v: g.get(u)) {
if (v==p) continue;
ans[u] -= (ans[v]>=0?ans[v]:0);
ans[v] += (ans[u]>=0?ans[u]:0);
dfs2(v, u);
ans[v] -= (ans[u]>=0?ans[u]:0);
ans[u] += (ans[v]>=0?ans[v]:0);
}
}
private static void dfs(int u, int p) {
ans[u] = (color[u]==1?1:-1);
for(int v: g.get(u)) {
if (v==p) continue;
dfs(v, u);
ans[u]+=(ans[v]>=0?ans[v]:0);
}
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
}
| Java | ["9\n0 1 1 1 0 0 0 0 1\n1 2\n1 3\n3 4\n3 5\n2 6\n4 7\n6 8\n5 9", "4\n0 0 1 0\n1 2\n1 3\n1 4"] | 2 seconds | ["2 2 2 2 2 1 1 0 2", "0 -1 1 -1"] | NoteThe first example is shown below:The black vertices have bold borders.In the second example, the best subtree for vertices $$$2, 3$$$ and $$$4$$$ are vertices $$$2, 3$$$ and $$$4$$$ correspondingly. And the best subtree for the vertex $$$1$$$ is the subtree consisting of vertices $$$1$$$ and $$$3$$$. | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | cb8895ddd54ffbd898b1bf5e169feb63 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the color of the $$$i$$$-th vertex. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \le u_i, v_i \le n, u_i \ne v_i$$$). It is guaranteed that the given edges form a tree. | 1,800 | Print $$$n$$$ integers $$$res_1, res_2, \dots, res_n$$$, where $$$res_i$$$ is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex $$$i$$$. | standard output | |
PASSED | e8230d0ef47594c724e78a957066f4d7 | train_003.jsonl | 1584018300 | You are given a tree consisting of $$$n$$$ vertices. A tree is a connected undirected graph with $$$n-1$$$ edges. Each vertex $$$v$$$ of this tree has a color assigned to it ($$$a_v = 1$$$ if the vertex $$$v$$$ is white and $$$0$$$ if the vertex $$$v$$$ is black).You have to solve the following problem for each vertex $$$v$$$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex $$$v$$$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $$$cnt_w$$$ white vertices and $$$cnt_b$$$ black vertices, you have to maximize $$$cnt_w - cnt_b$$$. | 256 megabytes | import java.util.*;
public class Main {
private static final Scanner sc = new Scanner(System.in);
static void print(int[] x) {
StringBuilder ans = new StringBuilder();
for (int y : x) ans.append(y + " ");
System.out.println(ans);
}
static class Tree {
int size;
int[] ans;
Stack<Node> leaves;
public Tree(int n, int[] color, int[] a, int[] b) {
size = n;
ans = new int[n];
ArrayList<Node> nodes = new ArrayList<Node>(n);
for (int i = 0; i < n; i++) {
nodes.add(new Node(i, color[i]));
}
for (int i = 0; i < n-1; i++) {
Node.addEdge(nodes.get(a[i]), nodes.get(b[i]));
}
leaves = new Stack<Node>();
for (Node x : nodes) {
if (x.degree == 1) leaves.push(x);
}
}
void calculate() {
// print(ans);
if (size == 1) {
Node x = leaves.pop();
ans[x.index] = x.color;
}
else {
Node x = leaves.pop();
// System.out.println("popped " + (x.index + 1) + " with color " + x.color);
if (x.degree != 1) throw new RuntimeException("sth wrong!");
Node y = x.children.iterator().next(); // only child of x
Node.delete(x, y); // delete x from y
size--;
boolean linked = x.color > 0; // y uses x in optimal subtree
if (y.degree == 1) leaves.push(y);
if (linked) {
y.color += x.color;
}
calculate();
int contribution = ans[y.index]; // from y
if (linked) contribution -= x.color;
ans[x.index] = x.color + Math.max(0, contribution);
}
}
}
static class Node {
int color;
int index;
int degree;
HashSet<Node> children;
public Node(int index, int color) {
this.index = index;
this.color = color;
degree = 0;
children = new HashSet<Node>();
}
static void addEdge(Node x, Node y) {
x.degree++;
y.degree++;
x.children.add(y);
y.children.add(x);
}
static void delete(Node x, Node y) {
x.children.remove(y);
y.children.remove(x);
x.degree--;
y.degree--;
}
}
public static void main(String[] args) {
int n = sc.nextInt();
int[] color = new int[n];
for (int i = 0; i < n; i++) {
color[i] = sc.nextInt();
if (color[i] == 0) color[i] = -1;
}
int[] a = new int[n-1];
int[] b = new int[n-1];
for (int i = 0; i < n-1; i++) {
a[i] = sc.nextInt() - 1;
b[i] = sc.nextInt() - 1;
}
Tree T = new Tree(n, color, a, b);
T.calculate();
print(T.ans);
}
} | Java | ["9\n0 1 1 1 0 0 0 0 1\n1 2\n1 3\n3 4\n3 5\n2 6\n4 7\n6 8\n5 9", "4\n0 0 1 0\n1 2\n1 3\n1 4"] | 2 seconds | ["2 2 2 2 2 1 1 0 2", "0 -1 1 -1"] | NoteThe first example is shown below:The black vertices have bold borders.In the second example, the best subtree for vertices $$$2, 3$$$ and $$$4$$$ are vertices $$$2, 3$$$ and $$$4$$$ correspondingly. And the best subtree for the vertex $$$1$$$ is the subtree consisting of vertices $$$1$$$ and $$$3$$$. | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | cb8895ddd54ffbd898b1bf5e169feb63 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the color of the $$$i$$$-th vertex. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \le u_i, v_i \le n, u_i \ne v_i$$$). It is guaranteed that the given edges form a tree. | 1,800 | Print $$$n$$$ integers $$$res_1, res_2, \dots, res_n$$$, where $$$res_i$$$ is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex $$$i$$$. | standard output | |
PASSED | d8e847acc156008e12ed8fb47f10b066 | train_003.jsonl | 1584018300 | You are given a tree consisting of $$$n$$$ vertices. A tree is a connected undirected graph with $$$n-1$$$ edges. Each vertex $$$v$$$ of this tree has a color assigned to it ($$$a_v = 1$$$ if the vertex $$$v$$$ is white and $$$0$$$ if the vertex $$$v$$$ is black).You have to solve the following problem for each vertex $$$v$$$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex $$$v$$$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $$$cnt_w$$$ white vertices and $$$cnt_b$$$ black vertices, you have to maximize $$$cnt_w - cnt_b$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class F {
static int n;
static int[] arr, dp1, dp2;
static ArrayList<Integer> adj[];
static void dfs1(int nd, int pr) {
dp1[nd] = (arr[nd] == 1)? 1 : -1;
for(Integer ch : adj[nd]) {
if(ch == pr)
continue;
dfs1(ch, nd);
dp1[nd] += Math.max(0, dp1[ch]);
}
}
static void dfs2(int nd, int pr) {
dp2[nd] = dp1[nd];
if(pr != 0) {
int val = dp2[pr] - Math.max(0, dp1[nd]);
dp2[nd] += Math.max(0, val);
}
for(Integer ch : adj[nd]) {
if(ch == pr)
continue;
dfs2(ch, nd);
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
n = Integer.parseInt(br.readLine());
arr = new int[n+1];
dp1 = new int[n+1];
dp2 = new int[n+1];
adj = new ArrayList[n+1];
for(int i = 1; i<=n; i++)
adj[i] = new ArrayList<>();
StringTokenizer st = new StringTokenizer(br.readLine());
for(int i = 1; i<=n; i++){
arr[i] = Integer.parseInt(st.nextToken());
}
for(int i = 0; i<n-1; i++) {
st = new StringTokenizer(br.readLine());
int u = Integer.parseInt(st.nextToken());
int v = Integer.parseInt(st.nextToken());
adj[u].add(v);
adj[v].add(u);
}
dfs1(1, 0);
dfs2(1, 0);
for(int i = 1; i<=n; i++)
bw.write(dp2[i] + " ");
bw.flush();
bw.close();
br.close();
}
} | Java | ["9\n0 1 1 1 0 0 0 0 1\n1 2\n1 3\n3 4\n3 5\n2 6\n4 7\n6 8\n5 9", "4\n0 0 1 0\n1 2\n1 3\n1 4"] | 2 seconds | ["2 2 2 2 2 1 1 0 2", "0 -1 1 -1"] | NoteThe first example is shown below:The black vertices have bold borders.In the second example, the best subtree for vertices $$$2, 3$$$ and $$$4$$$ are vertices $$$2, 3$$$ and $$$4$$$ correspondingly. And the best subtree for the vertex $$$1$$$ is the subtree consisting of vertices $$$1$$$ and $$$3$$$. | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | cb8895ddd54ffbd898b1bf5e169feb63 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the color of the $$$i$$$-th vertex. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \le u_i, v_i \le n, u_i \ne v_i$$$). It is guaranteed that the given edges form a tree. | 1,800 | Print $$$n$$$ integers $$$res_1, res_2, \dots, res_n$$$, where $$$res_i$$$ is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex $$$i$$$. | standard output | |
PASSED | a8b51cdcdac91b2815d00370c34aa080 | train_003.jsonl | 1584018300 | You are given a tree consisting of $$$n$$$ vertices. A tree is a connected undirected graph with $$$n-1$$$ edges. Each vertex $$$v$$$ of this tree has a color assigned to it ($$$a_v = 1$$$ if the vertex $$$v$$$ is white and $$$0$$$ if the vertex $$$v$$$ is black).You have to solve the following problem for each vertex $$$v$$$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex $$$v$$$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $$$cnt_w$$$ white vertices and $$$cnt_b$$$ black vertices, you have to maximize $$$cnt_w - cnt_b$$$. | 256 megabytes | import static java.util.Arrays.* ;
import static java.lang.Math.* ;
import java.io.*;
import java.util.*;
public class Main
{
int ref ;
int [] head , next , to ;
int [] dp_down , dp_up , a ;
void addEdge(int a , int b)
{
next[++ref] = head[a] ;
head[a] = ref ;
to[ref] = b ;
}
void dfs1(int u , int p)
{
dp_down[u] = a[u] ;
for(int i = head[u] ; i != 0 ; i = next[i])
{
int v = to[i] ;
if(v != p)
{
dfs1(v, u);
dp_down[u] = max(dp_down[u] , dp_down[u] + dp_down[v]);
}
}
}
void dfs2(int u , int p)
{
for(int i = head[u] ; i != 0 ; i = next[i])
{
int v = to[i] ;
if(v != p)
{
dp_up[v] = max(dp_up[u] , 0) + dp_down[u] - max(0 , dp_down[v]);
dfs2(v, u);
}
}
}
void main() throws Exception
{
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out) ;
int n = sc.nextInt() ;
a = new int [n] ;
head = new int [n] ;
next = new int [n << 1] ;
to = new int [n << 1] ;
dp_up = new int [n] ;
dp_down = new int [n] ;
for(int i = 0; i < n ; i++)
{
a[i] = sc.nextInt();
if(a[i] == 0)
a[i] = -1 ;
}
for(int i = 0 ;i < n - 1 ; i++)
{
int a = sc.nextInt() - 1 , b = sc.nextInt() - 1 ;
addEdge(a , b);
addEdge(b , a);
}
dfs1(0 , -1);
dfs2(0 , -1);
for(int i = 0 ; i < n ; i ++)
{
if(i > 0) out.print(" ");
out.print(max(dp_down[i] , dp_down[i] +dp_up[i]));
}
out.println();
out.flush();
}
public static void main(String[] args) throws Exception { new Main().main(); }
static class Scanner
{
BufferedReader br ;
StringTokenizer st ;
Scanner(InputStream in)
{
br = new BufferedReader(new InputStreamReader(in)) ;
}
String next() throws Exception
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken() ;
}
int nextInt() throws Exception { return Integer.parseInt(next()) ; }
// long nextLong() throws Exception {return Long.parseLong(next());}
//
// double nextDouble() throws Exception {return Double.parseDouble(next());}
}
} | Java | ["9\n0 1 1 1 0 0 0 0 1\n1 2\n1 3\n3 4\n3 5\n2 6\n4 7\n6 8\n5 9", "4\n0 0 1 0\n1 2\n1 3\n1 4"] | 2 seconds | ["2 2 2 2 2 1 1 0 2", "0 -1 1 -1"] | NoteThe first example is shown below:The black vertices have bold borders.In the second example, the best subtree for vertices $$$2, 3$$$ and $$$4$$$ are vertices $$$2, 3$$$ and $$$4$$$ correspondingly. And the best subtree for the vertex $$$1$$$ is the subtree consisting of vertices $$$1$$$ and $$$3$$$. | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | cb8895ddd54ffbd898b1bf5e169feb63 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the color of the $$$i$$$-th vertex. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \le u_i, v_i \le n, u_i \ne v_i$$$). It is guaranteed that the given edges form a tree. | 1,800 | Print $$$n$$$ integers $$$res_1, res_2, \dots, res_n$$$, where $$$res_i$$$ is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex $$$i$$$. | standard output | |
PASSED | bd18dacd4b7dd21005d5dbab968fc48b | train_003.jsonl | 1584018300 | You are given a tree consisting of $$$n$$$ vertices. A tree is a connected undirected graph with $$$n-1$$$ edges. Each vertex $$$v$$$ of this tree has a color assigned to it ($$$a_v = 1$$$ if the vertex $$$v$$$ is white and $$$0$$$ if the vertex $$$v$$$ is black).You have to solve the following problem for each vertex $$$v$$$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex $$$v$$$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $$$cnt_w$$$ white vertices and $$$cnt_b$$$ black vertices, you have to maximize $$$cnt_w - cnt_b$$$. | 256 megabytes | import java.io.*;
import java.io.IOException;
import java.util.*;
//import javafx.util.Pair;
//import java.util.concurrent.LinkedBlockingDeque;
//import sun.net.www.content.audio.wav;
public class Codeforces {
public static long mod = (long)Math.pow(10, 9)+7 ;
public static double epsilon=0.00000000008854;//value of epsilon
public static InputReader sc = new InputReader(System.in);
public static PrintWriter pw = new PrintWriter(System.out);
public static long gcd(long a,long b){
while(b>0){
long t=b;
b=a%b;
a=t;
}
return a;
}
public static int fun(int n,int h,int th,int dp[][],int a[],int l,int r){
if(n==a.length){
if(l<=h&&r>=h)
return 1;
else return 0;
}
if(dp[n][h]>-1){
return dp[n][h];
}
if(n>0&&l<=h&&r>=h){
//pw.println(h);
dp[n][h]=1;
}
else dp[n][h]=0;
//pw.println(n+" "+(h+a[n]+th)%th+" "+(h+a[n]-1+th)%th);
return dp[n][h]+=Math.max(fun(n+1, (h+a[n]+th)%th, th, dp, a,l,r),fun(n+1, (h+a[n]-1+th)%th, th, dp, a,l,r));
}
public static ArrayList<ArrayList <Integer>> GetGraph(int n,int m){
ArrayList<ArrayList <Integer>> a=new ArrayList<>();
for(int i=0;i<n;i++){
a.add(new ArrayList<>());
}
for(int i=0;i<m;i++){
int u=sc.nextInt()-1;
int v=sc.nextInt()-1;
a.get(u).add(v);
a.get(v).add(u);
}
return a;
}
static int dfs(int src, ArrayList<ArrayList<Integer>> list, int vis[],int dp[],int p[])
{
//Here 0-white,1-gray & 2-black;
// Time complexity O(n+m)
vis[src]=1;
for(int i=0;i<list.get(src).size();i++){
int v=list.get(src).get(i);
if(vis[v]==0){
p[v]=src;
dp[src] += Math.max(dfs(v, list, vis, dp, p), 0);
}
}
vis[src]=2;
return dp[src];
}
static void dfs1(int src, ArrayList<ArrayList<Integer>> list, int vis[],int dp[],int p[])
{
//Here 0-white,1-gray & 2-black;
// Time complexity O(n+m)
vis[src]=1;
for(int i=0;i<list.get(src).size();i++){
int v=list.get(src).get(i);
if(vis[v]==0){
//p[v]=src;
if(dp[v]>=0){
int pv=dp[src]-dp[v];
dp[v]+=Math.max(pv, 0);
}
else{
dp[v]+=Math.max(dp[src], 0);
}
dfs1(v, list, vis, dp, p);
}
}
vis[src]=2;
//return dp[src];
}
public static void main(String[] args) {
// code starts..
int n=sc.nextInt();
int a[]=scanArray(n);
ArrayList<ArrayList<Integer>> g=GetGraph(n, n-1);
int p[]=new int[n];
int dp[]=new int[n];
for(int i=0;i<n;i++){
if(a[i]==0){
dp[i]=-1;
}
else dp[i]=1;
}
dfs(0, g, new int[n], dp, p);
dfs1(0, g, new int[n], dp, p);
for(int i=0;i<n;i++){
pw.print(dp[i]+" ");
}
// Code ends...
pw.flush();
pw.close();
}
public static Comparator<Integer[]> column(int i){
return
new Comparator<Integer[]>() {
@Override
public int compare(Integer[] o1, Integer[] o2) {
return o1[i].compareTo(o2[i]);//for ascending
//return o2[i].compareTo(o1[i]);//for descending
}
};
}
public static String reverseString(String s){
StringBuilder input1 = new StringBuilder();
input1.append(s);
input1 = input1.reverse();
return input1.toString();
}
public static int[] scanArray(int n){
int a[]=new int [n];
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
return a;
}
public static long[] scanLongArray(int n){
long a[]=new long [n];
for(int i=0;i<n;i++)
a[i]=sc.nextLong();
return a;
}
public static String [] scanStrings(int n){
String a[]=new String [n];
for(int i=0;i<n;i++)
a[i]=sc.nextLine();
return a;
}
}
class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
| Java | ["9\n0 1 1 1 0 0 0 0 1\n1 2\n1 3\n3 4\n3 5\n2 6\n4 7\n6 8\n5 9", "4\n0 0 1 0\n1 2\n1 3\n1 4"] | 2 seconds | ["2 2 2 2 2 1 1 0 2", "0 -1 1 -1"] | NoteThe first example is shown below:The black vertices have bold borders.In the second example, the best subtree for vertices $$$2, 3$$$ and $$$4$$$ are vertices $$$2, 3$$$ and $$$4$$$ correspondingly. And the best subtree for the vertex $$$1$$$ is the subtree consisting of vertices $$$1$$$ and $$$3$$$. | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | cb8895ddd54ffbd898b1bf5e169feb63 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the color of the $$$i$$$-th vertex. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \le u_i, v_i \le n, u_i \ne v_i$$$). It is guaranteed that the given edges form a tree. | 1,800 | Print $$$n$$$ integers $$$res_1, res_2, \dots, res_n$$$, where $$$res_i$$$ is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex $$$i$$$. | standard output | |
PASSED | 88b43dfe08e482c7686371810d99e30c | train_003.jsonl | 1584018300 | You are given a tree consisting of $$$n$$$ vertices. A tree is a connected undirected graph with $$$n-1$$$ edges. Each vertex $$$v$$$ of this tree has a color assigned to it ($$$a_v = 1$$$ if the vertex $$$v$$$ is white and $$$0$$$ if the vertex $$$v$$$ is black).You have to solve the following problem for each vertex $$$v$$$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex $$$v$$$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $$$cnt_w$$$ white vertices and $$$cnt_b$$$ black vertices, you have to maximize $$$cnt_w - cnt_b$$$. | 256 megabytes | import java.io.*;
import java.util.*;
import java.text.*;
public final class isc
{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static int dp1[];
static int dp2[];
static int arr[];
static ArrayList adj[];
public static void main(String[] args)
{
FastReader sc = new FastReader();
int n = sc.nextInt();
arr = new int[n];
adj = new ArrayList[n];
for(int i=0; i<n; i++)
{
arr[i] = sc.nextInt();
adj[i] = new ArrayList();
}
for(int i=0; i<n-1; i++)
{
int a = sc.nextInt()-1;
int b = sc.nextInt()-1;
adj[a].add(b);
adj[b].add(a);
}
dp1 = new int[n];
dp2 = new int[n];
dfs1(0,-1);
dfs2(0,-1);
for(int i=0; i<n; i++)
System.out.print(dp2[i]+" ");
System.out.println();
}
static void dfs1(int nd, int pr)
{
dp1[nd] = (arr[nd]==1?1:-1);
for(Object ch:adj[nd])
{
if((int)ch!=pr)
{
dfs1((int)ch, nd);
dp1[nd] += Math.max(0, dp1[(int)ch]);
}
}
}
static void dfs2(int nd, int pr)
{
dp2[nd] = dp1[nd];
if(pr!=-1)
{
// contribution of nd to par
int val = dp2[pr]-Math.max(0,dp1[nd]);
dp2[nd] += Math.max(0, val);
}
for(Object ch:adj[nd])
{
if((int)ch!=pr)
dfs2((int)ch, nd);
}
}
} | Java | ["9\n0 1 1 1 0 0 0 0 1\n1 2\n1 3\n3 4\n3 5\n2 6\n4 7\n6 8\n5 9", "4\n0 0 1 0\n1 2\n1 3\n1 4"] | 2 seconds | ["2 2 2 2 2 1 1 0 2", "0 -1 1 -1"] | NoteThe first example is shown below:The black vertices have bold borders.In the second example, the best subtree for vertices $$$2, 3$$$ and $$$4$$$ are vertices $$$2, 3$$$ and $$$4$$$ correspondingly. And the best subtree for the vertex $$$1$$$ is the subtree consisting of vertices $$$1$$$ and $$$3$$$. | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | cb8895ddd54ffbd898b1bf5e169feb63 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the color of the $$$i$$$-th vertex. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \le u_i, v_i \le n, u_i \ne v_i$$$). It is guaranteed that the given edges form a tree. | 1,800 | Print $$$n$$$ integers $$$res_1, res_2, \dots, res_n$$$, where $$$res_i$$$ is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex $$$i$$$. | standard output | |
PASSED | 06e86cc201fae3b514bd58005ed25e61 | train_003.jsonl | 1584018300 | You are given a tree consisting of $$$n$$$ vertices. A tree is a connected undirected graph with $$$n-1$$$ edges. Each vertex $$$v$$$ of this tree has a color assigned to it ($$$a_v = 1$$$ if the vertex $$$v$$$ is white and $$$0$$$ if the vertex $$$v$$$ is black).You have to solve the following problem for each vertex $$$v$$$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex $$$v$$$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $$$cnt_w$$$ white vertices and $$$cnt_b$$$ black vertices, you have to maximize $$$cnt_w - cnt_b$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class F1324 {
static int n;
static ArrayList<Integer>[] adjList;
static ArrayList<Boolean>[] rootCheck;
static int[] score;
static int[] a;
static boolean[] vis;
public static int dfs(int u) {
vis[u] = true;
int sc = a[u];
for(int i = 0; i < adjList[u].size(); i++) {
int v = adjList[u].get(i);
if(!vis[v]) {
int x = dfs(v);
if(x > 0) {
sc += x;
rootCheck[u].add(true);
} else {
rootCheck[u].add(false);
}
} else {
rootCheck[u].add(false);
}
}
return score[u] = sc;
}
public static void bfs() {
boolean[] vis = new boolean[n];
Queue<Integer> qu = new LinkedList<>();
vis[0] = true;
qu.add(0);
while(!qu.isEmpty()) {
int u = qu.poll();
for(int i = 0; i < adjList[u].size(); i++) {
int v = adjList[u].get(i);
if(!vis[v]) {
if(rootCheck[u].get(i)) {
score[v] = Math.max(score[v], score[u]);
} else {
score[v] = Math.max(score[v], score[u] + score[v]);
}
vis[v] = true;
qu.add(v);
}
}
}
}
public static void main(String[] args) throws IOException {
//Scanner sc = new Scanner(System.in);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
StringTokenizer st;
n = Integer.parseInt(br.readLine());
a = new int[n];
st = new StringTokenizer(br.readLine());
for(int i = 0; i < n; i++) {
int x = Integer.parseInt(st.nextToken());
a[i] = x == 1 ? 1 : -1;
}
adjList = new ArrayList[n];
rootCheck = new ArrayList[n];
for(int i = 0; i < n; i++) {
adjList[i] = new ArrayList<Integer>();
rootCheck[i] = new ArrayList<Boolean>();
}
for(int i = 0; i < n - 1; i++) {
st = new StringTokenizer(br.readLine());
int u = Integer.parseInt(st.nextToken()) - 1, v = Integer.parseInt(st.nextToken()) - 1;
adjList[u].add(v);
adjList[v].add(u);
}
score = new int[n];
vis = new boolean[n];
dfs(0);
bfs();
for(int i = 0; i < n; i++)
pw.print(score[i] + (i == n - 1 ? "\n" : " "));
pw.flush();
}
}
| Java | ["9\n0 1 1 1 0 0 0 0 1\n1 2\n1 3\n3 4\n3 5\n2 6\n4 7\n6 8\n5 9", "4\n0 0 1 0\n1 2\n1 3\n1 4"] | 2 seconds | ["2 2 2 2 2 1 1 0 2", "0 -1 1 -1"] | NoteThe first example is shown below:The black vertices have bold borders.In the second example, the best subtree for vertices $$$2, 3$$$ and $$$4$$$ are vertices $$$2, 3$$$ and $$$4$$$ correspondingly. And the best subtree for the vertex $$$1$$$ is the subtree consisting of vertices $$$1$$$ and $$$3$$$. | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | cb8895ddd54ffbd898b1bf5e169feb63 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the color of the $$$i$$$-th vertex. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \le u_i, v_i \le n, u_i \ne v_i$$$). It is guaranteed that the given edges form a tree. | 1,800 | Print $$$n$$$ integers $$$res_1, res_2, \dots, res_n$$$, where $$$res_i$$$ is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex $$$i$$$. | standard output | |
PASSED | c8a6d48bbc1a92815623b5c4c0d1d1c9 | train_003.jsonl | 1584018300 | You are given a tree consisting of $$$n$$$ vertices. A tree is a connected undirected graph with $$$n-1$$$ edges. Each vertex $$$v$$$ of this tree has a color assigned to it ($$$a_v = 1$$$ if the vertex $$$v$$$ is white and $$$0$$$ if the vertex $$$v$$$ is black).You have to solve the following problem for each vertex $$$v$$$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex $$$v$$$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $$$cnt_w$$$ white vertices and $$$cnt_b$$$ black vertices, you have to maximize $$$cnt_w - cnt_b$$$. | 256 megabytes | // import java.util.*;
// import java.io.*;
// public class prob13 {
// static int[] val, dp;
// static ArrayList<Integer>[] adj;
// public static void main(String[] args) throws Exception {
// // Scanner in = new Scanner(new File("prob12.in"));
// Scanner in = new Scanner(System.in);
// // int t = in.nextInt();
// // for (int tt = 0; tt < t; tt++) {
// int n = in.nextInt();
// val = new int[n];
// dp = new int[n];
// adj = new ArrayList[n];
// for (int i = 0; i < n; i++) adj[i] = new ArrayList<>();
// for (int i = 0; i < n; i++) {
// val[i] = in.nextInt();
// if (val[i] == 0) val[i] = -1;
// }
// for (int i = 0; i < n - 1; i++) {
// int u = in.nextInt(), v = in.nextInt(); u--; v--;
// adj[u].add(v);
// adj[v].add(u);
// }
// down(0, -1);
// up(0, -1);
// for (int i = 0; i < n; i++) {
// System.out.println(dp[i]);
// }
// // }
// }
// static int down(int u, int parent) {
// dp[u] = val[u];
// for (int v : adj[u]) {
// if (v == parent) continue;
// int cur = down(v, u);
// if (cur > 0) dp[u] += cur;
// }
// return dp[u];
// }
// static void up(int u, int parent) {
// for (int v : adj[u]) {
// if (v == parent) continue;
// if (dp[v] < dp[u]) {
// if (dp[v] > 0) {
// dp[v] = dp[u];
// } else {
// dp[v] += dp[u];
// }
// }
// up(v, u);
// }
// }
// }
import java.io.*;
import java.util.*;
import java.nio.file.*;
import static java.lang.Math.*;
public class prob13 {
static int[] val, dp;
static ArrayList<Integer>[] adj;
public static void main(String[] args) throws Exception {
int n = i();
val = new int[n];
dp = new int[n];
adj = new ArrayList[n];
for (int i = 0; i < n; i++) adj[i] = new ArrayList<>();
for (int i = 0; i < n; i++) {
val[i] = i();
if (val[i] == 0) val[i] = -1;
}
for (int i = 0; i < n - 1; i++) {
int u = i(), v = i(); u--; v--;
adj[u].add(v);
adj[v].add(u);
}
down(0, -1);
up(0, -1);
for (int i = 0; i < n; i++) {
out.println(dp[i]);
}
out.close();
}
static int down(int u, int parent) {
dp[u] = val[u];
for (int v : adj[u]) {
if (v == parent) continue;
int cur = down(v, u);
if (cur > 0) dp[u] += cur;
}
return dp[u];
}
static void up(int u, int parent) {
for (int v : adj[u]) {
if (v == parent) continue;
if (dp[v] < dp[u]) {
if (dp[v] > 0) {
dp[v] = dp[u];
} else {
dp[v] += dp[u];
}
}
up(v, u);
}
}
static BufferedReader in;
static StringTokenizer st = new StringTokenizer("");
static PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
static {
try {
in = Files.newBufferedReader(Paths.get("prob13.dat"));
} catch (Exception e) {
in = new BufferedReader(new InputStreamReader(System.in));
}
}
static void check() throws Exception {
while (!st.hasMoreTokens()) st = new StringTokenizer(in.readLine());
}
static String s() throws Exception { check(); return st.nextToken(); }
static int i() throws Exception { return Integer.parseInt(s()); }
static long l() throws Exception { return Long.parseLong(s()); }
static double d() throws Exception { return Double.parseDouble(s()); }
}
| Java | ["9\n0 1 1 1 0 0 0 0 1\n1 2\n1 3\n3 4\n3 5\n2 6\n4 7\n6 8\n5 9", "4\n0 0 1 0\n1 2\n1 3\n1 4"] | 2 seconds | ["2 2 2 2 2 1 1 0 2", "0 -1 1 -1"] | NoteThe first example is shown below:The black vertices have bold borders.In the second example, the best subtree for vertices $$$2, 3$$$ and $$$4$$$ are vertices $$$2, 3$$$ and $$$4$$$ correspondingly. And the best subtree for the vertex $$$1$$$ is the subtree consisting of vertices $$$1$$$ and $$$3$$$. | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | cb8895ddd54ffbd898b1bf5e169feb63 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the color of the $$$i$$$-th vertex. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \le u_i, v_i \le n, u_i \ne v_i$$$). It is guaranteed that the given edges form a tree. | 1,800 | Print $$$n$$$ integers $$$res_1, res_2, \dots, res_n$$$, where $$$res_i$$$ is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex $$$i$$$. | standard output | |
PASSED | bc3135781d3bceac7312e4f9c90786cf | train_003.jsonl | 1584018300 | You are given a tree consisting of $$$n$$$ vertices. A tree is a connected undirected graph with $$$n-1$$$ edges. Each vertex $$$v$$$ of this tree has a color assigned to it ($$$a_v = 1$$$ if the vertex $$$v$$$ is white and $$$0$$$ if the vertex $$$v$$$ is black).You have to solve the following problem for each vertex $$$v$$$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex $$$v$$$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $$$cnt_w$$$ white vertices and $$$cnt_b$$$ black vertices, you have to maximize $$$cnt_w - cnt_b$$$. | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main
{
static long mod=(long)(1e+9 + 7);
//static long mod=(long)998244353;
static int[] sieve;
static ArrayList<Integer> primes;
static PrintWriter out;
static fast s;
static StringBuilder fans;
public static void dfs(int start,int[] d,int[] visited,ArrayList<Integer>[] graph,int a[])
{
if(visited[start]==1) return;
visited[start]=1;
if(a[start]==1) d[start]=1;
else d[start]=-1;
for(int i=0;i<graph[start].size();i++)
{
int u=start;
int v=graph[start].get(i);
if(visited[v]==0)
{
dfs(v,d,visited,graph,a);
d[u]=d[u]+Math.max(d[v],0);
}
}
}
public static void dfs2(int start,int[] d,int[] visited,ArrayList<Integer>[] graph,int a[],int[] ans,int prev)
{
if(visited[start]==1) return;
visited[start]=1;
ans[start]=d[start]+prev;
for(int i=0;i<graph[start].size();i++)
{
int u=start;
int v=graph[start].get(i);
if(visited[v]==0)
{
int exclude_u=0;
int include_u=ans[u]-Math.max(d[v], 0);
dfs2(v,d,visited,graph,a,ans,Math.max(exclude_u, include_u));
}
}
}
public static void solve()
{
int n=s.nextInt();
int a[]=new int[n+1];
for(int i=1;i<=n;i++) a[i]=s.nextInt();
ArrayList<Integer> graph[]=new ArrayList[n+1];
for(int i=1;i<=n;i++) graph[i]=new ArrayList<Integer>();
int diff[]=new int[n+1];
Arrays.fill(diff, Integer.MIN_VALUE);
int visited[]=new int[n+1];
for(int i=1;i<=n-1;i++)
{
int u=s.nextInt();
int v=s.nextInt();
graph[u].add(v);
graph[v].add(u);
}
int ans[]=new int[n+1];
dfs(1,diff,visited,graph,a);
Arrays.fill(visited, 0);
dfs2(1,diff,visited,graph,a,ans,0);
for(int i=1;i<=n;i++) System.out.print(ans[i]+" ");
}
public static void main(String[] args) throws java.lang.Exception
{
s = new fast();
out=new PrintWriter(System.out);
fans=new StringBuilder("");
int t=1;
while(t>0)
{
solve();
t--;
}
//System.out.println(fans);
}
static class fast {
private InputStream i;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
//Return floor log2n
public static long log2(long bits) // returns 0 for bits=0
{
int log = 0;
if( ( bits & 0xffff0000 ) != 0 ) { bits >>>= 16; log = 16; }
if( bits >= 256 ) { bits >>>= 8; log += 8; }
if( bits >= 16 ) { bits >>>= 4; log += 4; }
if( bits >= 4 ) { bits >>>= 2; log += 2; }
return log + ( bits >>> 1 );
}
public static boolean next_permutation(int a[])
{
int i=0,j=0;int index=-1;
int n=a.length;
for(i=0;i<n-1;i++)
if(a[i]<a[i+1]) index=i;
if(index==-1) return false;
i=index;
for(j=i+1;j<n && a[i]<a[j];j++);
int temp=a[i];
a[i]=a[j-1];
a[j-1]=temp;
for(int p=i+1,q=n-1;p<q;p++,q--)
{
temp=a[p];
a[p]=a[q];
a[q]=temp;
}
return true;
}
public static void division(char ch[],int divisor)
{
int div=Character.getNumericValue(ch[0]); int mul=10;int remainder=0;
StringBuilder quotient=new StringBuilder("");
for(int i=1;i<ch.length;i++)
{
div=div*mul+Character.getNumericValue(ch[i]);
if(div<divisor) {quotient.append("0");continue;}
quotient.append(div/divisor);
div=div%divisor;mul=10;
}
remainder=div;
while(quotient.charAt(0)=='0')quotient.deleteCharAt(0);
System.out.println(quotient+" "+remainder);
}
public static void sieve(int size)
{
sieve=new int[size+1];
primes=new ArrayList<Integer>();
sieve[1]=1;
for(int i=2;i*i<=size;i++)
{
if(sieve[i]==0)
{
for(int j=i*i;j<size;j+=i) {sieve[j]=1;}
}
}
for(int i=2;i<=size;i++)
{
if(sieve[i]==0) primes.add(i);
}
}
public static long pow(long n, long b, long MOD)
{
long x=1;long y=n;
while(b > 0)
{
if(b%2 == 1)
{
x=x*y;
if(x>MOD) x=x%(MOD);
}
y = y*y;
if(y>MOD) y=y%(MOD);
b >>= 1;
}
return x;
}
public static long mod_inv(long n,long mod)
{
return pow(n,mod-2,mod);
}
//Returns index of highest number less than or equal to key
public static int upper(long[] a,int length,long key)
{
int low = 0;
int high = length-1;
int ans=-1;
while (low <= high) {
int mid = (low + high) / 2;
if (key >= a[mid]) {
ans=mid;
low = mid+1;
} else if(a[mid]>key){
high = mid - 1;
}
}
return ans;
}
//Returns index of least number greater than or equal to key
public static int lower(long[] a,int length,long key)
{
int low = 0;
int high = length-1;
int ans=-1;
while (low <= high) {
int mid = (low + high) / 2;
if (key<=a[mid]) {
ans=mid;
high = mid-1;
}
else{
low=mid+1;
}
}
return ans;
}
public long gcd(long r,long ans)
{
if(r==0) return ans;
return gcd(ans%r,r);
}
public fast() {
this(System.in);
}
public fast(InputStream is) {
i = is;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = i.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
} | Java | ["9\n0 1 1 1 0 0 0 0 1\n1 2\n1 3\n3 4\n3 5\n2 6\n4 7\n6 8\n5 9", "4\n0 0 1 0\n1 2\n1 3\n1 4"] | 2 seconds | ["2 2 2 2 2 1 1 0 2", "0 -1 1 -1"] | NoteThe first example is shown below:The black vertices have bold borders.In the second example, the best subtree for vertices $$$2, 3$$$ and $$$4$$$ are vertices $$$2, 3$$$ and $$$4$$$ correspondingly. And the best subtree for the vertex $$$1$$$ is the subtree consisting of vertices $$$1$$$ and $$$3$$$. | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | cb8895ddd54ffbd898b1bf5e169feb63 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the color of the $$$i$$$-th vertex. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \le u_i, v_i \le n, u_i \ne v_i$$$). It is guaranteed that the given edges form a tree. | 1,800 | Print $$$n$$$ integers $$$res_1, res_2, \dots, res_n$$$, where $$$res_i$$$ is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex $$$i$$$. | standard output | |
PASSED | 370ca507ddab553e4d417109c1ea1c55 | train_003.jsonl | 1584018300 | You are given a tree consisting of $$$n$$$ vertices. A tree is a connected undirected graph with $$$n-1$$$ edges. Each vertex $$$v$$$ of this tree has a color assigned to it ($$$a_v = 1$$$ if the vertex $$$v$$$ is white and $$$0$$$ if the vertex $$$v$$$ is black).You have to solve the following problem for each vertex $$$v$$$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex $$$v$$$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $$$cnt_w$$$ white vertices and $$$cnt_b$$$ black vertices, you have to maximize $$$cnt_w - cnt_b$$$. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class MaximumWhiteSubtree {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
long mod = (long)(998244353);
long fact[];
public void solve(int testNumber, InputReader in, PrintWriter out) throws IOException {
while(testNumber-->0){
int n = in.nextInt();
int color[] = new int[n+1];
for(int i=1;i<=n;i++){
color[i] = in.nextInt();
if(color[i] == 0)
color[i]--;
}
ArrayList<ArrayList<Integer>> a = new ArrayList<>();
for(int i=0;i<=n;i++)
a.add(new ArrayList<>());
for(int i=0;i<n-1;i++){
int u = in.nextInt();
int v = in.nextInt();
a.get(u).add(v);
a.get(v).add(u);
}
int dp[] = new int[n+1];
dfs(a , new int[n+1] , 1 , color , dp);
// print1d(dp , out);
int ans[] = new int[n+1];
ans[1] = dp[1];
calculate(a , new int[n+1] , 1 , ans , dp);
for(int i=1;i<=n;i++)
out.print(ans[i] + " ");
out.println();
// print1d(ans , out);
}
}
public void calculate(ArrayList<ArrayList<Integer>> a , int visited[] , int index , int ans[] , int dp[]){
// ans[index] = dp[index];
visited[index] = 1;
int l = a.get(index).size();
for(int i=0;i<l;i++){
if(visited[a.get(index).get(i)] == 1)
continue;
if(dp[a.get(index).get(i)]>=0)
ans[a.get(index).get(i)] = Math.max(ans[index] , dp[a.get(index).get(i)]);
else
ans[a.get(index).get(i)] = Math.max(dp[a.get(index).get(i)] , dp[a.get(index).get(i)] + ans[index]);
calculate(a , visited , a.get(index).get(i) , ans , dp);
}
}
public void dfs(ArrayList<ArrayList<Integer>> a , int visited[] , int index , int color[] , int dp[]){
visited[index] = 1;
int l = a.get(index).size();
int sum = 0;
for(int i=0;i<l;i++){
if(visited[a.get(index).get(i)] == 1)
continue;
dfs(a , visited , a.get(index).get(i) , color , dp);
sum += Math.max(0 , dp[a.get(index).get(i)]);
}
dp[index] = color[index] + sum;
}
public boolean check(int table[][] , int level[] , int a , int b , int k){
int distanceA = level[a]+level[b] - 2*level[lca(table , a , b , level)];
if(k>=distanceA && (distanceA-k)%2==0)
return true;
return false;
}
public boolean check(int table[][] , int level[] , int a , int x , int b , int y , int k){
int distanceA = level[a]+level[x] - 2*level[lca(table , a , x , level)];
int distanceB = level[y]+level[b] - 2*level[lca(table , y , b , level)];
int total = distanceA + distanceB + 1;
if(k>=total && (total-k)%2==0)
return true;
return false;
}
public int lca(int table[][] , int u , int v , int level[]){
if(level[u]<level[v]){
int temp = u;
u = v;
v = temp;
}
for(int i=table[u].length-1;i>=0;i--){
if(level[u] - (int)pow(2 , i) >= level[v])
u = table[u][i];
}
if(u == v)
return u;
for(int i=table[u].length-1;i>=0;i--){
if(table[u][i] != table[v][i]){
u = table[u][i];
v = table[v][i];
}
}
return table[u][0];
}
// public void dfs(ArrayList<ArrayList<Integer>> a , int level[] , int index , int parent , int table[][]){
// table[index][0] = parent;
// for(int i=1;i<table[index].length;i++)
// table[index][i] = table[table[index][i-1]][i-1];
// for(int i=0;i<a.get(index).size();i++){
// if(a.get(index).get(i) == parent)
// continue;
// level[a.get(index).get(i)] = level[index] + 1;
// dfs(a , level , a.get(index).get(i) , index , table);
// }
// }
public void build(int lookup[][] , int arr[], int n) {
for (int i = 0; i < n; i++)
lookup[i][0] = arr[i];
for (int j = 1; (1 << j) <= n; j++) {
for (int i = 0; (i + (1 << j) - 1) < n; i++) {
if (lookup[i][j - 1] > lookup[i + (1 << (j - 1))][j - 1])
lookup[i][j] = lookup[i][j - 1];
else
lookup[i][j] = lookup[i + (1 << (j - 1))][j - 1];
}
}
}
public int query(int lookup[][] , int L, int R) {
int j = (int)(Math.log(R - L + 1)/Math.log(2));
if (lookup[L][j] >= lookup[R - (1 << j) + 1][j])
return lookup[L][j];
else
return lookup[R - (1 << j) + 1][j];
}
public void print1d(int a[] , PrintWriter out){
for(int i=0;i<a.length;i++)
out.print(a[i] + " ");
out.println();
}
public void print2d(int a[][] , PrintWriter out){
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++)
out.print(a[i][j] + " ");
out.println();
}
out.println();
}
public void sieve(int a[]){
a[0] = a[1] = 1;
int i;
for(i=2;i*i<=a.length;i++){
if(a[i] != 0)
continue;
a[i] = i;
for(int k = (i)*(i);k<a.length;k+=i){
if(a[k] != 0)
continue;
a[k] = i;
}
}
}
public int [][] matrixExpo(int c[][] , int n){
int a[][] = new int[c.length][c[0].length];
int b[][] = new int[a.length][a[0].length];
for(int i=0;i<c.length;i++)
for(int j=0;j<c[0].length;j++)
a[i][j] = c[i][j];
for(int i=0;i<a.length;i++)
b[i][i] = 1;
while(n!=1){
if(n%2 == 1){
b = matrixMultiply(a , a);
n--;
}
a = matrixMultiply(a , a);
n/=2;
}
return matrixMultiply(a , b);
}
public int [][] matrixMultiply(int a[][] , int b[][]){
int r1 = a.length;
int c1 = a[0].length;
int c2 = b[0].length;
int c[][] = new int[r1][c2];
for(int i=0;i<r1;i++){
for(int j=0;j<c2;j++){
for(int k=0;k<c1;k++)
c[i][j] += a[i][k]*b[k][j];
}
}
return c;
}
public long nCrPFermet(int n , int r , long p){
if(r==0)
return 1l;
// long fact[] = new long[n+1];
// fact[0] = 1;
// for(int i=1;i<=n;i++)
// fact[i] = (i*fact[i-1])%p;
long modInverseR = pow(fact[r] , p-2 , p);
long modInverseNR = pow(fact[n-r] , p-2 , p);
long w = (((fact[n]*modInverseR)%p)*modInverseNR)%p;
return w;
}
public long pow(long a, long b, long m) {
a %= m;
long res = 1;
while (b > 0) {
long x = b&1;
if (x == 1)
res = res * a % m;
a = a * a % m;
b >>= 1;
}
return res;
}
public long pow(long a, long b) {
long res = 1;
while (b > 0) {
long x = b&1;
if (x == 1)
res = res * a;
a = a * a;
b >>= 1;
}
return res;
}
public void swap(int a[] , int p1 , int p2){
int x = a[p1];
a[p1] = a[p2];
a[p2] = x;
}
public void sortedArrayToBST(TreeSet<Integer> a , int start, int end) {
if (start > end) {
return;
}
int mid = (start + end) / 2;
a.add(mid);
sortedArrayToBST(a, start, mid - 1);
sortedArrayToBST(a, mid + 1, end);
}
class Combine{
int value;
int delete;
Combine(int val , int delete){
this.value = val;
this.delete = delete;
}
}
class Sort2 implements Comparator<Combine>{
public int compare(Combine a , Combine b){
if(a.value > b.value)
return 1;
else if(a.value == b.value && a.delete>b.delete)
return 1;
else if(a.value == b.value && a.delete == b.delete)
return 0;
return -1;
}
}
public int lowerLastBound(ArrayList<Integer> a , int x){
int l = 0;
int r = a.size()-1;
if(a.get(l)>=x)
return -1;
if(a.get(r)<x)
return r;
int mid = -1;
while(l<=r){
mid = (l+r)/2;
if(a.get(mid) == x && a.get(mid-1)<x)
return mid-1;
else if(a.get(mid)>=x)
r = mid-1;
else if(a.get(mid)<x && a.get(mid+1)>=x)
return mid;
else if(a.get(mid)<x && a.get(mid+1)<x)
l = mid+1;
}
return mid;
}
public int upperFirstBound(ArrayList<Integer> a , Integer x){
int l = 0;
int r = a.size()-1;
if(a.get(l)>x)
return l;
if(a.get(r)<=x)
return r+1;
int mid = -1;
while(l<=r){
mid = (l+r)/2;
if(a.get(mid) == x && a.get(mid+1)>x)
return mid+1;
else if(a.get(mid)<=x)
l = mid+1;
else if(a.get(mid)>x && a.get(mid-1)<=x)
return mid;
else if(a.get(mid)>x && a.get(mid-1)>x)
r = mid-1;
}
return mid;
}
public int lowerLastBound(int a[] , int x){
int l = 0;
int r = a.length-1;
if(a[l]>=x)
return -1;
if(a[r]<x)
return r;
int mid = -1;
while(l<=r){
mid = (l+r)/2;
if(a[mid] == x && a[mid-1]<x)
return mid-1;
else if(a[mid]>=x)
r = mid-1;
else if(a[mid]<x && a[mid+1]>=x)
return mid;
else if(a[mid]<x && a[mid+1]<x)
l = mid+1;
}
return mid;
}
public int upperFirstBound(long a[] , long x){
int l = 0;
int r = a.length-1;
if(a[l]>x)
return l;
if(a[r]<=x)
return r+1;
int mid = -1;
while(l<=r){
mid = (l+r)/2;
if(a[mid] == x && a[mid+1]>x)
return mid+1;
else if(a[mid]<=x)
l = mid+1;
else if(a[mid]>x && a[mid-1]<=x)
return mid;
else if(a[mid]>x && a[mid-1]>x)
r = mid-1;
}
return mid;
}
public long log(float number , int base){
return (long) Math.ceil((Math.log(number) / Math.log(base)) + 1e-9);
}
public long gcd(long a , long b){
if(a<b){
long c = b;
b = a;
a = c;
}
while(b!=0){
long c = a;
a = b;
b = c%a;
}
return a;
}
public long[] gcdEx(long p, long q) {
if (q == 0)
return new long[] { p, 1, 0 };
long[] vals = gcdEx(q, p % q);
long d = vals[0];
long a = vals[2];
long b = vals[1] - (p / q) * vals[2];
// 0->gcd 1->xValue 2->yValue
return new long[] { d, a, b };
}
public void sievePhi(int a[]){
a[0] = 0;
a[1] = 1;
for(int i=2;i<a.length;i++)
a[i] = i-1;
for(int i=2;i<a.length;i++)
for(int j = 2*i;j<a.length;j+=i)
a[j] -= a[i];
}
public void lcmSum(long a[]){
int sievePhi[] = new int[(int)1e6 + 1];
sievePhi(sievePhi);
a[0] = 0;
for(int i=1;i<a.length;i++)
for(int j = i;j<a.length;j+=i)
a[j] += (long)i*sievePhi[i];
}
static class AVLTree{
Node root;
public AVLTree(){
this.root = null;
}
public int height(Node n){
return (n == null ? 0 : n.height);
}
public int getBalance(Node n){
return (n == null ? 0 : height(n.left) - height(n.right));
}
public Node rotateRight(Node a){
Node b = a.left;
Node br = b.right;
a.lSum -= b.lSum;
a.lCount -= b.lCount;
b.rSum += a.rSum;
b.rCount += a.rCount;
b.right = a;
a.left = br;
a.height = 1 + Math.max(height(a.left) , height(a.right));
b.height = 1 + Math.max(height(b.left) , height(b.right));
return b;
}
public Node rotateLeft(Node a){
Node b = a.right;
Node bl = b.left;
a.rSum -= b.rSum;
a.rCount -= b.rCount;
b.lSum += a.lSum;
b.lCount += a.lCount;
b.left = a;
a.right = bl;
a.height = 1 + Math.max(height(a.left) , height(a.right));
b.height = 1 + Math.max(height(b.left) , height(b.right));
return b;
}
public Node insert(Node root , long value){
if(root == null){
return new Node(value);
}
if(value<=root.value){
root.lCount++;
root.lSum += value;
root.left = insert(root.left , value);
}
if(value>root.value){
root.rCount++;
root.rSum += value;
root.right = insert(root.right , value);
}
// updating the height of the root
root.height = 1 + Math.max(height(root.left) , height(root.right));
int balance = getBalance(root);
//ll
if(balance>1 && value<=root.left.value)
return rotateRight(root);
//rr
if(balance<-1 && value>root.right.value)
return rotateLeft(root);
//lr
if(balance>1 && value>root.left.value){
root.left = rotateLeft(root.left);
return rotateRight(root);
}
//rl
if(balance<-1 && value<=root.right.value){
root.right = rotateRight(root.right);
return rotateLeft(root);
}
return root;
}
public void insertElement(long value){
this.root = insert(root , value);
}
public int getElementLessThanK(long k){
int count = 0;
Node temp = root;
while(temp!=null){
if(temp.value == k){
if(temp.left == null || temp.left.value<k){
count += temp.lCount;
return count-1;
}
else
temp = temp.left;
}
else if(temp.value>k){
temp = temp.left;
}
else{
count += temp.lCount;
temp = temp.right;
}
}
return count;
}
public void inorder(Node root , PrintWriter out){
Node temp = root;
if(temp!=null){
inorder(temp.left , out);
out.println(temp.value + " " + temp.lCount + " " + temp.rCount);
inorder(temp.right , out);
}
}
}
static class Node{
long value;
long lCount , rCount;
long lSum , rSum;
Node left , right;
int height;
public Node(long value){
this.value = value;
left = null;
right = null;
lCount = 1;
rCount = 1;
lSum = value;
rSum = value;
height = 1;
}
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["9\n0 1 1 1 0 0 0 0 1\n1 2\n1 3\n3 4\n3 5\n2 6\n4 7\n6 8\n5 9", "4\n0 0 1 0\n1 2\n1 3\n1 4"] | 2 seconds | ["2 2 2 2 2 1 1 0 2", "0 -1 1 -1"] | NoteThe first example is shown below:The black vertices have bold borders.In the second example, the best subtree for vertices $$$2, 3$$$ and $$$4$$$ are vertices $$$2, 3$$$ and $$$4$$$ correspondingly. And the best subtree for the vertex $$$1$$$ is the subtree consisting of vertices $$$1$$$ and $$$3$$$. | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | cb8895ddd54ffbd898b1bf5e169feb63 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the color of the $$$i$$$-th vertex. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \le u_i, v_i \le n, u_i \ne v_i$$$). It is guaranteed that the given edges form a tree. | 1,800 | Print $$$n$$$ integers $$$res_1, res_2, \dots, res_n$$$, where $$$res_i$$$ is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex $$$i$$$. | standard output | |
PASSED | a114cf82a86e98197d1c94e0ca59ba85 | train_003.jsonl | 1584018300 | You are given a tree consisting of $$$n$$$ vertices. A tree is a connected undirected graph with $$$n-1$$$ edges. Each vertex $$$v$$$ of this tree has a color assigned to it ($$$a_v = 1$$$ if the vertex $$$v$$$ is white and $$$0$$$ if the vertex $$$v$$$ is black).You have to solve the following problem for each vertex $$$v$$$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex $$$v$$$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $$$cnt_w$$$ white vertices and $$$cnt_b$$$ black vertices, you have to maximize $$$cnt_w - cnt_b$$$. | 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 p5
{
static class Input {
private StringTokenizer tokenizer = null;
private BufferedReader reader;
public Input(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException();
}
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(nextLine());
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public int[] nextIntArray(int n, int add) {
int[] result = new int[n];
for (int i = 0; i < n; i++) {
result[i] = nextInt() + add;
}
return result;
}
public long[] nextLongArray(int n, long add) {
long[] result = new long[n];
for (int i = 0; i < n; i++) {
result[i] = nextLong() + add;
}
return result;
}
public int[] nextIntArray(int n) {
return nextIntArray(n, 0);
}
}
static void dfs(int v,int p)
{
dp[v]=a[v];
for(int e:edg[v])
{
if(e!=p)
{
dfs(e,v);
dp[v]+=Math.max(dp[e],0);
}
}
}
static void dfs2(int v,int p)
{
ans[v]=dp[v];
//out.println("v "+v+" "+ans[v]);
for(int e:edg[v])
{
if(e!=p)
{
dp[v]-=Math.max(dp[e],0);
dp[e]+=Math.max(dp[v],0);
//out.println(dp[v]+" "+dp[e]);
dfs2(e,v);
dp[e]-=Math.max(dp[v],0);
dp[v]+=Math.max(dp[e],0);
}
}
}
static ArrayList<Integer> edg[];
static int a[],ans[];
static int dp[];
static PrintWriter out=new PrintWriter(System.out);
public static void main (String[] args) throws java.lang.Exception
{
Input s=new Input(System.in);
int t=1;
int n=s.nextInt();
a=s.nextIntArray(n);
for(int i=0;i<n;i++)
if(a[i]==0)a[i]=-1;
edg=new ArrayList[n];
for(int i=0;i<n;i++)
edg[i]=new ArrayList<Integer>();
ans=new int[n];
for(int i=0;i<n-1;i++)
{
int u=s.nextInt()-1;
int v=s.nextInt()-1;
edg[u].add(v);
edg[v].add(u);
}
dp=new int[n];
dfs(0,-1);
//for(int i=0;i<n;i++)
//out.print(dp[i]+" ");
//out.println();
dfs2(0,-1);
for(int i=0;i<n;i++)
out.print(ans[i]+" ");
out.println();
out.flush();
}
} | Java | ["9\n0 1 1 1 0 0 0 0 1\n1 2\n1 3\n3 4\n3 5\n2 6\n4 7\n6 8\n5 9", "4\n0 0 1 0\n1 2\n1 3\n1 4"] | 2 seconds | ["2 2 2 2 2 1 1 0 2", "0 -1 1 -1"] | NoteThe first example is shown below:The black vertices have bold borders.In the second example, the best subtree for vertices $$$2, 3$$$ and $$$4$$$ are vertices $$$2, 3$$$ and $$$4$$$ correspondingly. And the best subtree for the vertex $$$1$$$ is the subtree consisting of vertices $$$1$$$ and $$$3$$$. | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | cb8895ddd54ffbd898b1bf5e169feb63 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the color of the $$$i$$$-th vertex. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \le u_i, v_i \le n, u_i \ne v_i$$$). It is guaranteed that the given edges form a tree. | 1,800 | Print $$$n$$$ integers $$$res_1, res_2, \dots, res_n$$$, where $$$res_i$$$ is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex $$$i$$$. | standard output | |
PASSED | 721386ea5be3c948393c8b364a79f250 | train_003.jsonl | 1584018300 | You are given a tree consisting of $$$n$$$ vertices. A tree is a connected undirected graph with $$$n-1$$$ edges. Each vertex $$$v$$$ of this tree has a color assigned to it ($$$a_v = 1$$$ if the vertex $$$v$$$ is white and $$$0$$$ if the vertex $$$v$$$ is black).You have to solve the following problem for each vertex $$$v$$$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex $$$v$$$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $$$cnt_w$$$ white vertices and $$$cnt_b$$$ black vertices, you have to maximize $$$cnt_w - cnt_b$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class MaximumWhiteSubtree {
static int[] color;
static List<Integer>[] adj;
static int[] dp;
public static void main(String[] args) {
FastReader scanner = new FastReader();
int n = scanner.nextInt();
color = new int[n + 1];
for (int i = 1; i < n + 1; i++) color[i] = scanner.nextInt();
adj = new List[n + 1];
for (int i = 0; i <= n; i++) adj[i] = new LinkedList<>();
for (int i = 1; i < n; i++) {
int node = scanner.nextInt();
int child = scanner.nextInt();
adj[node].add(child);
adj[child].add(node);
}
solve(n);
}
private static void solve(int n) {
dp = new int[n + 1];
unmodifiedMaxWhiteSubTree(1, -1);
modifiedMaxWhiteSubTree(1, -1);
for (int i = 1; i <= n; i++) {
System.out.print(dp[i] + " ");
}
}
private static int unmodifiedMaxWhiteSubTree(int node, int parent) {
for (int child : adj[node]) {
if(child==parent) continue;
dp[node] += Math.max(0, unmodifiedMaxWhiteSubTree(child, node));
}
dp[node] += color[node] == 1 ? 1 : -1;
return dp[node];
}
private static void modifiedMaxWhiteSubTree(int node, int parent) {
if (parent != -1) dp[node] += Math.max(0, dp[parent] - Math.max(dp[node], 0));
for (int child : adj[node]) {
if(child!=parent) modifiedMaxWhiteSubTree(child, node);
}
}
static class FastReader {
private StringTokenizer st;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public String next() {
while(st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(nextLine());
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public String nextLine() {
try {
return br.readLine();
} catch(IOException ex) {
ex.printStackTrace();
return null;
}
}
}
}
| Java | ["9\n0 1 1 1 0 0 0 0 1\n1 2\n1 3\n3 4\n3 5\n2 6\n4 7\n6 8\n5 9", "4\n0 0 1 0\n1 2\n1 3\n1 4"] | 2 seconds | ["2 2 2 2 2 1 1 0 2", "0 -1 1 -1"] | NoteThe first example is shown below:The black vertices have bold borders.In the second example, the best subtree for vertices $$$2, 3$$$ and $$$4$$$ are vertices $$$2, 3$$$ and $$$4$$$ correspondingly. And the best subtree for the vertex $$$1$$$ is the subtree consisting of vertices $$$1$$$ and $$$3$$$. | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | cb8895ddd54ffbd898b1bf5e169feb63 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the color of the $$$i$$$-th vertex. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \le u_i, v_i \le n, u_i \ne v_i$$$). It is guaranteed that the given edges form a tree. | 1,800 | Print $$$n$$$ integers $$$res_1, res_2, \dots, res_n$$$, where $$$res_i$$$ is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex $$$i$$$. | standard output | |
PASSED | 9f9849d7a4a9cacb866687c934bc90d7 | train_003.jsonl | 1584018300 | You are given a tree consisting of $$$n$$$ vertices. A tree is a connected undirected graph with $$$n-1$$$ edges. Each vertex $$$v$$$ of this tree has a color assigned to it ($$$a_v = 1$$$ if the vertex $$$v$$$ is white and $$$0$$$ if the vertex $$$v$$$ is black).You have to solve the following problem for each vertex $$$v$$$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex $$$v$$$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $$$cnt_w$$$ white vertices and $$$cnt_b$$$ black vertices, you have to maximize $$$cnt_w - cnt_b$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution {
static int[] color;
static List<Integer>[] adj;
static int[] dp;
public static void main(String[] args) {
FastReader scanner = new FastReader();
// input
int n = scanner.nextInt();
color = new int[n+1];
for (int i = 1; i <= n; i++) color[i] = scanner.nextInt();
adj = new List[n + 1];
for (int i = 1; i <= n; i++) {
adj[i] = new LinkedList<>();
}
for (int i = 0; i < n - 1; i++) {
int parent = scanner.nextInt();
int node = scanner.nextInt();
adj[parent].add(node);
adj[node].add(parent);
}
dp = new int[n+1];
// calculate
unmodifiedMaxWhiteSubTree(1,-1);
modifiedMaxWhiteSubTree(1, -1);
// print
StringBuilder str = new StringBuilder();
for (int i = 1; i <= n; i++) {
str.append(dp[i]);
str.append(' ');
}
System.out.println(str.toString());
}
static int unmodifiedMaxWhiteSubTree(int node, int parent){
for(Integer child: adj[node]){
if(child==parent) continue;
dp[node] += Math.max(0, unmodifiedMaxWhiteSubTree(child, node));
}
dp[node] += color[node] == 1 ? 1 : -1;
return dp[node];
}
static void modifiedMaxWhiteSubTree(int node, int parent){
if(parent!=-1){
dp[node] += Math.max(0, dp[parent] - Math.max(0, dp[node]));
}
for(Integer child: adj[node]){
if(child==parent) continue;
modifiedMaxWhiteSubTree(child, node);
}
}
static class FastReader {
private StringTokenizer st;
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public String next() {
while(st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(nextLine());
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public String nextLine() {
try {
return br.readLine();
} catch(IOException ex) {
ex.printStackTrace();
return null;
}
}
}
}
| Java | ["9\n0 1 1 1 0 0 0 0 1\n1 2\n1 3\n3 4\n3 5\n2 6\n4 7\n6 8\n5 9", "4\n0 0 1 0\n1 2\n1 3\n1 4"] | 2 seconds | ["2 2 2 2 2 1 1 0 2", "0 -1 1 -1"] | NoteThe first example is shown below:The black vertices have bold borders.In the second example, the best subtree for vertices $$$2, 3$$$ and $$$4$$$ are vertices $$$2, 3$$$ and $$$4$$$ correspondingly. And the best subtree for the vertex $$$1$$$ is the subtree consisting of vertices $$$1$$$ and $$$3$$$. | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | cb8895ddd54ffbd898b1bf5e169feb63 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the color of the $$$i$$$-th vertex. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \le u_i, v_i \le n, u_i \ne v_i$$$). It is guaranteed that the given edges form a tree. | 1,800 | Print $$$n$$$ integers $$$res_1, res_2, \dots, res_n$$$, where $$$res_i$$$ is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex $$$i$$$. | standard output | |
PASSED | be7f49338e61e43b2d7566931b0749c7 | train_003.jsonl | 1584018300 | You are given a tree consisting of $$$n$$$ vertices. A tree is a connected undirected graph with $$$n-1$$$ edges. Each vertex $$$v$$$ of this tree has a color assigned to it ($$$a_v = 1$$$ if the vertex $$$v$$$ is white and $$$0$$$ if the vertex $$$v$$$ is black).You have to solve the following problem for each vertex $$$v$$$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex $$$v$$$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $$$cnt_w$$$ white vertices and $$$cnt_b$$$ black vertices, you have to maximize $$$cnt_w - cnt_b$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
public class MaximumWhiteSubtree { // Template for CF
public static class ListComparator implements Comparator<List<Integer>> {
@Override
public int compare(List<Integer> l1, List<Integer> l2) {
for (int i = 0; i < l1.size(); ++i) {
if (l1.get(i).compareTo(l2.get(i)) != 0) {
return l1.get(i).compareTo(l2.get(i));
}
}
return 0;
}
}
public static class Pair {
int first;
int second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
public int getFirst() {
return first;
}
public int getSecond() {
return second;
}
@Override
public String toString() {
return first + " " + second;
}
}
static int[] colors;
static Map<Integer, List<Integer>> map;
static int[] dp;
static boolean[] visited;
static int[] max;
public static void main(String[] args) throws IOException {
// Check for int overflow!!!!
// Should you use a long to store the sum or smthn?
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int n = Integer.parseInt(f.readLine());
StringTokenizer st = new StringTokenizer(f.readLine());
colors = new int[n + 1];
for (int i = 1; i <= n; i++) {
int a = Integer.parseInt(st.nextToken());
colors[i] = a;
}
map = new HashMap<>();
for (int i = 1; i <= n; i++) {
List<Integer> temp = new ArrayList<>();
map.put(i, temp);
}
for (int i = 0; i < n - 1; i++) {
StringTokenizer ab = new StringTokenizer(f.readLine());
int a = Integer.parseInt(ab.nextToken());
int b = Integer.parseInt(ab.nextToken());
map.get(a).add(b);
map.get(b).add(a);
}
dp = new int[n + 1];
visited = new boolean[n + 1];
dfs(1);
max = new int[n + 1];
visited = new boolean[n + 1];
visited[0] = true;
reroot(1, 0);
// System.out.println(Arrays.toString(dp));
// System.out.println(Arrays.toString(max));
for (int i = 1; i <= n; i++) {
out.print(max[i] + " ");
}
out.close();
}
public static void dfs(int curr) {
visited[curr] = true;
if (colors[curr] == 1) {
dp[curr] = 1;
} else {
dp[curr] = -1;
}
for (int a : map.get(curr)) {
if (!visited[a]) {
dfs(a);
int b = dp[a];
if (b > 0) {
dp[curr] += b;
}
// System.out.println(curr + " " + Arrays.toString(dp));
}
}
}
public static void reroot(int curr, int par) {
visited[curr] = true;
if (dp[curr] <= 0) {
max[curr] = Math.max(dp[curr], dp[curr] + max[par]);
} else {
max[curr] = Math.max(dp[curr], max[par]);
}
for (int a : map.get(curr)) {
if (visited[a] != true) {
reroot(a, curr);
}
}
}
} | Java | ["9\n0 1 1 1 0 0 0 0 1\n1 2\n1 3\n3 4\n3 5\n2 6\n4 7\n6 8\n5 9", "4\n0 0 1 0\n1 2\n1 3\n1 4"] | 2 seconds | ["2 2 2 2 2 1 1 0 2", "0 -1 1 -1"] | NoteThe first example is shown below:The black vertices have bold borders.In the second example, the best subtree for vertices $$$2, 3$$$ and $$$4$$$ are vertices $$$2, 3$$$ and $$$4$$$ correspondingly. And the best subtree for the vertex $$$1$$$ is the subtree consisting of vertices $$$1$$$ and $$$3$$$. | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | cb8895ddd54ffbd898b1bf5e169feb63 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the color of the $$$i$$$-th vertex. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \le u_i, v_i \le n, u_i \ne v_i$$$). It is guaranteed that the given edges form a tree. | 1,800 | Print $$$n$$$ integers $$$res_1, res_2, \dots, res_n$$$, where $$$res_i$$$ is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex $$$i$$$. | standard output | |
PASSED | c14c02843e6d76b13315ffe4e53f812e | train_003.jsonl | 1584018300 | You are given a tree consisting of $$$n$$$ vertices. A tree is a connected undirected graph with $$$n-1$$$ edges. Each vertex $$$v$$$ of this tree has a color assigned to it ($$$a_v = 1$$$ if the vertex $$$v$$$ is white and $$$0$$$ if the vertex $$$v$$$ is black).You have to solve the following problem for each vertex $$$v$$$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex $$$v$$$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $$$cnt_w$$$ white vertices and $$$cnt_b$$$ black vertices, you have to maximize $$$cnt_w - cnt_b$$$. | 256 megabytes | import java.util.*;
public class test2
{
static void dfs(int n , LinkedList<Integer> arr[] , boolean visited[] , int dp[] , int a[])
{
visited[n] = true;
for(Integer i : arr[n])
{
if(!visited[i])
{
dfs(i , arr, visited, dp,a);
dp[n] += Math.max(0, dp[i]);
}
}
dp[n] += a[n];
}
static void dfs2(int n , LinkedList<Integer> arr[] , boolean visited[] , int ans[] , int dp[] , int parent)
{
visited[n] = true;
if(parent == -1)
ans[n] = dp[n];
else
{
int temp = dp[n];
int temp2 = 0;
if(dp[n] < 0)
temp2 = ans[parent];
else
temp2 = ans[parent] - dp[n];
ans[n] = temp + Math.max(0,temp2);
}
for(Integer i : arr[n])
{
if(!visited[i])
{
dfs2(i,arr,visited,ans,dp,n);
}
}
}
public static void main(String []args)
{
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int a[] = new int[n+1];
for(int i = 1 ; i <= n ; i++)
{
int x = sc.nextInt();
if(x == 1)
a[i] = 1;
else
a[i] = -1;
}
LinkedList<Integer> arr[] = new LinkedList[n+1];
boolean visited[] = new boolean[n+1];
for(int i = 1 ; i <= n ;i++)
{
arr[i] = new LinkedList<Integer>();
}
for(int i = 1 ; i <= n-1 ; i++)
{
int x = sc.nextInt();
int y = sc.nextInt();
arr[x].add(y);
arr[y].add(x);
}
int dp[] = new int[n+1];
dfs(1,arr,visited,dp,a);
for(int i = 1 ; i <= n ; i++)
{
visited[i] = false;
}
int ans[] = new int[n+1];
ans[1] = dp[1];
//System.out.println(dp[2] + " " + dp[3]);
//System.out.println(a[1]);
dfs2(1,arr,visited,ans,dp,-1);
StringBuffer str = new StringBuffer("");
for(int i = 1 ; i <= n ; i++)
{
str.append(ans[i] + " ");
}
System.out.println(str);
}
} | Java | ["9\n0 1 1 1 0 0 0 0 1\n1 2\n1 3\n3 4\n3 5\n2 6\n4 7\n6 8\n5 9", "4\n0 0 1 0\n1 2\n1 3\n1 4"] | 2 seconds | ["2 2 2 2 2 1 1 0 2", "0 -1 1 -1"] | NoteThe first example is shown below:The black vertices have bold borders.In the second example, the best subtree for vertices $$$2, 3$$$ and $$$4$$$ are vertices $$$2, 3$$$ and $$$4$$$ correspondingly. And the best subtree for the vertex $$$1$$$ is the subtree consisting of vertices $$$1$$$ and $$$3$$$. | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | cb8895ddd54ffbd898b1bf5e169feb63 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the color of the $$$i$$$-th vertex. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \le u_i, v_i \le n, u_i \ne v_i$$$). It is guaranteed that the given edges form a tree. | 1,800 | Print $$$n$$$ integers $$$res_1, res_2, \dots, res_n$$$, where $$$res_i$$$ is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex $$$i$$$. | standard output | |
PASSED | 141bf02999faa6bc66547c0ae521c9fc | train_003.jsonl | 1584018300 | You are given a tree consisting of $$$n$$$ vertices. A tree is a connected undirected graph with $$$n-1$$$ edges. Each vertex $$$v$$$ of this tree has a color assigned to it ($$$a_v = 1$$$ if the vertex $$$v$$$ is white and $$$0$$$ if the vertex $$$v$$$ is black).You have to solve the following problem for each vertex $$$v$$$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex $$$v$$$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $$$cnt_w$$$ white vertices and $$$cnt_b$$$ black vertices, you have to maximize $$$cnt_w - cnt_b$$$. | 256 megabytes |
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
import java.text.*;
public class Prac{
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
}
catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int ni() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nl() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nia(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}
public String rs() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
public static class Key {
private final int x;
private final int y;
public Key(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Key)) return false;
Key key = (Key) o;
return x == key.x && y == key.y;
}
@Override
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
}
static PrintWriter w = new PrintWriter(System.out);
static long mod=998244353L,mod1=1000000007;
static int co[][];
static void dsort(){
Arrays.parallelSort(co,(o1,o2)->o1[0]!=o2[0]?o1[0]-o2[0]:o1[1]-o2[1]);
}
static class Pair{
int w,b;
public Pair(int w,int b){
this.b=b;
this.w=w;
}
}
static int c[],dp[],n,ans[];
static ArrayList<Integer> arr[];
static int dfs(int i,int p){
int di=-1;
if(c[i]==1)di=1;
for(int j:arr[i]){
if(j!=p){
di+=(Math.max(0,dfs(j,i)));
}
}
return dp[i] =di;
}
static void dfs1(int i,int p){
for(int j:arr[i]){
if(j!=p){
if(dp[j]<0){
dp[j]+=Math.max(0,dp[i]);
}
else{
dp[j]+=Math.max(0,dp[i]-dp[j]);
}
dfs1(j,i);
}
}
}
public static void main (String[] args)throws IOException{
InputReader sc=new InputReader(System.in);
n=sc.ni();
c=new int[n+1];
dp=new int[n+1];
ans=new int[n+1];
arr=new ArrayList[n+1];
for(int i=1;i<=n;i++){
c[i]=sc.ni();
arr[i]=new ArrayList<>();
}
for(int i=0;i<n-1;i++){
int u=sc.ni(),v=sc.ni();
arr[u].add(v);
arr[v].add(u);
}
dfs(1,1);
// for(int i=1;i<=n;i++){
// w.print(dp[i]+" ");
// }
dfs1(1,1);
//ans[1]=dp[1];
for(int i=1;i<=n;i++){
w.print(dp[i]+" ");
}
w.println();
w.close();
}
} | Java | ["9\n0 1 1 1 0 0 0 0 1\n1 2\n1 3\n3 4\n3 5\n2 6\n4 7\n6 8\n5 9", "4\n0 0 1 0\n1 2\n1 3\n1 4"] | 2 seconds | ["2 2 2 2 2 1 1 0 2", "0 -1 1 -1"] | NoteThe first example is shown below:The black vertices have bold borders.In the second example, the best subtree for vertices $$$2, 3$$$ and $$$4$$$ are vertices $$$2, 3$$$ and $$$4$$$ correspondingly. And the best subtree for the vertex $$$1$$$ is the subtree consisting of vertices $$$1$$$ and $$$3$$$. | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | cb8895ddd54ffbd898b1bf5e169feb63 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the color of the $$$i$$$-th vertex. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \le u_i, v_i \le n, u_i \ne v_i$$$). It is guaranteed that the given edges form a tree. | 1,800 | Print $$$n$$$ integers $$$res_1, res_2, \dots, res_n$$$, where $$$res_i$$$ is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex $$$i$$$. | standard output | |
PASSED | 77af8af25dac72f10e8a6f159b325ce3 | train_003.jsonl | 1584018300 | You are given a tree consisting of $$$n$$$ vertices. A tree is a connected undirected graph with $$$n-1$$$ edges. Each vertex $$$v$$$ of this tree has a color assigned to it ($$$a_v = 1$$$ if the vertex $$$v$$$ is white and $$$0$$$ if the vertex $$$v$$$ is black).You have to solve the following problem for each vertex $$$v$$$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex $$$v$$$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $$$cnt_w$$$ white vertices and $$$cnt_b$$$ black vertices, you have to maximize $$$cnt_w - cnt_b$$$. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class MaximumWhiteSubtree {
private static StringBuffer solve(int n, int[] color, List<List<Integer>> graph) {
StringBuffer ans = new StringBuffer();
int[] dp = new int[n];
boolean[] visited = new boolean[n];
dfs(graph, color, 0, visited, dp);
//System.out.println(Arrays.toString(dp));
Arrays.fill(visited, false);
bfs(graph, color, 0, visited, dp);
for(int res : dp){
ans.append(res).append(" ");
}
ans.append("\n");
return ans;
}
private static void bfs(List<List<Integer>> graph, int[] color, int source, boolean[] visited, int[] dp){
Queue<Integer> q = new LinkedList<>();
q.offer(source);
visited[source] = true;
while (!q.isEmpty()){
int u = q.poll();
for(int v : graph.get(u)){
if(!visited[v]){
visited[v] = true;
dp[v] += Math.max(0, (dp[u] - Math.max(0, dp[v])));
q.offer(v);
}
}
}
}
private static int dfs(List<List<Integer>> graph, int[] color, int u, boolean[] visited, int[] dp){
if(visited[u]) return 0;
visited[u] = true;
for(int v: graph.get(u)){
int resV = dfs(graph, color, v, visited, dp);
dp[u] += Math.max(0, resV);
}
if(color[u] == 1) ++dp[u];
else --dp[u];
return dp[u];
}
public static void main(String[] args) {
FastReader sc = new FastReader();
int n = sc.nextInt();
int[] colors = sc.readArray(n);
List<List<Integer>> graph = buildUnWeightedGraph(n, n - 1, sc);
StringBuffer sb = solve(n, colors, graph);
System.out.println(sb);
}
private static List<List<Integer>> buildUnWeightedGraph(int nodes, int edges, FastReader sc) {
List<List<Integer>> graph = new ArrayList<>();
for (int i = 1; i <= nodes; ++i)
graph.add(new ArrayList<>());
for (int i = 1; i <= edges; ++i) {
int u = sc.nextInt() - 1;
int v = sc.nextInt() - 1;
graph.get(u).add(v);
graph.get(v).add(u);
}
return graph;
}
private static class FastReader {
private 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;
}
int[] readArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; ++i)
arr[i] = nextInt();
return arr;
}
long[] readLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; ++i)
arr[i] = nextLong();
return arr;
}
double[] readDoubleArray(int n) {
double[] arr = new double[n];
for (int i = 0; i < n; ++i)
arr[i] = nextDouble();
return arr;
}
}
}
| Java | ["9\n0 1 1 1 0 0 0 0 1\n1 2\n1 3\n3 4\n3 5\n2 6\n4 7\n6 8\n5 9", "4\n0 0 1 0\n1 2\n1 3\n1 4"] | 2 seconds | ["2 2 2 2 2 1 1 0 2", "0 -1 1 -1"] | NoteThe first example is shown below:The black vertices have bold borders.In the second example, the best subtree for vertices $$$2, 3$$$ and $$$4$$$ are vertices $$$2, 3$$$ and $$$4$$$ correspondingly. And the best subtree for the vertex $$$1$$$ is the subtree consisting of vertices $$$1$$$ and $$$3$$$. | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | cb8895ddd54ffbd898b1bf5e169feb63 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the color of the $$$i$$$-th vertex. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \le u_i, v_i \le n, u_i \ne v_i$$$). It is guaranteed that the given edges form a tree. | 1,800 | Print $$$n$$$ integers $$$res_1, res_2, \dots, res_n$$$, where $$$res_i$$$ is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex $$$i$$$. | standard output | |
PASSED | e657aca6e9ca8583cd80f239dbf2c666 | train_003.jsonl | 1584018300 | You are given a tree consisting of $$$n$$$ vertices. A tree is a connected undirected graph with $$$n-1$$$ edges. Each vertex $$$v$$$ of this tree has a color assigned to it ($$$a_v = 1$$$ if the vertex $$$v$$$ is white and $$$0$$$ if the vertex $$$v$$$ is black).You have to solve the following problem for each vertex $$$v$$$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex $$$v$$$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $$$cnt_w$$$ white vertices and $$$cnt_b$$$ black vertices, you have to maximize $$$cnt_w - cnt_b$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class R627F {
private static int N;
private static int[] A, dp, fin;
private static List<List<Integer>> neighbors;
public static void main(String[] args) throws Exception {
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
N=Integer.parseInt(in.readLine());
A=new int[N];
StringTokenizer tok=new StringTokenizer(in.readLine());
for (int i=0; i<N; i++)
A[i]=Integer.parseInt(tok.nextToken());
//to find answer for v, root tree at v
//let dp[i]=max scr for any subtree contained inside the set of vertices descended from i
//dp[i]=A[i]+SUM(MAX(dp[c],0)) for ea. c that is a child of i
neighbors=new ArrayList<>();
for (int i=0; i<N; i++)
neighbors.add(new ArrayList<>());
for (int i=0; i<N-1; i++) {
tok=new StringTokenizer(in.readLine());
int a=Integer.parseInt(tok.nextToken())-1,
b=Integer.parseInt(tok.nextToken())-1;
neighbors.get(a).add(b);
neighbors.get(b).add(a);
}
//for (List<Integer> n:neighbors) System.out.println(n);
dp=new int[N];
visited=new boolean[N];
dfs(0);
//System.out.println(Arrays.toString(dp));
fin=new int[N];
Arrays.fill(visited,false);
finish(0);
StringBuilder str=new StringBuilder();
for (int i=0; i<N; i++)
str.append(i>0?" ":"").append(fin[i]);
System.out.println(str);
}
private static boolean[] visited;
private static void dfs(int i) {
dp[i]=A[i]==1?1:-1;
visited[i]=true;
for (int n:neighbors.get(i))
if (!visited[n]) {
dfs(n);
dp[i]+=Math.max(dp[n],0);
}
}
private static void finish(int i) {
fin[i]=dp[i];
visited[i]=true;
//rotate tree along ea. edge from i to a child
//this way we won't have to reprocess the entire tree
int pd=dp[i];
for (int n:neighbors.get(i))
if (!visited[n]) {
int pdc=dp[n];
dp[i]-=Math.max(0,dp[n]);
dp[n]+=Math.max(0,dp[i]);
finish(n);
dp[i]=pd;
dp[n]=pdc;
}
}
} | Java | ["9\n0 1 1 1 0 0 0 0 1\n1 2\n1 3\n3 4\n3 5\n2 6\n4 7\n6 8\n5 9", "4\n0 0 1 0\n1 2\n1 3\n1 4"] | 2 seconds | ["2 2 2 2 2 1 1 0 2", "0 -1 1 -1"] | NoteThe first example is shown below:The black vertices have bold borders.In the second example, the best subtree for vertices $$$2, 3$$$ and $$$4$$$ are vertices $$$2, 3$$$ and $$$4$$$ correspondingly. And the best subtree for the vertex $$$1$$$ is the subtree consisting of vertices $$$1$$$ and $$$3$$$. | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | cb8895ddd54ffbd898b1bf5e169feb63 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the color of the $$$i$$$-th vertex. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \le u_i, v_i \le n, u_i \ne v_i$$$). It is guaranteed that the given edges form a tree. | 1,800 | Print $$$n$$$ integers $$$res_1, res_2, \dots, res_n$$$, where $$$res_i$$$ is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex $$$i$$$. | standard output | |
PASSED | cc02a039be8616e9750215385e77ead9 | train_003.jsonl | 1584018300 | You are given a tree consisting of $$$n$$$ vertices. A tree is a connected undirected graph with $$$n-1$$$ edges. Each vertex $$$v$$$ of this tree has a color assigned to it ($$$a_v = 1$$$ if the vertex $$$v$$$ is white and $$$0$$$ if the vertex $$$v$$$ is black).You have to solve the following problem for each vertex $$$v$$$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex $$$v$$$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $$$cnt_w$$$ white vertices and $$$cnt_b$$$ black vertices, you have to maximize $$$cnt_w - cnt_b$$$. | 256 megabytes |
import java.util.*;
import java.io.*;
import java.text.*;
public class F1324 {
static int[] clr, p, down, ans;
static ArrayList<Integer>[] adjList;
public static int down(int u) {
int sum = 0;
for (int x : adjList[u]) {
if (x != p[u]) {
p[x] = u;
sum += Math.max(down(x), 0);
}
}
return down[u] = sum + clr[u];
}
public static void solve(int u) {
if (down[u] == -1) {
ans[u] = Math.max(down[u], -1 + (p[u] == -1 ? 0 : ans[p[u]]));
} else
ans[u] = Math.max(down[u], (p[u] == -1 ? 0 : ans[p[u]]));
for (int x : adjList[u]) {
if (x != p[u]) {
solve(x);
}
}
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
clr = sc.nextIntArr(n);
adjList = new ArrayList[n];
for (int i = 0; i < n; i++) {
adjList[i] = new ArrayList<Integer>();
}
for (int i = 0; i < n - 1; i++) {
int u = sc.nextInt() - 1;
int v = sc.nextInt() - 1;
adjList[u].add(v);
adjList[v].add(u);
}
p = new int[n];
Arrays.fill(p, -1);
down = new int[n];
ans = new int[n];
down(0);
// pw.println(Arrays.toString(down));
solve(0);
for (int x : ans) {
pw.print(x + " ");
}
pw.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public int[] nextIntArr(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++) {
arr[i] = nextInt();
if (arr[i] == 0)
arr[i] = -1;
}
return arr;
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
| Java | ["9\n0 1 1 1 0 0 0 0 1\n1 2\n1 3\n3 4\n3 5\n2 6\n4 7\n6 8\n5 9", "4\n0 0 1 0\n1 2\n1 3\n1 4"] | 2 seconds | ["2 2 2 2 2 1 1 0 2", "0 -1 1 -1"] | NoteThe first example is shown below:The black vertices have bold borders.In the second example, the best subtree for vertices $$$2, 3$$$ and $$$4$$$ are vertices $$$2, 3$$$ and $$$4$$$ correspondingly. And the best subtree for the vertex $$$1$$$ is the subtree consisting of vertices $$$1$$$ and $$$3$$$. | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | cb8895ddd54ffbd898b1bf5e169feb63 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the color of the $$$i$$$-th vertex. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \le u_i, v_i \le n, u_i \ne v_i$$$). It is guaranteed that the given edges form a tree. | 1,800 | Print $$$n$$$ integers $$$res_1, res_2, \dots, res_n$$$, where $$$res_i$$$ is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex $$$i$$$. | standard output | |
PASSED | e3e887d8f203f2d0dbba244d42166eb9 | train_003.jsonl | 1584018300 | You are given a tree consisting of $$$n$$$ vertices. A tree is a connected undirected graph with $$$n-1$$$ edges. Each vertex $$$v$$$ of this tree has a color assigned to it ($$$a_v = 1$$$ if the vertex $$$v$$$ is white and $$$0$$$ if the vertex $$$v$$$ is black).You have to solve the following problem for each vertex $$$v$$$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex $$$v$$$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $$$cnt_w$$$ white vertices and $$$cnt_b$$$ black vertices, you have to maximize $$$cnt_w - cnt_b$$$. | 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 Graph
{ static int parent[];
static ArrayList adj[];
static int dp[][];
public Graph(int n) {
parent = new int[n];
adj = new ArrayList[n];
dp = new int[3][n];
for(int i = 0; i < n; i++) {
adj[i] = new ArrayList();
}
}
public void addEdge(int u, int v) {
adj[u].add(v);
adj[v].add(u);
}
public void fillParentIndex(int root) {
Iterator itr = adj[root].iterator();
while(itr.hasNext()) {
int node = (int)itr.next();
if(parent[root] == node)
continue;
parent[node] = root;
fillParentIndex(node);
}
}
public int fillChild(int root) {
Iterator itr = adj[root].iterator();
while(itr.hasNext()) {
int node = (int)itr.next();
if(parent[root] == node)
continue;
dp[0][root] += Math.max(fillChild(node), 0);
}
return dp[0][root] + dp[1][root];
}
public void fillParent(int root) {
Iterator itr = adj[root].iterator();
if(root != 0){
int curr = dp[0][root] + dp[1][root];
int par = curr > 0 ? dp[0][parent[root]] - curr + dp[1][parent[root]] + dp[2][parent[root]] : (dp[0][parent[root]] + dp[1][parent[root]] + dp[2][parent[root]]);
dp[2][root] = Math.max(0, par);
//System.out.println(root + " " + curr + " " + par + " " + (dp[0][parent[root]] + dp[2][parent[root]]));
}
while(itr.hasNext()) {
int node = (int)itr.next();
if(parent[root] == node)
continue;
fillParent(node);
}
}
public static void main (String[] args) throws java.lang.Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String s[] = br.readLine().split(" ");
Graph g = new Graph(n);
for(int i = 0; i < n - 1; i++) {
String s1[] = br.readLine().split(" ");
int u = Integer.parseInt(s1[0]) - 1;
int v = Integer.parseInt(s1[1]) - 1;
g.addEdge(u, v);
}
for(int i = 0; i < n; i++)
dp[1][i] = Integer.parseInt(s[i]) == 1 ? 1 : -1;
g.fillParentIndex(0);
int child = g.fillChild(0);
g.fillParent(0);
for(int i = 0; i < n; i++) {
//System.out.println(dp[0][i] + " " + dp[1][i] + " " + dp[2][i] + " " + parent[i]);
System.out.print((dp[0][i] + dp[1][i] + dp[2][i]) + " ");
}
}
}
| Java | ["9\n0 1 1 1 0 0 0 0 1\n1 2\n1 3\n3 4\n3 5\n2 6\n4 7\n6 8\n5 9", "4\n0 0 1 0\n1 2\n1 3\n1 4"] | 2 seconds | ["2 2 2 2 2 1 1 0 2", "0 -1 1 -1"] | NoteThe first example is shown below:The black vertices have bold borders.In the second example, the best subtree for vertices $$$2, 3$$$ and $$$4$$$ are vertices $$$2, 3$$$ and $$$4$$$ correspondingly. And the best subtree for the vertex $$$1$$$ is the subtree consisting of vertices $$$1$$$ and $$$3$$$. | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | cb8895ddd54ffbd898b1bf5e169feb63 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the color of the $$$i$$$-th vertex. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \le u_i, v_i \le n, u_i \ne v_i$$$). It is guaranteed that the given edges form a tree. | 1,800 | Print $$$n$$$ integers $$$res_1, res_2, \dots, res_n$$$, where $$$res_i$$$ is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex $$$i$$$. | standard output | |
PASSED | 35966febb41cbfa05867b30040de28e1 | train_003.jsonl | 1584018300 | You are given a tree consisting of $$$n$$$ vertices. A tree is a connected undirected graph with $$$n-1$$$ edges. Each vertex $$$v$$$ of this tree has a color assigned to it ($$$a_v = 1$$$ if the vertex $$$v$$$ is white and $$$0$$$ if the vertex $$$v$$$ is black).You have to solve the following problem for each vertex $$$v$$$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex $$$v$$$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $$$cnt_w$$$ white vertices and $$$cnt_b$$$ black vertices, you have to maximize $$$cnt_w - cnt_b$$$. | 256 megabytes | // Don't place your source in a package
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.*;
// Please name your class Main
public class Main {
public static void main (String[] args) throws java.lang.Exception {
Scanner in = new Scanner(System.in);
//int T =in.nextInt();
PrintWriter out = new PrintWriter(System.out);
//for(int t=0;t<T;t++){
int n=in.nextInt();
int colors[]=new int[n+1];
List<Integer>adjecent[]=new ArrayList[n+1];
for(int i=0;i<adjecent.length;i++)adjecent[i]=new ArrayList<>();
for(int i=1;i<colors.length;i++)colors[i]=in.nextInt();
for(int i=0;i<n-1;i++){
int v1=in.nextInt();int v2=in.nextInt();
adjecent[v1].add(v2);
adjecent[v2].add(v1);
}
Solution s=new Solution();
s.solution(adjecent,colors,out);
out.flush();
//}
}
}
class Solution{
List<Integer>adjecent[];
int colors[];
int dp[];
boolean visit[];
PriorityQueue<int[]>pq=new PriorityQueue<>((a,b)->{
return a[0]-b[0];
});
public void solution(List<Integer>adjecent[],int colors[],PrintWriter out){
this.adjecent=adjecent;
this.colors=colors;
dp=new int[colors.length];
visit=new boolean[colors.length];
visit[1]=true;
dfs(1);
Arrays.fill(visit,false);
visit[1]=true;
dfs2(-1,1);
while(pq.size()!=0){
out.print(pq.peek()[1]+" ");
pq.poll();
}
}
public void dfs2(int parent,int root){
int res=dp[root];
List<Integer>childs=adjecent[root];
if(parent!=-1){
int other=dp[parent]-Math.max(0,res);
res+=Math.max(0,other);
}
dp[root]=res;
pq.add(new int[]{root,res});
for(int child:childs){
if(visit[child])continue;
visit[child]=true;
dfs2(root,child);
}
}
public int dfs(int root){
List<Integer>childs=adjecent[root];
int res=0;
for(int child:childs){
if(visit[child])continue;
visit[child]=true;
int val=dfs(child);
res+=Math.max(0,val);
}
if(colors[root]==1)res++;
else res--;
dp[root]=res;
return res;
}
}
| Java | ["9\n0 1 1 1 0 0 0 0 1\n1 2\n1 3\n3 4\n3 5\n2 6\n4 7\n6 8\n5 9", "4\n0 0 1 0\n1 2\n1 3\n1 4"] | 2 seconds | ["2 2 2 2 2 1 1 0 2", "0 -1 1 -1"] | NoteThe first example is shown below:The black vertices have bold borders.In the second example, the best subtree for vertices $$$2, 3$$$ and $$$4$$$ are vertices $$$2, 3$$$ and $$$4$$$ correspondingly. And the best subtree for the vertex $$$1$$$ is the subtree consisting of vertices $$$1$$$ and $$$3$$$. | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | cb8895ddd54ffbd898b1bf5e169feb63 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the color of the $$$i$$$-th vertex. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \le u_i, v_i \le n, u_i \ne v_i$$$). It is guaranteed that the given edges form a tree. | 1,800 | Print $$$n$$$ integers $$$res_1, res_2, \dots, res_n$$$, where $$$res_i$$$ is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex $$$i$$$. | standard output | |
PASSED | f93234b776b6a07d10cbadc4842e9e08 | train_003.jsonl | 1584018300 | You are given a tree consisting of $$$n$$$ vertices. A tree is a connected undirected graph with $$$n-1$$$ edges. Each vertex $$$v$$$ of this tree has a color assigned to it ($$$a_v = 1$$$ if the vertex $$$v$$$ is white and $$$0$$$ if the vertex $$$v$$$ is black).You have to solve the following problem for each vertex $$$v$$$: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex $$$v$$$? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains $$$cnt_w$$$ white vertices and $$$cnt_b$$$ black vertices, you have to maximize $$$cnt_w - cnt_b$$$. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in Actual solution is at the top
*
* @author MakeMoroccoGreatAgain
*/
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);
FMaximumWhiteSubtree solver = new FMaximumWhiteSubtree();
solver.solve(1, in, out);
out.close();
}
static class FMaximumWhiteSubtree {
public final void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = in.nextIntArrayOneBased(n);
int[][] e = in.nextIntMatrix(n - 1, 2);
int[][] t = GraphUtils.packUndirectedUnweighted(e, n);
int[] dp = new int[n + 1];
Arrays.fill(dp, -n * 2);
solveSubtrees(t, dp, a, 1, 0);
solve(t, dp, 1, 0, 0);
out.println(StringUtils.joinRange(1, n, dp));
}
private final void solveSubtrees(int[][] t, int[] dp, int[] a, int u, int p) {
dp[u] = a[u] * 2 - 1;
for (int v : t[u]) {
if (v == p) {
continue;
}
solveSubtrees(t, dp, a, v, u);
dp[u] += Math.max(0, dp[v]);
}
}
private final void solve(int[][] t, int[] dp, int u, int p, int parDiff) {
dp[u] += Math.max(0, parDiff);
for (int v : t[u]) {
if (v == p) {
continue;
}
solve(t, dp, v, u, dp[u] - Math.max(0, dp[v]));
}
}
}
static class StringUtils {
private StringUtils() {
throw new RuntimeException("DON'T");
}
public static final String joinRange(String delimiter, int from, int to, int[] a) {
if (from > to) {
return "";
}
StringBuilder sb = new StringBuilder();
sb.append(a[from]);
for (int i = from + 1; i <= to; i++) {
sb.append(delimiter).append(a[i]);
}
return sb.toString();
}
public static final String joinRange(int from, int to, int[] a) {
return joinRange(" ", from, to, a);
}
}
static final class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[1 << 16];
private int curChar;
private int numChars;
public InputReader() {
this.stream = System.in;
}
public InputReader(final InputStream stream) {
this.stream = stream;
}
private final int read() {
if (this.numChars == -1) {
throw new UnknownError();
} else {
if (this.curChar >= this.numChars) {
this.curChar = 0;
try {
this.numChars = this.stream.read(this.buf);
} catch (IOException ex) {
throw new InputMismatchException();
}
if (this.numChars <= 0) {
return -1;
}
}
return this.buf[this.curChar++];
}
}
public final int nextInt() {
int c;
for (c = this.read(); isSpaceChar(c); c = this.read()) {}
byte sgn = 1;
if (c == 45) { // 45 == '-'
sgn = -1;
c = this.read();
}
int res = 0;
while (c >= 48 && c <= 57) { // 48 == '0', 57 == '9'
res *= 10;
res += c - 48; // 48 == '0'
c = this.read();
if (isSpaceChar(c)) {
return res * sgn;
}
}
throw new InputMismatchException();
}
private static final boolean isSpaceChar(final int c) {
return c == 32 || c == 10 || c == 13 || c == 9
|| c == -1; // 32 == ' ', 10 == '\n', 13 == '\r', 9 == '\t'
}
public final int[][] nextIntMatrix(final int n, final int m) {
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = nextInt();
}
}
return arr;
}
public final int[] nextIntArrayOneBased(final int n) {
int[] ret = new int[n + 1];
for (int i = 1; i <= n; i++) {
ret[i] = nextInt();
}
return ret;
}
}
static final class GraphUtils {
private GraphUtils() {
throw new RuntimeException("DON'T");
}
public static final int[][] packUndirectedUnweighted(int[][] edges, int n) {
int[][] g = new int[n + 1][];
int[] size = new int[n + 1];
for (int[] edge : edges) {
++size[edge[0]];
++size[edge[1]];
}
for (int i = 0; i <= n; i++) {
g[i] = new int[size[i]];
}
for (int[] edge : edges) {
g[edge[0]][--size[edge[0]]] = edge[1];
g[edge[1]][--size[edge[1]]] = edge[0];
}
return g;
}
}
}
| Java | ["9\n0 1 1 1 0 0 0 0 1\n1 2\n1 3\n3 4\n3 5\n2 6\n4 7\n6 8\n5 9", "4\n0 0 1 0\n1 2\n1 3\n1 4"] | 2 seconds | ["2 2 2 2 2 1 1 0 2", "0 -1 1 -1"] | NoteThe first example is shown below:The black vertices have bold borders.In the second example, the best subtree for vertices $$$2, 3$$$ and $$$4$$$ are vertices $$$2, 3$$$ and $$$4$$$ correspondingly. And the best subtree for the vertex $$$1$$$ is the subtree consisting of vertices $$$1$$$ and $$$3$$$. | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees",
"graphs"
] | cb8895ddd54ffbd898b1bf5e169feb63 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of vertices in the tree. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \le a_i \le 1$$$), where $$$a_i$$$ is the color of the $$$i$$$-th vertex. Each of the next $$$n-1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by two integers $$$u_i$$$ and $$$v_i$$$, the labels of vertices it connects $$$(1 \le u_i, v_i \le n, u_i \ne v_i$$$). It is guaranteed that the given edges form a tree. | 1,800 | Print $$$n$$$ integers $$$res_1, res_2, \dots, res_n$$$, where $$$res_i$$$ is the maximum possible difference between the number of white and black vertices in some subtree that contains the vertex $$$i$$$. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.