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 | 3d1675f7e61947ddcbd7de68cb9f3254 | train_003.jsonl | 1270136700 | A line on the plane is described by an equation Ax + By + C = 0. You are to find any point on this line, whose coordinates are integer numbers from - 5·1018 to 5·1018 inclusive, or to find out that such points do not exist. | 256 megabytes |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws FileNotFoundException, IOException {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.flush();
out.close();
}
}
class Pair implements Comparable<Pair> {
long cost;
int idx;
Pair(long cost, int second) {
this.cost = cost;
idx = second;
}
@Override
public int compareTo(Pair e) {
if (this.cost != e.cost) {
return Long.compare(this.cost, e.cost);
} else {
return Integer.compare(this.idx, e.idx);
}
}
}
// pair problem can be done using stack
class TaskB {
int MAXN = (int) 1e9 + 7;
void solve(int testNumber, InputReader in, PrintWriter pw) {
long a = in.nextInt();
long b = in.nextInt();
long c = in.nextInt();
long x = a;
long y = b;
long xp = 1;
long xq = 0;
long yp = 0;
long yq = 1;
if (x < 0) {
x = -x;
xp = -1;
}
if (y < 0) {
y = -y;
yq = -1;
}
while (y > 0) {
long by = x / y;
long t = x - by * y;
long tp = xp - by * yp;
long tq = xq - by * yq;
x = y;
xp = yp;
xq = yq;
y = t;
yp = tp;
yq = tq;
System.err.println(x + " " + y + " " + " " + tp + " " + tq + " " + xp + " " + xq + " " + yp + " " + yq);
}
System.err.println(xp + " " + xq);
if (c % x != 0) {
pw.println(-1);
} else {
long p = xp;
long q = xq;
long z;
// p -= z * b;
// q += z * a;
p *= -c / x;
q *= -c / x;
pw.println(p + " " + q);
}
}
long pow(int n, int m) {
if (m == 0)
return 1;
long ans = pow(n, m / 2);
ans = (ans * ans);
if (m % 2 == 1) {
ans = (ans * n);
}
return ans;
}
double pow(double n, int m) {
if (m == 0)
return 1;
double ans = pow(n, m / 2);
ans = (ans * ans);
if (m % 2 == 1) {
ans = (ans * n);
}
return ans;
}
}
class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
st = null;
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
} | Java | ["2 5 3"] | 1 second | ["6 -3"] | null | Java 8 | standard input | [
"number theory",
"math"
] | a01e1c545542c1641eca556439f0692e | The first line contains three integers A, B and C ( - 2·109 ≤ A, B, C ≤ 2·109) — corresponding coefficients of the line equation. It is guaranteed that A2 + B2 > 0. | 1,800 | If the required point exists, output its coordinates, otherwise output -1. | standard output | |
PASSED | 5b7f623cd271ddbf3555a122ba4695f0 | train_003.jsonl | 1270136700 | A line on the plane is described by an equation Ax + By + C = 0. You are to find any point on this line, whose coordinates are integer numbers from - 5·1018 to 5·1018 inclusive, or to find out that such points do not exist. | 256 megabytes |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws FileNotFoundException, IOException {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.flush();
out.close();
}
}
class Pair implements Comparable<Pair> {
long cost;
int idx;
Pair(long cost, int second) {
this.cost = cost;
idx = second;
}
@Override
public int compareTo(Pair e) {
if (this.cost != e.cost) {
return Long.compare(this.cost, e.cost);
} else {
return Integer.compare(this.idx, e.idx);
}
}
}
// pair problem can be done using stack
class TaskB {
int MAXN = (int) 1e9 + 7;
void solve(int testNumber, InputReader in, PrintWriter pw) {
long a = in.nextInt();
long b = in.nextInt();
long c = in.nextInt();
long x = a;
long y = b;
long xp = 1;
long xq = 0;
long yp = 0;
long yq = 1;
if (x < 0) {
x = -x;
xp = -1;
}
if (y < 0) {
y = -y;
yq = -1;
}
while (y > 0) {
long by = x / y;
long t = x - by * y;
long tp = xp - by * yp;
long tq = xq - by * yq;
x = y;
xp = yp;
xq = yq;
y = t;
yp = tp;
yq = tq;
System.err.println(x + " " + y + " " + " " + tp + " " + tq + " " + xp + " " + xq + " " + yp + " " + yq);
}
System.err.println(xp + " " + xq);
if (c % x != 0) {
pw.println(-1);
} else {
long p = xp;
long q = xq;
long z;
if (b == 0) {
z = -q / a;
} else {
z = p / b;
}
// p -= z * b;
// q += z * a;
p *= -c / x;
q *= -c / x;
pw.println(p + " " + q);
}
}
long pow(int n, int m) {
if (m == 0)
return 1;
long ans = pow(n, m / 2);
ans = (ans * ans);
if (m % 2 == 1) {
ans = (ans * n);
}
return ans;
}
double pow(double n, int m) {
if (m == 0)
return 1;
double ans = pow(n, m / 2);
ans = (ans * ans);
if (m % 2 == 1) {
ans = (ans * n);
}
return ans;
}
}
class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
st = null;
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
} | Java | ["2 5 3"] | 1 second | ["6 -3"] | null | Java 8 | standard input | [
"number theory",
"math"
] | a01e1c545542c1641eca556439f0692e | The first line contains three integers A, B and C ( - 2·109 ≤ A, B, C ≤ 2·109) — corresponding coefficients of the line equation. It is guaranteed that A2 + B2 > 0. | 1,800 | If the required point exists, output its coordinates, otherwise output -1. | standard output | |
PASSED | 72bc67fc3308e1b9f5c4917384e1424b | train_003.jsonl | 1270136700 | A line on the plane is described by an equation Ax + By + C = 0. You are to find any point on this line, whose coordinates are integer numbers from - 5·1018 to 5·1018 inclusive, or to find out that such points do not exist. | 256 megabytes | /**
* Created by Akshay on 11/20/17.
*/
import java.util.*;
public class Week_7_Bonus_C {
public static long X;
public static long Y;
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
long A = scan.nextLong();
long B = scan.nextLong();
long C = scan.nextLong();
C = -C;
long d = gcd(A, B);
if(C % d != 0){
System.out.println(-1);
}
else{
System.out.println(X * C / d + " " + Y * C / d);
}
}
public static long gcd(long a, long b){
if(b == 0){
X = 1;
Y = 0;
return a;
}
else{
long ans = gcd(b,a%b);
long t = X;
X = Y;
Y = t - (a / b) * Y;
return ans;
}
}
}
| Java | ["2 5 3"] | 1 second | ["6 -3"] | null | Java 8 | standard input | [
"number theory",
"math"
] | a01e1c545542c1641eca556439f0692e | The first line contains three integers A, B and C ( - 2·109 ≤ A, B, C ≤ 2·109) — corresponding coefficients of the line equation. It is guaranteed that A2 + B2 > 0. | 1,800 | If the required point exists, output its coordinates, otherwise output -1. | standard output | |
PASSED | fd9d4ddde92fe34728b6240d957ff7fa | train_003.jsonl | 1348069500 | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. | 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;
public class pr225C {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
int[] black = new int[m+1];
int[] white = new int[m+1];
for (int i = 0; i < n; i++) {
char[] c = br.readLine().toCharArray();
for(int j = 1; j <= m; j++) {
if(c[j-1] == '.') white[j]++;
else black[j]++;
}
}
out.println(solve(n, m, x, y, white, black));
out.flush();
out.close();
}
private static int solve(int n, int m, int x, int y, int[] white, int[] black) {
for(int i = 1; i <= m; i++) {
white[i] += white[i-1];
black[i] += black[i-1];
}
int[][] dp = new int[m+1][m+1];
for(int i = 1; i <= m; i++) {
int m1 = 100000000;
int m2 = 100000000;
for(int k = x; k <= y; k++) {
if(i - k >= 0) {
m1 = Math.min(m1, dp[1][i - k] + (white[i] - white[i - k]));
m2 = Math.min(m2, dp[0][i - k] + (black[i] - black[i - k]));
}
}
dp[0][i] = m1;
dp[1][i] = m2;
}
return Math.min(dp[0][m], dp[1][m]);
}
}
| Java | ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."] | 2 seconds | ["11", "5"] | NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Java 8 | standard input | [
"dp",
"matrices"
] | 08d13e3c71040684d5a056bd1b53ef3b | The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#". | 1,700 | In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. | standard output | |
PASSED | d5d47ec7637cd0348b8f1f11e415e6f5 | train_003.jsonl | 1348069500 | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. | 256 megabytes | import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
public class Barcode {
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[10005]; // 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, j, t, n, m, x, y;
n = in.nextInt();
m = in.nextInt();
x = in.nextInt();
y = in.nextInt();
in.readLine();
StringBuilder ans = new StringBuilder();
char[][] barcode = new char[n][m];
int hashes[] = new int[m + 1];
for (i = 0; i < n; i++) {
String s = in.readLine();
barcode[i] = s.substring(0, m).toCharArray();
for (j = 0; j < m; j++)
hashes[j + 1] += barcode[i][j] == '#' ? 1 : 0;
}
long dp[][] = new long[2][m + 1];
Arrays.fill(dp[0], Integer.MAX_VALUE);
Arrays.fill(dp[1], Integer.MAX_VALUE);
dp[0][0] = 0;
dp[1][0] = 0;
// dp[i][0]-> if last ith state '.'
for (i = 1; i <= m; i++)
hashes[i] += hashes[i - 1];
dp[0][x] = hashes[x];
dp[1][x] = n * x - hashes[x];
for (i = 0; i <= m - x; i++) {
for (j = i + x; j <= i + y && j <= m; j++) {
dp[0][j] = Math.min(dp[1][i] + hashes[j] - hashes[i], dp[0][j]);
dp[1][j] = Math.min(dp[0][i] + ((j - i) * n - (hashes[j] - hashes[i])), dp[1][j]);
}
}
// System.out.println(Arrays.toString(hashes));
// System.out.println(Arrays.toString(dp[0]) + "\n " + Arrays.toString(dp[1]));
System.out.println(Math.min(dp[0][m], dp[1][m]));
}
}
| Java | ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."] | 2 seconds | ["11", "5"] | NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Java 8 | standard input | [
"dp",
"matrices"
] | 08d13e3c71040684d5a056bd1b53ef3b | The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#". | 1,700 | In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. | standard output | |
PASSED | 62aa599112acb91cd553fcd28f4ff865 | train_003.jsonl | 1348069500 | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. | 256 megabytes | import java.util.*;
public class Barcode {
static int[] columnCount;
static int n, m, x, y;
static Integer[][][] dp;
static final int INF = (int) 1e9;
static int solve(int index, int currentWidth, boolean previousWhite) {
if (index == m) {
return x <= currentWidth && currentWidth <= y ? 0 : INF;
}
if (dp[index][currentWidth][previousWhite ? 1 : 0] != null) {
return dp[index][currentWidth][previousWhite ? 1 : 0];
}
// try painting all column with white
int ans1 = INF;
int newWidth = index == 0 ? 1 : (previousWhite ? currentWidth + 1 : 1);
if ((index == 0 || previousWhite || currentWidth >= x) && newWidth <= y) {
ans1 = (n - columnCount[index]) + solve(index + 1, newWidth, true);
}
// try painting all column with black
int ans2 = INF;
newWidth = index == 0 ? 1 : (previousWhite ? 1 : currentWidth + 1);
if ((index == 0 || !previousWhite || currentWidth >= x) && newWidth <= y) {
ans2 = columnCount[index] + solve(index + 1, newWidth, false);
}
return dp[index][currentWidth][previousWhite ? 1 : 0] = Math.min(ans1, ans2);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
n = in.nextInt();
m = in.nextInt();
x = in.nextInt();
y = in.nextInt();
columnCount = new int[m];
dp = new Integer[m + 1][m + 1][2];
for (int i = 0; i < n; i++) {
char[] row = in.next().toCharArray();
for (int j = 0; j < m; j++) {
columnCount[j] += row[j] == '.' ? 1 : 0;
}
}
System.out.println(solve(0, 0, true));
in.close();
System.exit(0);
}
}
| Java | ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."] | 2 seconds | ["11", "5"] | NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Java 8 | standard input | [
"dp",
"matrices"
] | 08d13e3c71040684d5a056bd1b53ef3b | The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#". | 1,700 | In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. | standard output | |
PASSED | b431f0653e61c491acffab8a2cecdf7c | train_003.jsonl | 1348069500 | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. | 256 megabytes | import java.util.*;
public class Barcode {
static int[] columnCount;
static int n, m, x, y;
static Integer[][][] dp;
static final int INF = (int) 1e9;
static int solve(int index, int currentWidth, boolean previousWhite) {
if (index == m) {
return x <= currentWidth && currentWidth <= y ? 0 : INF;
}
if (dp[index][currentWidth][previousWhite ? 1 : 0] != null) {
return dp[index][currentWidth][previousWhite ? 1 : 0];
}
// try painting all column with white
int ans1 = INF;
int newWidth = previousWhite ? currentWidth + 1 : 1;
if ((index == 0 || previousWhite || currentWidth >= x) && newWidth <= y) {
ans1 = (n - columnCount[index]) + solve(index + 1, index == 0 ? 1 : newWidth, true);
}
// try painting all column with black
int ans2 = INF;
newWidth = previousWhite ? 1 : currentWidth + 1;
if ((index == 0 || !previousWhite || currentWidth >= x) && newWidth <= y) {
ans2 = columnCount[index] + solve(index + 1, index == 0 ? 1 : newWidth, false);
}
return dp[index][currentWidth][previousWhite ? 1 : 0] = Math.min(ans1, ans2);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
n = in.nextInt();
m = in.nextInt();
x = in.nextInt();
y = in.nextInt();
columnCount = new int[m];
dp = new Integer[m + 1][m + 1][2];
for (int i = 0; i < n; i++) {
char[] row = in.next().toCharArray();
for (int j = 0; j < m; j++) {
columnCount[j] += row[j] == '.' ? 1 : 0;
}
}
System.out.println(solve(0, 0, true));
in.close();
System.exit(0);
}
}
| Java | ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."] | 2 seconds | ["11", "5"] | NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Java 8 | standard input | [
"dp",
"matrices"
] | 08d13e3c71040684d5a056bd1b53ef3b | The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#". | 1,700 | In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. | standard output | |
PASSED | 0f925598aa7e7c9fbfc0f83bb6ae36bb | train_003.jsonl | 1348069500 | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. | 256 megabytes | /**
* ******* Created on 10/12/19 2:45 AM*******
*/
import java.io.*;
import java.util.*;
public class C225 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);
private void solve() throws IOException {
int n = reader.nextInt();
int m = reader.nextInt();
int x = reader.nextInt();
int y = reader.nextInt();
char[][] s = new char[1005][1005];
for(int i=0;i<n;i++)
s[i] = reader.next().toCharArray();
int[] marked = new int[1005];
for(int i=0;i<n;i++)
for(int j =0;j<m;j++)
if(s[i][j] == '#')
marked[j]++;
int[] taken = new int[1005];
int[] notTaken = new int[1005];
for(int i =1; i<= m;i++){
taken[i] =notTaken[i] = Integer.MAX_VALUE/2;
int currentMarked = 0;
int currentUnmarked = 0;
for(int j =1;j <= y && j <= i; j++){
currentMarked += marked[i-j];
currentUnmarked += n - marked[i-j];
if(j >= x){
taken[i] = Math.min(taken[i],currentMarked + notTaken[i-j]);
notTaken[i] = Math.min(notTaken[i], currentUnmarked + taken[i-j]);
}
}
}
writer.println(Math.min(taken[m], notTaken[m]));
}
public static void main(String[] args) throws IOException {
try (Input reader = new StandardInput(); PrintWriter writer = new PrintWriter(System.out)) {
new C225().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 | ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."] | 2 seconds | ["11", "5"] | NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Java 8 | standard input | [
"dp",
"matrices"
] | 08d13e3c71040684d5a056bd1b53ef3b | The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#". | 1,700 | In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. | standard output | |
PASSED | c634834ad09f41c4b1e51e0c02aff92e | train_003.jsonl | 1348069500 | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. | 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 C225_1
{
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 m=in.nextInt();
int x=in.nextInt();
int y=in.nextInt();
char[][] arr=new char[n+1][m+1];
for(int i=1;i<=n;i++)
{
String s=in.nextLine();
for(int j=1;j<=m;j++)
{
arr[i][j]=s.charAt(j-1);
}
}
int[] hashincol=new int[m+1];
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(arr[i][j]=='#')
hashincol[j]++;
}
}
int[] sum1=new int[m+1];
int[] sum2=new int[m+1];
for(int i=1;i<=m;i++)
{
sum1[i]=sum1[i-1]+hashincol[i];
sum2[i]=sum2[i-1]+n-hashincol[i];
}
int[][] dp=new int[m+1][2];
for(int i=0;i<=m;i++)
{
fill(dp[i], mod);
}
dp[0][0]=0; //0-> hash
dp[0][1]=0; //1-> dot
for(int i=0;i<=m;i++)
{
for(int j=x;j<=y;j++)
{
if(i+j>m)
break;
dp[i+j][0]=min(dp[i+j][0], dp[i][1]+sum2[i+j]-sum2[i]);
dp[i+j][1]=min(dp[i+j][1], dp[i][0]+sum1[i+j]-sum1[i]);
}
}
out.println(min(dp[m][0], dp[m][1]));
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 | ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."] | 2 seconds | ["11", "5"] | NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Java 8 | standard input | [
"dp",
"matrices"
] | 08d13e3c71040684d5a056bd1b53ef3b | The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#". | 1,700 | In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. | standard output | |
PASSED | a54c627dfd9030adbfc5ab7ab230701c | train_003.jsonl | 1348069500 | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. | 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 C225
{
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 m=in.nextInt();
int x=in.nextInt();
int y=in.nextInt();
char[][] arr=new char[n+1][m+1];
for(int i=1;i<=n;i++)
{
String s=in.nextLine();
for(int j=1;j<=m;j++)
{
arr[i][j]=s.charAt(j-1);
}
}
int[] hashincol=new int[m+1];
int[] dotincol=new int[m+1];
for(int i=1;i<=m;i++)
{
int count=0;
for(int j=1;j<=n;j++)
{
if(arr[j][i]=='#')
count++;
}
hashincol[i]=count;
dotincol[i]=n-count;
}
int[][][] dp=new int[m+1][y+1][3]; //0-> hash 1->dot
for(int i=0;i<=m;i++)
{
for(int j=0;j<=y;j++)
{
fill(dp[i][j], Integer.MAX_VALUE);
}
}
dp[1][1][0]=dotincol[1];
dp[1][1][1]=hashincol[1];
for(int i=2;i<=m;i++)
{
for(int j=1;j<=y;j++)
{
if(dp[i-1][j-1][0]!=Integer.MAX_VALUE)
{
dp[i][j][0]=min(dp[i][j][0], dp[i-1][j-1][0]+dotincol[i]);
}
if(dp[i-1][j][0]!=Integer.MAX_VALUE && j>=x)
{
//we can start new from here
dp[i][1][1]=min(dp[i][1][1], dp[i-1][j][0]+hashincol[i]);
}
if(dp[i-1][j-1][1]!=Integer.MAX_VALUE)
{
dp[i][j][1]=min(dp[i][j][1], dp[i-1][j-1][1]+hashincol[i]);
}
if(dp[i-1][j][1]!=Integer.MAX_VALUE && j>=x)
{
//we can start new from here
dp[i][1][0]=min(dp[i][1][0], dp[i-1][j][1]+dotincol[i]);
}
}
}
int answer=Integer.MAX_VALUE;
for(int i=x;i<=y;i++)
{
answer=min(answer, dp[m][i][0]);
answer=min(answer, dp[m][i][1]);
}
out.println(answer);
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 | ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."] | 2 seconds | ["11", "5"] | NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Java 8 | standard input | [
"dp",
"matrices"
] | 08d13e3c71040684d5a056bd1b53ef3b | The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#". | 1,700 | In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. | standard output | |
PASSED | f00a20ba69c7bbee6474043bcfcbd5fc | train_003.jsonl | 1348069500 | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.stream.Stream;
public class TestClass implements Runnable {
static final long MOD = Long.MAX_VALUE;
static final Reader in = new Reader();
static final PrintWriter out = new PrintWriter(System.out);
StringBuilder answer = new StringBuilder();
public static void main(String[] args) {
// long startt = System.nanoTime();
new Thread(null, new TestClass(), "persefone", 1 << 28).start();
// out.println((System.nanoTime() - startt));
}
@Override
public void run() {
solve(in.nextInt(), in.nextInt(), in.nextInt(), in.nextInt());
printf();
}
void solve(int n, int m , int x, int y) {
int[] a = new int[m];
int[] b = new int[m];
for (int i = 0; i < n; i++) {
String s = in.next();
for (int j = 0; j < m; j++) {
if (s.charAt(j) == '#') a[j]++; else b[j]++;
}
}
int[] sa = new int[m + 1];
for (int i = 0; i < m ; i++) sa[i + 1] = sa[i] + a[i];
int[] sb = new int[m + 1];
for (int i = 0; i < m; i++) sb[i + 1] = sb[i] + b[i];
int[] dpa = new int[m + 1];
Arrays.fill(dpa, (int) 1e6);
int[] dpb = new int[m + 1];
Arrays.fill(dpb, (int) 1e6);
dpa[0] = 0; dpb[0] = 0;
for (int i = 0; i <= m; i++)
for (int j = i + 1; j <= m; j++)
if (j - i >= x && j - i <=y) {
dpa[j] = Math.min(dpa[j], dpb[i] + sa[j] - sa[i]);
dpb[j] = Math.min(dpb[j], dpa[i] + sb[j] - sb[i]);
}
printf(Math.min(dpa[m], dpb[m]));
}
void computeHashArray(long[] hash, String s, int n) {
for (int i = 1; i <= n; i++)
hash[i] = (31 * hash[i - 1] + s.charAt(i - 1) - 'a') % MOD;
}
void computeModArray(long[] mod, int n) {
mod[0] = 1;
for (int i = 1; i <= n; i++)
mod[i] = (mod[i - 1] * 31) % MOD;
}
long getHash(long[] hash, long[] mod, int i, int j) {
return (hash[j] - hash[i] * mod[j - i]) % MOD;
}
long getHash(String s) {
long hash = 0;
for (int i = 0; i < s.length(); i++)
hash = (hash * 31 + s.charAt(i) - 'a') % MOD;
return hash;
}
void printf() {
out.print(answer);
out.close();
}
void printf(Stream<?> str) {
str.forEach(o -> add(o, " "));
add("\n");
}
void printf(Object... obj) {
if (obj.getClass().isPrimitive()) {
add(obj, "\n");
return;
}
if (obj.length > 1) {
printf(Arrays.stream(obj));
return;
}
if (obj.length == 1) {
Object o = obj[0];
if (o instanceof int[])
printf(Arrays.stream((int[]) o).boxed());
else if (o instanceof char[])
printf(String.valueOf(o).chars());
else if (o instanceof long[])
printf(Arrays.stream((long[]) o).boxed());
else if (o instanceof double[])
printf(Arrays.stream((double[]) o).boxed());
else
add(o, "\n");
}
}
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);
}
static class Node {
private int x, y;
Node(int x, int y) {
this.x = x;
this.y = y;
}
int getX() {
return x;
}
int getY() {
return y;
}
@Override
public String toString() {
return x + " " + y;
}
}
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());
}
String nextLine() {
String s = "";
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
}
} | Java | ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."] | 2 seconds | ["11", "5"] | NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Java 8 | standard input | [
"dp",
"matrices"
] | 08d13e3c71040684d5a056bd1b53ef3b | The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#". | 1,700 | In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. | standard output | |
PASSED | 8649150259219f5e676687ad9198d5b5 | train_003.jsonl | 1348069500 | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. | 256 megabytes | import java.util.*;
public class Main {
static int n, m, x, y;
static int[][] s, mem;
static int[] w;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt(); m = sc.nextInt(); x = sc.nextInt(); y = sc.nextInt();
w = new int[m];
s = new int[2][m];
for (int i = 0; i < n; i++) {
char[] line = sc.next().toCharArray();
for (int j = 0; j < m; j++) {
if(line[j]=='.')
w[j]++;
}
}
mem = new int[2][m];
Arrays.fill(mem[0], -1);
Arrays.fill(mem[1], -1);
int res = Math.min(sol(0, 0), sol(0, 1));
System.out.println(res);
}
private static int sol(int pos, int white) {
if(pos==m)
return 0;
if(mem[white][pos]!=-1)
return mem[white][pos];
int posIn = pos;
int cost = 0;
for (int i = 0; i < x; i++) {
if(pos>=m) {
mem[white][posIn] = n*m;
return mem[white][posIn];
}
cost += (white==1) ? (n-w[pos]) : w[pos];
pos++;
}
int res = cost + sol(pos, 1-white);
for (int i = 1; i <= y-x && pos<m; i++) {
cost += (white==1) ? (n-w[pos]) : w[pos];
pos++;
res = Math.min(res, cost + sol(pos, 1-white));
}
mem[white][posIn] = res;
return res;
}
}
| Java | ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."] | 2 seconds | ["11", "5"] | NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Java 8 | standard input | [
"dp",
"matrices"
] | 08d13e3c71040684d5a056bd1b53ef3b | The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#". | 1,700 | In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. | standard output | |
PASSED | 0487beddeacd9049dedbfd56c1fe4c6f | train_003.jsonl | 1348069500 | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. | 256 megabytes |
import java.io.*;
import java.util.*;
public class C
{
static int n , m , x , y ;
static int [] a , memo [][];
static final int INF = (int)1e9 ;
static int dp(int idx , int w , int lst)
{
if(idx == m)
return x <= w && w <= y ? 0 : INF;
if(memo[idx][w][lst] != -1)
return memo[idx][w][lst];
int ans = INF ;
if(w >= x)
ans = Math.min(ans, (lst == 0 ? n - a[idx] : a[idx]) + dp(idx + 1, 1, lst ^ 1));
if(w + 1 <= y)
ans = Math.min(ans, (lst == 0 ? a[idx] : n - a[idx]) + dp(idx + 1, w + 1, lst)) ;
return memo[idx][w][lst] = ans;
}
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
n = sc.nextInt() ; m = sc.nextInt() ; x = sc.nextInt() ; y = sc.nextInt();
a = new int [m];
for(int i = 0 ; i < n ; i ++)
{
char [] c = sc.next().toCharArray();
for(int j = 0 ; j < m ; j++)
a[j] += c[j] == '#' ? 0 : 1 ;
}
memo = new int [m+1][m+1][2];
for(int [][] x : memo)
for(int [] xx : x)
Arrays.fill(xx, -1);
System.out.println(Math.min(n - a[0] + dp(1, 1, 1),a[0] + dp(1, 1, 0)));
}
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());
}
}
} | Java | ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."] | 2 seconds | ["11", "5"] | NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Java 8 | standard input | [
"dp",
"matrices"
] | 08d13e3c71040684d5a056bd1b53ef3b | The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#". | 1,700 | In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. | standard output | |
PASSED | c6c2a0d2df3cd1b94a78f1d81f10ba88 | train_003.jsonl | 1348069500 | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. | 256 megabytes |
import java.io.*;
import java.util.*;
public class C
{
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt() , m = sc.nextInt() ,x = sc.nextInt() , y = sc.nextInt();
int [] a = new int [m];
for(int i = 0 ; i < n ; i ++)
{
char [] c = sc.next().toCharArray();
for(int j = 0 ; j < m ; j++)
a[j] += c[j] == '#' ? 0 : 1 ;
}
int [][][] memo = new int [m+1][m+2][2];
for(int w = 0 ; w <= m ; w++)
for(int lst = 0 ; lst < 2 ; lst ++)
memo[m][w][lst] = x <= w && w <= y ? 0 : 1_000_000_000;
for(int idx = m - 1 ; idx >= 0 ; idx --)
for(int w = m ; w >= 0 ; w--)
for(int lst = 0 ; lst < 2 ; lst ++)
{
int ans = 1_000_000_000 ;
if(w >= x)
ans = Math.min(ans, (lst == 0 ? n - a[idx] : a[idx]) + memo[idx + 1] [1][lst ^ 1]);
if(w + 1 <= y)
ans = Math.min(ans, (lst == 0 ? a[idx] : n - a[idx]) + memo[idx + 1] [w + 1][ lst]) ;
memo[idx][w][lst] = ans ;
}
System.out.println(Math.min(n - a[0] + memo[1][1][1],a[0] + memo[1] [1] [0]));
}
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());
}
}
} | Java | ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."] | 2 seconds | ["11", "5"] | NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Java 8 | standard input | [
"dp",
"matrices"
] | 08d13e3c71040684d5a056bd1b53ef3b | The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#". | 1,700 | In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. | standard output | |
PASSED | 9f367b438052179a57fa004f5c8f5de3 | train_003.jsonl | 1348069500 | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. | 256 megabytes |
import java.io.*;
import java.util.*;
public class C
{
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt() , m = sc.nextInt() ,x = sc.nextInt() , y = sc.nextInt();
int [] a = new int [m];
for(int i = 0 ; i < n ; i ++)
{
char [] c = sc.next().toCharArray();
for(int j = 0 ; j < m ; j++)
a[j] += c[j] == '#' ? 0 : 1 ;
}
int [][][] memo = new int [2][m+2][m+1];
for(int w = 0 ; w <= m ; w++)
for(int lst = 0 ; lst < 2 ; lst ++)
memo[lst][w][m] = x <= w && w <= y ? 0 : 1_000_000_000;
for(int idx = m - 1 ; idx >= 0 ; idx --)
for(int w = m ; w >= 0 ; w--)
for(int lst = 0 ; lst < 2 ; lst ++)
{
int ans = 1_000_000_000 ;
if(w >= x)
ans = Math.min(ans, (lst == 0 ? n - a[idx] : a[idx]) + memo[lst ^ 1] [1][idx +1]);
if(w + 1 <= y)
ans = Math.min(ans, (lst == 0 ? a[idx] : n - a[idx]) + memo[lst] [w + 1][ idx + 1]) ;
memo[lst][w][idx] = ans ;
}
System.out.println(Math.min(n - a[0] + memo[1][1][1],a[0] + memo[0] [1] [1]));
}
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());
}
}
} | Java | ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."] | 2 seconds | ["11", "5"] | NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Java 8 | standard input | [
"dp",
"matrices"
] | 08d13e3c71040684d5a056bd1b53ef3b | The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#". | 1,700 | In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. | standard output | |
PASSED | 38a0f88cbe31b2b82daa16626324f6b9 | train_003.jsonl | 1348069500 | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. | 256 megabytes | import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.StringTokenizer;
public class l062 {
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());
Integer m = Integer.parseInt(stok.nextToken());
Integer x = Integer.parseInt(stok.nextToken());
Integer y = Integer.parseInt(stok.nextToken());
int[] a = new int[m+1];
for(int i=0;i<n;i++) {
String s = stok.nextToken();
for(int j=0;j<m;j++) {
if(s.charAt(j)=='#') a[j+1]++;
}
}
long[][] dp = new long[m+1][2];
for(int i=0;i<=m;i++) for(int j=0;j<2;j++) dp[i][j] = Integer.MAX_VALUE;
dp[0][0]=0;dp[0][1]=0;
int[] pa = new int[m+1];
for(int i=1;i<=m;i++) pa[i] = a[i] + pa[i-1];
for(int i=1;i<=m;i++) {
for(int j=i+x-1;j<=i+y-1 && j<=m;j++) {
long sum = (j-i+1)*n-(pa[j]-pa[i-1]);
dp[j][1] = Math.min(dp[j][1], dp[i-1][0]+sum);
sum = pa[j]-pa[i-1];
dp[j][0] = Math.min(dp[j][0], dp[i-1][1]+sum);
}
}
System.out.println(Math.min(dp[m][0], dp[m][1]));
}
}
| Java | ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."] | 2 seconds | ["11", "5"] | NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Java 8 | standard input | [
"dp",
"matrices"
] | 08d13e3c71040684d5a056bd1b53ef3b | The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#". | 1,700 | In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. | standard output | |
PASSED | 3dae2da38b92f81d60df3826784a64ac | train_003.jsonl | 1348069500 | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Barcode
{
static char[][] grid;
static int x,y,m,n;
static int[][][] dp;
static int[] hashes;
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
x = sc.nextInt();
y = sc.nextInt();
grid = new char[n][m];
for (int i = 0; i < n; i++)
grid[i] = sc.next().toCharArray();
dp = new int[m+5][m+5][2];
hashes = new int[m];
for (int j = 0; j < m ;j++)
for (int i = 0; i < grid.length; i++)
if(grid[i][j] == '#')
hashes[j]++;
for (int i = 0; i < dp.length; i++)
for (int j = 0; j < dp[i].length; j++)
Arrays.fill(dp[i][j], -1);
System.out.println(Math.min(solve(0, 0, 0), solve(0, 0, 1)));
}
static int solve(int ind, int size, int color)
{
if(size > y)
return 100000000;
if(ind >= m)
if(size < x)
return 100000000;
else
return 0;
if(dp[ind][size][color] != -1)
return dp[ind][size][color];
int ans = 100000000;
// #
if(color == 1)
{
if(size < y)
ans = Math.min(ans, n - hashes[ind] + solve(ind+1, size+1, 1));
if(size >= x)
ans = Math.min(ans, hashes[ind] + solve(ind+1, 1, 0));
}
else
{
if(size < y)
ans = Math.min(ans, hashes[ind] + solve(ind+1, size+1, 0));
if(size >= x)
ans = Math.min(ans, n-hashes[ind] + solve(ind+1, 1, 1));
}
return dp[ind][size][color] = ans;
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s){ br = new BufferedReader(new InputStreamReader(s));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public long nextLong() throws IOException {return Long.parseLong(next());}
public String nextLine() throws IOException {return br.readLine();}
public double nextDouble() throws IOException
{
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if(x.charAt(0) == '-')
{
neg = true;
start++;
}
for(int i = start; i < x.length(); i++)
if(x.charAt(i) == '.')
{
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
}
else
{
sb.append(x.charAt(i));
if(dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg?-1:1);
}
public boolean ready() throws IOException {return br.ready();}
}
}
| Java | ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."] | 2 seconds | ["11", "5"] | NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Java 8 | standard input | [
"dp",
"matrices"
] | 08d13e3c71040684d5a056bd1b53ef3b | The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#". | 1,700 | In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. | standard output | |
PASSED | 98cd9adab120ccc9a29021f7f2eb9a32 | train_003.jsonl | 1348069500 | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static InputReader in = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
static int n, m, x, y;
static int[][] cost = new int[2][];
static final int oo = (int)1e9;
static int[][][] dp = new int[1005][2][1005];
public static void main(String[] args) throws IOException {
n = in.nextInt();
m = in.nextInt();
x = in.nextInt();
y = in.nextInt();
char[][] pic = new char[n][];
for(int i=0; i < n; ++i) {
pic[i] = in.readString().toCharArray();
}
int[] w = new int[m];
int[] b = new int[m];
for(int j=0; j < m; ++j) {
for(int i=0; i < n; ++i) {
if(pic[i][j] == '.')
w[j]++;
else if(pic[i][j] == '#')
b[j]++;
}
}
cost[0] = w;
cost[1] = b;
for(int i=0; i < 1005; ++i) {
for(int j=0; j < 2; ++j) {
for(int k=0; k < 1005; ++k) {
dp[i][j][k] = -1;
}
}
}
System.out.println( Math.min( minCost(0, 0, 0), minCost(0, 1, 0) ) );
out.close();
}
static int minCost(int i, int prevColor, int prevWidth) {
if(i == m) {
if(prevWidth >= x)
return 0;
return oo;
}
if(dp[i][prevColor][prevWidth] != -1)
return dp[i][prevColor][prevWidth];
int min = oo;
if(prevWidth >= x) {
int color = 1 - prevColor;
int width = 1;
min = Math.min(min, cost[color][i] + minCost(i + 1, color, width) );
}
if(prevWidth < y) {
int color = prevColor;
int width = prevWidth + 1;
min = Math.min(min, cost[color][i] + minCost(i + 1, color, width) );
}
return dp[i][prevColor][prevWidth] = min;
}
static int lower_bound(long[] a, int n, long k) {
int s = 0;
int e = n;
int m;
while (e - s > 0) {
m = (s + e) / 2;
if (a[m] < k)
s = m + 1;
else
e = m;
}
return e;
}
}
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 | ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."] | 2 seconds | ["11", "5"] | NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Java 8 | standard input | [
"dp",
"matrices"
] | 08d13e3c71040684d5a056bd1b53ef3b | The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#". | 1,700 | In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. | standard output | |
PASSED | fbab6c0e25c9b2c5df5369dcd323c085 | train_003.jsonl | 1348069500 | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static InputReader in = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
static int n, m, x, y;
static int[][] cost = new int[2][];
static final int oo = (int)1e9;
static int[][][] dp = new int[1005][2][1005];
public static void main(String[] args) throws IOException {
n = in.nextInt();
m = in.nextInt();
x = in.nextInt();
y = in.nextInt();
char[][] pic = new char[n][];
for(int i=0; i < n; ++i) {
pic[i] = in.readString().toCharArray();
}
int[] w = new int[m];
int[] b = new int[m];
for(int j=0; j < m; ++j) {
for(int i=0; i < n; ++i) {
if(pic[i][j] == '.')
w[j]++;
else if(pic[i][j] == '#')
b[j]++;
}
}
cost[0] = w;
cost[1] = b;
for(int i=0; i < 1005; ++i) {
for(int j=0; j < 2; ++j) {
for(int k=0; k < 1005; ++k) {
dp[i][j][k] = -1;
}
}
}
System.out.println( Math.min( minCost(0, 0, 0), minCost(0, 1, 0) ) );
out.close();
}
static int minCost(int i, int prevColor, int prevWidth) {
if(prevWidth > y)
return oo;
if(i == m) {
if(prevWidth >= x)
return 0;
return oo;
}
if(dp[i][prevColor][prevWidth] != -1)
return dp[i][prevColor][prevWidth];
int min = oo;
if(prevWidth >= x) {
int color = 1 - prevColor;
int width = 1;
min = Math.min(min, cost[color][i] + minCost(i + 1, color, width) );
}
// if(prevWidth < y) {
int color = prevColor;
int width = prevWidth + 1;
min = Math.min(min, cost[color][i] + minCost(i + 1, color, width) );
// }
return dp[i][prevColor][prevWidth] = min;
}
static int lower_bound(long[] a, int n, long k) {
int s = 0;
int e = n;
int m;
while (e - s > 0) {
m = (s + e) / 2;
if (a[m] < k)
s = m + 1;
else
e = m;
}
return e;
}
}
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 | ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."] | 2 seconds | ["11", "5"] | NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Java 8 | standard input | [
"dp",
"matrices"
] | 08d13e3c71040684d5a056bd1b53ef3b | The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#". | 1,700 | In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. | standard output | |
PASSED | 6e85b869c8b4c8e172ef6c7ea1532ed3 | train_003.jsonl | 1348069500 | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. | 256 megabytes | import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
// atharva washimkar
// Jan 26, 2018
public class CODEFORCES_225_C {
static int[][][] dp;
static char[][] arr;
static int[] cost1, cost2;
static int N, M, X, Y;
public static int solve (int m, int z, int last) {
if (dp[m][z][last] != -1)
return dp[m][z][last];
if (m == M) {
if (z < X || z > Y)
return dp[m][z][last] = 1 << 25;
else
return dp[m][z][last] = 0;
}
if (z < X) {
return dp[m][z][last] = (last == 0 ? cost1[m] : cost2[m]) + solve (m + 1, z + 1, last);
}
else if (z == Y) {
return dp[m][z][last] = (last == 0 ? cost2[m] : cost1[m]) + solve (m + 1, 1, last ^ 1);
}
else {
return dp[m][z][last] = Math.min ((last == 0 ? cost1[m] : cost2[m]) + solve (m + 1, z + 1, last),
(last == 0 ? cost2[m] : cost1[m]) + solve (m + 1, 1, last ^ 1));
}
}
public static void main (String[] t) throws IOException {
INPUT in = new INPUT (System.in);
PrintWriter out = new PrintWriter (System.out);
N = in.iscan ();
M = in.iscan ();
X = in.iscan ();
Y = in.iscan ();
arr = new char[N][M];
for (int n = 0; n < N; ++n)
arr[n] = in.sscan ().toCharArray ();
dp = new int[M + 1][Y + 1][2];
for (int m = 0; m <= M; ++m)
for (int z = 0; z <= Y; ++z)
for (int l = 0; l <= 1; ++l)
dp[m][z][l] = -1;
cost1 = new int[M];
cost2 = new int[M];
for (int n = 0; n < N; ++n)
for (int m = 0; m < M; ++m)
if (arr[n][m] == '#')
++cost1[m];
for (int m = 0; m < M; ++m)
cost2[m] = N - cost1[m];
out.print (Math.min (solve (0, 0, 0), solve (0, 0, 1)));
out.close ();
}
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);
}
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 | ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."] | 2 seconds | ["11", "5"] | NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Java 8 | standard input | [
"dp",
"matrices"
] | 08d13e3c71040684d5a056bd1b53ef3b | The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#". | 1,700 | In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. | standard output | |
PASSED | 7dce209a7372252c208f7ef5992ef642 | train_003.jsonl | 1348069500 | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
/**
*
* @author Saju
*
*/
public class Main {
private static int dx[] = { 1, 0, -1, 0 };
private static int dy[] = { 0, -1, 0, 1 };
private static final long INF = Long.MAX_VALUE;
private static final int INT_INF = Integer.MAX_VALUE;
private static final long NEG_INF = Long.MIN_VALUE;
private static final int NEG_INT_INF = Integer.MIN_VALUE;
private static final double EPSILON = 1e-10;
private static final int MAX = 1000000007;
private static final long MOD = 1000000007;
private static final int MAXN = 10000007;
private static final int MAXA = 100007;
private static final int MAXLOG = 22;
public static void main(String[] args) throws IOException {
InputReader in = new InputReader(System.in);
// Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
// InputReader in = new InputReader(new FileInputStream("src/test.in"));
// PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("src/test.out")));
/*
6 5 2 4
##.#.
.###.
###..
#...#
.##.#
###..
*/
int n = in.nextInt();
int m = in.nextInt();
int x = in.nextInt();
int y = in.nextInt();
char[][] grid = new char[n][m];
int[] whites = new int[m + 1];
int[] blacks = new int[m + 1];
for(int i = 0; i < n; i++) {
grid[i] = in.next().toCharArray();
for(int j = 0; j < m; j++) {
if(grid[i][j] == '.') {
whites[j + 1]++;
}
else {
blacks[j + 1]++;
}
}
}
// System.out.println(Arrays.toString(whites));
// System.out.println(Arrays.toString(blacks));
for(int i = 1; i <= m; i++) {
blacks[i] += blacks[i - 1];
whites[i] += whites[i - 1];
}
// System.out.println(Arrays.toString(whites));
// System.out.println(Arrays.toString(blacks));
int dp[][] = new int[2][m + 1];
Arrays.fill(dp[0], MAXN);
Arrays.fill(dp[1], MAXN);
dp[0][0] = 0;
dp[1][0] = 0;
for(int i = 1; i <= m; i++) {
for(int a = x; a <= y; a++) {
if(i - a >= 0) {
dp[0][i] = min(dp[0][i], dp[1][i - a] + (whites[i] - whites[i - a]));
dp[1][i] = min(dp[1][i], dp[0][i - a] + (blacks[i] - blacks[i - a]));
}
}
}
out.println(min(dp[0][m], dp[1][m]));
in.close();
out.flush();
out.close();
System.exit(0);
}
private static int[][] dp;
private static int call(int i, int j, int[] arr, int[] arr1) {
if(i < 0 || j < 0) {
return 0;
}
if(dp[i][j] != -1) {
return dp[i][j];
}
// System.out.println(i + " " + j);
int res = 0;
if(arr[i] > arr1[j]) {
res = 2 + call(i - 1, j - 1, arr, arr1);
}
else if(arr[i] == arr1[j]) {
res = max(1 + call(i - 1, j - 1, arr, arr1), call(i, j - 1, arr, arr1));
}
else {
res = call(i, j - 1, arr, arr1);
}
return dp[i][j] = res;
}
private static boolean isPalindrome(String str) {
StringBuilder sb = new StringBuilder();
sb.append(str);
String str1 = sb.reverse().toString();
return str.equals(str1);
}
private static String getBinaryStr(int n, int len) {
String str = Integer.toBinaryString(n);
int k = str.length();
for (int i = 1; i <= len - k; i++) {
str = "0" + str;
}
return str;
}
private static String getBinaryStr(long n, int j) {
String str = Long.toBinaryString(n);
int k = str.length();
for (int i = 1; i <= j - k; i++) {
str = "0" + str;
}
return str;
}
private static long modInverse(long r) {
return bigMod(r, MOD - 2, MOD);
}
private static long bigMod(long n, long k, long m) {
long ans = 1;
while (k > 0) {
if ((k & 1) == 1) {
ans = (ans * n) % m;
}
n = (n * n) % m;
k >>= 1;
}
return ans;
}
private static long ceil(long n, long x) {
long div = n / x;
if(div * x != n) {
div++;
}
return div;
}
private static int ceil(int n, int x) {
int div = n / x;
if(div * x != n) {
div++;
}
return div;
}
private static int abs(int x) {
if (x < 0) {
return -x;
}
return x;
}
private static long abs(long x) {
if(x < 0) {
return -x;
}
return x;
}
private static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
private static int gcd(int a, int b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
private static int log(long x, int base) {
return (int) (Math.log(x) / Math.log(base));
}
private static long min(long a, long b) {
if (a < b) {
return a;
}
return b;
}
private static int min(int a, int b) {
if (a < b) {
return a;
}
return b;
}
private static long max(long a, long b) {
if (a < b) {
return b;
}
return a;
}
private static int max(int a, int b) {
if (a < b) {
return b;
}
return a;
}
private static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
try {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
} catch (IOException e) {
return null;
}
return tokenizer.nextToken();
}
public String nextLine() {
String line = null;
try {
tokenizer = null;
line = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return line;
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public boolean hasNext() {
try {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
} catch (Exception e) {
return false;
}
return true;
}
public int[] nextIntArr(int n) {
int arr[] = new int[n];
for(int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArr(int n) {
long arr[] = new long[n];
for(int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
public int[] nextIntArr1(int n) {
int arr[] = new int[n + 1];
for(int i = 1; i <= n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArr1(int n) {
long arr[] = new long[n + 1];
for(int i = 1; i <= n; i++) {
arr[i] = nextLong();
}
return arr;
}
public void close() {
try {
if(reader != null) {
reader.close();
}
}
catch(Exception e) {
}
}
}
}
| Java | ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."] | 2 seconds | ["11", "5"] | NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Java 8 | standard input | [
"dp",
"matrices"
] | 08d13e3c71040684d5a056bd1b53ef3b | The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#". | 1,700 | In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. | standard output | |
PASSED | d6b83e96648c9e339e3b233cb96b7bba | train_003.jsonl | 1348069500 | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
/**
*
* @author Saju
*
*/
public class Main {
private static int dx[] = { 1, 0, -1, 0 };
private static int dy[] = { 0, -1, 0, 1 };
private static final long INF = Long.MAX_VALUE;
private static final int INT_INF = Integer.MAX_VALUE;
private static final long NEG_INF = Long.MIN_VALUE;
private static final int NEG_INT_INF = Integer.MIN_VALUE;
private static final double EPSILON = 1e-10;
private static final int MAX = 1000000007;
private static final long MOD = 1000000007;
private static final int MAXN = 10000007;
private static final int MAXA = 100007;
private static final int MAXLOG = 22;
public static void main(String[] args) throws IOException {
InputReader in = new InputReader(System.in);
// Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
// InputReader in = new InputReader(new FileInputStream("src/test.in"));
// PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("src/test.out")));
/*
6 5 2 4
##.#.
.###.
###..
#...#
.##.#
###..
*/
int n = in.nextInt();
int m = in.nextInt();
int x = in.nextInt();
int y = in.nextInt();
char[][] grid = new char[n][m];
int[] whites = new int[m + 1];
int[] blacks = new int[m + 1];
for(int i = 0; i < n; i++) {
grid[i] = in.next().toCharArray();
for(int j = 0; j < m; j++) {
if(grid[i][j] == '.') {
whites[j + 1]++;
}
else {
blacks[j + 1]++;
}
}
}
// System.out.println(Arrays.toString(whites));
// System.out.println(Arrays.toString(blacks));
for(int i = 1; i <= m; i++) {
blacks[i] += blacks[i - 1];
whites[i] += whites[i - 1];
}
// System.out.println(Arrays.toString(whites));
// System.out.println(Arrays.toString(blacks));
int dp[][] = new int[2][m + 1];
Arrays.fill(dp[0], MAXN);
Arrays.fill(dp[1], MAXN);
dp[0][0] = 0;
dp[1][0] = 0;
for(int i = 1; i <= m; i++) {
for(int a = x; a <= y; a++) {
if(i - a >= 0) {
dp[0][i] = min(dp[0][i], dp[1][i - a] + (blacks[i] - blacks[i - a]));
dp[1][i] = min(dp[1][i], dp[0][i - a] + (whites[i] - whites[i - a]));
}
}
}
out.println(min(dp[0][m], dp[1][m]));
in.close();
out.flush();
out.close();
System.exit(0);
}
private static int[][] dp;
private static int call(int i, int j, int[] arr, int[] arr1) {
if(i < 0 || j < 0) {
return 0;
}
if(dp[i][j] != -1) {
return dp[i][j];
}
// System.out.println(i + " " + j);
int res = 0;
if(arr[i] > arr1[j]) {
res = 2 + call(i - 1, j - 1, arr, arr1);
}
else if(arr[i] == arr1[j]) {
res = max(1 + call(i - 1, j - 1, arr, arr1), call(i, j - 1, arr, arr1));
}
else {
res = call(i, j - 1, arr, arr1);
}
return dp[i][j] = res;
}
private static boolean isPalindrome(String str) {
StringBuilder sb = new StringBuilder();
sb.append(str);
String str1 = sb.reverse().toString();
return str.equals(str1);
}
private static String getBinaryStr(int n, int len) {
String str = Integer.toBinaryString(n);
int k = str.length();
for (int i = 1; i <= len - k; i++) {
str = "0" + str;
}
return str;
}
private static String getBinaryStr(long n, int j) {
String str = Long.toBinaryString(n);
int k = str.length();
for (int i = 1; i <= j - k; i++) {
str = "0" + str;
}
return str;
}
private static long modInverse(long r) {
return bigMod(r, MOD - 2, MOD);
}
private static long bigMod(long n, long k, long m) {
long ans = 1;
while (k > 0) {
if ((k & 1) == 1) {
ans = (ans * n) % m;
}
n = (n * n) % m;
k >>= 1;
}
return ans;
}
private static long ceil(long n, long x) {
long div = n / x;
if(div * x != n) {
div++;
}
return div;
}
private static int ceil(int n, int x) {
int div = n / x;
if(div * x != n) {
div++;
}
return div;
}
private static int abs(int x) {
if (x < 0) {
return -x;
}
return x;
}
private static long abs(long x) {
if(x < 0) {
return -x;
}
return x;
}
private static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
private static int gcd(int a, int b) {
if (a == 0)
return b;
return gcd(b % a, a);
}
private static int log(long x, int base) {
return (int) (Math.log(x) / Math.log(base));
}
private static long min(long a, long b) {
if (a < b) {
return a;
}
return b;
}
private static int min(int a, int b) {
if (a < b) {
return a;
}
return b;
}
private static long max(long a, long b) {
if (a < b) {
return b;
}
return a;
}
private static int max(int a, int b) {
if (a < b) {
return b;
}
return a;
}
private static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
try {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
} catch (IOException e) {
return null;
}
return tokenizer.nextToken();
}
public String nextLine() {
String line = null;
try {
tokenizer = null;
line = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return line;
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public boolean hasNext() {
try {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
} catch (Exception e) {
return false;
}
return true;
}
public int[] nextIntArr(int n) {
int arr[] = new int[n];
for(int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArr(int n) {
long arr[] = new long[n];
for(int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
public int[] nextIntArr1(int n) {
int arr[] = new int[n + 1];
for(int i = 1; i <= n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArr1(int n) {
long arr[] = new long[n + 1];
for(int i = 1; i <= n; i++) {
arr[i] = nextLong();
}
return arr;
}
public void close() {
try {
if(reader != null) {
reader.close();
}
}
catch(Exception e) {
}
}
}
}
| Java | ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."] | 2 seconds | ["11", "5"] | NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Java 8 | standard input | [
"dp",
"matrices"
] | 08d13e3c71040684d5a056bd1b53ef3b | The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#". | 1,700 | In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. | standard output | |
PASSED | 481d5ff27acdc4f0cdfba61d45239c1c | train_003.jsonl | 1348069500 | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. | 256 megabytes | import java.io.IOException;
import java.util.Scanner;
public class Task225C {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
int x = sc.nextInt();
int y = sc.nextInt();
sc.nextLine();
int[] B = new int[m];
int[][] PSB = new int[2][m];
for (int i=0;i<n;i++) {
String s =sc.nextLine();
for (int j=0;j<m;j++) {
if (s.charAt(j)=='#') B[j]++;
}
}
PSB[0][0]=B[0];
PSB[1][0]=n-B[0];
for (int i=1;i<m;i++) {
PSB[0][i] = B[i]+PSB[0][i-1];
PSB[1][i] = (n-B[i])+PSB[1][i-1];
}
int[][] dp = new int[2][m];
for (int i=0;i<m;i++) {
dp[0][i] = Integer.MAX_VALUE;
for (int j=x;j<=y&&i-j>=-1;j++) {
int s = (i-j<0?0:dp[1][i-j])+sumOfWhite(PSB,n,i-j+1,i);
if ((i-j<0?0:dp[1][i-j]) != Integer.MAX_VALUE) dp[0][i] = Integer.min(dp[0][i],s);
}
dp[1][i] = Integer.MAX_VALUE;
for (int j=x;j<=y&&i-j>=-1;j++) {
int s = (i-j<0?0:dp[0][i-j])+sumOfBlack(PSB,n,i-j+1,i);
if ((i-j<0?0:dp[0][i-j]) != Integer.MAX_VALUE) dp[1][i] = Integer.min(dp[1][i],s);
}
}
System.out.println(Integer.min(dp[0][m-1],dp[1][m-1]));
}
public static int sumOfWhite(int[][] PSB,int n ,int a,int b) {
a--;
return PSB[1][b]-(a<0?0:PSB[1][a]);
}
public static int sumOfBlack(int[][] PSB,int n ,int a,int b) {
a--;
return PSB[0][b]-(a<0?0:PSB[0][a]);
}
} | Java | ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."] | 2 seconds | ["11", "5"] | NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Java 8 | standard input | [
"dp",
"matrices"
] | 08d13e3c71040684d5a056bd1b53ef3b | The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#". | 1,700 | In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. | standard output | |
PASSED | 4e45eb5698932c74bf3a922bfebca476 | train_003.jsonl | 1348069500 | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. | 256 megabytes | import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
/**
* Created by jizhe on 2016/1/21.
*/
public class Barcode {
public static class FasterScanner {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = System.in.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 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;
}
}
public static void main(String[] args) {
//Scanner in = new Scanner(new BufferedInputStream(System.in));
FasterScanner in = new FasterScanner();
StringBuilder out = new StringBuilder();
int N = in.nextInt();
int M = in.nextInt();
int X = in.nextInt();
int Y = in.nextInt();
int[][] change = new int[M+1][2];
for( int i = 0; i < N; i++ )
{
String s = in.nextString();
for( int j = 0; j < M; j++ )
{
if( s.charAt(j) == '.' )
{
change[j+1][0]++;
}
else
{
change[j+1][1]++;
}
}
}
/*for( int i = 1; i < M+1; i++ )
{
System.out.printf("change[%d][0]: %d, change[%d][1]: %d\n", i, change[i][0], i, change[i][1]);
}*/
for( int i = 2; i < M+1; i++ )
{
change[i][0] = change[i-1][0]+change[i][0];
change[i][1] = change[i-1][1]+change[i][1];
}
/*for( int i = 1; i < M+1; i++ )
{
System.out.printf("change[%d][0]: %d, change[%d][1]: %d\n", i, change[i][0], i, change[i][1]);
}*/
int[][] dp = new int[2][M+1];
for( int i = 0; i < 2; i++ )
{
Arrays.fill(dp[i], Integer.MAX_VALUE/2);
}
dp[0][0] = 0;
dp[1][0] = 0;
for( int i = 1; i < M+1; i++ )
{
int min0 = -1, min1 = -1;
for( int j = X; j <= Y; j++ )
{
if( i >= j )
{
dp[0][i] = Math.min(dp[0][i], dp[1][i-j]+change[i][0]-change[i-j][0]);
dp[1][i] = Math.min(dp[1][i], dp[0][i-j]+change[i][1]-change[i-j][1]);
}
}
}
/*for( int i = 0; i < M+1; i++ )
{
System.out.printf("dp[0][%d]: %d, dp[1][%d]: %d\n", i, dp[0][i], i, dp[1][i]);
}*/
System.out.printf("%d\n", Math.min(dp[0][M], dp[1][M]));
}
}
| Java | ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."] | 2 seconds | ["11", "5"] | NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Java 8 | standard input | [
"dp",
"matrices"
] | 08d13e3c71040684d5a056bd1b53ef3b | The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#". | 1,700 | In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. | standard output | |
PASSED | d8ea4ee6feb8c558c02051b6affef624 | train_003.jsonl | 1348069500 | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. | 256 megabytes |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class JavaApplication7
{
static String fixedLengthString(String string, int length) {
return String.format("%1$"+length+ "s", string);
}
static boolean cas(char c)
{
char ar [] = {'A', 'E', 'I', 'O', 'U','Y'} ;
for(int i = 0 ; i < ar.length ; i++)
if(ar[i] == c)
return true ;
return false ;
}
static StringBuilder ans = new StringBuilder() ;
static int ind = -1 ;
static int count = 0;
static void print(int ar [])
{ ind++;
int max = -3;
for(int x = 0 ; x <= ar.length-1 ; x++)
max = Math.max(max, ar[x]) ;
for(int z = 0 ; z <= ar.length-1 ; z++ )
{ if(max == ar[z] )
{
if(z + 1 <= ar.length -1 && max > ar[z+1])
{ for(int w = z ; w < ar.length-1 ; w++ )
ans.append((z+1+ind) +" R\n");
for(int w= z ; w > 0 ; w--)
ans.append((w+1+ind) +" L\n");
count++;
return ;
}
if(z - 1 >= 0 && max > ar[z-1])
{ for(int w= z ; w > 0 ; w--)
ans.append((w+1+ind) +" L\n");
for(int w = z ; w < ar.length -1 ; w++)
ans.append((ind+1) +" R\n");
count++;
return ;
}
}
}
if(ar.length == 1)
{ count++;
}
}
static pair pr[] ;
static int dp [][][] = new int [1001][2][1001] ;
static int rec(int n , int col , int xy )
{ if(n >= m )
{ if(xy <= y && xy >= x)
return 0 ;
else
return 899999999;
}
int min =999999999 ;
if(dp[n][col][xy] != -1)
return dp[n][col][xy] ;
if(col == 1)
{ if(xy < y)
min = Math.min(min, rec(n + 1 , 1 , xy+1) + pr[n].b );
if(xy >= x )
min = Math.min( rec(n + 1 , 0 , 1) + pr[n].a , min) ;
}
else
{ if(xy >= x )
min = Math.min(min , rec(n + 1 , 1 , 1) + pr[n].b );
if(xy < y)
min = Math.min( rec(n + 1 , 0 , xy+1) + pr[n].a , min) ;
}
return dp[n][col][xy] = min ;
}
static int ar [] ;
static int n,m,x,y ;
public static void main(String[] args) throws Exception
{
Reader.init(System.in);
n = Reader.nextInt();m = Reader.nextInt() ; x = Reader.nextInt(); y = Reader.nextInt() ;
char ar [] [] = new char[n][m] ;
for(int i = 0 ; i < n ; i++)
ar[i] = Reader.next().toCharArray() ;
pr = new pair[m] ;
for(int i = 0 ; i < m ; i++)
{for(int j =0 ; j < n ; j++)
if (ar[j][i] == '#' )
count++;
pr[i] = new pair(count , n - count) ;
count = 0 ;
}
for(int i = 0 ; i < dp.length ; i++)
for(int j = 0 ; j < dp[i].length ; j++)
Arrays.fill(dp[i][j], -1);
System.out.println( Math.min(rec(0,0,0),rec(0,1,0)));
}
}
class pair implements Comparable<pair>
{
int a , b;
pair(int a , int b)
{
this.a = a ;
this.b = b ;
}
public int compareTo(pair t) {
if(t.a <a)
return 1 ;
else if(t.a > a) return -1 ;
else return 0 ;
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
static long nextLong() throws IOException{
return Long.parseLong(next()) ;
}
} | Java | ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."] | 2 seconds | ["11", "5"] | NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Java 8 | standard input | [
"dp",
"matrices"
] | 08d13e3c71040684d5a056bd1b53ef3b | The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#". | 1,700 | In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. | standard output | |
PASSED | f006ac84be5ed8f9a4453a1472e358c9 | train_003.jsonl | 1348069500 | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import static java.lang.Math.*;
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.Double.parseDouble;
import static java.lang.String.*;
public class Main {
static int n,m,x,y;
static int [] white,black;
static char [][] g;
static int [][][] dp;
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//(new FileReader("input.in"));
StringBuilder out = new StringBuilder();
StringTokenizer tk;
//PrintWriter pw = new PrintWriter("output.out", "UTF-8");
tk = new StringTokenizer(in.readLine());
n = parseInt(tk.nextToken());
m = parseInt(tk.nextToken());
x = parseInt(tk.nextToken());
y = parseInt(tk.nextToken());
white = new int[m];
black = new int[m];
g = new char[n][m];
for(int i=0; i<n; i++) {
g[i] = in.readLine().toCharArray();
for(int j=0; j<m; j++)
if(g[i][j]=='#') black[j]++;
else white[j]++;
}
dp = new int[m+1][2][y+1];
for(int i=0; i<=m; i++)
for(int j=0; j<2; j++)
Arrays.fill(dp[i][j], -1);
int ans = calc(0,0,0);
for(int i=0; i<=m; i++)
for(int j=0; j<2; j++)
Arrays.fill(dp[i][j], -1);
ans = min(ans, calc(0,1,0));
System.out.println(ans);
}
static int calc(int i,int c,int w) {
if(i == m) {
if((w>=x && w<=y) || w==0)
return 0;
return (int)1e8;
}
if(dp[i][c][w]!=-1)
return dp[i][c][w];
int ans = 0;
if(w+1<x) ans = calc(i+1,c,w+1);
else if(w+1==y) ans = calc(i+1,c^1,0);
else ans = min(calc(i+1,c,w+1),calc(i+1,c^1,0));
return dp[i][c][w] = ans + (c==0 ? white[i] : black[i]);
}
} | Java | ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."] | 2 seconds | ["11", "5"] | NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Java 8 | standard input | [
"dp",
"matrices"
] | 08d13e3c71040684d5a056bd1b53ef3b | The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#". | 1,700 | In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. | standard output | |
PASSED | a18477cd24ea37472dbe33a9b598a598 | train_003.jsonl | 1348069500 | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. | 256 megabytes | import java.io.*;
import java.util.*;
public class test {
static boolean DEBUG_FLAG = false;
int INF = (int)1e9;
long MOD = 1000000007;
static void debug(String s) {
if(DEBUG_FLAG) {
System.out.print(s);
}
}
int n, m, x, y;
char[][] s;
int[][] p;
int[][][] mem;
boolean[][][] vis;
int go(int pos, int color, int cnt) {
if(pos>=m) {
if(cnt>=x) {
return 0;
} else {
return INF;
}
}
if(vis[pos][color][cnt]) {
return mem[pos][color][cnt];
}
int cost = 0;
if(cnt<x) {
cost += p[color][pos];
cost += go(pos+1, color, cnt+1);
} else if(cnt>=y) {
cost += go(pos, color==0?1:0, 0);
} else {
int x = p[color][pos];
x += go(pos+1, color, cnt+1);
int y = go(pos, color==0?1:0, 0);
cost = Math.min(x, y);
}
mem[pos][color][cnt] = cost;
vis[pos][color][cnt] = true;
return cost;
}
void solve(InputReader in, PrintWriter out) throws IOException {
n = in.nextInt();
m = in.nextInt();
x = in.nextInt();
y = in.nextInt();
s = new char[n][];
p = new int[2][m];
for(int i=0; i<n; i++) {
s[i] = in.next().toCharArray();
}
for(int j=0; j<m; j++) {
for(int i=0; i<n; i++) {
if(s[i][j]=='.') {
p[1][j]++;
} else {
p[0][j]++;
}
}
}
// out.println("0 "+Arrays.toString(p[0]));
// out.println("1 "+Arrays.toString(p[1]));
mem = new int[m][2][y+2];
vis = new boolean[m][2][y+2];
int min1 = go(0, 0, 0);
mem = new int[m][2][y+2];
vis = new boolean[m][2][y+2];
int min2 = go(0, 1, 0);
out.println(Math.min(min1, min2));
}
public static void main(String[] args) throws IOException {
if(args.length>0 && args[0].equalsIgnoreCase("d")) {
DEBUG_FLAG = true;
}
InputReader in = new InputReader();
PrintWriter out = new PrintWriter(System.out);
int t = 1;//in.nextInt();
long start = System.nanoTime();
while(t-- >0) {
new test().solve(in, out);
}
long end = System.nanoTime();
debug("\nTime: " + (end-start)/1e6 + " \n\n");
out.close();
}
static class InputReader {
static BufferedReader br;
static StringTokenizer st;
public InputReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
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());
}
}
} | Java | ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."] | 2 seconds | ["11", "5"] | NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Java 8 | standard input | [
"dp",
"matrices"
] | 08d13e3c71040684d5a056bd1b53ef3b | The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#". | 1,700 | In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. | standard output | |
PASSED | 5d6bad423a77b5a445a5810abbb03788 | train_003.jsonl | 1348069500 | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
/**
* Created by Ashiq on 2/13/2017.
*/
public class Main {
static int dp[][];
static int b[],w[];
static int len, x,y;
static int rec( int pos, int bw)
{
if( pos > len) return 0;
else if( dp[pos][bw]!=-1) return dp[pos][bw];
else
{
if( pos+x-1>len ) return 10000000;
else
{
int [] wo;
if(bw==1)wo=w;
else wo=b;
int dot=0;
for( int i=0;i<x;i++)
dot+=wo[pos+i];
int mn=dot+rec(pos+x,bw^1);
for( int n=x;n<y && pos+n<=len;n++)
{
dot+=wo[pos+n];
mn=Math.min( mn, dot+rec( pos+n+1,bw^1));
}
return dp[pos][bw]=mn;
}
}
}
public static void main(String[] args) {
dp=new int[1001][2];
b=new int[1001];
w=new int[1001];
for( int n=0;n<1001;n++)
{
dp[n][0]=-1;
dp[n][1]=-1;
}
int r;
Scanner s=new Scanner(System.in);
r=s.nextInt();
len=s.nextInt();
x=s.nextInt();
y=s.nextInt();
for( int n=0;n<=len;n++){w[n]=r;b[n]=r;}
for( int n=0;n<r;n++)
{
String cc;
cc=s.next();
for( int m=1;m<=len;m++)
{
char c=cc.charAt(m-1);
if( c=='.')w[m]--;
else b[m]--;
}
}
int ans=Math.min( rec(1,0), rec(1,1));
System.out.println(ans);
}
} | Java | ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."] | 2 seconds | ["11", "5"] | NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Java 8 | standard input | [
"dp",
"matrices"
] | 08d13e3c71040684d5a056bd1b53ef3b | The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#". | 1,700 | In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. | standard output | |
PASSED | e98e357553ce946531303708e85f449c | train_003.jsonl | 1348069500 | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. | 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;
public class Solve6 {
public static void main(String[] args) throws IOException {
PrintWriter pw = new PrintWriter(System.out);
new Solve6().solve(pw);
pw.flush();
pw.close();
}
public void solve(PrintWriter pw) throws IOException {
FastReader sc = new FastReader();
int n = sc.nextInt(), m = sc.nextInt(), x = sc.nextInt(), y = sc.nextInt();
int[] colorw = new int[m];
int[] colorb = new int[m];
for (int i = 0; i < n; i++) {
String temp = sc.next();
for (int j = 0; j < m; j++) {
if (temp.charAt(j) == '#') {
colorw[j]++;
}
}
}
for (int i = 0; i < m; i++) {
colorb[i] = n - colorw[i];
}
long[][] dp = new long[m][2];
for (int i = 0; i < m; i++) {
Arrays.fill(dp[i], Integer.MAX_VALUE);
}
for (int i = 0, w = 0, b = 0; i < x; i++) {
w += colorw[i];
b += colorb[i];
if (i + 1 == x) {
dp[i][0] = w;
dp[i][1] = b;
}
}
for (int i = x; i < m; i++) {
int w = 0, b = 0;
for (int j = i; j > i + 1 - x; j--) {
w += colorw[j];
b += colorb[j];
}
for (int j = i + 1 - x; j >= 0 && j >= i + 1 - y; j--) {
w += colorw[j];
b += colorb[j];
if (j < x && j != 0) {
continue;
}
dp[i][0] = Math.min(dp[i][0], w + (j > 0 ? dp[j - 1][1] : 0));
dp[i][1] = Math.min(dp[i][1], b + (j > 0 ? dp[j - 1][0] : 0));
}
}
pw.println(Math.min(dp[m - 1][0], dp[m - 1][1]));
}
static class FastReader {
StringTokenizer st;
BufferedReader br;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next() throws IOException {
if (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
public boolean hasNext() throws IOException {
if (st != null && st.hasMoreTokens()) {
return true;
}
String s = br.readLine();
if (s == null || s.isEmpty()) {
return false;
}
st = new StringTokenizer(s);
return true;
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
}
}
| Java | ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."] | 2 seconds | ["11", "5"] | NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Java 8 | standard input | [
"dp",
"matrices"
] | 08d13e3c71040684d5a056bd1b53ef3b | The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#". | 1,700 | In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. | standard output | |
PASSED | ea221f261f3d0db6d089bf681b580e17 | train_003.jsonl | 1348069500 | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Barcode {
private static int n, m, x, y;
private static Map<Integer, Pair> map = new HashMap<>();
private static int[][][] memo;
public static void main(String[] args) {
FastReader reader = new FastReader();
n = reader.nextInt();
m = reader.nextInt();
x = reader.nextInt();
y = reader.nextInt();
init(reader);
int left = solve(0, 0, 0, new ArrayList<>());
int right = solve(0, 0, 1, new ArrayList<>());
System.out.println(Math.min(left, right));
}
private static void init(FastReader reader) {
String[] s = new String[n];
for (int i = 0; i < n; i++) {
s[i] = reader.next();
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
Pair pair = map.getOrDefault(i, new Pair(0, 0));
if (s[j].charAt(i) == '.')
pair.white += 1;
else
pair.black += 1;
map.put(i, pair);
}
}
memo = new int[m][1001][2];
for (int i = 0; i < m; i++) {
for (int j = 0; j < 1001; j++) {
Arrays.fill(memo[i][j], -1);
}
}
}
private static int solve(int index, int subs, int c, List<Integer> list) {
if (index >= m) {
if (subs < x || subs > y)
return 1000000000;
return 0;
}
if (memo[index][subs][c] != -1) return memo[index][subs][c];
int value;
Pair pair = map.get(index);
if (c == 0)
value = pair.black;
else
value = pair.white;
if (subs < x) {
memo[index][subs][c] = value + solve(index+1, subs+1, c, list);
} else if (subs < y) {
int first = (c == 0 ? pair.black : pair.white) + solve(index+1, subs+1, c, list);
int second = (c == 0 ? pair.white : pair.black) + solve(index+1, 1, 1-c, list);
memo[index][subs][c] = Math.min(first, second);
} else {
memo[index][subs][c] = (c == 0 ? pair.white : pair.black) + solve(index+1, 1, 1-c, list);
}
return memo[index][subs][c];
}
private static class Pair {
int white, black;
public Pair(int white, int black) {
this.white = white;
this.black = black;
}
}
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 | ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."] | 2 seconds | ["11", "5"] | NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Java 8 | standard input | [
"dp",
"matrices"
] | 08d13e3c71040684d5a056bd1b53ef3b | The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#". | 1,700 | In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. | standard output | |
PASSED | ecdc0de189c606485e369cabdcc09e6b | train_003.jsonl | 1348069500 | You've got an n × m pixel picture. Each pixel can be white or black. Your task is to change the colors of as few pixels as possible to obtain a barcode picture.A picture is a barcode if the following conditions are fulfilled: All pixels in each column are of the same color. The width of each monochrome vertical line is at least x and at most y pixels. In other words, if we group all neighbouring columns of the pixels with equal color, the size of each group can not be less than x or greater than y. | 256 megabytes | import java.util.*;
import java.io.*;
public class Solution {
static class FastScanner implements Closeable {
BufferedReader in;
StringTokenizer st;
FastScanner() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = in.readLine();
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
public void close() throws IOException {
in.close();
st = null;
}
}
public static void main(String[] args) throws IOException{
try(FastScanner sc = new FastScanner();
PrintWriter out = new PrintWriter(System.out)){
int n = sc.nextInt();
int m = sc.nextInt();
int x = sc.nextInt();
int y = sc.nextInt();
char[][] arr = new char[n][m];
for(int i = 0; i < n ; i++){
String str = sc.next();
for(int j = 0; j < m; j++){
arr[i][j] = str.charAt(j);
}
}
int[] white = new int[m+1];
int[] black = new int[m+1];
for(int i = 0; i < m; i++){
int b = 0;
int w = 0;
for(int j = 0; j < n; j++){
if(arr[j][i] == '.')
w++;
else
b++;
}
white[i+1] += w;
black[i+1] += b;
}
for(int i = 1; i <= m; i++){
white[i] += white[i - 1];
black[i] += black[i - 1];
}
int[][] dp = new int[2][m+1];
Arrays.fill(dp[0], Integer.MAX_VALUE);
Arrays.fill(dp[1], Integer.MAX_VALUE);
dp[0][0] = dp[1][0] = 0;
for(int i = 1; i <= m; i++){
for(int j = y; j >= x; j--){
if(i - j >= 0 && dp[0][i - j] < Integer.MAX_VALUE){
dp[0][i] = Math.min(dp[0][i], (dp[1][i - j] + white[i] - white[i - j]));
dp[1][i] = Math.min(dp[1][i], (dp[0][i - j] + black[i] - black[i - j]));
}
}
//System.out.println(dp[0][i]+" "+dp[1][i]);
}
out.println(Math.min(dp[0][m], dp[1][m]));
}
}
}
| Java | ["6 5 1 2\n##.#.\n.###.\n###..\n#...#\n.##.#\n###..", "2 5 1 1\n#####\n....."] | 2 seconds | ["11", "5"] | NoteIn the first test sample the picture after changing some colors can looks as follows: .##...##...##...##...##...##.. In the second test sample the picture after changing some colors can looks as follows: .#.#..#.#. | Java 8 | standard input | [
"dp",
"matrices"
] | 08d13e3c71040684d5a056bd1b53ef3b | The first line contains four space-separated integers n, m, x and y (1 ≤ n, m, x, y ≤ 1000; x ≤ y). Then follow n lines, describing the original image. Each of these lines contains exactly m characters. Character "." represents a white pixel and "#" represents a black pixel. The picture description doesn't have any other characters besides "." and "#". | 1,700 | In the first line print the minimum number of pixels to repaint. It is guaranteed that the answer exists. | standard output | |
PASSED | 7c8f87daf1dda04f7beb86bc49b83053 | train_003.jsonl | 1476611100 | Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally. | 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.Arrays;
import java.util.StringTokenizer;
public class FunnyGame {
public static void main(String[] args) throws NumberFormatException, IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
int[] a = new int[n];
long[] dp = new long[n], acc = new long[n];
for(int i = 0; i < n; i++) {
acc[i] = a[i] = sc.nextInt();
if(i > 0)
acc[i] += acc[i - 1];
}
long max = acc[n - 1] - dp[n - 1];
for(int i = n - 2; i >= 0; i--) {
dp[i] = max;
max = Math.max(max, acc[i] - dp[i]);
}
System.out.println(dp[0]);
out.flush();
out.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner(FileReader f) {
br = new BufferedReader(f);
}
public boolean ready() throws IOException {
return br.ready();
}
Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
String nextLine() throws IOException {
return br.readLine();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(next());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(next());
}
}
}
| Java | ["3\n2 4 8", "4\n1 -7 -2 3"] | 1 second | ["14", "-3"] | NoteIn the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 3. | Java 8 | standard input | [
"dp",
"games"
] | b5b13cb304844a8bbd07e247150719f3 | The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall. The second line contains n integers a1, a2, ..., an ( - 10 000 ≤ ai ≤ 10 000) — the numbers on stickers in order from left to right. | 2,200 | Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally. | standard output | |
PASSED | 1b58458757f1fd75a42fc01036dad0fc | train_003.jsonl | 1476611100 | Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally. | 256 megabytes | import java.io.*;
import java.util.*;
public class TaskE
{
static InputReader in;
static PrintWriter out;
public static void main(String[] args) throws FileNotFoundException {
InputStream inputStream = System.in;
//FileInputStream inputStream = new FileInputStream("input.txt");
OutputStream outputStream = System.out;
in = new InputReader(inputStream);
out = new PrintWriter(outputStream);
new Task().run();
out.close();
}
static class Task {
void run() {
int i, n;
n = in.nextInt();
int a[] = new int[n];
int sum[] = new int[n];
for (i = 0; i < n; ++i) {
a[i] = in.nextInt();
sum[i] = a[i];
if (i > 0) sum[i] += sum[i-1];
}
int ans0 = -sum[n-1], ans1 = +sum[n-1];
int val0, val1;
for (i = n-1; i > 1; --i) {
val0 = ans1 - sum[i-1];
val1 = ans0 + sum[i-1];
//out.println("i=" + i + " " + d[i][0] + " " + d[i][1]);
ans0 = Math.min(ans0, val0);
ans1 = Math.max(ans1, val1);
}
//out.print("answer=");
out.println(ans1);
/*
int d[][] = new int[n+1][2];
d[n][0] = d[n][1] = 0;
for (i = n-1; i > 0; --i) {
d[i][0] = Integer.MIN_VALUE;
d[i][1] = Integer.MAX_VALUE;
for (int j = i + 1; j <= n; ++j)
{
d[i][0] = Math.max(d[i][0], d[j][1] + sum[j - 1]);
d[i][1] = Math.min(d[i][1], d[j][0] - sum[j - 1]);
}
}
for (i = 0; i < n; ++i) {
out.println("i=" + i + " " + d[i][0] + " " + d[i][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 | ["3\n2 4 8", "4\n1 -7 -2 3"] | 1 second | ["14", "-3"] | NoteIn the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 3. | Java 8 | standard input | [
"dp",
"games"
] | b5b13cb304844a8bbd07e247150719f3 | The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall. The second line contains n integers a1, a2, ..., an ( - 10 000 ≤ ai ≤ 10 000) — the numbers on stickers in order from left to right. | 2,200 | Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally. | standard output | |
PASSED | a7aacdb303ef584e26f5ad968e2c3572 | train_003.jsonl | 1476611100 | Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.*;
public class TestClass {
private static InputStream stream;
private static byte[] buf = new byte[1024];
private static int curChar;
private static int numChars;
private static SpaceCharFilter filter;
private static PrintWriter pw;
public static class Queue{
private class node{
int val;
node next;
node(int a){
val = a;
next = null;
}
}
node head,tail;
Queue(){
head = null;
tail = null;
}
public void EnQueue(int a){
if(head==null){
node p = new node(a);
head = p;
tail = p;
}
else{
node p = new node(a);
tail.next = p;
tail = p;
}
}
public int DeQueue(){
int a = head.val;
head = head.next;
return a;
}
public boolean isEmpty(){
return head==null;
}
}
public static long pow(long x,long y,long m){
if(y==0)
return 1;
long k = pow(x,y/2,m);
if(y%2==0)
return (k*k)%m;
else
return (((k*k)%m)*x)%m;
}
static long Inversex = 0,Inversey = 0;
public static void InverseModulo(long a,long m){
if(m==0){
Inversex = 1;
Inversey = 0;
}
else{
InverseModulo(m,a%m);
long temp = Inversex;
Inversex = Inversey;
Inversey = temp+ - (a/m)*Inversey;
}
}
static long mod1 = 1000000007;
static long mod2 = 1000000009;
public static long gcd(long a,long b){
if(a%b==0)
return b;
return gcd(b,a%b);
}
public static boolean isPrime(long a){
if(a==1)
return false;
else if(a==2||a==3)
return true;
for(long i=2;i<=Math.sqrt(a);i++)
if(a%i==0)
return false;
return true;
}
public static double distance(int a,int b,int x,int y){
return Math.sqrt(((long)(a-x)*(long)(a-x))+((long)(b-y)*(long)(b-y)));
}
public static class Pair implements Comparable<Pair> {
long u;
long v;
BigInteger bi;
public Pair(long u, long v) {
this.u = u;
this.v = v;
}
public int hashCode() {
int hu = (int) (u ^ (u >>> 32));
int hv = (int) (v ^ (v >>> 32));
return 31 * hu + hv;
}
public boolean equals(Object o) {
Pair other = (Pair) o;
return u == other.u && v == other.v;
}
public int compareTo(Pair other) {
return Long.compare(u, other.u) != 0 ? Long.compare(u, other.u) : Long.compare(v, other.v);
}
public String toString() {
return "[u=" + u + ", v=" + v + "]";
}
}
public static int seive(int a[],boolean b[],TreeSet<Integer> c){
int count = 0;
for(int i=2;i<a.length;i++){
if(!b[i]){
for(int j=i*i;j<a.length&&j>0;j=j+i)
b[j] = true;
c.add(i);
a[count++] = i;
}
}
return count;
}
public static void MatrixMultiplication(int a[][],int b[][],int c[][]){
for(int i=0;i<a.length;i++){
for(int j=0;j<b[0].length;j++){
c[i][j] = 0;
for(int k=0;k<b.length;k++)
c[i][j]=(int)((c[i][j]+((a[i][k]*(long)b[k][j])%mod1))%mod1);
}
}
}
public static void Equal(int arr[][],int temp[][]){
for(int i=0;i<arr.length;i++){
for(int j=0;j<arr.length;j++)
temp[i][j] = arr[i][j];
}
}
public static class Trie {
Node head;
private class Node{
Node a[] = new Node[2];
boolean val;
Node(){
a[0] = null;
a[1] = null;
val = false;
}
}
Trie(){
head = new Node();
}
public void insert(Stack<Integer> s){
Node temp = head;
while(!s.isEmpty()){
int q = s.pop();
if(temp.a[q]==null)
temp.a[q] = new Node();
temp = temp.a[q];
}
temp.val = true;
}
public Node delete(Stack<Integer> s,Node temp){
if(s.isEmpty())
return null;
int q = s.pop();
temp.a[q] = delete(s,temp.a[q]);
if(temp.a[q]==null&&temp.a[q^1]==null)
return null;
else
return temp;
}
public void get(Stack<Integer> s,Stack<Integer> p){
Node temp = head;
while(!p.isEmpty()){
int q = p.pop();
if(temp.a[q]!=null){
s.push(q);
temp = temp.a[q];
}
else{
s.push(q^1);
temp = temp.a[q^1];
}
}
}
}
public static void Merge(long a[][],int p,int r){
if(p<r){
int q = (p+r)/2;
Merge(a,p,q);
Merge(a,q+1,r);
Merge_Array(a,p,q,r);
}
}
public static void get(long a[][],long b[][],int i,int j){
for(int k=0;k<a[i].length;k++)
a[i][k] = b[j][k];
}
public static void Merge_Array(long a[][],int p,int q,int r){
long b[][] = new long[q-p+1][a[0].length];
long c[][] = new long[r-q][a[0].length];
for(int i=0;i<b.length;i++){
get(b,a,i,p+i);
}
for(int i=0;i<c.length;i++){
get(c,a,i,q+i+1);
}
int i = 0,j = 0;
for(int k=p;k<=r;k++){
if(i==b.length){
get(a,c,k,j);
j++;
}
else if(j==c.length){
get(a,b,k,i);
i++;
}
else if(b[i][0]<c[j][0]){
get(a,b,k,i);
i++;
}
else{
get(a,c,k,j);
j++;
}
}
}
public static void solve(int n){
if(n<=1)
return ;
solve(n/2);
MatrixMultiplication(temp2,temp2,result);
Equal(result,temp2);
if(n%2==1){
MatrixMultiplication(temp2,a,result);
Equal(result,temp2);
}
}
static int result[][] = new int[4][4];
static int temp[][] = new int[4][4];
static int temp2[][] = new int[4][4];
static int a[][] = new int[4][4];
static int[][] b = new int[4][1];
static int [][] c = new int[4][1];
public static int count(int n){
a[0][0] = 1 ;
a[0][1] = 1;
a[1][0] = 1;
a[2][1] = 1;
a[3][0] = 1;
a[3][1] = 1;
a[3][3] = 1;
b[0][0] = 1;
b[1][0] = 1;
b[2][0] = 0;
b[3][0] = 2;
Equal(a,temp2);
result[0][0] = 1;
result[1][1] = 1;
result[2][2] = 1;
result[3][3] = 1;
Equal(result,temp);
if(n<=0)
return 0;
else if(n==1)
return 1;
else if(n==2)
return 2;
n = n-2;
solve(n);
MatrixMultiplication(temp2,b,c);
return c[3][0];
}
private static void soln(){
int n = nI();
int arr[] = new int[n];
for(int i=0;i<n;i++)
arr[i] = nI();
if(n==1)
pw.println(arr[0]);
int pre[] = new int[n];
pre[0] = arr[0];
for(int i=1;i<n;i++)
pre[i]+=pre[i-1]+arr[i];
int dp[] = new int[n];
dp[n-1] = 0;
int max = pre[n-1];
for(int i=n-2;i>=0;i--){
dp[i] = max;
max = Math.max(max, pre[i]-dp[i]);
}
pw.println(dp[0]);
}
public static void main(String[] args) {
InputReader(System.in);
pw = new PrintWriter(System.out);
soln();
pw.close();
}
// To Get Input
// Some Buffer Methods
public static void InputReader(InputStream stream1) {
stream = stream1;
}
private static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private static boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
private static 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++];
}
private static int nI() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
private static long nL() {
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;
}
private static String nextToken() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private static String nLi() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
private static int[] nIA(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nI();
return arr;
}
private static long[] nLA(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nL();
return arr;
}
private static void pArray(int[] arr) {
for (int i = 0; i < arr.length; i++)
pw.print(arr[i] + " ");
pw.println();
return;
}
private static void pArray(long[] arr) {
for (int i = 0; i < arr.length; i++)
pw.print(arr[i] + " ");
pw.println();
return;
}
private static boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
private interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
} | Java | ["3\n2 4 8", "4\n1 -7 -2 3"] | 1 second | ["14", "-3"] | NoteIn the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 3. | Java 8 | standard input | [
"dp",
"games"
] | b5b13cb304844a8bbd07e247150719f3 | The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall. The second line contains n integers a1, a2, ..., an ( - 10 000 ≤ ai ≤ 10 000) — the numbers on stickers in order from left to right. | 2,200 | Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally. | standard output | |
PASSED | f0fdada8ed6917d488dbd7dfceb523de | train_003.jsonl | 1476611100 | Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main {
static PrintWriter out;
static Reader in;
public static void main(String[] args) throws IOException {
//out = new PrintWriter(new File("out.txt"));
//PrintWriter out = new PrintWriter(System.out);
//in = new Reader(new FileInputStream("in.txt"));
//Reader in = new Reader();
input_output();
Main solver = new Main();
solver.solve();
out.flush();
out.close();
}
static long INF = (long)1e16;
static int maxn = (int)1e6+5;
static int mod= 998_244_353;
static int n, m, q, k, t;
void solve() throws IOException{
n = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = in.nextInt();
long[] sum = new long[n+1];
sum[n-1] = arr[n-1];
for (int i = n-2; i >= 0; i--) {
sum[i] = sum[i+1]+arr[i];
}
long[] dp = new long[n+1];
for (int i = 0; i < n; i++) dp[i] = -mod;
dp[n-1] = sum[0];
TreeSet<Long> set = new TreeSet<>();
if (n != 2) set.add(-dp[n-1]-sum[n-1]);
set.add(0L);
for (int i = n-2; i >= 0; i--) {
dp[i] = sum[0]+set.last();
if (i == 1) continue;
set.add(-dp[i]-sum[i]);
}
out.println(dp[0]);
}
//<>
static class Reader {
private InputStream mIs;
private byte[] buf = new byte[1024];
private int curChar;
private int 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 next() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
double nextDouble()
{
return Double.parseDouble(next());
}
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;
}
}
static void input_output() throws IOException {
File f = new File("in.txt");
if(f.exists() && !f.isDirectory()) {
in = new Reader(new FileInputStream("in.txt"));
} else in = new Reader();
f = new File("out.txt");
if(f.exists() && !f.isDirectory()) {
out = new PrintWriter(new File("out.txt"));
} else out = new PrintWriter(System.out);
}
} | Java | ["3\n2 4 8", "4\n1 -7 -2 3"] | 1 second | ["14", "-3"] | NoteIn the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 3. | Java 8 | standard input | [
"dp",
"games"
] | b5b13cb304844a8bbd07e247150719f3 | The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall. The second line contains n integers a1, a2, ..., an ( - 10 000 ≤ ai ≤ 10 000) — the numbers on stickers in order from left to right. | 2,200 | Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally. | standard output | |
PASSED | 91be04e9e0f0f4e1a4d4af22f2a1ff5c | train_003.jsonl | 1476611100 | Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally. | 256 megabytes | import java.util.ArrayList;
import java.util.Scanner;
/**
* Created by пользователь on 02.01.2017.
*/
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Long> summ = new ArrayList<Long>();
int n = sc.nextInt();
int buf1 = sc.nextInt();
summ.add((long) (buf1 + sc.nextInt()));
for (int i = 1; i < n-1; i++) {
summ.add(summ.get(i-1) + sc.nextInt());
//System.out.println("dub " + summ.get(i));
}
long max = summ.get(summ.size() - 1);
for (int i = n-3; i >= 0; i--) {
//System.out.println(max);
if (max < summ.get(i) - max) {
//System.out.println("yes max = " + max + " summ = " + summ.get(i) + " i = " + i);
max = summ.get(i) - max;
//System.out.println("yes new " + max);
}
}
System.out.println(max);
}
}
| Java | ["3\n2 4 8", "4\n1 -7 -2 3"] | 1 second | ["14", "-3"] | NoteIn the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 3. | Java 8 | standard input | [
"dp",
"games"
] | b5b13cb304844a8bbd07e247150719f3 | The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall. The second line contains n integers a1, a2, ..., an ( - 10 000 ≤ ai ≤ 10 000) — the numbers on stickers in order from left to right. | 2,200 | Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally. | standard output | |
PASSED | f98ede763473e3fb4833c676e39e1bb5 | train_003.jsonl | 1476611100 | Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally. | 256 megabytes | import java.util.*;
import java.io.*;
// Main
public class Main
{
public static void main (String[] argv)
{
new Main();
}
boolean test = false;
public Main() {
FastReader in = new FastReader(new BufferedReader(new InputStreamReader(System.in)));
//FastReader in = new FastReader(new BufferedReader(new FileReader("Main.in")));
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = in.nextInt();
int[] csum = new int[n];
csum[0] = a[0];
for (int i = 1; i < n; i++) csum[i] = csum[i-1] + a[i];
int max = csum[n-1];
int dp = 0;
for (int i = n - 2; i > 0; i--) {
dp = max;
max = Math.max(max, csum[i] - dp);
}
System.out.println(max);
}
long mod = 1000000007;
private long power(long v, long n) {
long ans = 1;
while (n > 0) {
if (n % 2 == 1)
ans = (ans * v) % mod;
v = v * v % mod;
n /= 2;
}
return ans;
}
long a = 1, b = 1;
private long inv(long x) {
extended_gcd(x, mod);
return (a % mod + mod) % mod;
}
private void extended_gcd(long x, long y) {
if (y == 0) {
a = 1;
b = 0;
return;
}
long q = x / y;
long r = x - q * y;
extended_gcd(y, r);
long tmp_b = b;
long tmp_a = a;
a = tmp_b;
b = tmp_a - a * q;
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader(BufferedReader in)
{
br = in;
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
String line = br.readLine();
if (line == null || line.length() == 0) return "";
st = new StringTokenizer(line);
}
catch (IOException e)
{
return "";
//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)
{
return "";
//e.printStackTrace();
}
return str;
}
}
} | Java | ["3\n2 4 8", "4\n1 -7 -2 3"] | 1 second | ["14", "-3"] | NoteIn the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 3. | Java 8 | standard input | [
"dp",
"games"
] | b5b13cb304844a8bbd07e247150719f3 | The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall. The second line contains n integers a1, a2, ..., an ( - 10 000 ≤ ai ≤ 10 000) — the numbers on stickers in order from left to right. | 2,200 | Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally. | standard output | |
PASSED | 61d5de644a1aabcaef7f405370617fa8 | train_003.jsonl | 1476611100 | Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
// implementation author : jseo
public class TypoCoderDiv1 {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine());
String[] line = in.readLine().split("\\s+");
int[] arr = new int[n];
long[] pre = new long[n];
for(int i=0; i<n; i++) {
arr[i] = Integer.parseInt(line[i]);
pre[i] = arr[i];
if(i - 1 >= 0) {
pre[i] += pre[i-1];
}
}
long[] dp = new long[n];
dp[n-1] = 0;
dp[n-2] = pre[n-2] + arr[n-1];
long best = Math.max(pre[n-1] - dp[n-1], pre[n-2] - dp[n-2]);
for(int i=n-3; i>=0; i--) {
dp[i] = best;
best = Math.max(best, pre[i] - dp[i]);
}
System.out.println(dp[0]);
}
} | Java | ["3\n2 4 8", "4\n1 -7 -2 3"] | 1 second | ["14", "-3"] | NoteIn the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 3. | Java 8 | standard input | [
"dp",
"games"
] | b5b13cb304844a8bbd07e247150719f3 | The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall. The second line contains n integers a1, a2, ..., an ( - 10 000 ≤ ai ≤ 10 000) — the numbers on stickers in order from left to right. | 2,200 | Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally. | standard output | |
PASSED | 8ad55f15d63c394bb1956f13bad8ab32 | train_003.jsonl | 1476611100 | Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Hieu Le
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
static class TaskE {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
long[] prefix = new long[n];
prefix[0] = in.nextInt();
for (int i = 1; i < prefix.length; ++i)
prefix[i] = prefix[i - 1] + in.nextInt();
long[] dp = new long[n];
dp[n - 1] = prefix[n - 1];
long maximum = dp[n - 1];
for (int i = n - 2; i > 0; --i) {
dp[i] = prefix[i] - maximum;
maximum = Math.max(maximum, dp[i]);
}
out.println(maximum);
}
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
private static final int BUFFER_SIZE = 32768;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), BUFFER_SIZE);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["3\n2 4 8", "4\n1 -7 -2 3"] | 1 second | ["14", "-3"] | NoteIn the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 3. | Java 8 | standard input | [
"dp",
"games"
] | b5b13cb304844a8bbd07e247150719f3 | The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall. The second line contains n integers a1, a2, ..., an ( - 10 000 ≤ ai ≤ 10 000) — the numbers on stickers in order from left to right. | 2,200 | Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally. | standard output | |
PASSED | 0f45df8b8542e07613e1183072f5b24f | train_003.jsonl | 1476611100 | Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Hieu Le
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
static class TaskE {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
long[] prefix = new long[n];
prefix[0] = in.nextInt();
for (int i = 1; i < prefix.length; ++i)
prefix[i] = prefix[i - 1] + in.nextInt();
long maximum = prefix[n - 1];
for (int i = n - 2; i > 0; --i) {
long temp = prefix[i] - maximum;
maximum = Math.max(maximum, temp);
}
out.println(maximum);
}
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
private static final int BUFFER_SIZE = 32768;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), BUFFER_SIZE);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["3\n2 4 8", "4\n1 -7 -2 3"] | 1 second | ["14", "-3"] | NoteIn the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 3. | Java 8 | standard input | [
"dp",
"games"
] | b5b13cb304844a8bbd07e247150719f3 | The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall. The second line contains n integers a1, a2, ..., an ( - 10 000 ≤ ai ≤ 10 000) — the numbers on stickers in order from left to right. | 2,200 | Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally. | standard output | |
PASSED | 6c85e9f7768763db8909c824d9923b5e | train_003.jsonl | 1476611100 | Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally. | 256 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
InputReader in=new InputReader(System.in);
PrintWriter out=new PrintWriter(System.out);
//Scanner in=new Scanner(System.in);
int n=in.nextInt();
int[] a=new int[n];
for(int i=0;i<n;i++){
a[i]=in.nextInt();
}
long ans=0;
if(n==2){
ans=a[0]+a[1];
System.out.println(ans);
return;
}
int[] sum=new int[n];
sum[0]=a[0];
for(int i=1;i<n;i++){
sum[i]=sum[i-1]+a[i];
}
long[][] d=new long[n][2];
d[n-1][0]=d[n-1][1]=0;
d[n-2][0]=d[n-2][1]=sum[n-1];
for(int i=n-3;i>=0;i--){
d[i][0]=Math.max(d[i+1][0],sum[i+1]-d[i+1][1]);
d[i][1]=Math.max(d[i+1][1],sum[i+1]-d[i+1][0]);
}
System.out.println(d[0][0]);
out.close();
}
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader (File f){
try{
br=new BufferedReader(new FileReader(f));
}catch(FileNotFoundException e){
e.printStackTrace();
}
}
public InputReader (InputStream in){
br=new BufferedReader(new InputStreamReader(in));
}
public String next(){
while(st==null||!st.hasMoreTokens()){
try{
st=new StringTokenizer(br.readLine());
}catch(IOException e){
e.printStackTrace();
}
}
return st.nextToken();
}
public boolean hasNext(){
while(st==null||!st.hasMoreTokens()){
String s=null;
try{
s=br.readLine();
}catch(IOException e){
e.printStackTrace();
}
if(s==null)
return false;
st=new StringTokenizer(s);
}
return true;
}
public int nextInt(){
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble(){
return Double.parseDouble(next());
}
}
} | Java | ["3\n2 4 8", "4\n1 -7 -2 3"] | 1 second | ["14", "-3"] | NoteIn the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 3. | Java 8 | standard input | [
"dp",
"games"
] | b5b13cb304844a8bbd07e247150719f3 | The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall. The second line contains n integers a1, a2, ..., an ( - 10 000 ≤ ai ≤ 10 000) — the numbers on stickers in order from left to right. | 2,200 | Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally. | standard output | |
PASSED | 2f667f0d097bf5a60f7142c88ec711bd | train_003.jsonl | 1476611100 | Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
* @author Don Li
*/
public class FunnyGame {
void solve() {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = in.nextInt();
int[] sum = new int[n + 1];
for (int i = 0; i < n; i++) sum[i + 1] = sum[i] + a[i];
int[] dp = new int[n];
dp[n - 2] = sum[n];
for (int i = n - 3; i >= 0; i--) {
dp[i] = Math.max(dp[i + 1], sum[i + 2] - dp[i + 1]);
}
out.println(dp[0]);
}
public static void main(String[] args) {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
new FunnyGame().solve();
out.close();
}
static FastScanner in;
static PrintWriter out;
static class FastScanner {
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
| Java | ["3\n2 4 8", "4\n1 -7 -2 3"] | 1 second | ["14", "-3"] | NoteIn the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 3. | Java 8 | standard input | [
"dp",
"games"
] | b5b13cb304844a8bbd07e247150719f3 | The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall. The second line contains n integers a1, a2, ..., an ( - 10 000 ≤ ai ≤ 10 000) — the numbers on stickers in order from left to right. | 2,200 | Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally. | standard output | |
PASSED | 11d73a2f7bebcafc25305145dc23e346 | train_003.jsonl | 1476611100 | Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally. | 256 megabytes | import java.io.*;
import java.util.*;
public class CF731E {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
int[] aa = new int[n];
for (int i = 0; i < n; i++)
aa[i] = Integer.parseInt(st.nextToken());
long[] ss = new long[n];
ss[0] = aa[0];
for (int i = 1; i < n; i++)
ss[i] += ss[i - 1] + aa[i];
long[] dp = new long[n]; // dp[i]: first cut after i
dp[n - 1] = ss[n - 1];
long max = Long.MIN_VALUE;
for (int i = n - 1; i > 1; i--) {
max = Math.max(max, -dp[i]);
dp[i - 1] = Math.max(dp[i], ss[i - 1] + max);
max += aa[i - 1];
}
max = Long.MIN_VALUE;
for (int i = 1; i < n; i++)
max = Math.max(max, dp[i]);
System.out.println(max);
}
}
| Java | ["3\n2 4 8", "4\n1 -7 -2 3"] | 1 second | ["14", "-3"] | NoteIn the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 3. | Java 8 | standard input | [
"dp",
"games"
] | b5b13cb304844a8bbd07e247150719f3 | The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall. The second line contains n integers a1, a2, ..., an ( - 10 000 ≤ ai ≤ 10 000) — the numbers on stickers in order from left to right. | 2,200 | Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally. | standard output | |
PASSED | a5abd0ceb40271a24b9d6d836a2a043c | train_003.jsonl | 1476611100 | Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally. | 256 megabytes | import java.io.*;
import java.util.*;
public class ETask {
public static void main(String[] args) {
MyInputReader in = new MyInputReader(System.in);
int n = in.nextInt();
long[] arr = new long[n];
long[] cum = new long[n - 1];
for (int i = 0; i < n; i++) {
arr[i] = in.nextLong();
}
cum[0] = arr[0] + arr[1];
for (int i = 1; i < n - 1; i++) {
cum[i] = cum[i - 1] + arr[i + 1];
}
long[] dp = new long[n - 1];
dp[n - 2] = cum[n - 2];
for (int i = n - 3; i >= 0; i--) {
dp[i] = Math.max(dp[i + 1], cum[i] - dp[i + 1]);
}
System.out.println(dp[0]);
}
static class MyInputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public MyInputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768 * 10);
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 | ["3\n2 4 8", "4\n1 -7 -2 3"] | 1 second | ["14", "-3"] | NoteIn the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 3. | Java 8 | standard input | [
"dp",
"games"
] | b5b13cb304844a8bbd07e247150719f3 | The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall. The second line contains n integers a1, a2, ..., an ( - 10 000 ≤ ai ≤ 10 000) — the numbers on stickers in order from left to right. | 2,200 | Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally. | standard output | |
PASSED | 72741ebf4d4326067793d05955135876 | train_003.jsonl | 1476611100 | Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally. | 256 megabytes | import java.io.*;
import java.util.*;
/**
* Created by fcdkbear on 15.10.16.
*/
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);
new Task().solve(in, out);
out.close();
}
static class Task {
int[][] dp;
boolean[][] visited;
int[] a;
int[] prefixSums;
private int r(int position, int who) {
if (position == a.length) {
return 0;
}
if (visited[position][who]) {
return dp[position][who];
}
visited[position][who] = true;
int res;
if (who == 0) {
res = a[position] + r(position + 1, 0);
res = Math.max(res, -prefixSums[position] + r(position + 1, 1));
} else {
res = -a[position] + r(position + 1, 1);
res = Math.min(res, prefixSums[position] + r(position + 1, 0));
}
dp[position][who] = res;
return res;
}
public void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
a = new int[n];
prefixSums = new int[n];
for (int i = 0; i < n; ++i) {
a[i] = in.nextInt();
prefixSums[i] = a[i];
if (i > 0) {
prefixSums[i] += prefixSums[i - 1];
}
}
dp = new int[n][2];
visited = new boolean[n][2];
int res = a[0] + a[1] + r(2, 0);
out.println(res);
}
}
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 | ["3\n2 4 8", "4\n1 -7 -2 3"] | 1 second | ["14", "-3"] | NoteIn the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 3. | Java 8 | standard input | [
"dp",
"games"
] | b5b13cb304844a8bbd07e247150719f3 | The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall. The second line contains n integers a1, a2, ..., an ( - 10 000 ≤ ai ≤ 10 000) — the numbers on stickers in order from left to right. | 2,200 | Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally. | standard output | |
PASSED | 7df5685b1f5a3a6ac72a8082da139449 | train_003.jsonl | 1476611100 | Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally. | 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 E_Round_376_Div2 {
public static long MOD = 1000000007;
static long[][]dp;
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];
long[]pre = new long[n];
dp = new long[2][n];
for(long[]a : dp){
Arrays.fill(a, -1);
}
for(int i = 0; i < n; i++){
data[i] = in.nextInt();
pre[i] = data[i] + (i > 0 ? pre[i - 1] : 0);
}
out.println(cal(1,0,data,pre));
out.close();
}
public static long cal(int index, int start, int[]data , long[]pre){
if(index == data.length){
return 0;
}
if(dp[start][index] != -1){
return dp[start][index];
}
long result = 0;
if(start == 0){
result = pre[index ] ;
}else{
result = data[index];
}
result += max(cal(index + 1, 1, data, pre) , -cal(index + 1, 0, data, pre));
return dp[start][index] = result;
}
static long max(long a, long b){
return a > b ? a : b;
}
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) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2);
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\n2 4 8", "4\n1 -7 -2 3"] | 1 second | ["14", "-3"] | NoteIn the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 3. | Java 8 | standard input | [
"dp",
"games"
] | b5b13cb304844a8bbd07e247150719f3 | The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall. The second line contains n integers a1, a2, ..., an ( - 10 000 ≤ ai ≤ 10 000) — the numbers on stickers in order from left to right. | 2,200 | Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally. | standard output | |
PASSED | 2eadbf820f93736146bee31098c3e88b | train_003.jsonl | 1476611100 | Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class Solve3 {
public static boolean cmp(ArrayList<Integer> t1, ArrayList<Integer> t2, int shift, int c) {
int size = Math.min(t1.size(), t2.size());
for(int i = 0; i < size; i++) {
if((t1.get(i) +shift) % c > (t2.get(i)+shift) % c) return false;
if((t1.get(i) +shift) % c < (t2.get(i)+shift) % c) return true;
}
return t1.size() <= t2.size();
}
static long inf = 1000000000000L;
public static void main(String[] args) {
MyScanner scanner = new MyScanner();
PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
int n = scanner.nextInt();
long t[] = new long[n];
for(int i = 0; i < n; i++)
t[i] = scanner.nextLong();
long t2[] = new long[n];
t2[0] = t[0];
for(int i = 1; i < n; i++)
t2[i] = t2[i-1] + t[i];
long res = t2[n-1];
Tree tree = new Tree(n+2);
tree.update(n-1, t2[n-1]);
for(int i = n-3; i>=0; i--) {
long val = tree.query(i+1, n);
long r1 = Math.max(t2[i] + t[i+1] - val, val);
res = Math.max(res, r1);
tree.update(i, r1);
//System.out.println(r1);
}
out.println(res);
out.close();
}
static class Tree{
int n;
long[] d;
Tree(int nmin) {
for(n = 1; n < nmin; n *= 2);
d = new long[2 * n];
Arrays.fill(d, -inf);
}
void update(int i, long x) {
d[n + i] = x;
for(int k = (n + i) / 2; k > 0; k >>= 1)
d[k] = Math.max(d[k * 2], d[k * 2 + 1]);
}
long get(int i) { return d[n + i]; }
//[l, r)
long query(int l, int r) {
long m = -inf;
for(; l != 0 && l + (l&-l) <= r; l += l&-l)
m = Math.max(m, d[(n + l) / (l&-l)]);
for(; l < r; r -= r&-r)
m = Math.max(m, d[(n + r) / (r&-r) - 1]);
return m;
}
}
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["3\n2 4 8", "4\n1 -7 -2 3"] | 1 second | ["14", "-3"] | NoteIn the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 3. | Java 8 | standard input | [
"dp",
"games"
] | b5b13cb304844a8bbd07e247150719f3 | The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall. The second line contains n integers a1, a2, ..., an ( - 10 000 ≤ ai ≤ 10 000) — the numbers on stickers in order from left to right. | 2,200 | Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally. | standard output | |
PASSED | af890a13f70f865098c037eafc6f3bf3 | train_003.jsonl | 1476611100 | Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally. | 256 megabytes | // package codeforces.cf3xx.cf376.div2;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class E {
private static final long INF = (long) 1e18;
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int[] a = in.nextInts(n);
long[] imos = new long[n];
imos[0] = a[0];
for (int i = 1 ; i < n ; i++) {
imos[i] = imos[i-1] + a[i];
}
long[] dp = new long[n];
Arrays.fill(dp, -INF);
dp[n-1] = 0;
long best = -INF;
for (int x = n-2 ; x >= 0 ; x--) {
best = Math.max(best, imos[x+1] - dp[x+1]);
dp[x] = best;
}
out.println(dp[0]);
out.flush();
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int[] nextInts(int n) {
int[] ret = new int[n];
for (int i = 0; i < n; i++) {
ret[i] = nextInt();
}
return ret;
}
private int[][] nextIntTable(int n, int m) {
int[][] ret = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
ret[i][j] = nextInt();
}
}
return ret;
}
private long[] nextLongs(int n) {
long[] ret = new long[n];
for (int i = 0; i < n; i++) {
ret[i] = nextLong();
}
return ret;
}
private long[][] nextLongTable(int n, int m) {
long[][] ret = new long[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
ret[i][j] = nextLong();
}
}
return ret;
}
private double[] nextDoubles(int n) {
double[] ret = new double[n];
for (int i = 0; i < n; i++) {
ret[i] = nextDouble();
}
return ret;
}
private int next() {
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 char nextChar() {
int c = next();
while (isSpaceChar(c))
c = next();
if ('a' <= c && c <= 'z') {
return (char) c;
}
if ('A' <= c && c <= 'Z') {
return (char) c;
}
throw new InputMismatchException();
}
public String nextToken() {
int c = next();
while (isSpaceChar(c))
c = next();
StringBuilder res = new StringBuilder();
do {
res.append((char) c);
c = next();
} while (!isSpaceChar(c));
return res.toString();
}
public int nextInt() {
int c = next();
while (isSpaceChar(c))
c = next();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = next();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c-'0';
c = next();
} while (!isSpaceChar(c));
return res*sgn;
}
public long nextLong() {
int c = next();
while (isSpaceChar(c))
c = next();
long sgn = 1;
if (c == '-') {
sgn = -1;
c = next();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c-'0';
c = next();
} while (!isSpaceChar(c));
return res*sgn;
}
public double nextDouble() {
return Double.valueOf(nextToken());
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static void debug(Object... o) {
System.err.println(Arrays.deepToString(o));
}
}
| Java | ["3\n2 4 8", "4\n1 -7 -2 3"] | 1 second | ["14", "-3"] | NoteIn the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 3. | Java 8 | standard input | [
"dp",
"games"
] | b5b13cb304844a8bbd07e247150719f3 | The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall. The second line contains n integers a1, a2, ..., an ( - 10 000 ≤ ai ≤ 10 000) — the numbers on stickers in order from left to right. | 2,200 | Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally. | standard output | |
PASSED | d6ce2cb4bb9af507d3dbc11327e5513b | train_003.jsonl | 1476611100 | Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally. | 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 beginner1010
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
static class TaskE {
int[][] dp;
boolean[][] visited;
int rec(int turn, int pos, int[] prefixSum, int n) {
if (pos == n) {
return 0;
}
int res = dp[turn][pos];
if (visited[turn][pos] == true)
return res;
visited[turn][pos] = true;
res = turn == 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE;
if (turn == 0) {
if (pos + 1 < n) {
res = Math.max(res, rec(turn, pos + 1, prefixSum, n));
}
if (pos > 0)
res = Math.max(res, rec(1 - turn, pos + 1, prefixSum, n) + prefixSum[pos]);
} else {
if (pos + 1 < n) {
res = Math.min(res, rec(turn, pos + 1, prefixSum, n));
}
res = Math.min(res, rec(1 - turn, pos + 1, prefixSum, n) - prefixSum[pos]);
}
return dp[turn][pos] = res;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = in.nextInt();
}
visited = new boolean[2][n];
dp = new int[2][n];
for (int[] aux : dp)
Arrays.fill(aux, -1);
int[] prefixSum = new int[n];
prefixSum[0] = nums[0];
for (int i = 1; i < n; i++) {
prefixSum[i] = prefixSum[i - 1] + nums[i];
}
int ans = rec(0, 0, prefixSum, n);
out.print(ans);
}
}
static class InputReader {
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputStream stream;
public InputReader(InputStream stream) {
this.stream = stream;
}
private boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isWhitespace(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 (!isWhitespace(c));
return res * sgn;
}
}
}
| Java | ["3\n2 4 8", "4\n1 -7 -2 3"] | 1 second | ["14", "-3"] | NoteIn the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 3. | Java 8 | standard input | [
"dp",
"games"
] | b5b13cb304844a8bbd07e247150719f3 | The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall. The second line contains n integers a1, a2, ..., an ( - 10 000 ≤ ai ≤ 10 000) — the numbers on stickers in order from left to right. | 2,200 | Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally. | standard output | |
PASSED | bbe88a5f241f547c00193f5ef2856bad | train_003.jsonl | 1476611100 | Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally. | 256 megabytes | //package round376;
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 E {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int[] a = na(n);
long[] cum = new long[n+1];
for(int i = 0;i < n;i++){
cum[i+1] = cum[i] + a[i];
}
long[] dp = new long[n+1];
long[] ep = new long[n+1];
long dpmin = Long.MAX_VALUE / 2, epmin = 0;
long dpmax = 0, epmax = Long.MIN_VALUE / 2;
// ep[j]+cum[j]
for(int i = n-1;i >= 0;i--){
// tr(i, cum[i], dpmin, epmax);
dp[i] = Math.max(cum[n], epmax);
ep[i] = Math.min(-cum[n], dpmin);
dpmin = Math.min(dpmin, dp[i]-cum[i]);
epmax = Math.max(epmax, ep[i]+cum[i]);
}
long ret = cum[n];
for(int j = 2;j < n;j++){
ret = Math.max(ret, cum[j] + ep[j]);
}
out.println(ret);
}
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 E().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\n2 4 8", "4\n1 -7 -2 3"] | 1 second | ["14", "-3"] | NoteIn the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 3. | Java 8 | standard input | [
"dp",
"games"
] | b5b13cb304844a8bbd07e247150719f3 | The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall. The second line contains n integers a1, a2, ..., an ( - 10 000 ≤ ai ≤ 10 000) — the numbers on stickers in order from left to right. | 2,200 | Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally. | standard output | |
PASSED | 2dcf98ddea6c3477a2a103684ade6c5f | train_003.jsonl | 1476611100 | Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally. | 256 megabytes | //package CF731;
import java.io.*;
import java.util.Comparator;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class CF731E {
public static void main(String[] args) throws FileNotFoundException {
InputStream inputStream = System.in;
// InputStream inputStream = new FileInputStream(new File("input"));
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 {
int n;
int[] a;
long[] s;
long[] dp;
public void solve(int testNumber, InputReader in, PrintWriter out) {
n = in.nextInt();
a = new int[n + 1];
s = new long[n + 1];
dp = new long[n + 1];
for (int i = 1; i <= n; ++i) {
a[i] = in.nextInt();
s[i] = s[i - 1] + a[i];
}
dp[n] = 0;
PriorityQueue<Long> maxHeap = new PriorityQueue<>((o1, o2) -> {
if (o2 == o1) return 0;
if (o2 < o1) return -1;
return 1;
});
maxHeap.add(s[n] - dp[n]);
for (int i = n - 1; i >= 1; --i) {
dp[i] = maxHeap.peek();
maxHeap.add(s[i] - dp[i]);
}
out.println(dp[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 | ["3\n2 4 8", "4\n1 -7 -2 3"] | 1 second | ["14", "-3"] | NoteIn the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 3. | Java 8 | standard input | [
"dp",
"games"
] | b5b13cb304844a8bbd07e247150719f3 | The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall. The second line contains n integers a1, a2, ..., an ( - 10 000 ≤ ai ≤ 10 000) — the numbers on stickers in order from left to right. | 2,200 | Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally. | standard output | |
PASSED | ec56d196519870315decf2d3624d3a02 | train_003.jsonl | 1476611100 | Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally. | 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.util.InputMismatchException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main
{
public static void main(String[] args)
{
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
QuickScanner in = new QuickScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
static class TaskE
{
public void solve(int testNumber, QuickScanner in, PrintWriter out)
{
int n = in.nextInt();
int a[] = in.nextInts(n);
int s[] = new int[n + 1];
for (int i = 0; i < n; i++)
s[i + 1] = s[i] + a[i];
int dp[] = new int[n + 1];
int maxV = s[n];
for (int i = n - 1; i > 0; i--)
{
dp[i] = maxV;
maxV = Math.max(maxV, s[i] - dp[i]);
}
out.println(dp[1]);
}
}
static class QuickScanner
{
BufferedReader in;
StringTokenizer token;
String delim;
public QuickScanner(InputStream inputStream)
{
this.in = new BufferedReader(new InputStreamReader(inputStream));
this.delim = " \n\t";
this.token = new StringTokenizer("", delim);
}
public QuickScanner(InputStream inputStream, String delim)
{
this.in = new BufferedReader(new InputStreamReader(inputStream));
this.delim = delim;
this.token = new StringTokenizer("", delim);
}
public boolean hasNext()
{
while (!token.hasMoreTokens())
{
try
{
String s = in.readLine();
if (s == null) return false;
token = new StringTokenizer(s, delim);
} catch (IOException e)
{
throw new InputMismatchException();
}
}
return true;
}
public String next()
{
hasNext();
return token.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public int[] nextInts(int n)
{
int[] res = new int[n];
for (int i = 0; i < n; i++)
res[i] = nextInt();
return res;
}
}
}
| Java | ["3\n2 4 8", "4\n1 -7 -2 3"] | 1 second | ["14", "-3"] | NoteIn the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 3. | Java 8 | standard input | [
"dp",
"games"
] | b5b13cb304844a8bbd07e247150719f3 | The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall. The second line contains n integers a1, a2, ..., an ( - 10 000 ≤ ai ≤ 10 000) — the numbers on stickers in order from left to right. | 2,200 | Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally. | standard output | |
PASSED | c78cac1048878465cbfe2b8ceed1e1a2 | train_003.jsonl | 1476611100 | Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally. | 256 megabytes | import java.util.*;
public class Cheker{
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+1;i++){
int a=sc.nextInt();
A[i]=A[i-1]+a;
}
int dp=A[n];
for(int i=n-1;i>1;i--){
dp=max(dp,A[i]-dp);
}
System.out.println(dp);
sc.close();
}
static int max(int a,int b){
if(a>b)return a;
return b;
}
} | Java | ["3\n2 4 8", "4\n1 -7 -2 3"] | 1 second | ["14", "-3"] | NoteIn the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 3. | Java 8 | standard input | [
"dp",
"games"
] | b5b13cb304844a8bbd07e247150719f3 | The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall. The second line contains n integers a1, a2, ..., an ( - 10 000 ≤ ai ≤ 10 000) — the numbers on stickers in order from left to right. | 2,200 | Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally. | standard output | |
PASSED | 02d89d1fc91c0f2697bdab9e0c122224 | train_003.jsonl | 1476611100 | Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally. | 256 megabytes | import java.util.Scanner;
public class R731E {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n=in.nextInt(), max=Integer.MIN_VALUE;
int[]a=new int[n], d=new int[n];
a[0]=in.nextInt();
for(int i=1; i<n; i++)
a[i]=a[i-1]+in.nextInt();
d[n-1]=0;
for(int i=n-2; i>=0; i--) {
max=Math.max(max, a[i+1]-d[i+1]);
d[i]=max;
}
System.out.println(d[0]);
}
}
| Java | ["3\n2 4 8", "4\n1 -7 -2 3"] | 1 second | ["14", "-3"] | NoteIn the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 3. | Java 8 | standard input | [
"dp",
"games"
] | b5b13cb304844a8bbd07e247150719f3 | The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall. The second line contains n integers a1, a2, ..., an ( - 10 000 ≤ ai ≤ 10 000) — the numbers on stickers in order from left to right. | 2,200 | Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally. | standard output | |
PASSED | e25823f2436946b168577ab7783fda7c | train_003.jsonl | 1476611100 | Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.The game they came up with has the following rules. Initially, there are n stickers on the wall arranged in a row. Each sticker has some number written on it. Now they alternate turn, Petya moves first.One move happens as follows. Lets say there are m ≥ 2 stickers on the wall. The player, who makes the current move, picks some integer k from 2 to m and takes k leftmost stickers (removes them from the wall). After that he makes the new sticker, puts it to the left end of the row, and writes on it the new integer, equal to the sum of all stickers he took on this move. Game ends when there is only one sticker left on the wall. The score of the player is equal to the sum of integers written on all stickers he took during all his moves. The goal of each player is to maximize the difference between his score and the score of his opponent.Given the integer n and the initial sequence of stickers on the wall, define the result of the game, i.e. the difference between the Petya's and Gena's score if both players play optimally. | 256 megabytes | import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author flk
*/
public class Main {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
//OutputStream outputStream = System.out;
//BufferedOutputStream buffered = new BufferedOutputStream(outputStream);
BufferedOutputStream buffered = new BufferedOutputStream(System.out);
//Scanner in = new Scanner(inputStream);
Reader in = new Reader(); in.init(inputStream);
PrintWriter out = new PrintWriter(buffered);
Task solver = new Task();
solver.solve(1, in, out);
out.close();
}
}
class Task {
public void solve(int testNumber, Reader in, PrintWriter out) throws IOException {
int N = in.nextInt();
int [] A = new int[N+1];
A[1] = in.nextInt();
for (int i = 2; i <= N; i++) {
A[i] = A[i-1] + in.nextInt();
}
int V [] = new int[N+3];
int prevMax = Integer.MIN_VALUE;
for (int i = N; i >= 2 ; i--) {
// int max = A[N];
// for (int j = i; j < N; j++) {
// if (A[j] - V[j+1] > max) max = A[j] - V[j+1];
// }
// V[i] = max;
if (A[i] - V[i+1] > prevMax) prevMax = A[i] - V[i+1];
V[i] = prevMax;
}
out.println(V[2]);
}
}
/** Class for buffered reading int and double values */
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static long nextLong() throws IOException {
return Long.parseLong( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
}
| Java | ["3\n2 4 8", "4\n1 -7 -2 3"] | 1 second | ["14", "-3"] | NoteIn the first sample, the optimal move for Petya is to take all the stickers. As a result, his score will be equal to 14 and Gena's score will be equal to 0.In the second sample, the optimal sequence of moves is the following. On the first move Petya will take first three sticker and will put the new sticker with value - 8. On the second move Gena will take the remaining two stickers. The Petya's score is 1 + ( - 7) + ( - 2) = - 8, Gena's score is ( - 8) + 3 = - 5, i.e. the score difference will be - 3. | Java 8 | standard input | [
"dp",
"games"
] | b5b13cb304844a8bbd07e247150719f3 | The first line of input contains a single integer n (2 ≤ n ≤ 200 000) — the number of stickers, initially located on the wall. The second line contains n integers a1, a2, ..., an ( - 10 000 ≤ ai ≤ 10 000) — the numbers on stickers in order from left to right. | 2,200 | Print one integer — the difference between the Petya's score and Gena's score at the end of the game if both players play optimally. | standard output | |
PASSED | bcb6675af6a14a990a9879982f0bc4b8 | train_003.jsonl | 1530110100 | Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment $$$0$$$ and turn power off at moment $$$M$$$. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunately, some program is already installed into the lamp.The lamp allows only good programs. Good program can be represented as a non-empty array $$$a$$$, where $$$0 < a_1 < a_2 < \dots < a_{|a|} < M$$$. All $$$a_i$$$ must be integers. Of course, preinstalled program is a good program.The lamp follows program $$$a$$$ in next manner: at moment $$$0$$$ turns power and light on. Then at moment $$$a_i$$$ the lamp flips its state to opposite (if it was lit, it turns off, and vice versa). The state of the lamp flips instantly: for example, if you turn the light off at moment $$$1$$$ and then do nothing, the total time when the lamp is lit will be $$$1$$$. Finally, at moment $$$M$$$ the lamp is turning its power off regardless of its state.Since you are not among those people who read instructions, and you don't understand the language it's written in, you realize (after some testing) the only possible way to alter the preinstalled program. You can insert at most one element into the program $$$a$$$, so it still should be a good program after alteration. Insertion can be done between any pair of consecutive elements of $$$a$$$, or even at the begining or at the end of $$$a$$$.Find such a way to alter the program that the total time when the lamp is lit is maximum possible. Maybe you should leave program untouched. If the lamp is lit from $$$x$$$ till moment $$$y$$$, then its lit for $$$y - x$$$ units of time. Segments of time when the lamp is lit are summed up. | 256 megabytes | import java.io.*;
import java.util.*;
public class A {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt() + 2;
int m = scanner.nextInt();
long list[] = new long[n];
list[0] = 0;
list[n - 1] = m;
for (int i = 1; i < n - 1; i++) {
list[i] = scanner.nextInt();
}
long even[] = new long[n];
long odd[] = new long[n];
even[0] = 0;
odd[0] = 0;
for (int i = 1; i < n; i++) {
if (i % 2 == 0) {
even[i] = even[i - 1] + Math.abs(list[i] - list[i - 1]);
odd[i] = odd[i - 1];
} else {
even[i] = even[i - 1];
odd[i] = odd[i - 1] + Math.abs(list[i] - list[i - 1]);
}
}
long answer = 0;
for (int i = 1; i < n; i++) {
if (list[i] - list[i - 1] <= 1) {
continue;
}
long curr = odd[i - 1] + list[i] - list[i - 1] - 1;
if (i % 2 == 1) {
curr += odd[n - 1] - odd[i];
} else {
curr += even[n - 1] - even[i];
}
answer = Math.max(answer, curr);
}
System.out.print(Math.max(answer, Math.max(even[n - 1], odd[n - 1])));
}
} | Java | ["3 10\n4 6 7", "2 12\n1 10", "2 7\n3 4"] | 1 second | ["8", "9", "6"] | NoteIn the first example, one of possible optimal solutions is to insert value $$$x = 3$$$ before $$$a_1$$$, so program will be $$$[3, 4, 6, 7]$$$ and time of lamp being lit equals $$$(3 - 0) + (6 - 4) + (10 - 7) = 8$$$. Other possible solution is to insert $$$x = 5$$$ in appropriate place.In the second example, there is only one optimal solution: to insert $$$x = 2$$$ between $$$a_1$$$ and $$$a_2$$$. Program will become $$$[1, 2, 10]$$$, and answer will be $$$(1 - 0) + (10 - 2) = 9$$$.In the third example, optimal answer is to leave program untouched, so answer will be $$$(3 - 0) + (7 - 4) = 6$$$. | Java 8 | standard input | [
"greedy"
] | 085b03a45fec13b759c3bd334888caf5 | First line contains two space separated integers $$$n$$$ and $$$M$$$ ($$$1 \le n \le 10^5$$$, $$$2 \le M \le 10^9$$$) — the length of program $$$a$$$ and the moment when power turns off. Second line contains $$$n$$$ space separated integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 < a_1 < a_2 < \dots < a_n < M$$$) — initially installed program $$$a$$$. | 1,500 | Print the only integer — maximum possible total time when the lamp is lit. | standard output | |
PASSED | 1fe857b62aee1e056197f7a1b53c4aea | train_003.jsonl | 1530110100 | Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment $$$0$$$ and turn power off at moment $$$M$$$. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunately, some program is already installed into the lamp.The lamp allows only good programs. Good program can be represented as a non-empty array $$$a$$$, where $$$0 < a_1 < a_2 < \dots < a_{|a|} < M$$$. All $$$a_i$$$ must be integers. Of course, preinstalled program is a good program.The lamp follows program $$$a$$$ in next manner: at moment $$$0$$$ turns power and light on. Then at moment $$$a_i$$$ the lamp flips its state to opposite (if it was lit, it turns off, and vice versa). The state of the lamp flips instantly: for example, if you turn the light off at moment $$$1$$$ and then do nothing, the total time when the lamp is lit will be $$$1$$$. Finally, at moment $$$M$$$ the lamp is turning its power off regardless of its state.Since you are not among those people who read instructions, and you don't understand the language it's written in, you realize (after some testing) the only possible way to alter the preinstalled program. You can insert at most one element into the program $$$a$$$, so it still should be a good program after alteration. Insertion can be done between any pair of consecutive elements of $$$a$$$, or even at the begining or at the end of $$$a$$$.Find such a way to alter the program that the total time when the lamp is lit is maximum possible. Maybe you should leave program untouched. If the lamp is lit from $$$x$$$ till moment $$$y$$$, then its lit for $$$y - x$$$ units of time. Segments of time when the lamp is lit are summed up. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author programajor
*/
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);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
long m = in.nextLong();
long[] times = new long[n + 2];
long[] sum = new long[n + 2];
times[0] = 0;
times[n + 1] = m;
for (int i = 1; i <= n; i++) {
times[i] = in.nextLong();
}
for (int i = 1; i <= n + 1; i++) {
sum[i] = sum[i - 1];
if ((i % 2) == 1) {
sum[i] += times[i] - times[i - 1];
}
}
long ans = sum[n + 1];
for (int i = 0; i <= n; i++) {
if (times[i] != times[i + 1] - 1) {
long timeTotal = m - times[i];
long timeLighted = sum[n + 1] - sum[i];
ans = Math.max(ans, sum[i] + timeTotal - timeLighted - 1);
}
}
out.print(ans);
}
}
static class InputReader {
private BufferedReader reader;
private 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 | ["3 10\n4 6 7", "2 12\n1 10", "2 7\n3 4"] | 1 second | ["8", "9", "6"] | NoteIn the first example, one of possible optimal solutions is to insert value $$$x = 3$$$ before $$$a_1$$$, so program will be $$$[3, 4, 6, 7]$$$ and time of lamp being lit equals $$$(3 - 0) + (6 - 4) + (10 - 7) = 8$$$. Other possible solution is to insert $$$x = 5$$$ in appropriate place.In the second example, there is only one optimal solution: to insert $$$x = 2$$$ between $$$a_1$$$ and $$$a_2$$$. Program will become $$$[1, 2, 10]$$$, and answer will be $$$(1 - 0) + (10 - 2) = 9$$$.In the third example, optimal answer is to leave program untouched, so answer will be $$$(3 - 0) + (7 - 4) = 6$$$. | Java 8 | standard input | [
"greedy"
] | 085b03a45fec13b759c3bd334888caf5 | First line contains two space separated integers $$$n$$$ and $$$M$$$ ($$$1 \le n \le 10^5$$$, $$$2 \le M \le 10^9$$$) — the length of program $$$a$$$ and the moment when power turns off. Second line contains $$$n$$$ space separated integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 < a_1 < a_2 < \dots < a_n < M$$$) — initially installed program $$$a$$$. | 1,500 | Print the only integer — maximum possible total time when the lamp is lit. | standard output | |
PASSED | 43d3259fba1d4d5c8c0ee2c88fc01b3a | train_003.jsonl | 1530110100 | Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment $$$0$$$ and turn power off at moment $$$M$$$. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunately, some program is already installed into the lamp.The lamp allows only good programs. Good program can be represented as a non-empty array $$$a$$$, where $$$0 < a_1 < a_2 < \dots < a_{|a|} < M$$$. All $$$a_i$$$ must be integers. Of course, preinstalled program is a good program.The lamp follows program $$$a$$$ in next manner: at moment $$$0$$$ turns power and light on. Then at moment $$$a_i$$$ the lamp flips its state to opposite (if it was lit, it turns off, and vice versa). The state of the lamp flips instantly: for example, if you turn the light off at moment $$$1$$$ and then do nothing, the total time when the lamp is lit will be $$$1$$$. Finally, at moment $$$M$$$ the lamp is turning its power off regardless of its state.Since you are not among those people who read instructions, and you don't understand the language it's written in, you realize (after some testing) the only possible way to alter the preinstalled program. You can insert at most one element into the program $$$a$$$, so it still should be a good program after alteration. Insertion can be done between any pair of consecutive elements of $$$a$$$, or even at the begining or at the end of $$$a$$$.Find such a way to alter the program that the total time when the lamp is lit is maximum possible. Maybe you should leave program untouched. If the lamp is lit from $$$x$$$ till moment $$$y$$$, then its lit for $$$y - x$$$ units of time. Segments of time when the lamp is lit are summed up. | 256 megabytes | //package practice.codeforces.greedy;
import java.io.*;
import java.util.*;
/**
* greedy
* http://codeforces.com/contest/1000/problem/B
*/
public class LightItUp
{
BufferedReader in;
PrintWriter ob;
StringTokenizer st;
String path = "/Users/crraksh/Documents/competitive competition/src/practice/codeforces/greedy/1.txt";
public static void main(String[] args) throws IOException {
new LightItUp().run();
}
void run() throws IOException {
in=new BufferedReader(bufferRead());
ob=new PrintWriter(System.out);
solve();
ob.flush();
}
void solve() throws IOException {
int n = ni(), m = ni();
int lightPoints[] = new int[100005];
int lightPointsRangeValue[] = new int[100005];
for (int i = 0; i < n; i++) {
lightPoints[i] = ni();
}
lightPoints[n] = m;
n++;
for (int i = 0; i < n; i++) {
lightPointsRangeValue[i] = lightPoints[i] - (i==0? 0 : lightPoints[i-1]);
}
for (int i = n-3; i >= 0; i--) {
lightPointsRangeValue[i] += lightPointsRangeValue[i+2];
}
int ac = Math.max(lightPointsRangeValue[0], lightPointsRangeValue[1]);
for (int i = 0; i < n; i += 2) {
ac = Math.max(getFirstValue(lightPoints, i, lightPointsRangeValue), ac);
ac = Math.max(getSecondValue(lightPoints, i, lightPointsRangeValue, n), ac);
}
System.out.println(ac);
}
private int getFirstValue(int [] lightPoints, int index, int [] lightPointsRangeValue) {
int value = lightPoints[index] -1;
if ((index ==0) && value == 0) return -1;
else if ((index != 0) && (value == lightPoints[index-1])) return -1;
int maxVal = lightPointsRangeValue[0] - lightPointsRangeValue[index];
if (index == 0) {
maxVal += (value - 0) + lightPointsRangeValue[index+1];
} else {
maxVal += (value - lightPoints[index-1]) + lightPointsRangeValue[index +1];
}
return maxVal;
}
private int getSecondValue(int [] lightPoints, int index, int [] lightPointsRangeValue, int n) {
int value = lightPoints[index] +1;
if (index == n) return -1;
else if (lightPoints[index+1] == value) return -1;
int maxVal = lightPointsRangeValue[0];
if (index+2 < n) {
maxVal -= lightPointsRangeValue[index+2];
}
maxVal += lightPointsRangeValue[index+1] - value;
return maxVal;
}
private boolean valid(int x, int y, int value, int n) {
if ((x == -1) && (value == 0)) {
return false;
} else if (value == x || value == y) {
return false;
} else
return true;
}
String ns() throws IOException {
return nextToken();
}
long nl() throws IOException {
return Long.parseLong(nextToken());
}
int ni() throws IOException {
return Integer.parseInt(nextToken());
}
double nd() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
if(st==null || !st.hasMoreTokens())
st=new StringTokenizer(in.readLine());
return st.nextToken();
}
int[] nia(int start,int b) throws IOException {
int a[]=new int[b];
for(int i=start;i<b;i++)
a[i]=ni();
return a;
}
long[] nla(int start,int n) throws IOException {
long a[]=new long[n];
for (int i=start; i<n ;i++ ) {
a[i]=nl();
}
return a;
}
FileReader fileRead() throws FileNotFoundException {
return new FileReader(path);
}
InputStreamReader bufferRead() {
return new InputStreamReader(System.in);
}
} | Java | ["3 10\n4 6 7", "2 12\n1 10", "2 7\n3 4"] | 1 second | ["8", "9", "6"] | NoteIn the first example, one of possible optimal solutions is to insert value $$$x = 3$$$ before $$$a_1$$$, so program will be $$$[3, 4, 6, 7]$$$ and time of lamp being lit equals $$$(3 - 0) + (6 - 4) + (10 - 7) = 8$$$. Other possible solution is to insert $$$x = 5$$$ in appropriate place.In the second example, there is only one optimal solution: to insert $$$x = 2$$$ between $$$a_1$$$ and $$$a_2$$$. Program will become $$$[1, 2, 10]$$$, and answer will be $$$(1 - 0) + (10 - 2) = 9$$$.In the third example, optimal answer is to leave program untouched, so answer will be $$$(3 - 0) + (7 - 4) = 6$$$. | Java 8 | standard input | [
"greedy"
] | 085b03a45fec13b759c3bd334888caf5 | First line contains two space separated integers $$$n$$$ and $$$M$$$ ($$$1 \le n \le 10^5$$$, $$$2 \le M \le 10^9$$$) — the length of program $$$a$$$ and the moment when power turns off. Second line contains $$$n$$$ space separated integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 < a_1 < a_2 < \dots < a_n < M$$$) — initially installed program $$$a$$$. | 1,500 | Print the only integer — maximum possible total time when the lamp is lit. | standard output | |
PASSED | d4b9488c0d1fc123764c169e95aa47b7 | train_003.jsonl | 1530110100 | Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment $$$0$$$ and turn power off at moment $$$M$$$. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunately, some program is already installed into the lamp.The lamp allows only good programs. Good program can be represented as a non-empty array $$$a$$$, where $$$0 < a_1 < a_2 < \dots < a_{|a|} < M$$$. All $$$a_i$$$ must be integers. Of course, preinstalled program is a good program.The lamp follows program $$$a$$$ in next manner: at moment $$$0$$$ turns power and light on. Then at moment $$$a_i$$$ the lamp flips its state to opposite (if it was lit, it turns off, and vice versa). The state of the lamp flips instantly: for example, if you turn the light off at moment $$$1$$$ and then do nothing, the total time when the lamp is lit will be $$$1$$$. Finally, at moment $$$M$$$ the lamp is turning its power off regardless of its state.Since you are not among those people who read instructions, and you don't understand the language it's written in, you realize (after some testing) the only possible way to alter the preinstalled program. You can insert at most one element into the program $$$a$$$, so it still should be a good program after alteration. Insertion can be done between any pair of consecutive elements of $$$a$$$, or even at the begining or at the end of $$$a$$$.Find such a way to alter the program that the total time when the lamp is lit is maximum possible. Maybe you should leave program untouched. If the lamp is lit from $$$x$$$ till moment $$$y$$$, then its lit for $$$y - x$$$ units of time. Segments of time when the lamp is lit are summed up. | 256 megabytes | import java.io.*;
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 solve()
{
int n=s.nextInt();
long m=s.nextLong();
long a[]=new long[n+2];
a[0]=0;
a[n+1]=m;
for(int i=1;i<=n;i++) a[i]=s.nextLong();
//n==1
if(n==1)
{
long aa=0,bb=0,cc=0;
aa=a[1];
if(a[1]>a[0]+1) bb=(a[1]-1)+(m-a[1]);
if(a[2]>a[1]+1) cc=a[1]+(m-(a[1]+1));
System.out.println(Math.max(aa, Math.max(bb, cc)));
return;
}
long on[]=new long[n+2];
long off[]=new long[n+2];
long prefix[]=new long[n+2];
prefix[0]=a[0];
for(int i=1;i<prefix.length;i+=2)
{
prefix[i]=prefix[i-1]+(a[i]-a[i-1]);
if(i+1<prefix.length) prefix[i+1]=prefix[i];
}
on[a.length-1]=0;
off[a.length-1]=0;
for(int i=a.length-2;i>=0;i--)
{
on[i]=a[i+1]-a[i]+off[i+1];
off[i]=on[i+1];
}
long ans=prefix[a.length-1];
for(int i=0;i<a.length-1;i++)
{
if(a[i+1]-a[i]>=2)
{
long req=0;
if((i%2)==1)
req=a[i+1]-(a[i]+1)+off[i+1];
else
req=(a[i+1]-1)-a[i]+on[i+1];
long temp1=prefix[i]+req;
//System.out.println(i+" "+temp1+" "+prefix[i]+" "+incorrect[i+1]);
ans=Math.max(ans, temp1);
}
}
System.out.println(ans);
}
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--;
}
}
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 | ["3 10\n4 6 7", "2 12\n1 10", "2 7\n3 4"] | 1 second | ["8", "9", "6"] | NoteIn the first example, one of possible optimal solutions is to insert value $$$x = 3$$$ before $$$a_1$$$, so program will be $$$[3, 4, 6, 7]$$$ and time of lamp being lit equals $$$(3 - 0) + (6 - 4) + (10 - 7) = 8$$$. Other possible solution is to insert $$$x = 5$$$ in appropriate place.In the second example, there is only one optimal solution: to insert $$$x = 2$$$ between $$$a_1$$$ and $$$a_2$$$. Program will become $$$[1, 2, 10]$$$, and answer will be $$$(1 - 0) + (10 - 2) = 9$$$.In the third example, optimal answer is to leave program untouched, so answer will be $$$(3 - 0) + (7 - 4) = 6$$$. | Java 8 | standard input | [
"greedy"
] | 085b03a45fec13b759c3bd334888caf5 | First line contains two space separated integers $$$n$$$ and $$$M$$$ ($$$1 \le n \le 10^5$$$, $$$2 \le M \le 10^9$$$) — the length of program $$$a$$$ and the moment when power turns off. Second line contains $$$n$$$ space separated integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 < a_1 < a_2 < \dots < a_n < M$$$) — initially installed program $$$a$$$. | 1,500 | Print the only integer — maximum possible total time when the lamp is lit. | standard output | |
PASSED | 6805b5d6b6175be8831266e6d2c66e74 | train_003.jsonl | 1530110100 | Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment $$$0$$$ and turn power off at moment $$$M$$$. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunately, some program is already installed into the lamp.The lamp allows only good programs. Good program can be represented as a non-empty array $$$a$$$, where $$$0 < a_1 < a_2 < \dots < a_{|a|} < M$$$. All $$$a_i$$$ must be integers. Of course, preinstalled program is a good program.The lamp follows program $$$a$$$ in next manner: at moment $$$0$$$ turns power and light on. Then at moment $$$a_i$$$ the lamp flips its state to opposite (if it was lit, it turns off, and vice versa). The state of the lamp flips instantly: for example, if you turn the light off at moment $$$1$$$ and then do nothing, the total time when the lamp is lit will be $$$1$$$. Finally, at moment $$$M$$$ the lamp is turning its power off regardless of its state.Since you are not among those people who read instructions, and you don't understand the language it's written in, you realize (after some testing) the only possible way to alter the preinstalled program. You can insert at most one element into the program $$$a$$$, so it still should be a good program after alteration. Insertion can be done between any pair of consecutive elements of $$$a$$$, or even at the begining or at the end of $$$a$$$.Find such a way to alter the program that the total time when the lamp is lit is maximum possible. Maybe you should leave program untouched. If the lamp is lit from $$$x$$$ till moment $$$y$$$, then its lit for $$$y - x$$$ units of time. Segments of time when the lamp is lit are summed up. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB {
private long[][] dp;
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.nextInt(), m = in.nextInt();
int a[] = in.parseInt1D(n);
dp = new long[n + 1][2];
for (long d[] : dp) Arrays.fill(d, -1);
long max = getSum(a, 0, true, m, 0);
boolean isOn = true;
long current = 0;
int last = 0;
for (int i = 0; i < a.length; i++) {
if (isOn) {
// if (a[i] - 1 != last) {
max = Math.max(current + (a[i] - last - 1) + getSum(a, i, !isOn, m, a[i] - 1), max);
//}
current += (a[i] - last);
} else {
//if (last + 1 != a[i]) {
max = Math.max(current + getSum(a, i, !isOn, m, last) - 1, max);
//}
}
isOn = !isOn;
last = a[i];
}
out.println(max);
}
private long getSum(int a[], int st, boolean isOn, int m, int last) {
if (st == a.length) {
if (isOn) {
return m - last;
} else return 0;
} else {
if (dp[st][isOn ? 0 : 1] != -1) return dp[st][isOn ? 0 : 1];
return dp[st][isOn ? 0 : 1] = (getSum(a, st + 1, !isOn, m, a[st]) + (isOn ? a[st] - last : 0));
}
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void println(long 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 readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public int nextInt() {
return readInt();
}
public int[] parseInt1D(int n) {
int r[] = new int[n];
for (int i = 0; i < n; i++) {
r[i] = nextInt();
}
return r;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["3 10\n4 6 7", "2 12\n1 10", "2 7\n3 4"] | 1 second | ["8", "9", "6"] | NoteIn the first example, one of possible optimal solutions is to insert value $$$x = 3$$$ before $$$a_1$$$, so program will be $$$[3, 4, 6, 7]$$$ and time of lamp being lit equals $$$(3 - 0) + (6 - 4) + (10 - 7) = 8$$$. Other possible solution is to insert $$$x = 5$$$ in appropriate place.In the second example, there is only one optimal solution: to insert $$$x = 2$$$ between $$$a_1$$$ and $$$a_2$$$. Program will become $$$[1, 2, 10]$$$, and answer will be $$$(1 - 0) + (10 - 2) = 9$$$.In the third example, optimal answer is to leave program untouched, so answer will be $$$(3 - 0) + (7 - 4) = 6$$$. | Java 8 | standard input | [
"greedy"
] | 085b03a45fec13b759c3bd334888caf5 | First line contains two space separated integers $$$n$$$ and $$$M$$$ ($$$1 \le n \le 10^5$$$, $$$2 \le M \le 10^9$$$) — the length of program $$$a$$$ and the moment when power turns off. Second line contains $$$n$$$ space separated integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 < a_1 < a_2 < \dots < a_n < M$$$) — initially installed program $$$a$$$. | 1,500 | Print the only integer — maximum possible total time when the lamp is lit. | standard output | |
PASSED | ac410a6bc8a4afb374a4e509309f7da7 | train_003.jsonl | 1530110100 | Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment $$$0$$$ and turn power off at moment $$$M$$$. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunately, some program is already installed into the lamp.The lamp allows only good programs. Good program can be represented as a non-empty array $$$a$$$, where $$$0 < a_1 < a_2 < \dots < a_{|a|} < M$$$. All $$$a_i$$$ must be integers. Of course, preinstalled program is a good program.The lamp follows program $$$a$$$ in next manner: at moment $$$0$$$ turns power and light on. Then at moment $$$a_i$$$ the lamp flips its state to opposite (if it was lit, it turns off, and vice versa). The state of the lamp flips instantly: for example, if you turn the light off at moment $$$1$$$ and then do nothing, the total time when the lamp is lit will be $$$1$$$. Finally, at moment $$$M$$$ the lamp is turning its power off regardless of its state.Since you are not among those people who read instructions, and you don't understand the language it's written in, you realize (after some testing) the only possible way to alter the preinstalled program. You can insert at most one element into the program $$$a$$$, so it still should be a good program after alteration. Insertion can be done between any pair of consecutive elements of $$$a$$$, or even at the begining or at the end of $$$a$$$.Find such a way to alter the program that the total time when the lamp is lit is maximum possible. Maybe you should leave program untouched. If the lamp is lit from $$$x$$$ till moment $$$y$$$, then its lit for $$$y - x$$$ units of time. Segments of time when the lamp is lit are summed up. | 256 megabytes | import java.util.*;
public class B{
public static void main(String[] args){
final int MAXN = 123456;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int M = sc.nextInt();
int a[] = new int[MAXN];
int presum[][] = new int[2][MAXN];
for(int i = 1; i <= n; i++) a[i] = sc.nextInt();
a[++n] = M; a[0] = 0;
presum[0][0] = presum[1][0];
for(int i = 1; i <= n; i++){
presum[0][i] = presum[0][i-1];
presum[1][i] = presum[1][i-1];
presum[i&1][i] += (a[i] - a[i-1]);
//System.out.println(presum[0][i] + " " + presum[1][i]);
}
int ans = presum[1][n];
for(int i = 1; i <= n; i++){
if(a[i] - a[i-1] <= 1) continue;
ans = Math.max(ans, presum[1][i-1] + (presum[0][n]-presum[0][i]) + (a[i]-a[i-1]-1));
}
System.out.println(ans);
}
}
| Java | ["3 10\n4 6 7", "2 12\n1 10", "2 7\n3 4"] | 1 second | ["8", "9", "6"] | NoteIn the first example, one of possible optimal solutions is to insert value $$$x = 3$$$ before $$$a_1$$$, so program will be $$$[3, 4, 6, 7]$$$ and time of lamp being lit equals $$$(3 - 0) + (6 - 4) + (10 - 7) = 8$$$. Other possible solution is to insert $$$x = 5$$$ in appropriate place.In the second example, there is only one optimal solution: to insert $$$x = 2$$$ between $$$a_1$$$ and $$$a_2$$$. Program will become $$$[1, 2, 10]$$$, and answer will be $$$(1 - 0) + (10 - 2) = 9$$$.In the third example, optimal answer is to leave program untouched, so answer will be $$$(3 - 0) + (7 - 4) = 6$$$. | Java 8 | standard input | [
"greedy"
] | 085b03a45fec13b759c3bd334888caf5 | First line contains two space separated integers $$$n$$$ and $$$M$$$ ($$$1 \le n \le 10^5$$$, $$$2 \le M \le 10^9$$$) — the length of program $$$a$$$ and the moment when power turns off. Second line contains $$$n$$$ space separated integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 < a_1 < a_2 < \dots < a_n < M$$$) — initially installed program $$$a$$$. | 1,500 | Print the only integer — maximum possible total time when the lamp is lit. | standard output | |
PASSED | 9d8da415000a983e35d4cf8f6c135023 | train_003.jsonl | 1530110100 | Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment $$$0$$$ and turn power off at moment $$$M$$$. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunately, some program is already installed into the lamp.The lamp allows only good programs. Good program can be represented as a non-empty array $$$a$$$, where $$$0 < a_1 < a_2 < \dots < a_{|a|} < M$$$. All $$$a_i$$$ must be integers. Of course, preinstalled program is a good program.The lamp follows program $$$a$$$ in next manner: at moment $$$0$$$ turns power and light on. Then at moment $$$a_i$$$ the lamp flips its state to opposite (if it was lit, it turns off, and vice versa). The state of the lamp flips instantly: for example, if you turn the light off at moment $$$1$$$ and then do nothing, the total time when the lamp is lit will be $$$1$$$. Finally, at moment $$$M$$$ the lamp is turning its power off regardless of its state.Since you are not among those people who read instructions, and you don't understand the language it's written in, you realize (after some testing) the only possible way to alter the preinstalled program. You can insert at most one element into the program $$$a$$$, so it still should be a good program after alteration. Insertion can be done between any pair of consecutive elements of $$$a$$$, or even at the begining or at the end of $$$a$$$.Find such a way to alter the program that the total time when the lamp is lit is maximum possible. Maybe you should leave program untouched. If the lamp is lit from $$$x$$$ till moment $$$y$$$, then its lit for $$$y - x$$$ units of time. Segments of time when the lamp is lit are summed up. | 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 B1000
{
static class Scanner
{
BufferedReader br;
StringTokenizer tk=new StringTokenizer("");
public Scanner(InputStream is)
{
br=new BufferedReader(new InputStreamReader(is));
}
public int nextInt() throws IOException
{
if(tk.hasMoreTokens())
return Integer.parseInt(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextInt();
}
public long nextLong() throws IOException
{
if(tk.hasMoreTokens())
return Long.parseLong(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextLong();
}
public String next() throws IOException
{
if(tk.hasMoreTokens())
return (tk.nextToken());
tk=new StringTokenizer(br.readLine());
return next();
}
public String nextLine() throws IOException
{
tk=new StringTokenizer("");
return br.readLine();
}
public double nextDouble() throws IOException
{
if(tk.hasMoreTokens())
return Double.parseDouble(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextDouble();
}
public char nextChar() throws IOException
{
if(tk.hasMoreTokens())
return (tk.nextToken().charAt(0));
tk=new StringTokenizer(br.readLine());
return nextChar();
}
public int[] nextIntArray(int n) throws IOException
{
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=nextInt();
return a;
}
public long[] nextLongArray(int n) throws IOException
{
long a[]=new long[n];
for(int i=0;i<n;i++)
a[i]=nextLong();
return a;
}
public int[] nextIntArrayOneBased(int n) throws IOException
{
int a[]=new int[n+1];
for(int i=1;i<=n;i++)
a[i]=nextInt();
return a;
}
public long[] nextLongArrayOneBased(int n) throws IOException
{
long a[]=new long[n+1];
for(int i=1;i<=n;i++)
a[i]=nextLong();
return a;
}
}
public static void main(String args[]) throws IOException
{
Scanner in=new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
int n=in.nextInt();
int m=in.nextInt();
int a[]=in.nextIntArray(n);
int on[]=new int[n];
int off[]=new int[n];
int last=m;
on[n-1]=m-a[n-1];
for(int i=n-2;i>=0;i--)
{
on[i]=a[i+1]-a[i]+off[i+1];
off[i]=on[i+1];
}
int ans=a[0]-0+off[0];
if(a[0]>=2)
{
ans=Math.max(ans,1+on[0]);
ans=Math.max(ans,a[0]-1+on[0]);
}
int onv=a[0];
int cur=0;
for(int i=1;i<n;i++)
{
//try a[i-1]+1
if(a[i]-a[i-1]>1)
{
if(cur==0)
{
ans=Math.max(ans,onv+a[i]-a[i-1]-1+off[i]);
}
if(cur==1)
{
ans=Math.max(ans,onv+a[i]-a[i-1]-1+on[i]);
}
}
if(cur==1)
onv+=a[i]-a[i-1];
cur=1-cur;
}
if(cur==1)
ans=Math.max(ans,onv+m-a[n-1]);
if(m-a[n-1]>1&&cur==0)
{
ans=Math.max(ans,onv+m-a[n-1]-1);
}
out.println(ans);
out.close();
}
}
| Java | ["3 10\n4 6 7", "2 12\n1 10", "2 7\n3 4"] | 1 second | ["8", "9", "6"] | NoteIn the first example, one of possible optimal solutions is to insert value $$$x = 3$$$ before $$$a_1$$$, so program will be $$$[3, 4, 6, 7]$$$ and time of lamp being lit equals $$$(3 - 0) + (6 - 4) + (10 - 7) = 8$$$. Other possible solution is to insert $$$x = 5$$$ in appropriate place.In the second example, there is only one optimal solution: to insert $$$x = 2$$$ between $$$a_1$$$ and $$$a_2$$$. Program will become $$$[1, 2, 10]$$$, and answer will be $$$(1 - 0) + (10 - 2) = 9$$$.In the third example, optimal answer is to leave program untouched, so answer will be $$$(3 - 0) + (7 - 4) = 6$$$. | Java 8 | standard input | [
"greedy"
] | 085b03a45fec13b759c3bd334888caf5 | First line contains two space separated integers $$$n$$$ and $$$M$$$ ($$$1 \le n \le 10^5$$$, $$$2 \le M \le 10^9$$$) — the length of program $$$a$$$ and the moment when power turns off. Second line contains $$$n$$$ space separated integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 < a_1 < a_2 < \dots < a_n < M$$$) — initially installed program $$$a$$$. | 1,500 | Print the only integer — maximum possible total time when the lamp is lit. | standard output | |
PASSED | 6e0d0ec0f5129ee7d86b772b46c77796 | train_003.jsonl | 1530110100 | Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment $$$0$$$ and turn power off at moment $$$M$$$. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunately, some program is already installed into the lamp.The lamp allows only good programs. Good program can be represented as a non-empty array $$$a$$$, where $$$0 < a_1 < a_2 < \dots < a_{|a|} < M$$$. All $$$a_i$$$ must be integers. Of course, preinstalled program is a good program.The lamp follows program $$$a$$$ in next manner: at moment $$$0$$$ turns power and light on. Then at moment $$$a_i$$$ the lamp flips its state to opposite (if it was lit, it turns off, and vice versa). The state of the lamp flips instantly: for example, if you turn the light off at moment $$$1$$$ and then do nothing, the total time when the lamp is lit will be $$$1$$$. Finally, at moment $$$M$$$ the lamp is turning its power off regardless of its state.Since you are not among those people who read instructions, and you don't understand the language it's written in, you realize (after some testing) the only possible way to alter the preinstalled program. You can insert at most one element into the program $$$a$$$, so it still should be a good program after alteration. Insertion can be done between any pair of consecutive elements of $$$a$$$, or even at the begining or at the end of $$$a$$$.Find such a way to alter the program that the total time when the lamp is lit is maximum possible. Maybe you should leave program untouched. If the lamp is lit from $$$x$$$ till moment $$$y$$$, then its lit for $$$y - x$$$ units of time. Segments of time when the lamp is lit are summed up. | 256 megabytes | import java.util.*;
import java.io.*;
public class A
{
public static void main(String ar[]) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s1[]=br.readLine().split(" ");
String s2[]=br.readLine().split(" ");
int n=Integer.parseInt(s1[0]);
int m=Integer.parseInt(s1[1]);
int a[]=new int[n];
int b[]=new int[n];
int c[]=new int[n];
int d[]=new int[n];
HashSet<Integer> hs=new HashSet<Integer>();
hs.add(0);
hs.add(m);
int max=0;
for(int i=0;i<n;i++)
{
a[i]=Integer.parseInt(s2[i]);
if(i%2==0)
b[i]=1;
hs.add(a[i]);
}
c[0]=a[0];
for(int i=1;i<n;i++)
{
if(b[i]==0)
c[i]=c[i-1];
else
c[i]=c[i-1]+a[i]-a[i-1];
}
if(b[n-1]==0)
d[n-1]=m-a[n-1];
for(int i=n-2;i>=0;i--)
{
if(b[i]==1)
d[i]=d[i+1];
else
d[i]=d[i+1]+a[i+1]-a[i];
}
max=c[n-1];
if(b[n-1]==0)
max+=m-a[n-1];
//System.out.println(max);
for(int i=n-1;i>=0;i--)
{
int u=a[i]-1;
int v=a[i]+1;
if(!hs.contains(u))
{
if(b[i]==0)
{
int r=1+m-a[i]-d[i]+c[i-1];
max=Math.max(max,r);
}
else
{
int l=0;
if(i>0)
l=a[i-1];
int r=c[i]-1+m-a[i]-d[i];
max=Math.max(max,r);
}
}
if(!hs.contains(v))
{
if(b[i]==0)
{
if(i==n-1)
{
int r=c[i]+1;
max=Math.max(max,r);
}
else
{
int r=c[i]+1+m-a[i+1]-d[i+1];
max=Math.max(max,r);
}
}
else
{
if(i==n-1)
{
int r=c[i]+m-a[i]-1;
max=Math.max(max,r);
}
else
{
int r=c[i]+m-a[i+1]-d[i+1]+a[i+1]-1-a[i];
max=Math.max(max,r);
}
}
}
}
System.out.println(max);
}
} | Java | ["3 10\n4 6 7", "2 12\n1 10", "2 7\n3 4"] | 1 second | ["8", "9", "6"] | NoteIn the first example, one of possible optimal solutions is to insert value $$$x = 3$$$ before $$$a_1$$$, so program will be $$$[3, 4, 6, 7]$$$ and time of lamp being lit equals $$$(3 - 0) + (6 - 4) + (10 - 7) = 8$$$. Other possible solution is to insert $$$x = 5$$$ in appropriate place.In the second example, there is only one optimal solution: to insert $$$x = 2$$$ between $$$a_1$$$ and $$$a_2$$$. Program will become $$$[1, 2, 10]$$$, and answer will be $$$(1 - 0) + (10 - 2) = 9$$$.In the third example, optimal answer is to leave program untouched, so answer will be $$$(3 - 0) + (7 - 4) = 6$$$. | Java 8 | standard input | [
"greedy"
] | 085b03a45fec13b759c3bd334888caf5 | First line contains two space separated integers $$$n$$$ and $$$M$$$ ($$$1 \le n \le 10^5$$$, $$$2 \le M \le 10^9$$$) — the length of program $$$a$$$ and the moment when power turns off. Second line contains $$$n$$$ space separated integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 < a_1 < a_2 < \dots < a_n < M$$$) — initially installed program $$$a$$$. | 1,500 | Print the only integer — maximum possible total time when the lamp is lit. | standard output | |
PASSED | f052f6bc26d1cdfcf76fb34c58c182d8 | train_003.jsonl | 1530110100 | Recently, you bought a brand new smart lamp with programming features. At first, you set up a schedule to the lamp. Every day it will turn power on at moment $$$0$$$ and turn power off at moment $$$M$$$. Moreover, the lamp allows you to set a program of switching its state (states are "lights on" and "lights off"). Unfortunately, some program is already installed into the lamp.The lamp allows only good programs. Good program can be represented as a non-empty array $$$a$$$, where $$$0 < a_1 < a_2 < \dots < a_{|a|} < M$$$. All $$$a_i$$$ must be integers. Of course, preinstalled program is a good program.The lamp follows program $$$a$$$ in next manner: at moment $$$0$$$ turns power and light on. Then at moment $$$a_i$$$ the lamp flips its state to opposite (if it was lit, it turns off, and vice versa). The state of the lamp flips instantly: for example, if you turn the light off at moment $$$1$$$ and then do nothing, the total time when the lamp is lit will be $$$1$$$. Finally, at moment $$$M$$$ the lamp is turning its power off regardless of its state.Since you are not among those people who read instructions, and you don't understand the language it's written in, you realize (after some testing) the only possible way to alter the preinstalled program. You can insert at most one element into the program $$$a$$$, so it still should be a good program after alteration. Insertion can be done between any pair of consecutive elements of $$$a$$$, or even at the begining or at the end of $$$a$$$.Find such a way to alter the program that the total time when the lamp is lit is maximum possible. Maybe you should leave program untouched. If the lamp is lit from $$$x$$$ till moment $$$y$$$, then its lit for $$$y - x$$$ units of time. Segments of time when the lamp is lit are summed up. | 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...
*/
//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?)
//always declare multidimensional arrays as [2][n] not [n][2]
//it can lead to upto 2-3x diff in runtime
//declare int/long tries with 16 array size due to object overhead :D
public class Main
{
public static void main(String[] args) throws Exception
{
int n=ni(),m=ni();
int[]a=new int[n+2];
a[n+1]=m;
int ans=0;
for(int i=1; i<=n; i++)
a[i]=ni();
for(int i=1; i<=n+1; i+=2)
ans+=a[i]-a[i-1];
int sum=ans;
int te=0;
for(int i=1; i<=n; i+=2)
{
te+=a[i]-a[i-1];
if(a[i]+1!=a[i+1]&&a[i]+1!=m)
{
int teans=2*te+m-a[i]-sum-1;
ans=max(teans,ans);
}
}
sop(ans);
System.out.print(output);
}
///////////////////////////////////////////
///////////////////////////////////////////
///template from here
static int pow(int a, int b)
{
int c=1;
while(b>0)
{
if(b%2!=0)
c*=a;
a*=a;
}
return c;
}
static class pair
{
int a, b;
pair(){}
pair(int c,int d){a=c;b=d;}
}
static interface combiner
{
public long combine(long a,long b);
}
static final long mod=1000000007;
static final double eps=1e-9;
static final long inf=1000_000_000_000_000_000L;
static Reader in=new Reader();
static StringBuilder output=new StringBuilder();
static Random rn=new Random();
static void reverse(int[]a){for(int i=0; i<a.length/2; i++){a[i]^=a[a.length-i-1];a[a.length-i-1]^=a[i];a[i]^=a[a.length-i-1];}}
static void sort(int[]a)
{
int te;
for(int i=0; i<a.length; i+=2)
{
te=rn.nextInt(a.length);
if(i!=te)
{
a[i]^=a[te];
a[te]^=a[i];
a[i]^=a[te];
}
}
Arrays.sort(a);
}
static void sort(long[]a)
{
int te;
for(int i=0; i<a.length; i+=2)
{
te=rn.nextInt(a.length);
if(i!=te)
{
a[i]^=a[te];
a[te]^=a[i];
a[i]^=a[te];
}
}
Arrays.sort(a);
}
static void sort(double[]a)
{
int te;
double te1;
for(int i=0; i<a.length; i+=2)
{
te=rn.nextInt(a.length);
if(i!=te)
{
te1=a[te];
a[te]=a[i];
a[i]=te1;
}
}
Arrays.sort(a);
}
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 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 vectorl implements Iterable<Long>
{
long a[];
int size;
vectorl(){a=new long[10];size=0;}
vectorl(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);}
@Override
public Iterator<Long> iterator() {
Iterator<Long> hola=new Iterator<Long>()
{
int cur=0;
@Override
public boolean hasNext() {
return cur<size;
}
@Override
public Long next() {
return a[cur++];
}
};
return hola;
}
}
static class vector implements Iterable<Integer>
{
int a[],size;
vector(){a=new int[10];size=0;}
vector(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);}
@Override
public Iterator<Integer> iterator() {
Iterator<Integer> hola=new Iterator<Integer>()
{
int cur=0;
@Override
public boolean hasNext() {
return cur<size;
}
@Override
public Integer next() {
return a[cur++];
}
};
return hola;
}
}
//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 Integer.parseInt(in.next());}
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;}
//////////////////////////////////
//some utility functions
static void exit(){System.out.print(output);System.exit(0);}
static int min(int... a){int min=a[0];for(int i:a)min=Math.min(min, i);return min;}
static int max(int... a){int max=a[0];for(int i:a)max=Math.max(max, i);return max;}
static int gcd(int... a){int gcd=a[0];for(int i:a)gcd=gcd(gcd, i);return gcd;}
static long min(long... a){long min=a[0];for(long i:a)min=Math.min(min, i);return min;}
static long max(long... a){long max=a[0];for(long i:a)max=Math.max(max, i);return max;}
static long gcd(long... a){long gcd=a[0];for(long i:a)gcd=gcd(gcd, i);return gcd;}
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;return gcd(b, a%b);}
static long gcd(long a, long b){if(b==0)return a;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();
}
}
} | Java | ["3 10\n4 6 7", "2 12\n1 10", "2 7\n3 4"] | 1 second | ["8", "9", "6"] | NoteIn the first example, one of possible optimal solutions is to insert value $$$x = 3$$$ before $$$a_1$$$, so program will be $$$[3, 4, 6, 7]$$$ and time of lamp being lit equals $$$(3 - 0) + (6 - 4) + (10 - 7) = 8$$$. Other possible solution is to insert $$$x = 5$$$ in appropriate place.In the second example, there is only one optimal solution: to insert $$$x = 2$$$ between $$$a_1$$$ and $$$a_2$$$. Program will become $$$[1, 2, 10]$$$, and answer will be $$$(1 - 0) + (10 - 2) = 9$$$.In the third example, optimal answer is to leave program untouched, so answer will be $$$(3 - 0) + (7 - 4) = 6$$$. | Java 8 | standard input | [
"greedy"
] | 085b03a45fec13b759c3bd334888caf5 | First line contains two space separated integers $$$n$$$ and $$$M$$$ ($$$1 \le n \le 10^5$$$, $$$2 \le M \le 10^9$$$) — the length of program $$$a$$$ and the moment when power turns off. Second line contains $$$n$$$ space separated integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 < a_1 < a_2 < \dots < a_n < M$$$) — initially installed program $$$a$$$. | 1,500 | Print the only integer — maximum possible total time when the lamp is lit. | standard output | |
PASSED | df2035759d25f2c0424b1ea6b6678a6e | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes | import java.io.*;
import java.util.*;
import java.lang.*;
import java.math.*;
import java.text.DecimalFormat;
import java.lang.reflect.Array;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
public class B{
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
static long MOD = (long)(1e9+7);
static long MOD2 = MOD*MOD;
//static long MOD = 998244353;
static FastReader sc = new FastReader();
static int pInf = Integer.MAX_VALUE;
static int nInf = Integer.MIN_VALUE;
static int[] ans;
public static void main(String[] args){
int test = 1;
test = sc.nextInt();
while(test-->0){
int n = sc.nextInt();
long a = sc.nextLong();
long b = sc.nextLong();
String s = sc.next();
boolean found = false;
int start = pInf;
int end = nInf;
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i)=='1') {
found = true;
start = Math.min(i, start);
end = Math.max(end, i);
}
}
if(!found) {
long ans = ((n+1)*b)+(a*n);
out.println(ans);
continue;
}
long ans = 0;
int state = 1;
long count = 0;
for(int i = start; i <= end; i++) {
if(state==1) {
while(i<n&& s.charAt(i)=='1') {
i++;
count++;
}
i--;
ans += (a*count)+(2*b*(count+1));
count = 0;
state = 0;
}
else {
while(i<n&& s.charAt(i)=='0') {
i++;
count++;
}
i--;
if(count==1) {
ans += a;
}
else {
ans += Math.min((count+2)*a+((count-1)*b) , (count*a)+2*((count-1)*b));
}
count = 0;
state = 1;
}
}
ans += (start+1)*a+(start*b);
ans += (n-end)*a+((n-end-1)*b);
out.println(ans);
}
out.flush();
out.close();
}
public static int lowerBound(int key, int[] a) {
int s = 0;
int e = a.length-1;
if(e==-1) {
return 0;
}
int ans = -1;
while(s<=e) {
int m = s+(e-s)/2;
if(a[m]>=key) {
ans = m;
e = m-1;
}
else {
s = m+1;
}
}
return ans==-1?s:ans;
}
public static int upperBound(int key, int[] a) {
int s = 0;
int e = a.length-1;
if(e==-1) {
return 0;
}
int ans = -1;
while(s<=e) {
int m = s+(e-s)/2;
if(a[m]>key) {
ans = m;
e = m-1;
}
else {
s = m+1;
}
}
return ans==-1?s:ans;
}
public static long c2(long n) {
if((n&1)==0) {
return mul(n/2, n-1);
}
else {
return mul(n, (n-1)/2);
}
}
public static long mul(long a, long b){
return ((a%MOD)*(b%MOD))%MOD;
}
public static long add(long a, long b){
return ((a%MOD)+(b%MOD))%MOD;
}
public static long sub(long a, long b){
return ((a%MOD)-(b%MOD))%MOD;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Integer.lowestOneBit(i) Equals k where k is the position of the first one in the binary
//Integer.highestOneBit(i) Equals k where k is the position of the last one in the binary
//Integer.bitCount(i) returns the number of one-bits
//Collections.sort(A,(p1,p2)->(int)(p2.x-p1.x)) To sort ArrayList in descending order wrt values of x.
// Arrays.parallelSort(a,new Comparator<TPair>() {
// public int compare(TPair a,TPair b) {
// if(a.y==b.y) return a.x-b.x;
// return b.y-a.y;
// }
// });
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//PrimeFactors
public static ArrayList<Long> primeFactors(long n) {
ArrayList<Long> arr = new ArrayList<>();
if (n % 2 == 0)
arr.add((long) 2);
while (n % 2 == 0)
n /= 2;
for (long i = 3; i <= Math.sqrt(n); i += 2) {
int flag = 0;
while (n % i == 0) {
n /= i;
flag = 1;
}
if (flag == 1)
arr.add(i);
}
if (n > 2)
arr.add(n);
return arr;
}
//Pair Class
static class Pair implements Comparable<Pair>{
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
if(this.x==o.x){
return (this.y-o.y);
}
return -1*(this.x-o.x);
}
}
static class TPair implements Comparable<TPair>{
int l;
int r;
int index;
int len;
public TPair(int l, int r, int index) {
this.l = l;
this.r = r;
this.index = index;
this.len = r-l+1;
}
@Override
public int compareTo(TPair o) {
if(this.l==o.l){
return -1*(this.len-o.len);
}
return (this.l-o.l);
}
}
//nCr
static long ncr(long n, long k) {
long ret = 1;
for (long x = n; x > n - k; x--) {
ret *= x;
ret /= (n - x + 1);
}
return ret;
}
static long finextDoubleMMI_fermat(long n,int M)
{
return fastExpo(n,M-2);
}
static long nCrModPFermat(int n, int r, int p)
{
if (r == 0)
return 1;
long[] fac = new long[n+1];
fac[0] = 1;
for (int i = 1 ;i <= n; i++)
fac[i] = fac[i-1] * i % p;
return (fac[n]* finextDoubleMMI_fermat(fac[r], p)% p * finextDoubleMMI_fermat(fac[n-r], p) % p) % p;
}
//Kadane's Algorithm
static long maxSubArraySum(ArrayList<Long> a) {
if(a.size()==0) {
return 0;
}
long max_so_far = a.get(0);
long curr_max = a.get(0);
for (int i = 1; i < a.size(); i++) {
curr_max = Math.max(a.get(i), curr_max+a.get(i));
max_so_far = Math.max(max_so_far, curr_max);
}
return max_so_far;
}
//Shuffle Sort
static final Random random=new Random();
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
//Merge Sort
static void merge(long arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
long L[] = new long [n1];
long R[] = new long [n2];
/*Copy data to temp arrays*/
for (int i=0; i<n1; ++i)
L[i] = arr[l + i];
for (int j=0; j<n2; ++j)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
static void sort(long arr[], int l, int r)
{
if (l < r)
{
// Find the middle point
int m = (l+r)/2;
// Sort first and second halves
sort(arr, l, m);
sort(arr , m+1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
//Brian Kernighans Algorithm
static long countSetBits(long n){
if(n==0) return 0;
return 1+countSetBits(n&(n-1));
}
//Factorial
static long factorial(long n){
if(n==1) return 1;
if(n==2) return 2;
if(n==3) return 6;
return n*factorial(n-1);
}
//Euclidean Algorithm
static long gcd(long A,long B){
if(B==0) return A;
return gcd(B,A%B);
}
//Modular Exponentiation
static long fastExpo(long x,long n){
if(n==0) return 1;
if((n&1)==0) return fastExpo((x*x)%MOD,n/2)%MOD;
return ((x%MOD)*fastExpo((x*x)%MOD,(n-1)/2))%MOD;
}
//AKS Algorithm
static boolean isPrime(long n){
if(n<=1) return false;
if(n<=3) return true;
if(n%2==0 || n%3==0) return false;
for(int i=5;i<=Math.sqrt(n);i+=6)
if(n%i==0 || n%(i+2)==0) return false;
return true;
}
//Reverse an array
static <T> void reverse(T arr[],int l,int r){
Collections.reverse(Arrays.asList(arr).subList(l, r));
}
//Print array
static void print1d(int arr[]) {
out.println(Arrays.toString(arr));
}
static void print2d(int arr[][]) {
for(int a[]: arr) out.println(Arrays.toString(a));
}
//Sieve of eratosthenes
static int[] findPrimes(int n){
boolean isPrime[]=new boolean[n+1];
ArrayList<Integer> a=new ArrayList<>();
int result[];
Arrays.fill(isPrime,true);
isPrime[0]=false;
isPrime[1]=false;
for(int i=2;i*i<=n;++i){
if(isPrime[i]==true){
for(int j=i*i;j<=n;j+=i) isPrime[j]=false;
}
}
for(int i=0;i<=n;i++) if(isPrime[i]==true) a.add(i);
result=new int[a.size()];
for(int i=0;i<a.size();i++) result[i]=a.get(i);
return result;
}
//Indivisual factors of all nos till n
static ArrayList<Integer>[] indiFactors(int n){
ArrayList<Integer>[] A = new ArrayList[n+1];
for(int i = 0; i <= n; i++) {
A[i] = new ArrayList<>();
}
int[] sieve = new int[n+1];
for(int i=2;i<=n;i++) {
if(sieve[i]==0) {
for(int j=i;j<=n;j+=i) if(sieve[j]==0) {
//sieve[j]=i;
A[j].add(i);
}
}
}
return A;
}
//Segmented Sieve
static boolean[] segmentedSieve(long l, long r){
boolean[] segSieve = new boolean[(int)(r-l+1)];
Arrays.fill(segSieve, true);
int[] prePrimes = findPrimes((int)Math.sqrt(r));
for(int p:prePrimes) {
long low = (l/p)*p;
if(low < l) {
low += p;
}
if(low == p) {
low += p;
}
for(long j = low; j<= r; j += p) {
segSieve[(int) (j-l)] = false;
}
}
if(l==1) {
segSieve[0] = false;
}
return segSieve;
}
//Euler Totent function
static long countCoprimes(long n){
ArrayList<Long> prime_factors=new ArrayList<>();
long x=n,flag=0;
while(x%2==0){
if(flag==0) prime_factors.add(2L);
flag=1;
x/=2;
}
for(long i=3;i*i<=x;i+=2){
flag=0;
while(x%i==0){
if(flag==0) prime_factors.add(i);
flag=1;
x/=i;
}
}
if(x>2) prime_factors.add(x);
double ans=(double)n;
for(Long p:prime_factors){
ans*=(1.0-(Double)1.0/p);
}
return (long)ans;
}
static long modulo = (long)1e9+7;
public static long modinv(long x){
return modpow(x, modulo-2);
}
public static long modpow(long a, long b){
if(b==0){
return 1;
}
long x = modpow(a, b/2);
x = (x*x)%modulo;
if(b%2==1){
return (x*a)%modulo;
}
return x;
}
public static class FastReader {
BufferedReader br;
StringTokenizer st;
//it reads the data about the specified point and divide the data about it ,it is quite fast
//than using direct
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception r) {
r.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());//converts string to integer
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (Exception r) {
r.printStackTrace();
}
return str;
}
}
} | Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | b74836c6f640d9c796bc5551300656ed | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes | import java.io.*;
import java.util.*;
public class C
{
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
long INF = 100_000_000_000_000_000L;
public void go() throws IOException
{
StringTokenizer tok = new StringTokenizer(in.readLine());
int zzz = Integer.parseInt(tok.nextToken());
for (int zz = 0; zz < zzz; zz++)
{
tok = new StringTokenizer(in.readLine());
int n = Integer.parseInt(tok.nextToken());
long a = Integer.parseInt(tok.nextToken());
long b = Integer.parseInt(tok.nextToken());
tok = new StringTokenizer(in.readLine());
char[] s = tok.nextToken().toCharArray();
long[][] dp = new long[n+1][2];
dp[n][0] = b;
dp[n][1] = INF;
for (int i = n-1; i >= 0; i--)
{
if (s[i] == '1')
{
dp[i][0] = INF;
dp[i][1] = dp[i+1][1] + a + b*2;
}
else
{
dp[i][0] = Math.min(dp[i+1][0] + a + b, dp[i+1][1] + a*2 + b);
dp[i][1] = Math.min(dp[i+1][0] + a*2 + b*2, dp[i+1][1] + a + b*2);
}
}
if (dp[0][0] >= INF && dp[0][0] < 0)
{
throw new RuntimeException();
}
out.println(dp[0][0]);
}
out.flush();
in.close();
}
public static void main(String[] args) throws IOException
{
new C().go();
}
}
| Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | 026dcb12199ddfb57438ecad541c17be | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author revanth
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
CGasPipeline solver = new CGasPipeline();
solver.solve(1, in, out);
out.close();
}
static class CGasPipeline {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int t = in.nextInt(), n, a, b;
String s;
long[][] dp;
while (t-- > 0) {
n = in.nextInt();
a = in.nextInt();
b = in.nextInt();
s = in.nextString();
dp = new long[n + 1][2];
for (int i = 0; i <= n; i++)
Arrays.fill(dp[i], (long) 1e18);
dp[0][0] = b;
for (int i = 0; i < n; i++) {
if (s.charAt(i) == '1')
dp[i + 1][1] = Math.min(dp[i][1] + a + 2 * b, dp[i + 1][1]);
else {
dp[i + 1][0] = Math.min(dp[i][0] + a + b, dp[i + 1][0]);
dp[i + 1][0] = Math.min(dp[i][1] + 2 * a + b, dp[i + 1][0]);
dp[i + 1][1] = Math.min(dp[i][0] + 2 * (a + b), dp[i + 1][1]);
dp[i + 1][1] = Math.min(dp[i][1] + a + 2 * b, dp[i + 1][1]);
}
}
out.println(dp[n][0]);
}
out.println();
}
}
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() {
writer.println();
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[8192];
private int curChar;
private int snumChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c))
c = snext();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
boolean isSpaceChar(int ch);
}
}
}
| Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | d0369df74fef787ef13fd92d4778182e | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes |
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.text.CollationKey;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class Main {
public static class edge {
int u;
int v;
public edge(int u, int v) {
this.u = u;
this.v = v;
}
public double getdist(edge e) {
return Math.sqrt((u - e.u) * (u - e.u) + (v - e.v) * (v - e.v));
}
}
public static class UnionFind {
int[] p, rank;
boolean[] cyclic;
public UnionFind(int N) {
p = new int[N];
rank = new int[N];
// cyclic = new boolean[N];
for (int i = 0; i < N; i++)
p[i] = i;
}
public int findSet(int x) {
return p[x] == x ? x : (p[x] = findSet(p[x]));
}
public boolean isunioned(int x, int y) {
return findSet(x) == findSet(y);
}
public boolean union(int x, int y) {
x = findSet(x);
y = findSet(y);
if (x == y) {
return false;
}
if (rank[x] > rank[y])
p[y] = x;
else {
p[x] = y;
if (rank[x] == rank[y])
++rank[y];
}
return true;
}
}
static PrintWriter pw;
static int n, m, a, b;
static long INF = (long) 1e15;
static int[] rock, scis, pap;
static int[] Arr;
static long[][] memo;
public static long dp(int idx, int up) {
if (idx == n - 1) {
if (up == 0)
return a + 2 * b;
else
return 2 * a + 2 * b;
}
long stay = INF, leave = INF;
if (memo[up][idx] != -1)
return memo[up][idx];
if (up == 0 && Arr[idx + 1] == 1)
leave = 2 * b + 2 * a + dp(idx + 1, 1);
else if (up == 0 && Arr[idx + 1] == 0)
stay = b + a + dp(idx + 1, up);
else if (up == 1 && Arr[idx] == 1)
stay = 2 * b + a + dp(idx + 1, up);
else if (up == 1 && Arr[idx] == 0) {
if(Arr[idx+1]==0)
leave = b + 2 * a + dp(idx + 1, 1 - up);
stay = 2 * b + a + dp(idx + 1, up);
}
return memo[up][idx] = Math.min(stay, leave);
}
public static void main(String[] args) throws IOException, InterruptedException {
// FileWriter f = new FileWriter("C:\\Users\\Hp\\Desktop\\out.txt");
// pw = new PrintWriter(System.in);
// pw = new PrintWriter(System.in);
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
n = sc.nextInt();
a = sc.nextInt();
b = sc.nextInt();
String str = sc.next();
Arr = new int[n];
memo = new long[2][n];
for (int i = 0; i < n; i++)
Arr[i] = str.charAt(i) - '0';
Arrays.fill(memo[0], -1);
Arrays.fill(memo[1], -1);
pw.println(dp(0, 0));
}
pw.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
| Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | e103fba38e5006857be1b25d75c090c8 | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes | import java.io.*;
import java.util.*;
public class c_gasPipline {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int T = Integer.parseInt(br.readLine()); // query
int n = 9;
int a = 9;
int b = 9;
long[][] dp = new long[n+1][2];
for(int t=0; t<T; t++){
String s = br.readLine();
StringTokenizer st = new StringTokenizer(s, " ");
n = Integer.parseInt(st.nextToken());
a = Integer.parseInt(st.nextToken());
b = Integer.parseInt(st.nextToken());
char[] graph = br.readLine().toCharArray();
dp = new long[n+1][2];
if(n<2||n>2*Math.pow(10,5)||a<1||a>Math.pow(10, 8)||b<1||b>Math.pow(a, 8)) {
//System.out.println("out");
bw.write("out\n");
bw.flush();
}
for(int i= 0; i<n+1; i++) {
Arrays.fill(dp[i], (long)Math.pow(10, 14));
}
dp[0][0]=b;
for (int i = 0; i < n; i++) {
if (graph[i] == '0') {
dp[i + 1][0] = dp[i][0] + a + b;
// System.out.println("비교: " + (dp[i][0]+a+b) + " / " + (dp[i][1]+(2*a)+b));
dp[i + 1][0] = Math.min(dp[i + 1][0], dp[i][1] + 2 * a + b);
// System.out.println("0/ dp[" + (i+1) + " ][0] : " + dp[i+1][0]);
dp[i + 1][1] = dp[i][1] + a + 2 * b;
// System.out.println("비교 : " + (dp[i][1]+a+2*b) + " / " + (dp[i][0]+(2*a)+(2*b)));
dp[i + 1][1] = Math.min(dp[i + 1][1], dp[i][0] + 2 * a + 2 * b);
// System.out.println("0/ dp[" + (i+1) +"][1] : " + dp[i+1][1]);
} else {
dp[i + 1][1] = Math.min(dp[i + 1][1], dp[i][1] + a + 2 * b);
// System.out.println("1/ dp[" + (i+1) +"][1] : " + dp[i+1][1]);
}
}
// System.out.println(dp[n][0]);
bw.write(dp[n][0]+"\n");
bw.flush();
}
bw.close();
}
} | Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | 5672bc91305f8ddd58ab75586f8ac009 | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static int inf = (int) 1e9 + 7;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(System.out);
int t = nextInt();
while(t-- > 0) {
int n = nextInt();
long a = nextLong();
long b = nextInt();
long ans = a * n + b * (n + 1);
char h[] = next().toCharArray();
ArrayList<Integer> cnt = new ArrayList<>();
int cnt_ = 1;
for(int i = 1;i < n;i++) {
if (h[i] != h[i - 1]) {
cnt.add(cnt_);
cnt_ = 1;
}else cnt_++;
}
cnt.add(cnt_);
int now = 1;
int me = 0;
cnt.remove(0);
for(int u = 0;u < cnt.size();u++) {
int i = cnt.get(u);
if (u == cnt.size() - 1) {
ans += a;
}else {
if (now == 1) {
if (me == 0) ans += b * (i + 1) + a;
else ans += b * (i + 1);
me = 1;
} else {
if (b * (i - 1) > 2 * a) {
me = 0;
ans += a;
}else ans += b * (i - 1);
}
now = 1 - now;
}
}
pw.println(ans);
}
pw.close();
}
static BufferedReader br;
static StringTokenizer st = new StringTokenizer("");
static PrintWriter pw;
static String next() throws IOException {
while (!st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
} | Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | 61f94eb6bd74c043f2489e9aa340a995 | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.StringTokenizer;
public class code {
static char[] a;
static int n;
static int m;
static int k;
static long memo[][];
public static long dp(int idx, int s) {
if (idx == n - 1) {
if (s == 1) {
return memo[s][idx] = 2 * m + 3 * k;
} else
return memo[s][idx] = m + 2 * k;
}
if (memo[s][idx] != -1)
return memo[s][idx];
if (a[idx] == '1') {
if (s == 0)
return memo[s][idx] = 2 * m + 2 * k + dp(idx + 1, 1);
else
return memo[s][idx] = m + 2 * k + dp(idx + 1, 1);
} else {
if (s == 0)
return memo[s][idx] = Math.min(m + k + dp(idx + 1, 0), 2 * m + k + dp(idx + 1, 1));
else
return memo[s][idx] = Math.min(m + 2 * k + dp(idx + 1, 1), 2 * m + 2 * k + dp(idx + 1, 0));
}
}
public static void main(String[] args) throws IOException, InterruptedException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
int t = Integer.parseInt(br.readLine());
for (int i = 0; i < t; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
k = Integer.parseInt(st.nextToken());
a = br.readLine().toCharArray();
memo = new long[2][n];
for (int j = 0; j < 2; j++) {
Arrays.fill(memo[j], -1);
}
pw.println(dp(0, 0));
}
pw.flush();
}
}
| Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | 4045042752250b2422232025980dcb4a | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes | import java.util.*;
public class CF_1207_C {
public static int solve(String s, int i, int a, int b,int c) {
if(i==s.length())
return 0;
if(s.charAt(i)=='1'&&s.charAt(i+1)=='0') {
int aa=0;
}
return 0;
}
public static long solve(String s, long a, long b) {
long sum=b;
int i;
for(i=0;i<s.length();++i) {
if(s.charAt(i)=='1') {
sum+=2*b+a;
i++;
break;
} else if(i+1<s.length()&&s.charAt(i+1)=='1') {
sum+=2*b+2*a;
} else {
sum+=a+b;
}
}
while(i<s.length()) {
if(s.charAt(i)=='0'&&s.charAt(i-1)=='1') {
int k=i;
while(k<s.length()&&s.charAt(k)=='0')
k++;
if(k!=s.length()&&k-1==i)
sum+=2*b+a;
else if(k-1==i) {
sum+=2*a+b;
}
else if(k!=s.length()){
sum+=Math.min((k-i-1)*b+2*a+(k-i)*a,(k-i-1)*2*b+a*(k-i))+2*b;
} else {
sum+=(k-i)*b+a*(k-i+1);
}
i=k;
} else if(s.charAt(i)=='1'){
sum+=2*b+a;
i++;
}
}
return sum;
}
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0) {
int n=sc.nextInt();
int a=sc.nextInt();
int b=sc.nextInt();
String s=sc.next();
System.out.println(solve(s,a,b));
}
}
} | Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | 79896914d915669034a11d725bda4e53 | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes | import java.io.*;
import java.util.*;
public class EDU71C {
public static void main(String[] args) {
JS scan = new JS();
int t = scan.nextInt();
while(t-->0) {
int n = scan.nextInt();
long a = scan.nextLong();
long b = scan.nextLong();
String s = scan.next();
int[] next1 = new int[n];
Arrays.fill(next1, -1);
int at = -1;
for(int i = n-1;i>=0;i--) {
next1[i] = at;
if(s.charAt(i)=='1')at = i;
}
boolean down = true;
long bes = 1;
long as = 0;
for(int i = 0;i<n;i++) {
if(s.charAt(i)=='1') {
//how far till the next one
if(down) {
as++;
down = false;
}
int dist = next1[i]-i;
as++;
bes+=2;
if(dist<=0) {
down = true;
as++;
bes++;
continue;
}
// //if we're down then we have to go spend some to go up regardless
long pillars = dist-2;
if(dist<=2) {
continue;
}
int gap = dist-1;
if(2*a<pillars*b) {
//drop
down = true;
as++;
bes++;
}
}else {
if(down) {
as++;
bes++;
}else {
as++;
bes+=2;
}
}
}
System.out.println((bes*b+as*a));
}
}
static class JS{
public int BS = 1<<16;
public char NC = (char)0;
byte[] buf = new byte[BS];
int bId = 0, size = 0;
char c = NC;
double num = 1;
BufferedInputStream in;
public JS() {
in = new BufferedInputStream(System.in, BS);
}
public JS(String s) throws FileNotFoundException {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
public char nextChar(){
while(bId==size) {
try {
size = in.read(buf);
}catch(Exception e) {
return NC;
}
if(size==-1)return NC;
bId=0;
}
return (char)buf[bId++];
}
public int nextInt() {
return (int)nextLong();
}
public long nextLong() {
num=1;
boolean neg = false;
if(c==NC)c=nextChar();
for(;(c<'0' || c>'9'); c = nextChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=nextChar()) {
res = (res<<3)+(res<<1)+c-'0';
num*=10;
}
return neg?-res:res;
}
public double nextDouble() {
double cur = nextLong();
return c!='.' ? cur:cur+nextLong()/num;
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c>32) {
res.append(c);
c=nextChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c!='\n') {
res.append(c);
c=nextChar();
}
return res.toString();
}
public boolean hasNext() {
if(c>32)return true;
while(true) {
c=nextChar();
if(c==NC)return false;
else if(c>32)return true;
}
}
}
}
| Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | 2bccb400f6e7ead61cad3e1bddd9bdf9 | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes | import java.util.*;
public class Boss {
static int c=0;
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
int n=sc.nextInt();
long a=sc.nextInt();
long b=sc.nextInt();
sc.nextLine();
String s=sc.nextLine();
/*
* int p=0; int o=0; int curr=0; int one=0; for(int i=0;i<n;i++) {
* if(s.charAt(i)=='1') { one++; if(curr!=1) { o++; } curr=1; } else
* if(s.charAt(i)=='0') { if(curr!=0) o++; curr=0; } } if(o==0) p=n+1; else
* p=(one+o/2)*2+(n+1-o/2-one); char c='0'; int pp=n; for(int i=0;i<n;i++) {
* if(c!=s.charAt(i)) { pp++; c=s.charAt(i); } } if(one>0)
* System.out.println(Math.min(p*b+a*pp,(n+1)*);
*/
ArrayList<Integer> st=new ArrayList<Integer>();
ArrayList<Integer> e=new ArrayList<Integer>();
int curr=0;
for(int i=0;i<n;i++)
{
if(s.charAt(i)=='1')
{
if(curr!=1)
st.add(i);
curr=1;
}
else
{
if(curr!=0)
e.add(i);
curr=0;
}
}
/*if(st.size()>e.size())
e.add(n-1);*/
//System.out.println(st);
//System.out.println(e);
if(st.size()==0)
{
System.out.println(n*a+(n+1)*b);
}
else
{
long p=0;
for(int i=0;i<st.size();i++)
{
p=p+(e.get(i)-st.get(i)+1)*2*b;
}
p=p+st.get(0)*b+n*a+a+(n-e.get(e.size()-1))*b+a;
for(int i=1;i<st.size();i++)
{
long p1=(st.get(i)-e.get(i-1)-1)*b*2;
long p2=(st.get(i)-e.get(i-1)-1)*b+2*a;
p=p+Math.min(p1, p2);
}
System.out.println(p);
}
}
}
}
| Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | b4b450e3162921f3e5e7bb4e32b61064 | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes |
import java.util.*;
import java.lang.*;
import java.math.*;
public class tc_2_3 {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int t=scn.nextInt();
while(t-- !=0) {
int n=scn.nextInt();
int a=scn.nextInt();
int b=scn.nextInt();
scn.nextLine();
String str=scn.nextLine();
long dp[][]=new long[n+1][2];
for(long[]arr:dp) {
Arrays.fill(arr,(long)1e18);
}
dp[0][0]=b;
for(int i=0;i<str.length();i++) {
// System.out.println(dp[i][0]+" "+dp[i][1]);
if(str.charAt(i)=='0') {
dp[i+1][0]=Math.min(dp[i+1][0],dp[i][0]+a+b);
dp[i+1][1]=Math.min(dp[i+1][1],dp[i][0]+2*(a+b));
dp[i+1][1]=Math.min(dp[i+1][1],dp[i][1]+a+(2*b));
dp[i+1][0]=Math.min(dp[i+1][0], dp[i][1]+(2*a)+b);
}else {
dp[i+1][1]=dp[i][1]+a+(2*b);
}
}
System.out.println(dp[n][0]);
}
}
} | Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | 146d35426791aefc86c97776ade7e253 | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class CF1207C_GasPipeline {
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() {
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 max(int a, int b) {
return Math.max(a, b);
}
static long min(long a, long b) {
return Math.min(a, b);
}
static void print(Object b) {
System.out.print(b);
}
static void println(Object b) {
System.out.println(b);
}
static void println() {
System.out.println();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner();
int te = scanner.nextInt();
for (int t = 0; t < te; t++) {
int n = scanner.nextInt(), a = scanner.nextInt(), b = scanner.nextInt();
String s = scanner.next();
long[][] dp = new long[n + 1][2];
for (int i = 0; i <= n; i++) {
dp[i][0] = 100000000000000L;
dp[i][1] = 100000000000000L;
}
dp[0][0] = b;
for (int i = 1; i <= n; i++) {
if (s.charAt(i - 1) == '0') {
dp[i][0] = min(dp[i][0], min(dp[i - 1][0] + a + b, dp[i - 1][1] + 2 * a + b));
dp[i][1] = min(dp[i][1], min(dp[i - 1][0] + 2 * a + 2 * b, dp[i - 1][1] + 2 * b + a));
} else {
dp[i][1] = min(dp[i][1], dp[i - 1][1] + a + 2 * b);
}
}
println(dp[n][0]);
}
}
} | Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | fcb784050a46d0afc9bfdf7bb2e66e5a | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes |
import java.util.*;
import java.io.*;
public class Main {
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[1000001]; // 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 print(int[] arr){
for(int i = 0 ;i<arr.length;i++){
System.out.print((arr[i])+" ");
}
System.out.println("");
}
public static void printlist(ArrayList<Integer> arr){
for(int i = 0 ;i<arr.size();i++){
System.out.print((arr.get(i)+1)+" ");
}
System.out.println("");
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int tc = sc.nextInt();
for(int g = 0;g<tc;g++){
int n = sc.nextInt();
long pipe_cost = sc.nextLong();
long piller = sc.nextLong();
String s = sc.nextLine();
s = sc.nextLine();
s = s.trim();
int start = -1;
int end = -1;
int len = 0;
long cost = pipe_cost * n;
for(int i = 0;i<n;i++){
if(s.charAt(i)=='1'){
if(start==-1){
start = i;
}
end = i;
len++;
}else{
if(len!=0){
cost+= (len+1)*2*piller;
}
len = 0;
}
}
// System.out.println("cost : "+cost);
if(start==-1){
cost += (n+1)*piller;
}else{
cost += (start + n-1-end)*piller;
cost += 2*pipe_cost;
// System.out.println("cost : "+cost);
len = 0;
int curr = start;
for(int i = start;i<=end;i++){
if(s.charAt(i)=='1'){
if(len>1){
cost += Math.min(2*(len-1)*piller,(len-1)*piller + 2*pipe_cost);
}
len = 0;
}else{
len++;
}
}
}
System.out.println(cost);
}
}
} | Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | 5c59590727879031cf2a8361f9c2ab64 | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes | import java.io.*;
import java.util.*;
import java.util.stream.IntStream;
public class Laba {
FScanner fs;
PrintWriter pw;
int n;
boolean[] used;
int[][] g;
int[][] dst;
public static void main(String[] args) throws IOException {
new Laba().start();
}
public void start() throws IOException {
fs = new FScanner(new InputStreamReader(System.in));
// reader = new FScanner(new FileReader("input"));
//pw = new PrintWriter("input.txt");
pw = new PrintWriter(System.out);
int q = fs.nextInt();
sqr: for (int i = 0; i < q; i++) {
int n = fs.nextInt(), a = fs.nextInt(), b = fs.nextInt();
char[] s = fs.nextLine().toCharArray();
int prev = 0;
int next = -1;
long total = b;
while (prev < s.length && s[prev] != '1') {
total += a + b;
prev++;
}
if (prev == s.length) {
pw.println(total);
} else {
total += a + b;
while (prev < s.length) {
if (s[prev] == '1') {
total += a + b * 2;
} else {
next = prev;
while (next < s.length && s[next] == '0')
next++;
if (next == s.length) {
total += (next - prev - 1 + 0l) * (a + b) + 2 * a + b;
pw.println(total);
continue sqr;
}
if (next == prev + 1) {
total += a + b * 2;
} else {
long a1 = (next - prev +0l) * (a+b*2);
long a2 = (next - prev - 2 + 0l) * (a + b) + 4 * a + 3 * b;
total += Math.min(a1, a2);
prev = next - 1;
}
}
prev++;
}
pw.println(total);
}
}
pw.close();
}
}
class FScanner {
StringTokenizer st;
BufferedReader reader;
FScanner(InputStreamReader isr) throws IOException {
reader = new BufferedReader(isr);
}
String nextLine() throws IOException {
return reader.readLine();
}
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String s = reader.readLine();
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
char nextChar() throws IOException {
return (char) reader.read();
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
int[] iarr(int n) throws IOException {
int[] mas = new int[n];
for (int i = 0; i < n; i++)
mas[i] = nextInt();
return mas;
}
double[] darr(int n) throws IOException {
double[] mas = new double[n];
for (int i = 0; i < n; i++)
mas[i] = nextDouble();
return mas;
}
char[][] cmas2(int n, int m) throws IOException {
char[][] mas = new char[n][m];
for (int i = 0; i < n; i++)
mas[i] = nextLine().toCharArray();
return mas;
}
long[] larr(int n) throws IOException {
long[] mas = new long[n];
for (int i = 0; i < n; i++)
mas[i] = nextLong();
return mas;
}
} | Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | b5b0dc1053b2d05af962b7ffa89e70a3 | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes | import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class pipeline{
public static void main(String[] args) throws IOException
{
new pipeline().run();
}
long max = Long.MAX_VALUE/2;
public void run() throws IOException
{
Scanner file = new Scanner(System.in);
int T = file.nextInt();
for(int zz = 0;zz<T;zz++)
{
int N = file.nextInt();
long pipe = file.nextLong();
long pillar = file.nextLong();
char[] str = (file.next()+"0").toCharArray();
long[][] dp = new long[N+1][2];
dp[0][0] = pillar;
dp[0][1] = max;
for(int i = 1;i<dp.length;i++)
{
dp[i][0] = pillar + Math.min(dp[i-1][0]+pipe,dp[i-1][1]+pipe*2);
dp[i][1] = pillar*2 + Math.min(dp[i-1][0]+pipe*2,dp[i-1][1]+pipe);
if(Math.max(str[i-1],str[i]) == '1')
dp[i][0] = max;
}
System.out.println(dp[N][0]);
}
}
} | Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | 9d4c8fc0a207875fe3a85f74d119fd0f | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes | import java.io.*;
import java.util.*;
public class A {
static BufferedReader br;
static StringTokenizer st;
static PrintWriter pw;
static String nextToken() {
try {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
static int nextInt() {
return Integer.parseInt(nextToken());
}
static long nextLong() {
return Long.parseLong(nextToken());
}
static double nextDouble() {
return Double.parseDouble(nextToken());
}
static char nextChar() throws IOException {
return (char) br.read();
}
static String next() throws IOException {
return nextToken();
}
static String nextLine() throws IOException {
return br.readLine();
}
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(System.out);
run();
pw.close();
}
private static void run() throws IOException {
int t = nextInt();
while (t-- > 0) {
long n = nextInt();
long a = nextInt();
long b = nextInt();
String s = next();
int prev = -1;
long ans = 0;
int i = 0;
for (; i < n; i++) {
if (s.charAt(i) == '1') {
break;
}
}
if (i == n) {
ans = (n + 1) * b + n * a;
} else {
ans = (i + 2) * a + (i + 4) * b;
prev = i;
for (int j = prev + 1; j < n; j++) {
if (s.charAt(j) == '1') {
if (j == prev + 1) {
ans += a + 2 * b;
}
if (j == prev + 2) {
ans += 4 * b + 2 * a;
}
if (j > prev + 2) {
ans += a + 4 * b;
int d = j - prev - 1;
long f1 = (d - 1) * 2 * b + d * a;
long f2 = (d + 2) * a + (d - 1) * b;
ans += Math.min(f1, f2);
}
prev = j;
}
}
long d = n - prev - 1;
ans += (d + 1) * a + d * b;
}
pw.println(ans + "");
}
}
static class Pair implements Comparable<Pair> {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair o) {
if (x == o.x)
return y - o.y;
return x - o.x;
}
}
}
| Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | edeee506c2649142871661a9d0711199 | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static int MOD=1000000000+7;
//Radix Sort
public static int[] radixSort(int[] f){ return radixSort(f, f.length); }
public static int[] radixSort(int[] f, int n)
{
int[] to = new int[n];
{
int[] b = new int[65537];
for(int i = 0;i < n;i++)b[1+(f[i]&0xffff)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < n;i++)to[b[f[i]&0xffff]++] = f[i];
int[] d = f; f = to;to = d;
}
{
int[] b = new int[65537];
for(int i = 0;i < n;i++)b[1+(f[i]>>>16)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < n;i++)to[b[f[i]>>>16]++] = f[i];
int[] d = f; f = to;to = d;
}
return f;
}
//Brian Kernighan’s Algorithm
static long countSetBits(long n){
if(n==0) return 0;
return 1+countSetBits(n&(n-1));
}
//Factorial
static long factorial(long n){
if(n==1) return 1;
if(n==2) return 2;
if(n==3) return 6;
return n*factorial(n-1);
}
//Euclidean Algorithm
static long gcd(long A,long B){
if(B==0) return A;
return gcd(B,A%B);
}
//Modular Exponentiation
static long fastExpo(long x,long n){
if(n==0) return 1;
if((n&1)==0) return fastExpo((x*x)%MOD,n/2)%MOD;
return ((x%MOD)*fastExpo((x*x)%MOD,(n-1)/2))%MOD;
}
//AKS Algorithm
static boolean isPrime(long n){
if(n<=1) return false;
if(n<=3) return true;
if(n%2==0 || n%3==0) return false;
for(int i=5;i*i<=n;i+=6)
if(n%i==0 || n%(i+2)==0) return false;
return true;
}
//Sieve of eratosthenes
static int[] findPrimes(int n){
boolean isPrime[]=new boolean[n+1];
ArrayList<Integer> a=new ArrayList<>();
int result[];
Arrays.fill(isPrime,true);
isPrime[0]=false;
isPrime[1]=false;
for(int i=2;i*i<=n;++i){
if(isPrime[i]==true){
for(int j=i*i;j<=n;j+=i) isPrime[j]=false;
}
}
for(int i=0;i<=n;i++) if(isPrime[i]==true) a.add(i);
result=new int[a.size()];
for(int i=0;i<a.size();i++) result[i]=a.get(i);
return result;
}
//Euler Totent function
static long countCoprimes(long n){
ArrayList<Long> prime_factors=new ArrayList<>();
long x=n,flag=0;
while(x%2==0){
if(flag==0) prime_factors.add(2L);
flag=1;
x/=2;
}
for(long i=3;i*i<=x;i+=2){
flag=0;
while(x%i==0){
if(flag==0) prime_factors.add(i);
flag=1;
x/=i;
}
}
if(x>2) prime_factors.add(x);
double ans=(double)n;
for(Long p:prime_factors){
ans*=(1.0-(Double)1.0/p);
}
return (long)ans;
}
//Lower Bound
static int lowerBound(int[] a, int low, int high, int element){
while(low < high){
int middle = low + (high - low)/2;
if(element > a[middle])
low = middle + 1;
else
high = middle;
}
return low;
}
//Upper Bound
static int upperBound(int[] a, int low, int high, int element){
while(low < high){
int middle = low + (high - low)/2;
if(a[middle] > element)
high = middle;
else
low = middle + 1;
}
return low;
}
static long dp[][]=new long[200005][2];
static long inf=1L<<60;
public static void main (String[] args) throws java.lang.Exception
{
FastReader sc=new FastReader();
int t=sc.nextInt();
while(t-->0){
int n=sc.nextInt(),a=sc.nextInt(),b=sc.nextInt();
String s=sc.nextLine();
dp[0][0]=b;
dp[0][1]=inf;
for(int i=1;i<=n;i++){
if(s.charAt(i-1)=='1'){
dp[i][1]=dp[i-1][1]+a+2*b;
dp[i][0]=inf;
}
else{
dp[i][0]=Math.min(dp[i-1][0]+a+b,dp[i-1][1]+2*a+b);
dp[i][1]=Math.min(dp[i-1][0]+2*a+2*b,dp[i-1][1]+a+2*b);
}
}
System.out.println(dp[n][0]);
}
}
} | Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | daff6f4bf6476b3be37e04517dd9eb58 | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Main
{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
static int MOD=1000000000+7;
//Radix Sort
public static int[] radixSort(int[] f){ return radixSort(f, f.length); }
public static int[] radixSort(int[] f, int n)
{
int[] to = new int[n];
{
int[] b = new int[65537];
for(int i = 0;i < n;i++)b[1+(f[i]&0xffff)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < n;i++)to[b[f[i]&0xffff]++] = f[i];
int[] d = f; f = to;to = d;
}
{
int[] b = new int[65537];
for(int i = 0;i < n;i++)b[1+(f[i]>>>16)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < n;i++)to[b[f[i]>>>16]++] = f[i];
int[] d = f; f = to;to = d;
}
return f;
}
//Brian Kernighan’s Algorithm
static long countSetBits(long n){
if(n==0) return 0;
return 1+countSetBits(n&(n-1));
}
//Factorial
static long factorial(long n){
if(n==1) return 1;
if(n==2) return 2;
if(n==3) return 6;
return n*factorial(n-1);
}
//Euclidean Algorithm
static long gcd(long A,long B){
if(B==0) return A;
return gcd(B,A%B);
}
//Modular Exponentiation
static long fastExpo(long x,long n){
if(n==0) return 1;
if((n&1)==0) return fastExpo((x*x)%MOD,n/2)%MOD;
return ((x%MOD)*fastExpo((x*x)%MOD,(n-1)/2))%MOD;
}
//AKS Algorithm
static boolean isPrime(long n){
if(n<=1) return false;
if(n<=3) return true;
if(n%2==0 || n%3==0) return false;
for(int i=5;i*i<=n;i+=6)
if(n%i==0 || n%(i+2)==0) return false;
return true;
}
//Sieve of eratosthenes
static int[] findPrimes(int n){
boolean isPrime[]=new boolean[n+1];
ArrayList<Integer> a=new ArrayList<>();
int result[];
Arrays.fill(isPrime,true);
isPrime[0]=false;
isPrime[1]=false;
for(int i=2;i*i<=n;++i){
if(isPrime[i]==true){
for(int j=i*i;j<=n;j+=i) isPrime[j]=false;
}
}
for(int i=0;i<=n;i++) if(isPrime[i]==true) a.add(i);
result=new int[a.size()];
for(int i=0;i<a.size();i++) result[i]=a.get(i);
return result;
}
//Euler Totent function
static long countCoprimes(long n){
ArrayList<Long> prime_factors=new ArrayList<>();
long x=n,flag=0;
while(x%2==0){
if(flag==0) prime_factors.add(2L);
flag=1;
x/=2;
}
for(long i=3;i*i<=x;i+=2){
flag=0;
while(x%i==0){
if(flag==0) prime_factors.add(i);
flag=1;
x/=i;
}
}
if(x>2) prime_factors.add(x);
double ans=(double)n;
for(Long p:prime_factors){
ans*=(1.0-(Double)1.0/p);
}
return (long)ans;
}
//Lower Bound
static int lowerBound(int[] a, int low, int high, int element){
while(low < high){
int middle = low + (high - low)/2;
if(element > a[middle])
low = middle + 1;
else
high = middle;
}
return low;
}
//Upper Bound
static int upperBound(int[] a, int low, int high, int element){
while(low < high){
int middle = low + (high - low)/2;
if(a[middle] > element)
high = middle;
else
low = middle + 1;
}
return low;
}
static long dp[][]=new long[299999][2];
static long inf=1L<<60;
public static void main (String[] args) throws java.lang.Exception
{
FastReader sc=new FastReader();
int t=sc.nextInt();
while(t-->0){
int n=sc.nextInt(),a=sc.nextInt(),b=sc.nextInt();
String s=sc.nextLine();
dp[0][0]=b;
dp[0][1]=inf;
for(int i=1;i<=n;i++){
if(s.charAt(i-1)=='1'){
dp[i][1]=dp[i-1][1]+a+2*b;
dp[i][0]=inf;
}
else{
dp[i][0]=Math.min(dp[i-1][0]+a+b,dp[i-1][1]+2*a+b);
dp[i][1]=Math.min(dp[i-1][0]+2*a+2*b,dp[i-1][1]+a+2*b);
}
}
System.out.println(dp[n][0]);
}
}
} | Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | 0e623433a1bdaf7e41c57ce2c23d7a98 | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 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 abc
{
public static void main(String[] args)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int t=Integer.parseInt(br.readLine());
while(t-->0)
{
StringTokenizer tk=new StringTokenizer(br.readLine());
long n=Long.parseLong(tk.nextToken());
long a=Long.parseLong(tk.nextToken());
long b=Long.parseLong(tk.nextToken());
String s=br.readLine();int size=0;char ch;int i;
s=" "+s;
int len=s.length();long sum=0;int flag=0;
int f=s.indexOf("1");int g=0;int dif;
if(f==-1)
{
//System.out.print(a+" "+b+" "+len+" ");
System.out.println((len-1)*a+(len)*b);
}
else
{
sum=sum+(((f)*a)+(f+1)*b);
// System.out.print(" "+sum);
while(true)
{
g=s.indexOf('1',f+1);
// System.out.println(f+" "+g);
if(g==-1)
{
flag=1;break;
}
dif=g-f;
if(dif<3)
{
sum=sum+(dif*a)+(dif*b)*2;
// System.out.print(" "+sum);
}
else if(dif>=3)
{
if((dif-2)*b>=(2*a))
{
sum=sum+4*b+a+(4+(dif-3))*a+(dif-2)*b;
// System.out.print(" "+sum);
}
else
{
sum=sum+dif*a+dif*b*2;
// System.out.print(" "+sum);
}
}
f=g;
}
sum=sum+2*b+2*a+((int)n-f)*(a+b);
System.out.println(sum);
}
}
}
}
| Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | 40e9dcff24f092be271c2e89d0e7d055 | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Washoum
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
inputClass in = new inputClass(inputStream);
PrintWriter out = new PrintWriter(outputStream);
CGasPipeline solver = new CGasPipeline();
solver.solve(1, in, out);
out.close();
}
static class CGasPipeline {
public void solve(int testNumber, inputClass sc, PrintWriter out) {
int t = sc.nextInt();
while (t > 0) {
t--;
int n = sc.nextInt();
long a = sc.nextInt();
long b = sc.nextLong();
String s = sc.nextLine();
StringBuilder m = new StringBuilder();
m.append(0);
for (int i = 1; i < n; i++) {
if (s.charAt(i) == '1') {
m.append(1);
} else {
if (s.charAt(i - 1) == '1') {
m.append(1);
} else {
m.append(0);
}
}
}
m.append(0);
long[][] dp = new long[n + 1][2];
for (int i = 0; i < n; i++) {
dp[i][0] = (long) 1e18;
dp[i][1] = (long) 1e18;
}
dp[0][0] = b;
for (int i = 1; i <= n; i++) {
if (m.charAt(i) == '1') {
if (m.charAt(i - 1) == '1') {
dp[i][1] = dp[i - 1][1] + a + 2 * b;
} else {
dp[i][1] = Math.min(dp[i - 1][0] + 2 * a, dp[i - 1][1] + a) + 2 * b;
}
} else {
if (m.charAt(i - 1) == '0') {
dp[i][0] = Math.min(dp[i - 1][0] + a + b, dp[i - 1][1] + 2 * a + b);
dp[i][1] = Math.min(dp[i - 1][0] + 2 * a + 2 * b, dp[i - 1][1] + a + 2 * b);
} else {
dp[i][0] = dp[i - 1][1] + 2 * a + b;
dp[i][1] = dp[i - 1][1] + a + 2 * b;
}
}
}
out.println(dp[n][0]);
}
}
}
static class inputClass {
BufferedReader br;
StringTokenizer st;
public inputClass(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
public String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | b91afa1d447df437485758c2a5eb0560 | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Washoum
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
inputClass in = new inputClass(inputStream);
PrintWriter out = new PrintWriter(outputStream);
CGasPipeline solver = new CGasPipeline();
solver.solve(1, in, out);
out.close();
}
static class CGasPipeline {
public void solve(int testNumber, inputClass sc, PrintWriter out) {
int t = sc.nextInt();
while (t > 0) {
t--;
int n = sc.nextInt();
long a = sc.nextInt();
long b = sc.nextLong();
String s = sc.nextLine();
StringBuilder m = new StringBuilder();
m.append(0);
for (int i = 1; i < n; i++) {
if (s.charAt(i) == '1') {
m.append(1);
} else {
if (s.charAt(i - 1) == '1') {
m.append(1);
} else {
m.append(0);
}
}
}
m.append(0);
long[][] dp = new long[n + 1][2];
for (int i = 0; i < n; i++) {
dp[i][0] = (long) 1e18;
dp[i][1] = (long) 1e18;
}
dp[0][0] = b;
for (int i = 1; i <= n; i++) {
if (m.charAt(i) == '1') {
if (m.charAt(i - 1) == '1') {
dp[i][1] = dp[i - 1][1] + a + 2 * b;
} else {
dp[i][1] = Math.min(dp[i - 1][0] + 2 * a, dp[i - 1][1] + a) + 2 * b;
}
} else {
if (m.charAt(i - 1) == '0') {
dp[i][0] = Math.min(dp[i - 1][0] + a + b, dp[i - 1][1] + 2 * a + b);
dp[i][1] = Math.min(dp[i - 1][0] + 2 * a + 2 * b, dp[i - 1][1] + a + 2 * b);
} else {
dp[i][0] = dp[i - 1][1] + 2 * a + b;
dp[i][1] = dp[i - 1][1] + a + 2 * b;
}
}
}
// for (int i=0;i<n-1;i++){
// if (s.charAt(i)==0){
// if (s.charAt(i+1)=='1'){
// dp[i+1][1]=dp[i][0]+2*a+2*b;
// }
// else{
// dp[i+1][1]=Math.min(dp[i][0] + 2*a+ 2*b, dp[i][1]+a+b);
// dp[i+1][0]=Math.min(dp[i][0]+a+b,dp[i][1]+2*a+2*b);
// }
// }
// else{
// if (s.charAt(i+1)==)
// }
// }
out.println(dp[n][0]);
}
}
}
static class inputClass {
BufferedReader br;
StringTokenizer st;
public inputClass(InputStream in) {
br = new BufferedReader(new InputStreamReader(in));
}
public String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | 6180bc917b90ad084e69f851111e850f | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
while (t-- > 0) {
int n = scanner.nextInt();
int a = scanner.nextInt();
int b = scanner.nextInt();
char[] ch = scanner.next().toCharArray();
long[][] dp = new long[n + 1][2];
for (int i = 0; i < n + 1; i++) {
Arrays.fill(dp[i], (long) Math.pow(10, 14));
}
dp[0][0] = b;
for (int i = 0; i < n; i++) {
if (ch[i] == '0') {
dp[i + 1][0] = dp[i][0] + a + b;
dp[i + 1][0] = Math.min(dp[i + 1][0], dp[i][1] + 2 * a + b);
dp[i + 1][1] = dp[i][1] + a + 2 * b;
dp[i + 1][1] = Math.min(dp[i + 1][1], dp[i][0] + 2 * a + 2 * b);
} else {
dp[i + 1][1] = Math.min(dp[i + 1][1], dp[i][1] + a + 2 * b);
}
}
System.out.println(dp[n][0]);
}
}
/*
1
10 2 5
0000 0010 10
*/
} | Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | ea84d6e1488f31f13d0151e5f9784f89 | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
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);
CGasPipeline solver = new CGasPipeline();
solver.solve(1, in, out);
out.close();
}
static class CGasPipeline {
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int t = in.scanInt();
while (t-- > 0) {
int n = in.scanInt();
long a = in.scanLong();
long b = in.scanLong();
char arr[] = new char[n];
arr = in.scanString().toCharArray();
long dp[][] = new long[n + 5][4];
for (long ar[] : dp) Arrays.fill(ar, Long.MAX_VALUE / 2);
dp[0][0] = a + b;
dp[0][2] = b + a + a;
for (int i = 1; i < n; i++) {
if (arr[i] == '1') {
dp[i][1] = Math.min(dp[i][1], dp[i - 1][1] + b + b + a);
if (arr[i - 1] == '0') dp[i][1] = Math.min(dp[i][1], dp[i - 1][2] + b + b + a);
} else {
dp[i][1] = Math.min(dp[i][1], dp[i - 1][1] + b + b + a);
if (arr[i - 1] == '0') dp[i][1] = Math.min(dp[i][1], dp[i - 1][2] + b + b + a);
if (arr[i - 1] == '0') dp[i][0] = Math.min(dp[i][0], dp[i - 1][0] + a + b);
if (arr[i - 1] == '0') dp[i][0] = Math.min(dp[i][0], dp[i - 1][3] + a + b);
if (arr[i - 1] == '0') dp[i][2] = Math.min(dp[i][2], dp[i - 1][0] + a + a + b);
if (arr[i - 1] == '0') dp[i][2] = Math.min(dp[i][2], dp[i - 1][3] + a + a + b);
dp[i][3] = Math.min(dp[i][3], dp[i - 1][1] + a + b + b + a);
if (arr[i - 1] == '0') dp[i][3] = Math.min(dp[i][3], dp[i - 1][2] + a + b + b + a);
}
}
long ans = dp[n - 1][0] + b;
ans = Math.min(ans, dp[n - 1][3] + b);
out.println(ans);
}
}
}
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;
}
public String scanString() {
int c = scan();
while (isWhiteSpace(c)) c = scan();
StringBuilder RESULT = new StringBuilder();
do {
RESULT.appendCodePoint(c);
c = scan();
} while (!isWhiteSpace(c));
return RESULT.toString();
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
public long scanLong() {
long I = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
I *= 10;
I += n - '0';
n = scan();
}
}
return neg * I;
}
}
}
| Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | ac8211013e1fea0324fc538f88b303c8 | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes | import javafx.util.Pair;
import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException{
Locale.setDefault(Locale.US);
//----------------CODE HERE-------------------
int t;
t = sc.nextInt();
while (t-- > 0) {
int n;
long a,b;
n = sc.nextInt();
a = sc.nextInt();
b = sc.nextInt();
char[] s;
s = sc.next().toCharArray();
int prev = 0;
long res = a+b+b;
long[] dp = new long[n];
for (int i = 1; i < n-1; i++) {
if (s[i] == '1') {
if (prev != 0) {
if (((long)i - (long)prev - (long)1)*b*(long)2 < ((long)i - (long)prev - (long)1)*b + 2*a) {
for (int j = prev; j < i; j++) {
s[j] = '1';
}
}
}
}
if (s[i] == '0' && s[i-1] == '1') {
prev = i;
}
}
prev = 0;
for (int i = 1; i < n-1; i++) {
if (s[i] == '1') {
if (prev == 0) {
prev = 1;
res+=a;
}
res+=b;
}
else {
if (prev == 1) {
prev = 0;
res+=a;
res+=b;
}
}
res+=a;
res+=b;
}
if (prev == 1) {
res+=a;
res+=b;
}
res+=a;
res+=b;
out.println(res);
}
//----------------CODE HERE--------------------
out.flush();
}
//-----------PrintWriter for faster output---------------------------------
public static MyScanner sc = new MyScanner();
public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
//-----------MyScanner class for faster input----------
public static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//--------------------------------------------------------
}
| Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | 34f543ee5b360e1e1dadeca63463618f | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0) {
int n = sc.nextInt();
long a = sc.nextLong();
long b = sc.nextLong();
char[] s = sc.next().toCharArray();
int[] pillars = new int[n+1];
pillars[0] = 1;
pillars[n] = 1;
for(int i=0;i<n;i++) {
if(s[i]=='1') {
pillars[i] = 2;
pillars[i+1] = 2;
}
}
for(int i=0;i<n;i++) {
if(s[i]=='0') {
pillars[i] = 1;
pillars[i+1] = 1;
}
else {
pillars[i] = 2;
break;
}
}
for(int i=n-1;i>=0;i--) {
if(s[i]=='0') {
pillars[i] = 1;
pillars[i+1] = 1;
}
else {
pillars[i+1] = 2;
break;
}
}
int c = 0;
int pipeline = 0, pillar = 0;
for(int i=0;i<=n;i++) {
if(pillars[i]==0) {
c++;
}
else {
if(c!=0) {
if(( c*b + (4+(c-1))*a ) <= 2*c*b + (c+1)*a) {
pillar+=c;
pipeline = pipeline +4+(c-1);
}
else {
pillar+=2*c;
pipeline = pipeline + c+1;
}
c = 0;
}
}
if(pillars[i]==1) {
pillar++;
if(i+1<=n) {
if(pillars[i+1]==2)
pipeline+=2;
if(pillars[i+1]==1)
pipeline++;
}
}
if(pillars[i]==2) {
pillar+=2;
if(i+1<=n) {
if(pillars[i+1]==1)
pipeline+=2;
if(pillars[i+1]==2)
pipeline++;
}
}
}
//System.out.println(pillar+" "+pipeline);
System.out.println(pillar*b+pipeline*a);
}
}
} | Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | 7afcdb50c6772bd6c0edf7c3bc1b5982 | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes | import java.util.*;
public class Main {
static String st;
static long min = Long.MAX_VALUE;
static long a;
static long b;
static long[][] dp;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int t = s.nextInt();
//int t = 1;
for (int T = 0; T < t; T++) {
int n = s.nextInt();
a = s.nextInt();
b = s.nextInt();
st = s.next() + "0";
System.out.println(solve());
}
}
public static long solve() {
dp = new long[st.length() + 1][2];
dp[0][0] = b;
dp[0][1] = Long.MAX_VALUE;
for (int i = 0; i < st.length() - 1; i++) {
dp[i + 1][1] = min(dp[i][0], 2 * a + 2 * b, dp[i][1], a + 2 * b);
if (st.charAt(i + 1) == '1' || st.charAt(i) == '1')
dp[i + 1][0] = Long.MAX_VALUE;
else
dp[i + 1][0] = min(dp[i][0], a + b, dp[i][1], 2 * a + b);
}
return dp[st.length() - 1][0];
}
public static long min(long a, long as, long b, long bs) {
if (a == Long.MAX_VALUE)
return b + bs;
else if (b == Long.MAX_VALUE)
return a + as;
return Math.min(a + as, b + bs);
}
} | Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | 444e517a11a3dfa0ecb2734cb4207a1f | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class C {
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
}
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args) {
FastReader f = new FastReader();
int t = f.nextInt();
while (t-- > 0) {
long n = f.nextLong();
long a = f.nextLong();
long b = f.nextLong();
String s = f.nextLine();
long lastc = 0L;
boolean on0 = false;
boolean seen1 = false;
long total = b;
for (int i = 0; i < n; i++) {
if (s.charAt(i) == '1' && on0) {
seen1 = true;
on0 = false;
total += a + 2 * b;
if (lastc == 0) {
total += a + b;
} else {
if (a * 2 + b < b * ((long) i - lastc)) {
total += a * 2 + b;
} else {
total += b * ((long) i - lastc);
}
}
} else if (s.charAt(i) == '1' && !on0) {
seen1 = true;
total += 2 * b + a;
} else if (s.charAt(i) == '0' && on0) {
total += a + b;
} else {
on0 = true;
lastc = (long) i;
total += a + b;
}
}
if (seen1) {
total += a;
}
System.out.println(total);
}
}
}
| Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | dd238d347dbe4f8d647beb21cd8f488b | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 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.*;
/**
* #
*
* @author pttrung
*/
public class C_Edu_Round_71 {
public static long MOD = 998244353;
static long[][] dp;
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 T = in.nextInt();
for (int z = 0; z < T; z++) {
int n = in.nextInt();
long a = in.nextInt();
long b = in.nextInt();
String data = in.next();
int[] tmp = new int[n + 1];
tmp[0] = 0;
for (int i = 0; i + 1 < n; i++) {
if (data.charAt(i) != data.charAt(i + 1)) {
tmp[i + 1] = 1;
} else {
tmp[i + 1] = data.charAt(i) - '0';
}
}
// System.out.println(Arrays.toString(tmp));
dp = new long[2][n + 1];
for (long[] x : dp) {
Arrays.fill(x, -1);
}
long re = cal(0, 0, a, b, tmp) + b;
out.println(re);
}
out.close();
}
static long cal(int index, int last, long a, long b, int[] data) {
if (index + 1 == data.length) {
return 0;
}
if (dp[last][index] != -1) {
return dp[last][index];
}
long result = 0;
int nxt = data[index + 1];
if (nxt == 1) {
if (last == 1) {
result = a + 2L * b + cal(index + 1, 1, a, b, data);
} else {
result = 2L * a + 2L * b + cal(index + 1, 1, a, b, data);
}
} else {
if (last == 1) {
long c = 2L * a + b + cal(index + 1, 0, a, b, data);
long d = Long.MAX_VALUE;
if (index + 2 < data.length) {
d = a + 2L * b + cal(index + 1, 1, a, b, data);
}
result = Long.min(c, d);
} else {
result = a + b + cal(index + 1, 0, a, b, data);
}
}
return dp[last][index] = result;
}
static int log(int n) {
int result = 0;
long st = 1;
for (int i = 0; st <= n; i++) {
result = i;
st *= 2L;
}
return result;
}
static long abs(long v) {
return v < 0 ? -v : v;
}
static int[] cal(double v) {
int[] re = new int[2];
if (v >= 0) {
re[0] = (int) Math.floor(v);
re[1] = (int) Math.ceil(v);
} else {
re[0] = (int) Math.ceil(v);
re[1] = (int) Math.floor(v);
}
return re;
}
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) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2);
if (b % 2 == 0) {
return val * val;
} else {
return val * (val * a);
}
}
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 | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | 5c8c075840eb929beaebed95a4adfde0 | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes | /*
* Author: Minho Kim (ISKU)
* Date: August 22, 2019
* E-mail: minho.kim093@gmail.com
*
* https://github.com/ISKU/Algorithm
* https://codeforces.com/problemset/problem/1207/C
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class C {
private static int N;
private static void solve() {
int T = io.nextInt();
while (T-- > 0) {
N = io.nextInt();
long A = io.nextLong();
long B = io.nextLong();
long g2p1 = A + A + B;
long g1p2 = A + B + B;
long g2p2 = A + A + B + B;
long g1p1 = A + B;
char[] array = io.nextToCharArray();
long sum = 0;
int dir = -1;
for (int i = 0; i < N - 1; i++) {
char cur = array[i];
char next = array[i + 1];
if (cur == '0' && next == '0') {
int nextIndex = dfs(array, i);
int dist = nextIndex - i;
if (nextIndex == N - 1) {
sum += (dist + 1) * g1p1;
} else {
sum += g2p2;
sum += dist * g1p1;
}
i = nextIndex;
} else if (cur == '0' && next == '1') {
if (dir == -1) {
sum += g2p2;
dir = 1;
} else
sum += g1p2;
} else if (cur == '1' && next == '1') {
sum += g1p2;
} else if (cur == '1' && next == '0') {
int nextIndex = dfs(array, i + 1);
int dist = nextIndex - i;
if (nextIndex == N - 1) {
if (dist == 1) {
sum += g1p2;
sum += g2p1;
} else {
sum += g1p2;
sum += Math.min(g2p1 + (dist - 1) * g1p1, g2p1 + ((dist - 1) * g1p2));
}
} else {
if (dist == 1) {
sum += g1p2 + g1p2;
} else if (dist == 2) {
sum += g1p2;
sum += Math.min(g2p1 + g2p2, g1p2 + g1p2);
} else {
sum += g1p2;
long first = g2p1 + g2p2 + ((dist - 2) * g1p1);
long second = g1p2 * dist;
sum += Math.min(first, second);
}
}
i = nextIndex;
}
}
io.println(sum + B);
}
}
private static int dfs(char[] array, int i) {
if (i == N - 1)
return i;
if (array[i] != '0')
return i - 1;
return dfs(array, i + 1);
}
public static void main(String[] args) {
io = new FastIO(System.in, System.out);
solve();
io.close();
}
private static FastIO io;
/**
* https://github.com/ISKU/FastIO-Java
*
* @author Minho Kim <minho.kim093@gmail.com>
*/
private static class FastIO {
public static final int DEFAULT_BUFFER_SIZE = 65536;
public static final int DEFAULT_INTEGER_SIZE = 11;
public static final int DEFAULT_LONG_SIZE = 20;
public static final int DEFAULT_WORD_SIZE = 256;
public static final int DEFAULT_LINE_SIZE = 8192;
public static final int EOF = -1;
private final InputStream in;
private final OutputStream out;
private byte[] inBuffer;
private int nextIn, inLength;
private byte[] outBuffer;
private int nextOut;
private char[] charBuffer;
private byte[] byteBuffer;
public FastIO(InputStream in, OutputStream out, int inBufferSize, int outBufferSize) {
this.in = in;
this.inBuffer = new byte[inBufferSize];
this.nextIn = 0;
this.inLength = 0;
this.out = out;
this.outBuffer = new byte[outBufferSize];
this.nextOut = 0;
this.charBuffer = new char[DEFAULT_LINE_SIZE];
this.byteBuffer = new byte[DEFAULT_LONG_SIZE];
}
public FastIO(InputStream in, OutputStream out) {
this(in, out, DEFAULT_BUFFER_SIZE, DEFAULT_BUFFER_SIZE);
}
public FastIO(InputStream in, OutputStream out, int bufferSize) {
this(in, out, bufferSize, bufferSize);
}
public char nextChar() {
byte b;
while (isSpace(b = read()))
;
return (char) b;
}
public String next() {
byte b;
while (isSpace(b = read()))
;
int pos = 0;
do {
charBuffer[pos++] = (char) b;
ensureCapacity(pos);
} while (!isSpace(b = read()));
return new String(charBuffer, 0, pos);
}
public String nextLine() {
byte b;
int pos = 0;
while (!isLine(b = read())) {
charBuffer[pos++] = (char) b;
ensureCapacity(pos);
}
return new String(charBuffer, 0, pos);
}
public int nextInt() {
byte b;
while (isSpace(b = read()))
;
boolean negative = false;
int result = b - '0';
if (b == '-') {
negative = true;
result = 0;
}
while (isDigit(b = read()))
result = (result * 10) + (b - '0');
return negative ? -result : result;
}
public long nextLong() {
byte b;
while (isSpace(b = read()))
;
boolean negative = false;
long result = b - '0';
if (b == '-') {
negative = true;
result = 0;
}
while (isDigit(b = read()))
result = (result * 10) + (b - '0');
return negative ? -result : result;
}
public float nextFloat() {
byte b;
while (isSpace(b = read()))
;
int pos = 0;
do {
charBuffer[pos++] = (char) b;
} while (!isSpace(b = read()));
return Float.parseFloat(new String(charBuffer, 0, pos));
}
public float nextFloat2() {
byte b;
while (isSpace(b = read()))
;
boolean negative = false;
float result = b - '0';
if (b == '-') {
negative = true;
result = 0;
}
while (isDigit(b = read()))
result = (result * 10) + (b - '0');
float d = 1;
if (b == '.') {
while (isDigit(b = read()))
result += (b - '0') / (d *= 10);
}
return negative ? -result : result;
}
public double nextDouble() {
byte b;
while (isSpace(b = read()))
;
int pos = 0;
do {
charBuffer[pos++] = (char) b;
} while (!isSpace(b = read()));
return Double.parseDouble(new String(charBuffer, 0, pos));
}
public double nextDouble2() {
byte b;
while (isSpace(b = read()))
;
boolean negative = false;
double result = b - '0';
if (b == '-') {
negative = true;
result = 0;
}
while (isDigit(b = read()))
result = (result * 10) + (b - '0');
double d = 1;
if (b == '.') {
while (isDigit(b = read()))
result += (b - '0') / (d *= 10);
}
return negative ? -result : result;
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
public BigDecimal nextBigDecimal() {
return new BigDecimal(next());
}
public char[] nextToCharArray() {
byte b;
while (isSpace(b = read()))
;
int pos = 0;
do {
charBuffer[pos++] = (char) b;
ensureCapacity(pos);
} while (!isSpace(b = read()));
char[] array = new char[pos];
System.arraycopy(charBuffer, 0, array, 0, pos);
return array;
}
public int[] nextIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = nextInt();
return array;
}
public long[] nextLongArray(int size) {
long[] array = new long[size];
for (int i = 0; i < size; i++)
array[i] = nextLong();
return array;
}
public int[][] nextInt2DArray(int Y, int X) {
int[][] array = new int[Y][X];
for (int y = 0; y < Y; y++)
for (int x = 0; x < X; x++)
array[y][x] = nextInt();
return array;
}
public void print(char c) {
write((byte) c);
}
public void print(char[] chars) {
print(chars, 0, chars.length);
}
public void print(char[] chars, int start) {
print(chars, start, chars.length);
}
public void print(char[] chars, int start, int end) {
for (int i = start; i < end; i++)
write((byte) chars[i]);
}
public void print(String s) {
for (int i = 0; i < s.length(); i++)
write((byte) s.charAt(i));
}
public void print(int i) {
if (i == 0) {
write((byte) '0');
return;
}
if (i == Integer.MIN_VALUE) {
write((byte) '-');
write((byte) '2');
write((byte) '1');
write((byte) '4');
write((byte) '7');
write((byte) '4');
write((byte) '8');
write((byte) '3');
write((byte) '6');
write((byte) '4');
write((byte) '8');
return;
}
if (i < 0) {
write((byte) '-');
i = -i;
}
int pos = 0;
while (i > 0) {
byteBuffer[pos++] = (byte) ((i % 10) + '0');
i /= 10;
}
while (pos-- > 0)
write(byteBuffer[pos]);
}
public void print(long l) {
if (l == 0) {
write((byte) '0');
return;
}
if (l == Long.MIN_VALUE) {
write((byte) '-');
write((byte) '9');
write((byte) '2');
write((byte) '2');
write((byte) '3');
write((byte) '3');
write((byte) '7');
write((byte) '2');
write((byte) '0');
write((byte) '3');
write((byte) '6');
write((byte) '8');
write((byte) '5');
write((byte) '4');
write((byte) '7');
write((byte) '7');
write((byte) '5');
write((byte) '8');
write((byte) '0');
write((byte) '8');
return;
}
if (l < 0) {
write((byte) '-');
l = -l;
}
int pos = 0;
while (l > 0) {
byteBuffer[pos++] = (byte) ((l % 10) + '0');
l /= 10;
}
while (pos-- > 0)
write(byteBuffer[pos]);
}
public void print(float f) {
String sf = Float.toString(f);
for (int i = 0; i < sf.length(); i++)
write((byte) sf.charAt(i));
}
public void print(double d) {
String sd = Double.toString(d);
for (int i = 0; i < sd.length(); i++)
write((byte) sd.charAt(i));
}
public void printls(char c) {
print(c);
write((byte) ' ');
}
public void printls(String s) {
print(s);
write((byte) ' ');
}
public void printls(int i) {
print(i);
write((byte) ' ');
}
public void printls(long l) {
print(l);
write((byte) ' ');
}
public void printls(float f) {
print(f);
write((byte) ' ');
}
public void printls(double d) {
print(d);
write((byte) ' ');
}
public void printls() {
write((byte) ' ');
}
public void println(char c) {
print(c);
write((byte) '\n');
}
public void println(char[] chars) {
print(chars, 0, chars.length);
write((byte) '\n');
}
public void println(String s) {
print(s);
write((byte) '\n');
}
public void println(int i) {
print(i);
write((byte) '\n');
}
public void println(long l) {
print(l);
write((byte) '\n');
}
public void println(float f) {
print(f);
write((byte) '\n');
}
public void println(double d) {
print(d);
write((byte) '\n');
}
public void println() {
write((byte) '\n');
}
public void printf(String format, Object... args) {
String s = String.format(format, args);
for (int i = 0; i < s.length(); i++)
write((byte) s.charAt(i));
}
public void fprint(char c) {
print(c);
flushBuffer();
}
public void fprint(String s) {
print(s);
flushBuffer();
}
public void fprint(int i) {
print(i);
flushBuffer();
}
public void fprint(long l) {
print(l);
flushBuffer();
}
public void fprint(float f) {
print(f);
flushBuffer();
}
public void fprint(double d) {
print(d);
flushBuffer();
}
public void fprintf(String format, Object... args) {
printf(format, args);
flushBuffer();
}
private byte read() {
if (nextIn >= inLength) {
if ((inLength = fill()) == EOF)
return EOF;
nextIn = 0;
}
return inBuffer[nextIn++];
}
private void write(byte b) {
if (nextOut >= outBuffer.length)
flushBuffer();
outBuffer[nextOut++] = b;
}
private int fill() {
try {
return in.read(inBuffer, 0, inBuffer.length);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void flush() {
flushBuffer();
}
private void flushBuffer() {
if (nextOut == 0)
return;
try {
out.write(outBuffer, 0, nextOut);
} catch (Exception e) {
throw new RuntimeException(e);
}
nextOut = 0;
}
public void close() {
flush();
}
public void exit(char c) {
fprint(c);
System.exit(0);
}
public void exit(String s) {
fprint(s);
System.exit(0);
}
public void exit(int i) {
fprint(i);
System.exit(0);
}
public void exit(long l) {
fprint(l);
System.exit(0);
}
public void exit(float f) {
fprint(f);
System.exit(0);
}
public void exit(double d) {
fprint(d);
System.exit(0);
}
public void exit(String format, Object... args) {
fprintf(format, args);
System.exit(0);
}
public void exit() {
flushBuffer();
System.exit(0);
}
private void ensureCapacity(int size) {
if (size < charBuffer.length)
return;
char[] array = new char[size * 2];
System.arraycopy(charBuffer, 0, array, 0, size);
charBuffer = array;
}
private boolean isDigit(byte b) {
return b >= '0' && b <= '9';
}
private boolean isLine(byte b) {
return b == '\n' || b == '\r' || b == EOF;
}
private boolean isSpace(byte b) {
return b == ' ' || b == '\t' || b == '\n' || b == '\r' || b == '\f' || b == EOF;
}
}
} | Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | 11ea8fce92e4c1848a5f5069a9cb2d87 | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes | import java.util.*;
import java.awt.Point;
import java.io.*;
public class Main{
public static void read(long[] a,int n) throws IOException{for (int i=0;i<n;i++){a[i]=Reader.nextLong();}}
public static String print(int[] a,int n,String c){String A=""; for (int i : a){ A+=i+c;} return A;}
public static String send(String a,String b){ if (a.charAt(0)==b.charAt(0)){ if (a.equals("R")){ return "B";}else if(a.equals("B")){ return "G";}else{ return "R";}}
else{ if (a.equals("R") && b.equals("B") || a.equals("B") && b.equals("R")){ return "G";}else if (a.equals("R") && b.equals("G") || a.equals("G") && b.equals("R")){ return "B";}else { return "R";}}
}
public static void main(String[] args) throws IOException{
Reader scan = new Reader();
scan.init(System.in);
OutputStream output = System.out;
PrintWriter out = new PrintWriter(output);
int t = scan.nextInt();
for (int o=0;o<t;o++){
int n = scan.nextInt();
long a = scan.nextLong();
long b = scan.nextLong();
String str = scan.next();
long[] L = new long[n+1];
long[] U = new long[n+1];
Arrays.fill(L,((long)Integer.MAX_VALUE)*100000);
Arrays.fill(U,((long)Integer.MAX_VALUE)*100000);
L[0]=b;
for (int i=1;i<=n;i++){
if (str.charAt(i-1)=='1'){
U[i] = Math.min(U[i],U[i-1]+a+2*b);
}
else{
L[i] = Math.min(L[i],L[i-1]+a+b);
U[i] = Math.min(U[i],L[i-1]+2*(a+b));
L[i] = Math.min(L[i],U[i-1]+(2*a)+b);
U[i] = Math.min(U[i],U[i-1]+a+(2*b));
}
}
out.println(L[n]);
}
out.close();
}
}
class Comp implements Comparator<String>{
public int compare(String a,String b){
return (b.length()-a.length());
}
}
class dsu{
int[] arr;
dsu(int N){
arr = new int[N];
for (int i=0;i<N;i++){
arr[i] = i;
}
}
public void joint(int A,int B){
int a = find(A);
int b = find(B);
arr[a] = b;
}
public int find(int A){
while(A!=arr[A]){
A = arr[A];
}
return A;
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static long nextLong() throws IOException {
return Long.parseLong( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
} | Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | 31efb4bf825210d414af58090bab4b3b | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes | import java.util.*;
import java.math.*;
public class Main
{
public static void main(String[] args)
{
int k,n,p,q;
BigInteger res,a,b;
String str;
Scanner in=new Scanner(System.in);
LinkedList<Integer> list=new LinkedList<>();
k=in.nextInt();
while(k>0)
{
n=in.nextInt();
a=new BigInteger(String.valueOf(in.nextInt()));
b=new BigInteger(String.valueOf(in.nextInt()));
str=in.next();
list.clear();
res=new BigInteger(String.valueOf(a.multiply(new BigInteger(String.valueOf(n)))));
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)=='1')
list.add(i);
}
if(list.isEmpty())
{
res=res.add(new BigInteger(String.valueOf(b.multiply(new BigInteger(String.valueOf(n+1))))));
}
else
{
p=list.remove();
res=res.add(new BigInteger(String.valueOf(b.multiply(new BigInteger(String.valueOf(p+4))).add(new BigInteger(String.valueOf(a))))));
while(!list.isEmpty())
{
q=list.remove();
if(q-p<3)
res=res.add(new BigInteger(String.valueOf(b.multiply(new BigInteger(String.valueOf((q-p)*2))))));
else
{
res=res.add(b.multiply(new BigInteger(String.valueOf((q-p)*2))).min(b.multiply(new BigInteger(String.valueOf(q-p+2))).
add(a.multiply(new BigInteger("2")))));
}
p=q;
}
res=res.add(b.multiply(new BigInteger(String.valueOf(n-1-p))).add(a));
}
System.out.println(res);
k--;
}
}
}
| Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | 1ae55ad6bc323e8d449ee4efafb9bc43 | train_003.jsonl | 1566484500 | You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment $$$[0, n]$$$ on $$$OX$$$ axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval $$$(x, x + 1)$$$ with integer $$$x$$$. So we can represent the road as a binary string consisting of $$$n$$$ characters, where character 0 means that current interval doesn't contain a crossroad, and 1 means that there is a crossroad.Usually, we can install the pipeline along the road on height of $$$1$$$ unit with supporting pillars in each integer point (so, if we are responsible for $$$[0, n]$$$ road, we must install $$$n + 1$$$ pillars). But on crossroads we should lift the pipeline up to the height $$$2$$$, so the pipeline won't obstruct the way for cars.We can do so inserting several zig-zag-like lines. Each zig-zag can be represented as a segment $$$[x, x + 1]$$$ with integer $$$x$$$ consisting of three parts: $$$0.5$$$ units of horizontal pipe + $$$1$$$ unit of vertical pipe + $$$0.5$$$ of horizontal. Note that if pipeline is currently on height $$$2$$$, the pillars that support it should also have length equal to $$$2$$$ units. Each unit of gas pipeline costs us $$$a$$$ bourles, and each unit of pillar — $$$b$$$ bourles. So, it's not always optimal to make the whole pipeline on the height $$$2$$$. Find the shape of the pipeline with minimum possible cost and calculate that cost.Note that you must start and finish the pipeline on height $$$1$$$ and, also, it's guaranteed that the first and last characters of the input string are equal to 0. | 256 megabytes | import java.math.BigInteger;
import java.util.Scanner;
public class Kazusa
{
public static void main(String[] args)
{
int k,n;
long a,b;
BigInteger[][] dp;
String str;
Scanner in=new Scanner(System.in);
k=in.nextInt();
while(k>0)
{
n=in.nextInt();
a=in.nextLong();
b=in.nextLong();
str=in.next();
dp=new BigInteger[n][2];
dp[0][0]=new BigInteger(String.valueOf(b*2+a));
dp[0][1]=new BigInteger(String.valueOf(3*b+2*a));
for(int i=1;i<n;i++)
{
dp[i][1]=dp[i-1][1].add(new BigInteger(String.valueOf(a+2*b)));
if(str.charAt(i)=='0')
{
dp[i][0]=dp[i-1][1].add(new BigInteger(String.valueOf(2*a+b)));
if(dp[i-1][0]!=null)
{
dp[i][1] = dp[i][1].min(dp[i - 1][0].add(new BigInteger(String.valueOf(2 * a + 2 * b))));
dp[i][0]=dp[i][0].min(dp[i-1][0].add(new BigInteger(String.valueOf(a+b))));
}
}
}
System.out.println(dp[n-1][0]);
k--;
}
}
}
| Java | ["4\n8 2 5\n00110010\n8 1 1\n00110010\n9 100000000 100000000\n010101010\n2 5 1\n00"] | 2 seconds | ["94\n25\n2900000000\n13"] | NoteThe optimal pipeline for the first query is shown at the picture above.The optimal pipeline for the second query is pictured below: The optimal (and the only possible) pipeline for the third query is shown below: The optimal pipeline for the fourth query is shown below: | Java 8 | standard input | [
"dp",
"greedy"
] | 4fa609ef581f705df901f7532b52cf7c | The fist line contains one integer $$$T$$$ ($$$1 \le T \le 100$$$) — the number of queries. Next $$$2 \cdot T$$$ lines contain independent queries — one query per two lines. The first line contains three integers $$$n$$$, $$$a$$$, $$$b$$$ ($$$2 \le n \le 2 \cdot 10^5$$$, $$$1 \le a \le 10^8$$$, $$$1 \le b \le 10^8$$$) — the length of the road, the cost of one unit of the pipeline and the cost of one unit of the pillar, respectively. The second line contains binary string $$$s$$$ ($$$|s| = n$$$, $$$s_i \in \{0, 1\}$$$, $$$s_1 = s_n = 0$$$) — the description of the road. It's guaranteed that the total length of all strings $$$s$$$ doesn't exceed $$$2 \cdot 10^5$$$. | 1,500 | Print $$$T$$$ integers — one per query. For each query print the minimum possible cost of the constructed pipeline. | standard output | |
PASSED | 146df7e61be85568879e3e2db0145e3c | train_003.jsonl | 1568822700 | Gardener Alex loves to grow trees. We remind that tree is a connected acyclic graph on $$$n$$$ vertices. Today he decided to grow a rooted binary tree. A binary tree is a tree where any vertex has no more than two sons. Luckily, Alex has a permutation of numbers from $$$1$$$ to $$$n$$$ which he was presented at his last birthday, so he decided to grow a tree according to this permutation. To do so he does the following process: he finds a minimum element and makes it a root of the tree. After that permutation is divided into two parts: everything that is to the left of the minimum element, and everything that is to the right. The minimum element on the left part becomes the left son of the root, and the minimum element on the right part becomes the right son of the root. After that, this process is repeated recursively on both parts.Now Alex wants to grow a forest of trees: one tree for each cyclic shift of the permutation. He is interested in what cyclic shift gives the tree of minimum depth. Unfortunately, growing a forest is a hard and long process, but Alex wants the answer right now. Will you help him?We remind that cyclic shift of permutation $$$a_1, a_2, \ldots, a_k, \ldots, a_n$$$ for $$$k$$$ elements to the left is the permutation $$$a_{k + 1}, a_{k + 2}, \ldots, a_n, a_1, a_2, \ldots, a_k$$$. | 256 megabytes | import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.InputMismatchException;
public class F1220 {
static class Solver {
int N, perm[], firstLeft[], firstRight[];
Node st; RMQ RMQ;
void solve(int testNumber, FastScanner s, PrintWriter out) {
N = s.nextInt(); perm = new int[N << 1];
firstLeft = new int[N << 1]; firstRight = new int[N << 1];
for(int i = 0; i < N; i++) perm[i] = perm[i + N] = s.nextInt();
st = new Node(0, 2 * N - 1);
RMQ = new RMQ(perm);
int lo, hi, m, f, v;
for(int i = 0; i < 2 * N; i++) {
lo = 1; hi = i; f = i + 1; v = perm[i];
while(lo <= hi) {
m = lo + (hi - lo) / 2;
if(RMQ.query(i - m, i - 1) <= v) {
f = m; hi = m - 1;
} else {
lo = m + 1;
}
}
firstLeft[i] = i - f + 1;
lo = 1; hi = 2 * N - i - 1; f = 2 * N;
while(lo <= hi) {
m = lo + (hi - lo) / 2;
if(RMQ.query(i + 1, i + m) <= v) {
f = m; hi = m - 1;
} else {
lo = m + 1;
}
}
firstRight[i] = i + f - 1;
}
for (int i = 0; i < N; i++) st.add(firstLeft[i], firstRight[i], 1);
int mindepth = 69_420_1337, shift = -1;
for(int l = 0, r = N - 1; l < N; l++, r++) {
int cd = st.max(l, r);
if(cd < mindepth) {
mindepth = cd; shift = l;
}
st.add(firstLeft[l], firstRight[l], -1);
if(r != 2 * N - 1) st.add(firstLeft[r + 1], firstRight[r + 1], 1);
}
out.printf("%d %d%n", mindepth, shift);
}
class Node {
int l, m, r, lz, max, mn;
Node L, R;
Node(int ll, int rr) {
l = ll; r = rr; m = l + (r - l) / 2;
lz = max = 0;
if(l == r) return;
L = new Node(l, m); R = new Node(m + 1, r);
mn = L.mn < R.mn ? L.mn : R.mn;
}
void push() {
if(lz != 0) {
L.add(l, r, lz); R.add(l, r, lz);
max = L.max > R.max ? L.max : R.max;
} lz = 0;
}
void add(int s, int e, int x) {
if(s <= l && r <= e) {
lz += x; max += x; return;
}
push();
if(s <= m) L.add(s, e, x);
if(m < e) R.add(s, e, x);
max = L.max > R.max ? L.max : R.max;
}
int max(int s, int e) {
if(s <= l && r <= e) { return max; }
push();
int mx = 0;
if(s <= m) mx = Math.max(mx, L.max(s, e));
if(m < e) mx = Math.max(mx, R.max(s, e));
return mx;
}
}
static class RMQ {
int[] vs;
int[][] lift;
public RMQ(int[] vs) {
this.vs = vs;
int n = vs.length;
int maxlog = Integer.numberOfTrailingZeros(Integer.highestOneBit(n)) + 2;
lift = new int[maxlog][n];
for (int i = 0; i < n; i++)
lift[0][i] = vs[i];
int lastRange = 1;
for (int lg = 1; lg < maxlog; lg++) {
for (int i = 0; i < n; i++) {
lift[lg][i] = Math.min(lift[lg - 1][i], lift[lg - 1][Math.min(i + lastRange, n - 1)]);
}
lastRange *= 2;
}
}
public int query(int low, int hi) {
int range = hi - low + 1;
int exp = Integer.highestOneBit(range);
int lg = Integer.numberOfTrailingZeros(exp);
return Math.min(lift[lg][low], lift[lg][hi - exp + 1]);
}
}
}
final static boolean cases = false;
public static void main(String[] args) {
FastScanner s = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
Solver solver = new Solver();
for (int t = 1, T = cases ? s.nextInt() : 1; t <= T; t++)
solver.solve(t, s, out);
out.close();
}
static int min(int a, int b) {
return a < b ? a : b;
}
static int max(int a, int b) {
return a > b ? a : b;
}
static long min(long a, long b) {
return a < b ? a : b;
}
static long max(long a, long b) {
return a > b ? a : b;
}
static int swap(int a, int b) {
return a;
}
static Object swap(Object a, Object b) {
return a;
}
static String ts(Object... o) {
return Arrays.deepToString(o);
}
static class FastScanner {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastScanner(InputStream stream) {
this.stream = stream;
}
public FastScanner(File f) throws FileNotFoundException {
this(new FileInputStream(f));
}
public FastScanner(String s) {
this.stream = new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8));
}
int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
boolean isEndline(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndline(c));
return res.toString();
}
// Jacob Garbage
public int[] nextIntArray(int N) {
int[] ret = new int[N];
for (int i = 0; i < N; i++)
ret[i] = this.nextInt();
return ret;
}
public int[][] next2DIntArray(int N, int M) {
int[][] ret = new int[N][];
for (int i = 0; i < N; i++)
ret[i] = this.nextIntArray(M);
return ret;
}
public long[] nextLongArray(int N) {
long[] ret = new long[N];
for (int i = 0; i < N; i++)
ret[i] = this.nextLong();
return ret;
}
public long[][] next2DLongArray(int N, int M) {
long[][] ret = new long[N][];
for (int i = 0; i < N; i++)
ret[i] = nextLongArray(M);
return ret;
}
public double[] nextDoubleArray(int N) {
double[] ret = new double[N];
for (int i = 0; i < N; i++)
ret[i] = this.nextDouble();
return ret;
}
public double[][] next2DDoubleArray(int N, int M) {
double[][] ret = new double[N][];
for (int i = 0; i < N; i++)
ret[i] = this.nextDoubleArray(M);
return ret;
}
}
}
| Java | ["4\n1 2 3 4"] | 2 seconds | ["3 2"] | NoteThe following picture depicts all possible trees for sample test and cyclic shifts on which they are achieved. | Java 8 | standard input | [
"data structures",
"binary search"
] | 0cd663950ce384c506f2eaa6e14b9880 | First line contains an integer number $$$n ~ (1 \leqslant n \leqslant 200\,000)$$$ — length of the permutation. Second line contains $$$n$$$ integer numbers $$$a_1, a_2, \ldots, a_n ~ (1 \leqslant a_i \leqslant n)$$$, and it is guaranteed that all numbers occur exactly one time. | 2,700 | Print two numbers separated with space: minimum possible depth of a tree and how many elements we need to shift left to achieve this depth. The number of elements should be a number from $$$0$$$ to $$$n - 1$$$. If there are several possible answers, print any of them. | standard output | |
PASSED | 653fc01a8acd2a7aabfce3d6cfada6c7 | train_003.jsonl | 1568822700 | Gardener Alex loves to grow trees. We remind that tree is a connected acyclic graph on $$$n$$$ vertices. Today he decided to grow a rooted binary tree. A binary tree is a tree where any vertex has no more than two sons. Luckily, Alex has a permutation of numbers from $$$1$$$ to $$$n$$$ which he was presented at his last birthday, so he decided to grow a tree according to this permutation. To do so he does the following process: he finds a minimum element and makes it a root of the tree. After that permutation is divided into two parts: everything that is to the left of the minimum element, and everything that is to the right. The minimum element on the left part becomes the left son of the root, and the minimum element on the right part becomes the right son of the root. After that, this process is repeated recursively on both parts.Now Alex wants to grow a forest of trees: one tree for each cyclic shift of the permutation. He is interested in what cyclic shift gives the tree of minimum depth. Unfortunately, growing a forest is a hard and long process, but Alex wants the answer right now. Will you help him?We remind that cyclic shift of permutation $$$a_1, a_2, \ldots, a_k, \ldots, a_n$$$ for $$$k$$$ elements to the left is the permutation $$$a_{k + 1}, a_{k + 2}, \ldots, a_n, a_1, a_2, \ldots, a_k$$$. | 256 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
public class f {
class Node {
int l, r, d, v;
Node left, right;
public Node(int ll, int rr) {
l = ll; r = rr;
if(l != r) {
int m = (l + r) / 2;
left = new Node(l, m);
right = new Node(m + 1, r);
}
}
void prop() {
left.d += d; right.d += d;
d = 0;
}
void update() {
v = Math.max(left.v + left.d, right.v + right.d);
}
void inc(int a, int b, int x) {
if(b < l || r < a) return;
if(a <= l && r <= b) {
d += x;
return;
}
prop();
left.inc(a, b, x);
right.inc(a, b, x);
update();
}
int max(int a, int b) {
if(b < l || r < a) return -oo;
if(a <= l && r <= b) return v + d;
prop();
int maxl = left.max(a, b);
int maxr = right.max(a, b);
update();
return Math.max(maxl, maxr);
}
void print() {
if(l == r) {
System.out.print(v + d + " ");
return;
}
prop();
left.print();
right.print();
update();
}
}
final int oo = (int) 1e9;
class Graph {
int n;
List<Integer>[] adj;
public Graph(int nn) {
adj = new ArrayList[n = nn];
for(int i = 0 ; i < n ; adj[i++] = new ArrayList<>());
}
void add(int u, int v) {
adj[u].add(v);
}
int t = 0;
int[] pre, post;
void prepost() {
pre = new int[n];
post = new int[n];
dfs(0);
}
void dfs(int u) {
pre[u] = post[u] = t++;
for(int v : adj[u]) {
dfs(v);
post[u] = Math.max(post[u], post[v]);
}
}
}
int buildGraph(int l, int r) {
if(r < l) return -1;
int min = -max.max(l, r);
int id = rev[min];
int minL = buildGraph(l, id - 1);
int minR = buildGraph(id + 1, r);
if(minL != -1) g.add(min, minL);
if(minR != -1) g.add(min, minR);
return min;
}
int[] p, rev;
Graph g;
Node max;
List<Integer> perm;
public f() {
FS scan = new FS();
int n = scan.nextInt();
p = new int[n];
int id0 = -1;
for(int i = 0 ; i < n ; i++) {
p[i] = scan.nextInt() - 1;
if(p[i] == 0) id0 = i;
}
int[] tp = new int[n];
for(int i = 0 ; i < n ; i++) {
tp[i] = p[id0++];
if(id0 == n) id0 -= n;
}
p = tp;
max = new Node(0, n - 1);
for(int i = 0 ; i < n ; i++)
max.inc(i, i, -p[i]);
g = new Graph(n);
rev = new int[n];
for(int i = 0 ; i < n ; i++)
rev[p[i]] = i;
buildGraph(0, n - 1);
g.prepost();
int[] maxRtoL = new int[n];
Node st = new Node(0, n - 1);
for(int i = 0 ; i < n ; i++)
st.inc(g.pre[i], g.post[i], +1);
for(int i = n - 1 ; i >= 0 ; i--) {
maxRtoL[i] = st.max(0, n - 1);
st.inc(g.pre[p[i]], g.pre[p[i]], -oo);
st.inc(g.pre[p[i]], g.post[p[i]], -1);
}
for(int i = 0 ; i < n - 1 ; i++)
p[i] = p[i + 1];
p[n - 1] = 0;
max = new Node(0, n - 1);
for(int i = 0 ; i < n ; i++)
max.inc(i, i, -p[i]);
g = new Graph(n);
for(int i = 0 ; i < n ; i++)
rev[p[i]] = i;
buildGraph(0, n - 1);
g.prepost();
int[] maxLtoR = new int[n];
st = new Node(0, n - 1);
for(int i = 0 ; i < n ; i++)
st.inc(g.pre[i], g.post[i], +1);
// st.print();
// System.out.println();
// System.out.println("pre: " + Arrays.toString(g.pre));
// System.out.println("post: " + Arrays.toString(g.post));
for(int i = 0 ; i < n ; i++) {
maxLtoR[i] = st.max(0, n - 1);
st.inc(g.pre[p[i]], g.pre[p[i]], -oo);
st.inc(g.pre[p[i]], g.post[p[i]], -1);
}
int min = oo, ind = -1;
for(int i = 0 ; i < n ; i++) {
int maxboth = Math.max(maxLtoR[i], maxRtoL[i]);
if(maxboth < min) {
min = maxboth;
ind = n - i - 1;
}
}
int shift = id0 - ind;
if(shift < 0) shift += n;
System.out.println(min + " " + shift);
// System.out.println(ind);
// System.out.println(id0);
// System.out.println(Arrays.toString(maxRtoL));
// System.out.println(Arrays.toString(maxLtoR));
}
class FS {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public String next() {
while(!st.hasMoreTokens()) {
try { st = new StringTokenizer(br.readLine()); }
catch(Exception e) { e.printStackTrace(); }
}
return st.nextToken();
}
public int nextInt() { return Integer.parseInt(next()); }
}
public static void main(String[] args) throws Exception { new f(); }
}
/*
6
4 2 5 1 6 3
https://codeforces.com/problemset/problem/1220/F
*/ | Java | ["4\n1 2 3 4"] | 2 seconds | ["3 2"] | NoteThe following picture depicts all possible trees for sample test and cyclic shifts on which they are achieved. | Java 8 | standard input | [
"data structures",
"binary search"
] | 0cd663950ce384c506f2eaa6e14b9880 | First line contains an integer number $$$n ~ (1 \leqslant n \leqslant 200\,000)$$$ — length of the permutation. Second line contains $$$n$$$ integer numbers $$$a_1, a_2, \ldots, a_n ~ (1 \leqslant a_i \leqslant n)$$$, and it is guaranteed that all numbers occur exactly one time. | 2,700 | Print two numbers separated with space: minimum possible depth of a tree and how many elements we need to shift left to achieve this depth. The number of elements should be a number from $$$0$$$ to $$$n - 1$$$. If there are several possible answers, print any of them. | standard output | |
PASSED | 6bfa2ec172c4bd1608ff1e80ad375960 | train_003.jsonl | 1568822700 | Gardener Alex loves to grow trees. We remind that tree is a connected acyclic graph on $$$n$$$ vertices. Today he decided to grow a rooted binary tree. A binary tree is a tree where any vertex has no more than two sons. Luckily, Alex has a permutation of numbers from $$$1$$$ to $$$n$$$ which he was presented at his last birthday, so he decided to grow a tree according to this permutation. To do so he does the following process: he finds a minimum element and makes it a root of the tree. After that permutation is divided into two parts: everything that is to the left of the minimum element, and everything that is to the right. The minimum element on the left part becomes the left son of the root, and the minimum element on the right part becomes the right son of the root. After that, this process is repeated recursively on both parts.Now Alex wants to grow a forest of trees: one tree for each cyclic shift of the permutation. He is interested in what cyclic shift gives the tree of minimum depth. Unfortunately, growing a forest is a hard and long process, but Alex wants the answer right now. Will you help him?We remind that cyclic shift of permutation $$$a_1, a_2, \ldots, a_k, \ldots, a_n$$$ for $$$k$$$ elements to the left is the permutation $$$a_{k + 1}, a_{k + 2}, \ldots, a_n, a_1, a_2, \ldots, a_k$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static int inf = (int) (1e9 + 7);
static int n;
static int[] pref(int a[]) {
ArrayDeque<Integer> id = new ArrayDeque<>();
ArrayDeque<Integer> h = new ArrayDeque<>();
int res[] = new int [a.length];
for(int i = 0;i < a.length;i++) {
while(!id.isEmpty() && a[id.getLast()] > a[i]) {
id.pollLast();
int q = h.pollLast();
if (!h.isEmpty()) {
q = Math.max(q, h.pollLast());
h.add(q);
}
}
if (!id.isEmpty()) {
int temp = h.pollLast();
h.add(temp + 1);
}
res[i] = h.size() + 1;
if (i != 0) res[i] = res[i - 1];
if (i != 0) res[i] = Math.max(res[i], (h.isEmpty() ? res[i - 1] + 1 : h.peekLast()));
id.add(i);
h.add(h.size() + 1);
}
return res;
}
static int[] reverse(int b[]) {
int res[] = new int [b.length];
for(int i = 0;i < b.length;i++) res[i] = b[b.length - i - 1];
return res;
}
static void solve() throws IOException {
n = sc.nextInt();
if (n == 1) {
pw.println(1 + " " + 0);
return;
}
int temp[] = new int [n];
for(int i = 0;i < n;i++) temp[i] = sc.nextInt();
int a[] = new int [n - 1];
int temp1 = 0;
int id_one = 0;
for(int i = 0;i < n;i++) if (temp[i] == 1)id_one = i;
for(int i = id_one + 1;i < n;i++) a[temp1++] = temp[i];
for(int i = 0;i < id_one;i++) a[temp1++] = temp[i];
int pref[] = pref(a);
int suf[] = reverse(pref(reverse(a)));
int min_id = -1;
int min = suf[0];
for(int i = 0;i < pref.length;i++) {
int num = pref[i];
if (i != pref.length - 1) num = Math.max(num, suf[i + 1]);
if (num < min) {
min = num;
min_id = i;
}
}
int sec = (id_one + 1 + min_id + 1) % n;
pw.print(min + 1 + " " + sec);
}
public static void main(String[] args) throws IOException {
sc = new Scanner(System.in);
pw = new PrintWriter(System.out);
solve();
pw.close();
}
static Scanner sc;
static PrintWriter pw;
static class Scanner {
BufferedReader br;
StringTokenizer st = new StringTokenizer("");
Scanner(InputStream in) throws FileNotFoundException {
br = new BufferedReader(new InputStreamReader(in));
}
Scanner(String in) throws FileNotFoundException {
br = new BufferedReader(new FileReader(in));
}
String next() throws IOException {
while (!st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
} | Java | ["4\n1 2 3 4"] | 2 seconds | ["3 2"] | NoteThe following picture depicts all possible trees for sample test and cyclic shifts on which they are achieved. | Java 8 | standard input | [
"data structures",
"binary search"
] | 0cd663950ce384c506f2eaa6e14b9880 | First line contains an integer number $$$n ~ (1 \leqslant n \leqslant 200\,000)$$$ — length of the permutation. Second line contains $$$n$$$ integer numbers $$$a_1, a_2, \ldots, a_n ~ (1 \leqslant a_i \leqslant n)$$$, and it is guaranteed that all numbers occur exactly one time. | 2,700 | Print two numbers separated with space: minimum possible depth of a tree and how many elements we need to shift left to achieve this depth. The number of elements should be a number from $$$0$$$ to $$$n - 1$$$. If there are several possible answers, print any of them. | standard output | |
PASSED | e54b05462fb5123c77a51d07198ab706 | train_003.jsonl | 1545143700 | Vova's family is building the Great Vova Wall (named by Vova himself). Vova's parents, grandparents, grand-grandparents contributed to it. Now it's totally up to Vova to put the finishing touches.The current state of the wall can be respresented by a sequence $$$a$$$ of $$$n$$$ integers, with $$$a_i$$$ being the height of the $$$i$$$-th part of the wall.Vova can only use $$$2 \times 1$$$ bricks to put in the wall (he has infinite supply of them, however).Vova can put bricks horizontally on the neighboring parts of the wall of equal height. It means that if for some $$$i$$$ the current height of part $$$i$$$ is the same as for part $$$i + 1$$$, then Vova can put a brick there and thus increase both heights by 1. Obviously, Vova can't put bricks in such a way that its parts turn out to be off the borders (to the left of part $$$1$$$ of the wall or to the right of part $$$n$$$ of it).The next paragraph is specific to the version 1 of the problem.Vova can also put bricks vertically. That means increasing height of any part of the wall by 2.Vova is a perfectionist, so he considers the wall completed when: all parts of the wall has the same height; the wall has no empty spaces inside it. Can Vova complete the wall using any amount of bricks (possibly zero)? | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
private static final Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
StringTokenizer st = new StringTokenizer(br.readLine());
int[] arr = new int[n];
for (int i=0; i<n; ++i){
arr[i] = Integer.parseInt(st.nextToken())%2;
}
int[] zz = new int[n];
for (int i=0; i<n; ++i)
zz[i] = arr[i]^1;
int ans = solve(arr,n);
ans |= solve(zz,n);
System.out.println(ans==1?"YES":"NO");
sc.close();
br.close();
bw.close();
}
public static int solve(int[] arr, int n){
Stack<Integer> stack = new Stack<>();
for (int i=0; i<n; ++i){
if (stack.isEmpty())
stack.add(arr[i]);
else {
if (arr[i] > stack.peek()){
stack.add(arr[i]);
} else if (arr[i] == stack.peek())
stack.pop();
else stack.add(arr[i]);
}
}
if (stack.size() > 1){
return 0;
}
return 1;
}
} | Java | ["5\n2 1 1 2 5", "3\n4 5 3", "2\n10 10", "3\n1 2 3"] | 2 seconds | ["YES", "YES", "YES", "NO"] | NoteIn the first example Vova can put a brick on parts 2 and 3 to make the wall $$$[2, 2, 2, 2, 5]$$$ and then put 3 bricks on parts 1 and 2 and 3 bricks on parts 3 and 4 to make it $$$[5, 5, 5, 5, 5]$$$.In the second example Vova can put a brick vertically on part 3 to make the wall $$$[4, 5, 5]$$$, then horizontally on parts 2 and 3 to make it $$$[4, 6, 6]$$$ and then vertically on part 1 to make it $$$[6, 6, 6]$$$.In the third example the wall is already complete. | Java 8 | standard input | [
"implementation",
"greedy",
"math"
] | bb4ecfaaccd538e23f883a18f9672af8 | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 2 \cdot 10^5$$$) — the number of parts in the wall. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$) — the initial heights of the parts of the wall. | 2,200 | Print "YES" if Vova can complete the wall using any amount of bricks (possibly zero). Print "NO" otherwise. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.