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 | 552510fcf24a1b370c56a4e0b6f25084 | train_004.jsonl | 1323443100 | Little Petya very much likes rectangular tables that consist of characters "0" and "1". Recently he has received one such table as a gift from his mother. The table contained n rows and m columns. The rows are numbered from top to bottom from 1 to n, the columns are numbered from the left to the right from 1 to m. Petya immediately decided to find the longest cool cycle whatever it takes.A cycle is a sequence of pairwise distinct cells where each two consecutive cells have a common side; besides, the first cell has a common side with the last cell. A cycle is called cool if it fulfills all the following conditions simultaneously: The cycle entirely consists of the cells that contain "1". Each cell that belongs to the cycle, has a common side with exactly two other cells that belong to the cycle. Each cell of the table that contains "1" either belongs to the cycle or is positioned outside of it (see definition below). To define the notion of "outside" formally, let's draw a cycle on a plane. Let each cell of the cycle (i, j) (i is the row number, j is the column number) correspond to the point (i, j) on the coordinate plane. Let a straight line segment join each pair of points that correspond to the cells belonging to the cycle and sharing a side. Thus, we will get a closed polyline that has no self-intersections and self-touches. The polyline divides the plane into two connected parts: the part of an infinite area and the part of a finite area. It is considered that cell (r, c) lies outside of the cycle if it does not belong to the cycle and the corresponding point on the plane with coordinates (r, c) lies in the part with the infinite area.Help Petya to find the length of the longest cool cycle in the table. The cycle length is defined as the number of cells that belong to the cycle. | 256 megabytes | import java.io.*;
import java.util.*;
public class D135 {
public D135 () throws IOException {
String input = r.readLine();
String [] NM = input.split(" ");
int N = Integer.parseInt(NM[0]);
int M = Integer.parseInt(NM[1]);
boolean [][] G = new boolean [N][M];
for (int i = 0; i < N; ++i) {
String row = r.readLine();
for (int j = 0; j < M; ++j)
G[i][j] = (row.charAt(j) == '1');
}
this.G = G;
this.N = N;
this.M = M;
solve();
}
int N, M;
boolean [][] G;
int res;
final static int K = 1000000;
public void solve () {
t = millis();
boolean [][] V = new boolean [N][M];
res = 0;
for (int i = 0; i < N-1; ++i)
for (int j = 0; j < M-1; ++j) {
int i0 = i, j0 = j;
if (G[i][j] && !V[i][j]) {
if (G[i][j+1] && G[i+1][j+1] && G[i+1][j]) {
if (res < 4) res = 4;
continue;
}
List<Integer> path = new LinkedList<Integer>();
Set<Integer> points = new HashSet<Integer>();
int [] D = { 0, 1};
int z = i;
if (!next(i,j,D) || !next(i,j,inner(D))) {
V[i][j] = true;
continue;
}
else {
{
int p = K*i+j;
points.add(p);
path.add(p);
++j;
}
do {
int p = K*i+j;
path.add(p);
if (!points.add(p)) {
while (!path.get(0).equals(p))
points.remove(path.remove(0));
if (safeInt(path, points))
res = Math.max(res, path.size() - 1);
break;
}
int [] IN = inner(D), OUT = outer(D);
if (next(i,j,IN))
D = IN;
else if (!next(i,j,D))
D = OUT;
if (r(D))
V[i][j] = true;
if (next(i,j,D)) {
i += D[0];
j += D[1];
} else
break;
if (i < z)
break;
} while (true);
}
}
i = i0; j = j0;
}
print (res);
}
int [] decode (int n) {
return new int [] { n/K, n%K };
}
boolean safeInt(List<Integer> path, Set<Integer> points) {
// if (path.size() <= res+1)
// return false;
if (path.size() == 5)
return true;
int [] zero = decode(path.get(0));
int [] one = decode(path.get(1));
if (one[0] == zero[0] + 1 && one[1] == zero[1]) {
List<Integer> reverse = new LinkedList<Integer>();
for (int p : path)
reverse.add(0, p);
return safeInt(reverse, points);
}
for (int p : path) {
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int c = 0;
if (points.contains(K*(x-1) + y))
++c;
if (points.contains(K*(x+1) + y))
++c;
if (points.contains(K*x + (y-1)))
++c;
if (points.contains(K*x + (y+1)))
++c;
if (c != 2)
return false;
}
int [] D = { 0, 1 };
Set<Integer> IP = new HashSet<Integer>();
Queue<Integer> Q = new LinkedList<Integer>();
for (int p : path) {
if (p == path.get(0))
continue;
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int [] IN = inner(D);
if (next(x,y,IN))
D = IN;
else {
if (!next(x,y,D))
D = outer(D);
x += IN[0]; y += IN[1];
if (x >= 0 && y >= 0 && x < N && y < M) {
int ip = K*x+y;
if (IP.add(ip))
Q.add(ip);
}
}
}
while (!Q.isEmpty()) {
int p = Q.poll();
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int nx, ny;
boolean t = true;
nx = x+1; ny = y;
t = t && test(nx, ny, points, IP, Q);
nx = x; ny = y+1;
t = t && test(nx, ny, points, IP, Q);
nx = x-1; ny = y;
t = t && test(nx, ny, points, IP, Q);
nx = x; ny = y-1;
t = t && test(nx, ny, points, IP, Q);
if (!t)
return false;
}
return true;
}
boolean test(int nx, int ny, Set<Integer> points, Set<Integer> IP, Queue<Integer> Q) {
int np = K*nx+ny;
if (nx >= 0 && ny >= 0 && nx < N && ny < M) {
if (!points.contains(np)) {
if (G[nx][ny])
return false;
if (IP.add(np))
Q.add(np);
}
}
return true;
}
boolean next (int x, int y, int [] d) {
x += d[0]; y += d[1];
return x >= 0 && y >= 0 && x < N && y < M && G[x][y];
}
boolean r(int [] d) {
return (d[0] == 0 && d[1] == 1);
}
int [] inner (int [] d) {
int s = K*d[0] + d[1];
if (s == 1)
return new int [] { 1, 0 };
if (s == K)
return new int [] { 0, -1 };
if (s == -1)
return new int [] { -1, 0 };
if (s == -K)
return new int [] { 0, 1 };
return null;
}
int [] outer (int [] d) {
int [] IN = inner(d);
return new int [] { -IN[0], -IN[1] };
}
////////////////////////////////////////////////////////////////////////////////////
static BufferedReader r;
static long t;
static void print2 (Object o) {
System.out.println(o);
}
static void print (Object o) {
print2(o);
//print2((millis() - t) / 1000.0);
System.exit(0);
}
static void run () throws IOException {
r = new BufferedReader(new InputStreamReader(System.in));
new D135();
}
public static void main(String[] args) throws IOException {
run();
}
static long millis() {
return System.currentTimeMillis();
}
} | Java | ["3 3\n111\n101\n111", "5 5\n01010\n10101\n01010\n10101\n01010", "7 7\n1111111\n1000101\n1000101\n1000101\n1000111\n1000001\n1111111", "5 5\n11111\n10001\n10101\n10001\n11111"] | 3 seconds | ["8", "0", "24", "0"] | NoteIn the first example there's only one cycle and it is cool.In the second sample there's no cycle at all.In the third sample there are two cool cycles: their lengths are 12 and 24.In the fourth sample there also is only one cycle but it isn't cool as there's a cell containing "1" inside this cycle. | Java 6 | standard input | [
"implementation",
"dfs and similar",
"brute force"
] | 26909af720a7b1fbd247e61af6054174 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns in the table, respectively. Each of the following n lines contains m characters. Each character can be either "0" or "1". | 2,500 | Print a single number — the length of the longest cool cycle in the table. If such cycles do not exist, print 0. | standard output | |
PASSED | 3d9a4e1600a0b87c048e7289c2974983 | train_004.jsonl | 1323443100 | Little Petya very much likes rectangular tables that consist of characters "0" and "1". Recently he has received one such table as a gift from his mother. The table contained n rows and m columns. The rows are numbered from top to bottom from 1 to n, the columns are numbered from the left to the right from 1 to m. Petya immediately decided to find the longest cool cycle whatever it takes.A cycle is a sequence of pairwise distinct cells where each two consecutive cells have a common side; besides, the first cell has a common side with the last cell. A cycle is called cool if it fulfills all the following conditions simultaneously: The cycle entirely consists of the cells that contain "1". Each cell that belongs to the cycle, has a common side with exactly two other cells that belong to the cycle. Each cell of the table that contains "1" either belongs to the cycle or is positioned outside of it (see definition below). To define the notion of "outside" formally, let's draw a cycle on a plane. Let each cell of the cycle (i, j) (i is the row number, j is the column number) correspond to the point (i, j) on the coordinate plane. Let a straight line segment join each pair of points that correspond to the cells belonging to the cycle and sharing a side. Thus, we will get a closed polyline that has no self-intersections and self-touches. The polyline divides the plane into two connected parts: the part of an infinite area and the part of a finite area. It is considered that cell (r, c) lies outside of the cycle if it does not belong to the cycle and the corresponding point on the plane with coordinates (r, c) lies in the part with the infinite area.Help Petya to find the length of the longest cool cycle in the table. The cycle length is defined as the number of cells that belong to the cycle. | 256 megabytes | import java.io.*;
import java.util.*;
public class D {
public D () throws IOException {
String input = r.readLine();
String [] NM = input.split(" ");
int N = Integer.parseInt(NM[0]);
int M = Integer.parseInt(NM[1]);
boolean [][] G = new boolean [N][M];
for (int i = 0; i < N; ++i) {
String row = r.readLine();
for (int j = 0; j < M; ++j)
G[i][j] = (row.charAt(j) == '1');
}
this.G = G;
this.N = N;
this.M = M;
solve();
}
int N, M;
boolean [][] G;
final static int K = 1000000;
public void solve () {
t = millis();
boolean [][] V = new boolean [N][M];
int res = 0;
for (int i = 0; i < N-1; ++i)
for (int j = 0; j < M-1; ++j) {
int i0 = i, j0 = j;
if (G[i][j] && !V[i][j]) {
List<Integer> path = new LinkedList<Integer>();
Set<Integer> points = new HashSet<Integer>();
int [] D = { 0, 1};
int z = i;
if (!next(i,j,D) || !next(i,j,inner(D))) {
V[i][j] = true;
continue;
}
else {
{
int p = K*i+j;
points.add(p);
path.add(p);
++j;
}
do {
int p = K*i+j;
path.add(p);
if (!points.add(p)) {
while (!path.get(0).equals(p))
points.remove(path.remove(0));
if (safeInt(path, points))
res = Math.max(res, path.size() - 1);
break;
}
int [] IN = inner(D), OUT = outer(D);
if (next(i,j,IN))
D = IN;
else if (!next(i,j,D))
D = OUT;
if (r(D))
V[i][j] = true;
if (next(i,j,D)) {
i += D[0];
j += D[1];
} else
break;
if (i < z)
break;
} while (true);
}
}
i = i0; j = j0;
}
print (res);
}
int [] decode (int n) {
return new int [] { n/K, n%K };
}
boolean safeInt(List<Integer> path, Set<Integer> points) {
if (path.size() == 4)
return true;
for (int p : path) {
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int c = 0;
if (points.contains(K*(x-1) + y))
++c;
if (points.contains(K*(x+1) + y))
++c;
if (points.contains(K*x + (y-1)))
++c;
if (points.contains(K*x + (y+1)))
++c;
if (c != 2)
return false;
}
int [] D = { 0, 1 };
Set<Integer> IP = new HashSet<Integer>();
Queue<Integer> Q = new LinkedList<Integer>();
int [] zero = decode(path.get(0));
int [] one = decode(path.get(1));
if (one[0] == zero[0] + 1 && one[1] == zero[0]) {
List<Integer> reverse = new LinkedList<Integer>();
for (int p : path)
reverse.add(0, p);
return safeInt(reverse, points);
}
for (int p : path) {
if (p == path.get(0))
continue;
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int [] IN = inner(D);
if (next(x,y,IN))
D = IN;
else {
if (!next(x,y,D))
D = outer(D);
x += IN[0]; y += IN[1];
if (x >= 0 && y >= 0 && x < N && y < M) {
int ip = K*x+y;
if (IP.add(ip))
Q.add(ip);
}
}
}
while (!Q.isEmpty()) {
int p = Q.poll();
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int nx, ny;
boolean t = true;
nx = x+1; ny = y;
t = t && test(nx, ny, points, IP, Q);
nx = x; ny = y+1;
t = t && test(nx, ny, points, IP, Q);
nx = x-1; ny = y;
t = t && test(nx, ny, points, IP, Q);
nx = x; ny = y-1;
t = t && test(nx, ny, points, IP, Q);
if (!t)
return false;
}
return true;
}
boolean test(int nx, int ny, Set<Integer> points, Set<Integer> IP, Queue<Integer> Q) {
int np = K*nx+ny;
if (nx >= 0 && ny >= 0 && nx < N && ny < M) {
if (!points.contains(np)) {
if (G[nx][ny])
return false;
if (IP.add(np))
Q.add(np);
}
}
return true;
}
boolean next (int x, int y, int [] d) {
x += d[0]; y += d[1];
return x >= 0 && y >= 0 && x < N && y < M && G[x][y];
}
boolean r(int [] d) {
return (d[0] == 0 && d[1] == 1);
}
int [] inner (int [] d) {
int s = K*d[0] + d[1];
if (s == 1)
return new int [] { 1, 0 };
if (s == K)
return new int [] { 0, -1 };
if (s == -1)
return new int [] { -1, 0 };
if (s == -K)
return new int [] { 0, 1 };
return null;
}
int [] outer (int [] d) {
int [] IN = inner(d);
return new int [] { -IN[0], -IN[1] };
}
////////////////////////////////////////////////////////////////////////////////////
static BufferedReader r;
static long t;
static void print2 (Object o) {
System.out.println(o);
}
static void print (Object o) {
print2(o);
//print2((millis() - t) / 1000.0);
System.exit(0);
}
static void run () throws IOException {
r = new BufferedReader(new InputStreamReader(System.in));
new D();
}
public static void main(String[] args) throws IOException {
run();
}
static long millis() {
return System.currentTimeMillis();
}
} | Java | ["3 3\n111\n101\n111", "5 5\n01010\n10101\n01010\n10101\n01010", "7 7\n1111111\n1000101\n1000101\n1000101\n1000111\n1000001\n1111111", "5 5\n11111\n10001\n10101\n10001\n11111"] | 3 seconds | ["8", "0", "24", "0"] | NoteIn the first example there's only one cycle and it is cool.In the second sample there's no cycle at all.In the third sample there are two cool cycles: their lengths are 12 and 24.In the fourth sample there also is only one cycle but it isn't cool as there's a cell containing "1" inside this cycle. | Java 6 | standard input | [
"implementation",
"dfs and similar",
"brute force"
] | 26909af720a7b1fbd247e61af6054174 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns in the table, respectively. Each of the following n lines contains m characters. Each character can be either "0" or "1". | 2,500 | Print a single number — the length of the longest cool cycle in the table. If such cycles do not exist, print 0. | standard output | |
PASSED | 525a1575154b1a46648387cfff753b05 | train_004.jsonl | 1323443100 | Little Petya very much likes rectangular tables that consist of characters "0" and "1". Recently he has received one such table as a gift from his mother. The table contained n rows and m columns. The rows are numbered from top to bottom from 1 to n, the columns are numbered from the left to the right from 1 to m. Petya immediately decided to find the longest cool cycle whatever it takes.A cycle is a sequence of pairwise distinct cells where each two consecutive cells have a common side; besides, the first cell has a common side with the last cell. A cycle is called cool if it fulfills all the following conditions simultaneously: The cycle entirely consists of the cells that contain "1". Each cell that belongs to the cycle, has a common side with exactly two other cells that belong to the cycle. Each cell of the table that contains "1" either belongs to the cycle or is positioned outside of it (see definition below). To define the notion of "outside" formally, let's draw a cycle on a plane. Let each cell of the cycle (i, j) (i is the row number, j is the column number) correspond to the point (i, j) on the coordinate plane. Let a straight line segment join each pair of points that correspond to the cells belonging to the cycle and sharing a side. Thus, we will get a closed polyline that has no self-intersections and self-touches. The polyline divides the plane into two connected parts: the part of an infinite area and the part of a finite area. It is considered that cell (r, c) lies outside of the cycle if it does not belong to the cycle and the corresponding point on the plane with coordinates (r, c) lies in the part with the infinite area.Help Petya to find the length of the longest cool cycle in the table. The cycle length is defined as the number of cells that belong to the cycle. | 256 megabytes | import java.io.*;
import java.util.*;
public class D135 {
public D135 () throws IOException {
String input = r.readLine();
String [] NM = input.split(" ");
int N = Integer.parseInt(NM[0]);
int M = Integer.parseInt(NM[1]);
boolean [][] G = new boolean [N][M];
for (int i = 0; i < N; ++i) {
String row = r.readLine();
for (int j = 0; j < M; ++j)
G[i][j] = (row.charAt(j) == '1');
}
this.G = G;
this.N = N;
this.M = M;
solve();
}
int N, M;
boolean [][] G;
public void solve () {
t = millis();
boolean [][] V = new boolean [N][M];
int res = 0;
for (int i = 0; i < N-1; ++i)
for (int j = 0; j < M-1; ++j) {
int i0 = i, j0 = j;
if (G[i][j] && !V[i][j]) {
// if (G[i][j+1] && G[i+1][j+1] && G[i+1][j]) {
// res = Math.max(res, 4);
// continue;
// }
List<Integer> path = new LinkedList<Integer>();
Set<Integer> points = new HashSet<Integer>();
int [] D = { 0, 1};
int z = i;
if (!next(i,j,D) || !next(i,j,inner(D))) {
V[i][j] = true;
continue;
}
else {
{
int p = 10000*i + j;
points.add(p);
path.add(p);
++j;
}
do {
int p = 10000*i+j;
path.add(p);
if (!points.add(p)) {
while (!path.get(0).equals(p))
points.remove(path.remove(0));
if (safeInt(path, points))
res = Math.max(res, path.size() - 1);
break;
}
int [] IN = inner(D), OUT = outer(D);
if (next(i,j,IN))
D = IN;
else if (!next(i,j,D))
D = OUT;
if (r(D))
V[i][j] = true;
if (next(i,j,D)) {
i += D[0];
j += D[1];
} else
break;
if (i < z)
break;
} while (true);
}
}
i = i0; j = j0;
}
print (res);
}
int [] decode (int s) {
return new int [] { s/10000, s%10000 };
}
boolean safeInt(List<Integer> path, Set<Integer> points) {
if (path.size() == 4)
return true;
for (int p : path) {
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int c = 0;
if (points.contains(10000*(x-1)+y))
++c;
if (points.contains(10000*(x+1) + y))
++c;
if (points.contains(10000*x + (y-1)))
++c;
if (points.contains(10000*x + (y+1)))
++c;
if (c != 2)
return false;
}
int [] D = { 0, 1 };
Set<Integer> IP = new HashSet<Integer>();
Queue<Integer> Q = new LinkedList<Integer>();
int [] zero = decode(path.get(0));
int [] one = decode(path.get(1));
if (one[0] == zero[0] + 1 && one[1] == zero[0]) {
List<Integer> reverse = new LinkedList<Integer>();
for (int p : path)
reverse.add(0, p);
return safeInt(reverse, points);
}
for (int p : path) {
if (p == path.get(0))
continue;
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int [] IN = inner(D);
if (next(x,y,IN))
D = IN;
else {
if (!next(x,y,D))
D = outer(D);
x += IN[0]; y += IN[1];
if (x >= 0 && y >= 0 && x < N && y < M) {
int ip = 10000*x + y;
if (IP.add(ip))
Q.add(ip);
}
}
}
while (!Q.isEmpty()) {
int p = Q.poll();
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int nx, ny;
boolean t = true;
nx = x+1; ny = y;
t = t && test(nx, ny, points, IP, Q);
nx = x; ny = y+1;
t = t && test(nx, ny, points, IP, Q);
nx = x-1; ny = y;
t = t && test(nx, ny, points, IP, Q);
nx = x; ny = y-1;
t = t && test(nx, ny, points, IP, Q);
if (!t)
return false;
}
return true;
}
boolean test(int nx, int ny, Set<Integer> points, Set<Integer> IP, Queue<Integer> Q) {
int np = 10000*nx + ny;
if (nx >= 0 && ny >= 0 && nx < N && ny < M) {
if (!points.contains(np)) {
if (G[nx][ny])
return false;
if (IP.add(np))
Q.add(np);
}
}
return true;
}
boolean next (int x, int y, int [] d) {
x += d[0]; y += d[1];
return x >= 0 && y >= 0 && x < N && y < M && G[x][y];
}
boolean r(int [] d) {
return d[0] == 0 && d[1] == 1;
}
int [] inner (int [] d) {
int s = 10000*d[0] + d[1];
if (s == 1)
return new int [] { 1, 0 };
if (s == 10000)
return new int [] { 0, -1 };
if (s == -1)
return new int [] { -1, 0 };
if (s == -10000)
return new int [] { 0, 1 };
return null;
}
int [] outer (int [] d) {
int [] IN = inner(d);
return new int [] { -IN[0], -IN[1] };
}
////////////////////////////////////////////////////////////////////////////////////
static BufferedReader r;
static long t;
static void print2 (Object o) {
System.out.println(o);
}
static void print (Object o) {
print2(o);
//print2((millis() - t) / 1000.0);
System.exit(0);
}
static void run () throws IOException {
r = new BufferedReader(new InputStreamReader(System.in));
new D135();
}
public static void main(String[] args) throws IOException {
run();
}
static long millis() {
return System.currentTimeMillis();
}
}
| Java | ["3 3\n111\n101\n111", "5 5\n01010\n10101\n01010\n10101\n01010", "7 7\n1111111\n1000101\n1000101\n1000101\n1000111\n1000001\n1111111", "5 5\n11111\n10001\n10101\n10001\n11111"] | 3 seconds | ["8", "0", "24", "0"] | NoteIn the first example there's only one cycle and it is cool.In the second sample there's no cycle at all.In the third sample there are two cool cycles: their lengths are 12 and 24.In the fourth sample there also is only one cycle but it isn't cool as there's a cell containing "1" inside this cycle. | Java 6 | standard input | [
"implementation",
"dfs and similar",
"brute force"
] | 26909af720a7b1fbd247e61af6054174 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns in the table, respectively. Each of the following n lines contains m characters. Each character can be either "0" or "1". | 2,500 | Print a single number — the length of the longest cool cycle in the table. If such cycles do not exist, print 0. | standard output | |
PASSED | 364566a90488c92030bac88e149c28bc | train_004.jsonl | 1323443100 | Little Petya very much likes rectangular tables that consist of characters "0" and "1". Recently he has received one such table as a gift from his mother. The table contained n rows and m columns. The rows are numbered from top to bottom from 1 to n, the columns are numbered from the left to the right from 1 to m. Petya immediately decided to find the longest cool cycle whatever it takes.A cycle is a sequence of pairwise distinct cells where each two consecutive cells have a common side; besides, the first cell has a common side with the last cell. A cycle is called cool if it fulfills all the following conditions simultaneously: The cycle entirely consists of the cells that contain "1". Each cell that belongs to the cycle, has a common side with exactly two other cells that belong to the cycle. Each cell of the table that contains "1" either belongs to the cycle or is positioned outside of it (see definition below). To define the notion of "outside" formally, let's draw a cycle on a plane. Let each cell of the cycle (i, j) (i is the row number, j is the column number) correspond to the point (i, j) on the coordinate plane. Let a straight line segment join each pair of points that correspond to the cells belonging to the cycle and sharing a side. Thus, we will get a closed polyline that has no self-intersections and self-touches. The polyline divides the plane into two connected parts: the part of an infinite area and the part of a finite area. It is considered that cell (r, c) lies outside of the cycle if it does not belong to the cycle and the corresponding point on the plane with coordinates (r, c) lies in the part with the infinite area.Help Petya to find the length of the longest cool cycle in the table. The cycle length is defined as the number of cells that belong to the cycle. | 256 megabytes | import java.io.*;
import java.util.*;
public class D135 {
public D135 () throws IOException {
String input = r.readLine();
String [] NM = input.split(" ");
int N = Integer.parseInt(NM[0]);
int M = Integer.parseInt(NM[1]);
boolean [][] G = new boolean [N][M];
for (int i = 0; i < N; ++i) {
String row = r.readLine();
for (int j = 0; j < M; ++j)
G[i][j] = (row.charAt(j) == '1');
}
this.G = G;
this.N = N;
this.M = M;
solve();
}
int N, M;
boolean [][] G;
int res;
final static int K = 1000000;
public void solve () {
t = millis();
boolean [][] V = new boolean [N][M];
res = 0;
for (int i = 0; i < N-1; ++i)
for (int j = 0; j < M-1; ++j) {
int i0 = i, j0 = j;
if (G[i][j] && !V[i][j]) {
if (G[i][j+1] && G[i+1][j+1] && G[i+1][j]) {
if (res < 4) res = 4;
continue;
}
List<Integer> path = new LinkedList<Integer>();
Set<Integer> points = new HashSet<Integer>();
int [] D = { 0, 1};
int z = i;
if (!next(i,j,D) || !next(i,j,inner(D))) {
V[i][j] = true;
continue;
}
else {
{
int p = K*i+j;
points.add(p);
path.add(p);
++j;
}
do {
int p = K*i+j;
path.add(p);
if (!points.add(p)) {
while (!path.get(0).equals(p))
points.remove(path.remove(0));
if (safeInt(path, points))
res = Math.max(res, path.size() - 1);
break;
}
int [] IN = inner(D), OUT = outer(D);
if (next(i,j,IN))
D = IN;
else if (!next(i,j,D))
D = OUT;
if (r(D))
V[i][j] = true;
if (next(i,j,D)) {
i += D[0];
j += D[1];
} else
break;
if (i < z)
break;
} while (true);
}
}
i = i0; j = j0;
}
print (res);
}
int [] decode (int n) {
return new int [] { n/K, n%K };
}
boolean safeInt(List<Integer> path, Set<Integer> points) {
if (path.size() <= res)
return false;
if (path.size() == 4)
return true;
for (int p : path) {
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int c = 0;
if (points.contains(K*(x-1) + y))
++c;
if (points.contains(K*(x+1) + y))
++c;
if (points.contains(K*x + (y-1)))
++c;
if (points.contains(K*x + (y+1)))
++c;
if (c != 2)
return false;
}
int [] D = { 0, 1 };
Set<Integer> IP = new HashSet<Integer>();
Queue<Integer> Q = new LinkedList<Integer>();
for (int p : path) {
if (p == path.get(0))
continue;
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int [] IN = inner(D);
if (next(x,y,IN))
D = IN;
else {
if (!next(x,y,D))
D = outer(D);
x += IN[0]; y += IN[1];
if (x >= 0 && y >= 0 && x < N && y < M) {
int ip = K*x+y;
if (IP.add(ip))
Q.add(ip);
}
}
}
while (!Q.isEmpty()) {
int p = Q.poll();
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int nx, ny;
boolean t = true;
nx = x+1; ny = y;
t = t && test(nx, ny, points, IP, Q);
nx = x; ny = y+1;
t = t && test(nx, ny, points, IP, Q);
nx = x-1; ny = y;
t = t && test(nx, ny, points, IP, Q);
nx = x; ny = y-1;
t = t && test(nx, ny, points, IP, Q);
if (!t)
return false;
}
return true;
}
boolean test(int nx, int ny, Set<Integer> points, Set<Integer> IP, Queue<Integer> Q) {
int np = K*nx+ny;
if (nx >= 0 && ny >= 0 && nx < N && ny < M) {
if (!points.contains(np)) {
if (G[nx][ny])
return false;
if (IP.add(np))
Q.add(np);
}
}
return true;
}
boolean next (int x, int y, int [] d) {
x += d[0]; y += d[1];
return x >= 0 && y >= 0 && x < N && y < M && G[x][y];
}
boolean r(int [] d) {
return (d[0] == 0 && d[1] == 1);
}
int [] inner (int [] d) {
int s = K*d[0] + d[1];
if (s == 1)
return new int [] { 1, 0 };
if (s == K)
return new int [] { 0, -1 };
if (s == -1)
return new int [] { -1, 0 };
if (s == -K)
return new int [] { 0, 1 };
return null;
}
int [] outer (int [] d) {
int [] IN = inner(d);
return new int [] { -IN[0], -IN[1] };
}
////////////////////////////////////////////////////////////////////////////////////
static BufferedReader r;
static long t;
static void print2 (Object o) {
System.out.println(o);
}
static void print (Object o) {
print2(o);
//print2((millis() - t) / 1000.0);
System.exit(0);
}
static void run () throws IOException {
r = new BufferedReader(new InputStreamReader(System.in));
new D135();
}
public static void main(String[] args) throws IOException {
run();
}
static long millis() {
return System.currentTimeMillis();
}
} | Java | ["3 3\n111\n101\n111", "5 5\n01010\n10101\n01010\n10101\n01010", "7 7\n1111111\n1000101\n1000101\n1000101\n1000111\n1000001\n1111111", "5 5\n11111\n10001\n10101\n10001\n11111"] | 3 seconds | ["8", "0", "24", "0"] | NoteIn the first example there's only one cycle and it is cool.In the second sample there's no cycle at all.In the third sample there are two cool cycles: their lengths are 12 and 24.In the fourth sample there also is only one cycle but it isn't cool as there's a cell containing "1" inside this cycle. | Java 6 | standard input | [
"implementation",
"dfs and similar",
"brute force"
] | 26909af720a7b1fbd247e61af6054174 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns in the table, respectively. Each of the following n lines contains m characters. Each character can be either "0" or "1". | 2,500 | Print a single number — the length of the longest cool cycle in the table. If such cycles do not exist, print 0. | standard output | |
PASSED | abb96665cd3d0e104df2c6f1cfe91ec2 | train_004.jsonl | 1323443100 | Little Petya very much likes rectangular tables that consist of characters "0" and "1". Recently he has received one such table as a gift from his mother. The table contained n rows and m columns. The rows are numbered from top to bottom from 1 to n, the columns are numbered from the left to the right from 1 to m. Petya immediately decided to find the longest cool cycle whatever it takes.A cycle is a sequence of pairwise distinct cells where each two consecutive cells have a common side; besides, the first cell has a common side with the last cell. A cycle is called cool if it fulfills all the following conditions simultaneously: The cycle entirely consists of the cells that contain "1". Each cell that belongs to the cycle, has a common side with exactly two other cells that belong to the cycle. Each cell of the table that contains "1" either belongs to the cycle or is positioned outside of it (see definition below). To define the notion of "outside" formally, let's draw a cycle on a plane. Let each cell of the cycle (i, j) (i is the row number, j is the column number) correspond to the point (i, j) on the coordinate plane. Let a straight line segment join each pair of points that correspond to the cells belonging to the cycle and sharing a side. Thus, we will get a closed polyline that has no self-intersections and self-touches. The polyline divides the plane into two connected parts: the part of an infinite area and the part of a finite area. It is considered that cell (r, c) lies outside of the cycle if it does not belong to the cycle and the corresponding point on the plane with coordinates (r, c) lies in the part with the infinite area.Help Petya to find the length of the longest cool cycle in the table. The cycle length is defined as the number of cells that belong to the cycle. | 256 megabytes | import java.io.*;
import java.util.*;
public class D135 {
public D135 () throws IOException {
final String input = r.readLine();
final String [] NM = input.split(" ");
final int N = Integer.parseInt(NM[0]);
final int M = Integer.parseInt(NM[1]);
final boolean [][] G = new boolean [N][M];
for (int i = 0; i < N; ++i) {
final String row = r.readLine();
for (int j = 0; j < M; ++j)
G[i][j] = (row.charAt(j) == '1');
}
this.G = G;
this.N = N;
this.M = M;
solve();
}
final int N, M;
final boolean [][] G;
int res;
final static int K = 1000000;
final public void solve () {
t = millis();
final boolean [][] V = new boolean [N][M];
res = 0;
for (int i = 0; i < N-1; ++i)
for (int j = 0; j < M-1; ++j) {
final int i0 = i, j0 = j;
if (G[i][j] && !V[i][j]) {
if (G[i][j+1] && G[i+1][j+1] && G[i+1][j]) {
if (res < 4) res = 4;
continue;
}
final List<Integer> path = new LinkedList<Integer>();
final Set<Integer> points = new HashSet<Integer>();
int [] D = { 0, 1};
final int z = i;
if (!next(i,j,D) || !next(i,j,inner(D))) {
V[i][j] = true;
continue;
}
else {
{
final int p = K*i+j;
points.add(p);
path.add(p);
++j;
}
do {
final int p = K*i+j;
path.add(p);
if (!points.add(p)) {
while (!path.get(0).equals(p))
points.remove(path.remove(0));
if (safeInt(path, points))
res = Math.max(res, path.size() - 1);
break;
}
final int [] IN = inner(D), OUT = outer(D);
if (next(i,j,IN))
D = IN;
else if (!next(i,j,D))
D = OUT;
if (r(D))
V[i][j] = true;
if (next(i,j,D)) {
i += D[0];
j += D[1];
} else
break;
if (i < z)
break;
} while (true);
}
}
i = i0; j = j0;
}
print (res);
}
final int [] decode (final int n) {
return new int [] { n/K, n%K };
}
final boolean safeInt(final List<Integer> path, final Set<Integer> points) {
if (path.size() <= res+1)
return false;
if (path.size() == 5)
return true;
for (final int p : path) {
final int [] xy = decode(p);
final int x = xy[0], y = xy[1];
int c = 0;
if (points.contains(K*(x-1) + y))
++c;
if (points.contains(K*(x+1) + y))
++c;
if (points.contains(K*x + (y-1)))
++c;
if (points.contains(K*x + (y+1)))
++c;
if (c != 2)
return false;
}
int [] D = { 0, 1 };
final Set<Integer> IP = new HashSet<Integer>();
final Queue<Integer> Q = new LinkedList<Integer>();
for (final int p : path) {
if (p == path.get(0))
continue;
final int [] xy = decode(p);
int x = xy[0], y = xy[1];
final int [] IN = inner(D);
if (next(x,y,IN))
D = IN;
else {
if (!next(x,y,D))
D = outer(D);
x += IN[0]; y += IN[1];
if (x >= 0 && y >= 0 && x < N && y < M) {
final int ip = K*x+y;
if (IP.add(ip))
Q.add(ip);
}
}
}
while (!Q.isEmpty()) {
final int p = Q.poll();
final int [] xy = decode(p);
final int x = xy[0], y = xy[1];
int nx, ny;
boolean t = true;
nx = x+1; ny = y;
t = t && test(nx, ny, points, IP, Q);
nx = x; ny = y+1;
t = t && test(nx, ny, points, IP, Q);
nx = x-1; ny = y;
t = t && test(nx, ny, points, IP, Q);
nx = x; ny = y-1;
t = t && test(nx, ny, points, IP, Q);
if (!t)
return false;
}
return true;
}
final boolean test(final int nx, final int ny, final Set<Integer> points, final Set<Integer> IP, final Queue<Integer> Q) {
final int np = K*nx+ny;
if (nx >= 0 && ny >= 0 && nx < N && ny < M) {
if (!points.contains(np)) {
if (G[nx][ny])
return false;
if (IP.add(np))
Q.add(np);
}
}
return true;
}
final boolean next (int x, int y, final int [] d) {
x += d[0]; y += d[1];
return x >= 0 && y >= 0 && x < N && y < M && G[x][y];
}
final boolean r(int [] d) {
return (d[0] == 0 && d[1] == 1);
}
final int [] inner (final int [] d) {
int s = K*d[0] + d[1];
if (s == 1)
return new int [] { 1, 0 };
if (s == K)
return new int [] { 0, -1 };
if (s == -1)
return new int [] { -1, 0 };
if (s == -K)
return new int [] { 0, 1 };
return null;
}
final int [] outer (final int [] d) {
final int [] IN = inner(d);
return new int [] { -IN[0], -IN[1] };
}
////////////////////////////////////////////////////////////////////////////////////
static BufferedReader r;
static long t;
static void print2 (Object o) {
System.out.println(o);
}
static void print (Object o) {
print2(o);
//print2((millis() - t) / 1000.0);
System.exit(0);
}
static void run () throws IOException {
r = new BufferedReader(new InputStreamReader(System.in));
new D135();
}
public static void main(String[] args) throws IOException {
run();
}
static long millis() {
return System.currentTimeMillis();
}
} | Java | ["3 3\n111\n101\n111", "5 5\n01010\n10101\n01010\n10101\n01010", "7 7\n1111111\n1000101\n1000101\n1000101\n1000111\n1000001\n1111111", "5 5\n11111\n10001\n10101\n10001\n11111"] | 3 seconds | ["8", "0", "24", "0"] | NoteIn the first example there's only one cycle and it is cool.In the second sample there's no cycle at all.In the third sample there are two cool cycles: their lengths are 12 and 24.In the fourth sample there also is only one cycle but it isn't cool as there's a cell containing "1" inside this cycle. | Java 6 | standard input | [
"implementation",
"dfs and similar",
"brute force"
] | 26909af720a7b1fbd247e61af6054174 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns in the table, respectively. Each of the following n lines contains m characters. Each character can be either "0" or "1". | 2,500 | Print a single number — the length of the longest cool cycle in the table. If such cycles do not exist, print 0. | standard output | |
PASSED | 4ffbc3568153ed49cbb6d73098de5781 | train_004.jsonl | 1323443100 | Little Petya very much likes rectangular tables that consist of characters "0" and "1". Recently he has received one such table as a gift from his mother. The table contained n rows and m columns. The rows are numbered from top to bottom from 1 to n, the columns are numbered from the left to the right from 1 to m. Petya immediately decided to find the longest cool cycle whatever it takes.A cycle is a sequence of pairwise distinct cells where each two consecutive cells have a common side; besides, the first cell has a common side with the last cell. A cycle is called cool if it fulfills all the following conditions simultaneously: The cycle entirely consists of the cells that contain "1". Each cell that belongs to the cycle, has a common side with exactly two other cells that belong to the cycle. Each cell of the table that contains "1" either belongs to the cycle or is positioned outside of it (see definition below). To define the notion of "outside" formally, let's draw a cycle on a plane. Let each cell of the cycle (i, j) (i is the row number, j is the column number) correspond to the point (i, j) on the coordinate plane. Let a straight line segment join each pair of points that correspond to the cells belonging to the cycle and sharing a side. Thus, we will get a closed polyline that has no self-intersections and self-touches. The polyline divides the plane into two connected parts: the part of an infinite area and the part of a finite area. It is considered that cell (r, c) lies outside of the cycle if it does not belong to the cycle and the corresponding point on the plane with coordinates (r, c) lies in the part with the infinite area.Help Petya to find the length of the longest cool cycle in the table. The cycle length is defined as the number of cells that belong to the cycle. | 256 megabytes | import java.io.*;
import java.util.*;
public class D135 {
public D135 () throws IOException {
String input = r.readLine();
String [] NM = input.split(" ");
int N = Integer.parseInt(NM[0]);
int M = Integer.parseInt(NM[1]);
boolean [][] G = new boolean [N][M];
for (int i = 0; i < N; ++i) {
String row = r.readLine();
for (int j = 0; j < M; ++j)
G[i][j] = (row.charAt(j) == '1');
}
this.G = G;
this.N = N;
this.M = M;
solve();
}
int N, M;
boolean [][] G;
int res;
final static int K = 1000000;
public void solve () {
t = millis();
boolean [][] V = new boolean [N][M];
res = 0;
for (int i = 0; i < N-1; ++i)
for (int j = 0; j < M-1; ++j) {
int i0 = i, j0 = j;
if (G[i][j] && !V[i][j]) {
if (G[i][j+1] && G[i+1][j+1] && G[i+1][j]) {
if (res < 4) res = 4;
continue;
}
List<Integer> path = new LinkedList<Integer>();
Set<Integer> points = new HashSet<Integer>();
int [] D = { 0, 1};
int z = i;
if (!next(i,j,D) || !next(i,j,inner(D))) {
V[i][j] = true;
continue;
}
else {
{
int p = K*i+j;
points.add(p);
path.add(p);
++j;
}
do {
int p = K*i+j;
path.add(p);
if (!points.add(p)) {
while (!path.get(0).equals(p))
points.remove(path.remove(0));
if (safeInt(path, points))
res = Math.max(res, path.size() - 1);
break;
}
int [] IN = inner(D), OUT = outer(D);
if (next(i,j,IN))
D = IN;
else if (!next(i,j,D))
D = OUT;
if (r(D))
V[i][j] = true;
if (next(i,j,D)) {
i += D[0];
j += D[1];
} else
break;
if (i < z)
break;
} while (true);
}
}
i = i0; j = j0;
}
print (res);
}
int [] decode (int n) {
return new int [] { n/K, n%K };
}
boolean safeInt(List<Integer> path, Set<Integer> points) {
// if (path.size() <= res+1)
// return false;
if (path.size() == 5)
return true;
for (int p : path) {
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int c = 0;
if (points.contains(K*(x-1) + y))
++c;
if (points.contains(K*(x+1) + y))
++c;
if (points.contains(K*x + (y-1)))
++c;
if (points.contains(K*x + (y+1)))
++c;
if (c != 2)
return false;
}
int [] D = { 0, 1 };
Set<Integer> IP = new HashSet<Integer>();
Queue<Integer> Q = new LinkedList<Integer>();
for (int p : path) {
if (p == path.get(0))
continue;
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int [] IN = inner(D);
if (next(x,y,IN))
D = IN;
else {
if (!next(x,y,D))
D = outer(D);
x += IN[0]; y += IN[1];
if (x >= 0 && y >= 0 && x < N && y < M) {
int ip = K*x+y;
if (IP.add(ip))
Q.add(ip);
}
}
}
while (!Q.isEmpty()) {
int p = Q.poll();
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int nx, ny;
boolean t = true;
nx = x+1; ny = y;
t = t && test(nx, ny, points, IP, Q);
nx = x; ny = y+1;
t = t && test(nx, ny, points, IP, Q);
nx = x-1; ny = y;
t = t && test(nx, ny, points, IP, Q);
nx = x; ny = y-1;
t = t && test(nx, ny, points, IP, Q);
if (!t)
return false;
}
return true;
}
boolean test(int nx, int ny, Set<Integer> points, Set<Integer> IP, Queue<Integer> Q) {
int np = K*nx+ny;
if (nx >= 0 && ny >= 0 && nx < N && ny < M) {
if (!points.contains(np)) {
if (G[nx][ny])
return false;
if (IP.add(np))
Q.add(np);
}
}
return true;
}
boolean next (int x, int y, int [] d) {
x += d[0]; y += d[1];
return x >= 0 && y >= 0 && x < N && y < M && G[x][y];
}
boolean r(int [] d) {
return (d[0] == 0 && d[1] == 1);
}
int [] inner (int [] d) {
int s = K*d[0] + d[1];
if (s == 1)
return new int [] { 1, 0 };
if (s == K)
return new int [] { 0, -1 };
if (s == -1)
return new int [] { -1, 0 };
if (s == -K)
return new int [] { 0, 1 };
return null;
}
int [] outer (int [] d) {
int [] IN = inner(d);
return new int [] { -IN[0], -IN[1] };
}
////////////////////////////////////////////////////////////////////////////////////
static BufferedReader r;
static long t;
static void print2 (Object o) {
System.out.println(o);
}
static void print (Object o) {
print2(o);
//print2((millis() - t) / 1000.0);
System.exit(0);
}
static void run () throws IOException {
r = new BufferedReader(new InputStreamReader(System.in));
new D135();
}
public static void main(String[] args) throws IOException {
run();
}
static long millis() {
return System.currentTimeMillis();
}
} | Java | ["3 3\n111\n101\n111", "5 5\n01010\n10101\n01010\n10101\n01010", "7 7\n1111111\n1000101\n1000101\n1000101\n1000111\n1000001\n1111111", "5 5\n11111\n10001\n10101\n10001\n11111"] | 3 seconds | ["8", "0", "24", "0"] | NoteIn the first example there's only one cycle and it is cool.In the second sample there's no cycle at all.In the third sample there are two cool cycles: their lengths are 12 and 24.In the fourth sample there also is only one cycle but it isn't cool as there's a cell containing "1" inside this cycle. | Java 6 | standard input | [
"implementation",
"dfs and similar",
"brute force"
] | 26909af720a7b1fbd247e61af6054174 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns in the table, respectively. Each of the following n lines contains m characters. Each character can be either "0" or "1". | 2,500 | Print a single number — the length of the longest cool cycle in the table. If such cycles do not exist, print 0. | standard output | |
PASSED | 706d14ac92630ccf6c77d7d7c0a5264d | train_004.jsonl | 1323443100 | Little Petya very much likes rectangular tables that consist of characters "0" and "1". Recently he has received one such table as a gift from his mother. The table contained n rows and m columns. The rows are numbered from top to bottom from 1 to n, the columns are numbered from the left to the right from 1 to m. Petya immediately decided to find the longest cool cycle whatever it takes.A cycle is a sequence of pairwise distinct cells where each two consecutive cells have a common side; besides, the first cell has a common side with the last cell. A cycle is called cool if it fulfills all the following conditions simultaneously: The cycle entirely consists of the cells that contain "1". Each cell that belongs to the cycle, has a common side with exactly two other cells that belong to the cycle. Each cell of the table that contains "1" either belongs to the cycle or is positioned outside of it (see definition below). To define the notion of "outside" formally, let's draw a cycle on a plane. Let each cell of the cycle (i, j) (i is the row number, j is the column number) correspond to the point (i, j) on the coordinate plane. Let a straight line segment join each pair of points that correspond to the cells belonging to the cycle and sharing a side. Thus, we will get a closed polyline that has no self-intersections and self-touches. The polyline divides the plane into two connected parts: the part of an infinite area and the part of a finite area. It is considered that cell (r, c) lies outside of the cycle if it does not belong to the cycle and the corresponding point on the plane with coordinates (r, c) lies in the part with the infinite area.Help Petya to find the length of the longest cool cycle in the table. The cycle length is defined as the number of cells that belong to the cycle. | 256 megabytes | import java.io.*;
import java.util.*;
public class D135 {
public D135 () throws IOException {
String input = r.readLine();
String [] NM = input.split(" ");
int N = Integer.parseInt(NM[0]);
int M = Integer.parseInt(NM[1]);
boolean [][] G = new boolean [N][M];
for (int i = 0; i < N; ++i) {
String row = r.readLine();
for (int j = 0; j < M; ++j)
G[i][j] = (row.charAt(j) == '1');
}
this.G = G;
this.N = N;
this.M = M;
solve();
}
int N, M;
boolean [][] G;
int res;
final static int K = 1000000;
public void solve () {
t = millis();
boolean [][] V = new boolean [N][M];
res = 0;
for (int i = 0; i < N-1; ++i)
for (int j = 0; j < M-1; ++j) {
int i0 = i, j0 = j;
if (G[i][j] && !V[i][j]) {
if (G[i][j+1] && G[i+1][j+1] && G[i+1][j]) {
if (res < 4) res = 4;
continue;
}
List<Integer> path = new LinkedList<Integer>();
Set<Integer> points = new HashSet<Integer>();
int [] D = { 0, 1};
int z = i;
if (!next(i,j,D) || !next(i,j,inner(D))) {
V[i][j] = true;
continue;
}
else {
{
int p = K*i+j;
points.add(p);
path.add(p);
++j;
}
do {
int p = K*i+j;
path.add(p);
if (!points.add(p)) {
while (!path.get(0).equals(p))
points.remove(path.remove(0));
if (safeInt(path, points))
res = Math.max(res, path.size() - 1);
break;
}
int [] IN = inner(D), OUT = outer(D);
if (next(i,j,IN))
D = IN;
else if (!next(i,j,D))
D = OUT;
if (r(D))
V[i][j] = true;
if (next(i,j,D)) {
i += D[0];
j += D[1];
} else
break;
if (i < z)
break;
} while (true);
}
}
i = i0; j = j0;
}
print (res);
}
int [] decode (int n) {
return new int [] { n/K, n%K };
}
boolean safeInt(List<Integer> path, Set<Integer> points) {
// if (path.size() <= res+1)
// return false;
if (path.size() == 5)
return true;
int [] zero = decode(path.get(0));
int [] one = decode(path.get(1));
if (one[0] == zero[0] + 1 && one[1] == zero[0]) {
List<Integer> reverse = new LinkedList<Integer>();
for (int p : path)
reverse.add(0, p);
return safeInt(reverse, points);
}
for (int p : path) {
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int c = 0;
if (points.contains(K*(x-1) + y))
++c;
if (points.contains(K*(x+1) + y))
++c;
if (points.contains(K*x + (y-1)))
++c;
if (points.contains(K*x + (y+1)))
++c;
if (c != 2)
return false;
}
int [] D = { 0, 1 };
Set<Integer> IP = new HashSet<Integer>();
Queue<Integer> Q = new LinkedList<Integer>();
for (int p : path) {
if (p == path.get(0))
continue;
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int [] IN = inner(D);
if (next(x,y,IN))
D = IN;
else {
if (!next(x,y,D))
D = outer(D);
x += IN[0]; y += IN[1];
if (x >= 0 && y >= 0 && x < N && y < M) {
int ip = K*x+y;
if (IP.add(ip))
Q.add(ip);
}
}
}
while (!Q.isEmpty()) {
int p = Q.poll();
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int nx, ny;
boolean t = true;
nx = x+1; ny = y;
t = t && test(nx, ny, points, IP, Q);
nx = x; ny = y+1;
t = t && test(nx, ny, points, IP, Q);
nx = x-1; ny = y;
t = t && test(nx, ny, points, IP, Q);
nx = x; ny = y-1;
t = t && test(nx, ny, points, IP, Q);
if (!t)
return false;
}
return true;
}
boolean test(int nx, int ny, Set<Integer> points, Set<Integer> IP, Queue<Integer> Q) {
int np = K*nx+ny;
if (nx >= 0 && ny >= 0 && nx < N && ny < M) {
if (!points.contains(np)) {
if (G[nx][ny])
return false;
if (IP.add(np))
Q.add(np);
}
}
return true;
}
boolean next (int x, int y, int [] d) {
x += d[0]; y += d[1];
return x >= 0 && y >= 0 && x < N && y < M && G[x][y];
}
boolean r(int [] d) {
return (d[0] == 0 && d[1] == 1);
}
int [] inner (int [] d) {
int s = K*d[0] + d[1];
if (s == 1)
return new int [] { 1, 0 };
if (s == K)
return new int [] { 0, -1 };
if (s == -1)
return new int [] { -1, 0 };
if (s == -K)
return new int [] { 0, 1 };
return null;
}
int [] outer (int [] d) {
int [] IN = inner(d);
return new int [] { -IN[0], -IN[1] };
}
////////////////////////////////////////////////////////////////////////////////////
static BufferedReader r;
static long t;
static void print2 (Object o) {
System.out.println(o);
}
static void print (Object o) {
print2(o);
//print2((millis() - t) / 1000.0);
System.exit(0);
}
static void run () throws IOException {
r = new BufferedReader(new InputStreamReader(System.in));
new D135();
}
public static void main(String[] args) throws IOException {
run();
}
static long millis() {
return System.currentTimeMillis();
}
} | Java | ["3 3\n111\n101\n111", "5 5\n01010\n10101\n01010\n10101\n01010", "7 7\n1111111\n1000101\n1000101\n1000101\n1000111\n1000001\n1111111", "5 5\n11111\n10001\n10101\n10001\n11111"] | 3 seconds | ["8", "0", "24", "0"] | NoteIn the first example there's only one cycle and it is cool.In the second sample there's no cycle at all.In the third sample there are two cool cycles: their lengths are 12 and 24.In the fourth sample there also is only one cycle but it isn't cool as there's a cell containing "1" inside this cycle. | Java 6 | standard input | [
"implementation",
"dfs and similar",
"brute force"
] | 26909af720a7b1fbd247e61af6054174 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns in the table, respectively. Each of the following n lines contains m characters. Each character can be either "0" or "1". | 2,500 | Print a single number — the length of the longest cool cycle in the table. If such cycles do not exist, print 0. | standard output | |
PASSED | c2d09d9b45b38f835ca18be200aa6cac | train_004.jsonl | 1323443100 | Little Petya very much likes rectangular tables that consist of characters "0" and "1". Recently he has received one such table as a gift from his mother. The table contained n rows and m columns. The rows are numbered from top to bottom from 1 to n, the columns are numbered from the left to the right from 1 to m. Petya immediately decided to find the longest cool cycle whatever it takes.A cycle is a sequence of pairwise distinct cells where each two consecutive cells have a common side; besides, the first cell has a common side with the last cell. A cycle is called cool if it fulfills all the following conditions simultaneously: The cycle entirely consists of the cells that contain "1". Each cell that belongs to the cycle, has a common side with exactly two other cells that belong to the cycle. Each cell of the table that contains "1" either belongs to the cycle or is positioned outside of it (see definition below). To define the notion of "outside" formally, let's draw a cycle on a plane. Let each cell of the cycle (i, j) (i is the row number, j is the column number) correspond to the point (i, j) on the coordinate plane. Let a straight line segment join each pair of points that correspond to the cells belonging to the cycle and sharing a side. Thus, we will get a closed polyline that has no self-intersections and self-touches. The polyline divides the plane into two connected parts: the part of an infinite area and the part of a finite area. It is considered that cell (r, c) lies outside of the cycle if it does not belong to the cycle and the corresponding point on the plane with coordinates (r, c) lies in the part with the infinite area.Help Petya to find the length of the longest cool cycle in the table. The cycle length is defined as the number of cells that belong to the cycle. | 256 megabytes | import java.io.*;
import java.util.*;
public class D135 {
public D135 () throws IOException {
String input = r.readLine();
String [] NM = input.split(" ");
int N = Integer.parseInt(NM[0]);
int M = Integer.parseInt(NM[1]);
boolean [][] G = new boolean [N][M];
for (int i = 0; i < N; ++i) {
String row = r.readLine();
for (int j = 0; j < M; ++j)
G[i][j] = (row.charAt(j) == '1');
}
this.G = G;
this.N = N;
this.M = M;
solve();
}
int N, M;
boolean [][] G;
int res;
final static int K = 1000000;
public void solve () {
t = millis();
boolean [][] V = new boolean [N][M];
res = 0;
for (int i = 0; i < N-1; ++i)
for (int j = 0; j < M-1; ++j) {
int i0 = i, j0 = j;
if (G[i][j] && !V[i][j]) {
if (G[i][j+1] && G[i+1][j+1] && G[i+1][j]) {
if (res < 4) res = 4;
continue;
}
List<Integer> path = new LinkedList<Integer>();
Set<Integer> points = new HashSet<Integer>();
int [] D = { 0, 1};
int z = i;
if (!next(i,j,D) || !next(i,j,inner(D))) {
V[i][j] = true;
continue;
}
else {
{
int p = K*i+j;
points.add(p);
path.add(p);
++j;
}
do {
int p = K*i+j;
path.add(p);
if (!points.add(p)) {
while (!path.get(0).equals(p))
points.remove(path.remove(0));
if (safeInt(path, points))
res = Math.max(res, path.size() - 1);
break;
}
int [] IN = inner(D), OUT = outer(D);
if (next(i,j,IN))
D = IN;
else if (!next(i,j,D))
D = OUT;
if (r(D))
V[i][j] = true;
if (next(i,j,D)) {
i += D[0];
j += D[1];
} else
break;
if (i < z)
break;
} while (true);
}
}
i = i0; j = j0;
}
print (res);
}
int [] decode (int n) {
return new int [] { n/K, n%K };
}
boolean safeInt(List<Integer> path, Set<Integer> points) {
if (path.size() <= res+1)
return false;
if (path.size() == 5)
return true;
for (int p : path) {
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int c = 0;
if (points.contains(K*(x-1) + y))
++c;
if (points.contains(K*(x+1) + y))
++c;
if (points.contains(K*x + (y-1)))
++c;
if (points.contains(K*x + (y+1)))
++c;
if (c != 2)
return false;
}
int [] D = { 0, 1 };
Set<Integer> IP = new HashSet<Integer>();
Queue<Integer> Q = new LinkedList<Integer>();
for (int p : path) {
if (p == path.get(0))
continue;
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int [] IN = inner(D);
if (next(x,y,IN))
D = IN;
else {
if (!next(x,y,D))
D = outer(D);
x += IN[0]; y += IN[1];
if (x >= 0 && y >= 0 && x < N && y < M) {
int ip = K*x+y;
if (IP.add(ip))
Q.add(ip);
}
}
}
while (!Q.isEmpty()) {
int p = Q.poll();
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int nx, ny;
boolean t = true;
nx = x+1; ny = y;
t = t && test(nx, ny, points, IP, Q);
nx = x; ny = y+1;
t = t && test(nx, ny, points, IP, Q);
nx = x-1; ny = y;
t = t && test(nx, ny, points, IP, Q);
nx = x; ny = y-1;
t = t && test(nx, ny, points, IP, Q);
if (!t)
return false;
}
return true;
}
boolean test(int nx, int ny, Set<Integer> points, Set<Integer> IP, Queue<Integer> Q) {
int np = K*nx+ny;
if (nx >= 0 && ny >= 0 && nx < N && ny < M) {
if (!points.contains(np)) {
if (G[nx][ny])
return false;
if (IP.add(np))
Q.add(np);
}
}
return true;
}
boolean next (int x, int y, int [] d) {
x += d[0]; y += d[1];
return x >= 0 && y >= 0 && x < N && y < M && G[x][y];
}
boolean r(int [] d) {
return (d[0] == 0 && d[1] == 1);
}
int [] inner (int [] d) {
int s = K*d[0] + d[1];
if (s == 1)
return new int [] { 1, 0 };
if (s == K)
return new int [] { 0, -1 };
if (s == -1)
return new int [] { -1, 0 };
if (s == -K)
return new int [] { 0, 1 };
return null;
}
int [] outer (int [] d) {
int [] IN = inner(d);
return new int [] { -IN[0], -IN[1] };
}
////////////////////////////////////////////////////////////////////////////////////
static BufferedReader r;
static long t;
static void print2 (Object o) {
System.out.println(o);
}
static void print (Object o) {
print2(o);
//print2((millis() - t) / 1000.0);
System.exit(0);
}
static void run () throws IOException {
r = new BufferedReader(new InputStreamReader(System.in));
new D135();
}
public static void main(String[] args) throws IOException {
run();
}
static long millis() {
return System.currentTimeMillis();
}
} | Java | ["3 3\n111\n101\n111", "5 5\n01010\n10101\n01010\n10101\n01010", "7 7\n1111111\n1000101\n1000101\n1000101\n1000111\n1000001\n1111111", "5 5\n11111\n10001\n10101\n10001\n11111"] | 3 seconds | ["8", "0", "24", "0"] | NoteIn the first example there's only one cycle and it is cool.In the second sample there's no cycle at all.In the third sample there are two cool cycles: their lengths are 12 and 24.In the fourth sample there also is only one cycle but it isn't cool as there's a cell containing "1" inside this cycle. | Java 6 | standard input | [
"implementation",
"dfs and similar",
"brute force"
] | 26909af720a7b1fbd247e61af6054174 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns in the table, respectively. Each of the following n lines contains m characters. Each character can be either "0" or "1". | 2,500 | Print a single number — the length of the longest cool cycle in the table. If such cycles do not exist, print 0. | standard output | |
PASSED | 7f70a9abc20a8b342c56d8260f7778f9 | train_004.jsonl | 1323443100 | Little Petya very much likes rectangular tables that consist of characters "0" and "1". Recently he has received one such table as a gift from his mother. The table contained n rows and m columns. The rows are numbered from top to bottom from 1 to n, the columns are numbered from the left to the right from 1 to m. Petya immediately decided to find the longest cool cycle whatever it takes.A cycle is a sequence of pairwise distinct cells where each two consecutive cells have a common side; besides, the first cell has a common side with the last cell. A cycle is called cool if it fulfills all the following conditions simultaneously: The cycle entirely consists of the cells that contain "1". Each cell that belongs to the cycle, has a common side with exactly two other cells that belong to the cycle. Each cell of the table that contains "1" either belongs to the cycle or is positioned outside of it (see definition below). To define the notion of "outside" formally, let's draw a cycle on a plane. Let each cell of the cycle (i, j) (i is the row number, j is the column number) correspond to the point (i, j) on the coordinate plane. Let a straight line segment join each pair of points that correspond to the cells belonging to the cycle and sharing a side. Thus, we will get a closed polyline that has no self-intersections and self-touches. The polyline divides the plane into two connected parts: the part of an infinite area and the part of a finite area. It is considered that cell (r, c) lies outside of the cycle if it does not belong to the cycle and the corresponding point on the plane with coordinates (r, c) lies in the part with the infinite area.Help Petya to find the length of the longest cool cycle in the table. The cycle length is defined as the number of cells that belong to the cycle. | 256 megabytes | import java.io.*;
import java.util.*;
public class D135 {
public D135 () throws IOException {
String input = r.readLine();
String [] NM = input.split(" ");
int N = Integer.parseInt(NM[0]);
int M = Integer.parseInt(NM[1]);
boolean [][] G = new boolean [N][M];
for (int i = 0; i < N; ++i) {
String row = r.readLine();
for (int j = 0; j < M; ++j)
G[i][j] = (row.charAt(j) == '1');
}
this.G = G;
this.N = N;
this.M = M;
solve();
}
int N, M;
boolean [][] G;
int res;
final static int K = 1000000;
public void solve () {
t = millis();
boolean [][] V = new boolean [N][M];
res = 0;
for (int i = 0; i < N-1; ++i)
for (int j = 0; j < M-1; ++j) {
int i0 = i, j0 = j;
if (G[i][j] && !V[i][j]) {
if (G[i][j+1] && G[i+1][j+1] && G[i+1][j]) {
if (res < 4) res = 4;
continue;
}
List<Integer> path = new LinkedList<Integer>();
Set<Integer> points = new HashSet<Integer>();
int [] D = { 0, 1};
int z = i;
if (!next(i,j,D) || !next(i,j,inner(D))) {
V[i][j] = true;
continue;
}
else {
{
int p = K*i+j;
points.add(p);
path.add(p);
++j;
}
do {
int p = K*i+j;
path.add(p);
if (!points.add(p)) {
while (!path.get(0).equals(p))
points.remove(path.remove(0));
if (safeInt(p, path, points))
res = Math.max(res, path.size() - 1);
break;
}
int [] IN = inner(D), OUT = outer(D);
if (next(i,j,IN))
D = IN;
else if (!next(i,j,D))
D = OUT;
if (r(D))
V[i][j] = true;
if (next(i,j,D)) {
i += D[0];
j += D[1];
} else
break;
if (i < z)
break;
} while (true);
}
}
i = i0; j = j0;
}
print (res);
}
int [] decode (int n) {
return new int [] { n/K, n%K };
}
boolean safeInt(int p0, List<Integer> path, Set<Integer> points) {
if (path.size() <= res+1)
return false;
if (path.size() == 5)
return true;
for (int p : path) {
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int c = 0;
if (points.contains(K*(x-1) + y))
++c;
if (points.contains(K*(x+1) + y))
++c;
if (points.contains(K*x + (y-1)))
++c;
if (points.contains(K*x + (y+1)))
++c;
if (c != 2)
return false;
}
if (p0 != path.get(0)) {
int x = K, y = K;
for (int p : path) {
int [] xy = decode(p);
x = Math.min(x, xy[0]);
if (x == xy[0])
y = Math.min(y, xy[1]);
}
int p1 = K*x + y;
path.remove(0);
while(path.get(0) != p1)
path.add(path.remove(0));
path.add(p1);
if (decode(path.get(1))[0] > decode(path.get(0))[0]) {
List<Integer> reverse = new LinkedList<Integer>();
for (int q : path)
reverse.add(0, q);
path = reverse;
}
}
return safeInt2(path, points);
}
boolean safeInt2(List<Integer> path, Set<Integer> points) {
int [] D = { 0, 1 };
Set<Integer> IP = new HashSet<Integer>();
Queue<Integer> Q = new LinkedList<Integer>();
for (int p : path) {
if (p == path.get(0))
continue;
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int [] IN = inner(D);
if (next(x,y,IN))
D = IN;
else {
if (!next(x,y,D))
D = outer(D);
x += IN[0]; y += IN[1];
if (x >= 0 && y >= 0 && x < N && y < M) {
int ip = K*x+y;
if (IP.add(ip))
Q.add(ip);
}
}
}
while (!Q.isEmpty()) {
int p = Q.poll();
int [] xy = decode(p);
int x = xy[0], y = xy[1];
int nx, ny;
boolean t = true;
nx = x+1; ny = y;
t = t && test(nx, ny, points, IP, Q);
nx = x; ny = y+1;
t = t && test(nx, ny, points, IP, Q);
nx = x-1; ny = y;
t = t && test(nx, ny, points, IP, Q);
nx = x; ny = y-1;
t = t && test(nx, ny, points, IP, Q);
if (!t)
return false;
}
return true;
}
boolean test(int nx, int ny, Set<Integer> points, Set<Integer> IP, Queue<Integer> Q) {
int np = K*nx+ny;
if (nx >= 0 && ny >= 0 && nx < N && ny < M) {
if (!points.contains(np)) {
if (G[nx][ny])
return false;
if (IP.add(np))
Q.add(np);
}
}
return true;
}
boolean next (int x, int y, int [] d) {
x += d[0]; y += d[1];
return x >= 0 && y >= 0 && x < N && y < M && G[x][y];
}
boolean r(int [] d) {
return (d[0] == 0 && d[1] == 1);
}
int [] inner (int [] d) {
int s = K*d[0] + d[1];
if (s == 1)
return new int [] { 1, 0 };
if (s == K)
return new int [] { 0, -1 };
if (s == -1)
return new int [] { -1, 0 };
if (s == -K)
return new int [] { 0, 1 };
return null;
}
int [] outer (int [] d) {
int [] IN = inner(d);
return new int [] { -IN[0], -IN[1] };
}
////////////////////////////////////////////////////////////////////////////////////
static BufferedReader r;
static long t;
static void print2 (Object o) {
System.out.println(o);
}
static void print (Object o) {
print2(o);
//print2((millis() - t) / 1000.0);
System.exit(0);
}
static void run () throws IOException {
r = new BufferedReader(new InputStreamReader(System.in));
new D135();
}
public static void main(String[] args) throws IOException {
run();
}
static long millis() {
return System.currentTimeMillis();
}
} | Java | ["3 3\n111\n101\n111", "5 5\n01010\n10101\n01010\n10101\n01010", "7 7\n1111111\n1000101\n1000101\n1000101\n1000111\n1000001\n1111111", "5 5\n11111\n10001\n10101\n10001\n11111"] | 3 seconds | ["8", "0", "24", "0"] | NoteIn the first example there's only one cycle and it is cool.In the second sample there's no cycle at all.In the third sample there are two cool cycles: their lengths are 12 and 24.In the fourth sample there also is only one cycle but it isn't cool as there's a cell containing "1" inside this cycle. | Java 6 | standard input | [
"implementation",
"dfs and similar",
"brute force"
] | 26909af720a7b1fbd247e61af6054174 | The first line contains two integers n and m (1 ≤ n, m ≤ 1000) — the number of rows and columns in the table, respectively. Each of the following n lines contains m characters. Each character can be either "0" or "1". | 2,500 | Print a single number — the length of the longest cool cycle in the table. If such cycles do not exist, print 0. | standard output | |
PASSED | b9950de427d5bd58a68fa5fce8dc70b8 | train_004.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes |
// Working program with FastReader
import java.io.*;
import java.util.*;
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 List<Integer> list = new ArrayList<Integer>();
public static void main(String[] args) {
FastReader s = new FastReader();
int n = s.nextInt();
for (int i = 0; i < n; i++) {
int val = s.nextInt();
list.add(val);
}
int result = solve(list, n, n);
System.out.println(result);
}
public static int solve(List<Integer> list, int n, int f) {
int ar[] = new int[200005];
int rev[] = new int[200005];
for (int i = 0; i < list.size() + 2; i++) {
ar[i] = 1;
rev[i] = 1;
}
for (int i = 0; i < list.size() - 1; i++) {
if (list.get(i) < list.get(i + 1)) {
ar[i + 1] = ar[i] + 1;
} else {
ar[i+1] = 1;
}
}
for (int i = list.size() - 1; i >= 1; i--) {
if (list.get(i) > list.get(i - 1)) {
rev[i - 1] = rev[i] + 1;
} else {
rev[i-1] = 1;
}
}
int res = 0;
res = Math.max(ar[n - 1], rev[0]);
for (int i = 1; i < list.size() - 1; i++) {
if (list.get(i-1) < list.get(i + 1)) {
res = Math.max(res, ar[i-1] + rev[i + 1]);
}
res = Math.max(res, rev[i]);
res = Math.max(res, ar[i]);
}
return res;
}
} | Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | 365156f10a6bb655060dd5fa9a8600fc | train_004.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(br.readLine());
int[] arr = new int[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
pw.println(solve(arr));
pw.close();
}
//
// 5 6 6 7 7
private static int solve(int[] arr) {
int n = arr.length;
// dp(i, j) = max subarray up to i, j means whether a jump was used
int[][] dp = new int[n][2];
for (int k = 0; k < n; k++) {
dp[k][0] = 1;
dp[k][1] = 1;
if (k - 1 >= 0) {
if (arr[k] > arr[k - 1]) {
dp[k][0] = dp[k - 1][0] + 1;
dp[k][1] = Math.max(dp[k][0], dp[k - 1][1] + 1);
}
if (k - 2 >= 0) {
if (arr[k] > arr[k - 2]) {
dp[k][1] = Math.max(dp[k][1], dp[k - 2][0] + 1);
}
}
}
}
int max = 1;
for (int[] ints : dp) {
max = Math.max(max, ints[1]);
}
return max;
}
}
| Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | c76d15bfcfd493da15d39112da5bd837 | train_004.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.util.*;
import java.math.*;
public class Main
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=1;
int n=sc.nextInt();
int[] arr=new int[n+2];
arr[n+1]=arr[n]=-1;
for(int i=0;i<n;i++)
arr[i]=sc.nextInt();
int k=Integer.MAX_VALUE;
int[][] dp=new int[n+1][3];
dp[n-1][0]=1;
dp[n-1][1]=0;
dp[n-1][2]=1;
dp[n][0]=dp[n][1]=dp[n][2]=0;
int ans=1;
for(int i=n-2;i>=0;i--)
{
if(arr[i+1]>arr[i])
dp[i][0]=dp[i+1][0]+1;
else
dp[i][0]=1;
dp[i][1]=dp[i+1][0];
ans=Math.max(ans,Math.max(dp[i][0],dp[i][1]));
if((dp[i][0]!=1)&&(arr[i+dp[i][0]-2]<arr[i+dp[i][0]]))
ans=Math.max(ans,dp[i][0]-1+dp[i+dp[i][0]][0]);
if((dp[i][0]!=1)&&(arr[i+dp[i][0]-1]<arr[i+dp[i][0]+1]))
ans=Math.max(ans,dp[i][0]+dp[i+dp[i][0]][1]);
}
System.out.println(ans);
}
}
| Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | 726011880782d02103c9cda400e53b57 | train_004.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.util.*;
import java.math.*;
public class Main
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=1;
int n=sc.nextInt();
int[] arr=new int[n+2];
arr[n+1]=arr[n]=-1;
for(int i=0;i<n;i++)
arr[i]=sc.nextInt();
int k=Integer.MAX_VALUE;
int[][] dp=new int[n+1][1];
dp[n-1][0]=1;
dp[n][0]=0;
int ans=1;
for(int i=n-2;i>=0;i--)
{
if(arr[i+1]>arr[i])
dp[i][0]=dp[i+1][0]+1;
else
dp[i][0]=1;
ans=Math.max(ans,dp[i][0]);
if((dp[i][0]!=1)&&(arr[i+dp[i][0]-2]<arr[i+dp[i][0]]))
ans=Math.max(ans,dp[i][0]-1+dp[i+dp[i][0]][0]);
if((dp[i][0]!=1)&&(arr[i+dp[i][0]-1]<arr[i+dp[i][0]+1]))
ans=Math.max(ans,dp[i][0]+dp[i+dp[i][0]+1][0]);
}
System.out.println(ans);
}
}
| Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | a03daf61384cf4c314f12d8f73ca1a60 | train_004.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.util.*;
import java.math.*;
public class Main
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=1;
int n=sc.nextInt();
int[] arr=new int[n+2];
arr[n+1]=arr[n]=-1;
for(int i=0;i<n;i++)
arr[i]=sc.nextInt();
int k=Integer.MAX_VALUE;
int[][] dp=new int[n+1][3];
dp[n-1][0]=1;
dp[n-1][1]=0;
dp[n-1][2]=1;
dp[n][0]=dp[n][1]=dp[n][2]=0;
int ans=1;
for(int i=n-2;i>=0;i--)
{
if(arr[i+1]>arr[i])
dp[i][0]=dp[i+1][0]+1;
else
dp[i][0]=1;
dp[i][1]=dp[i+1][0];
ans=Math.max(ans,Math.max(dp[i][0],dp[i][1]));
if((dp[i][0]!=1)&&(arr[i+dp[i][0]-2]<arr[i+dp[i][0]]))
ans=Math.max(ans,dp[i][0]-1+dp[i+dp[i][0]][0]);
if(dp[i][0]==1)
{
if(arr[i+2]>arr[i])
ans=Math.max(ans,1+dp[i+2][0]);
}
if((dp[i][0]!=1)&&(arr[i+dp[i][0]-1]<arr[i+dp[i][0]+1]))
ans=Math.max(ans,dp[i][0]+dp[i+dp[i][0]][1]);
}
System.out.println(ans);
}
}
| Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | 3978877e8a4cf21db28f0378558227b3 | train_004.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.util.*;
import java.math.*;
public class Main
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=1;
int n=sc.nextInt();
int[] arr=new int[n+2];
arr[n+1]=arr[n]=-1;
for(int i=0;i<n;i++)
arr[i]=sc.nextInt();
int k=Integer.MAX_VALUE;
int[][] dp=new int[n+1][2];
dp[n-1][0]=1;
dp[n-1][1]=0;
dp[n][0]=dp[n][1]=0;
int ans=1;
for(int i=n-2;i>=0;i--)
{
if(arr[i+1]>arr[i])
dp[i][0]=dp[i+1][0]+1;
else
dp[i][0]=1;
dp[i][1]=dp[i+1][0];
ans=Math.max(ans,Math.max(dp[i][0],dp[i][1]));
if((dp[i][0]!=1)&&(arr[i+dp[i][0]-2]<arr[i+dp[i][0]]))
ans=Math.max(ans,dp[i][0]-1+dp[i+dp[i][0]][0]);
if((dp[i][0]!=1)&&(arr[i+dp[i][0]-1]<arr[i+dp[i][0]+1]))
ans=Math.max(ans,dp[i][0]+dp[i+dp[i][0]+1][0]);
}
System.out.println(ans);
}
}
| Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | fcc9a1e0adc75993e71e52b9880a63c9 | train_004.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.util.*;
public class Main {
private static final long MOD = 1_000_000_007;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
List<Section> list = new ArrayList<>();
int prev = 1_000_000_001;
int length = 0;
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
if (prev >= a[i]) {
length = 1;
list.add(new Section(i, i, length));
} else {
length++;
Section removed = list.remove(list.size()-1);
list.add(new Section(removed.l, i, length));
}
prev = a[i];
}
if (list.size() == 1) {
System.out.println(list.get(0).len);
return;
}
long max = (list.get(0)).len;
for (int i = 0; i < list.size()-1; i++) {
Section s1 = list.get(i);
Section s2 = list.get(i+1);
int sum = 0;
if (s2.len == 1 && i < list.size()-2
&& a[s1.r] < a[(list.get(i+2)).l]) {
sum = s1.len + (list.get(i+2)).len;
} else if ((s1.len >= 2 && a[s1.r-1] < a[s2.l])
|| (s2.len >= 2 && a[s1.r] < a[s2.l+1])) {
sum = s1.len + s2.len - 1;
} else {
sum = Math.max(s1.len, s2.len);
}
max = Math.max(max, sum);
}
System.out.println(max);
}
static class Section {
int l;
int r;
int len;
Section(int l, int r, int len) {
this.l = l;
this.r = r;
this.len = len;
}
}
}
| Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | dc89d8066ffc1d51ab724bd51994f3bc | train_004.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;
public class Main {
public static int a[]=new int [200005];
public static int dp1[]=new int [200005];
public static int dp2[]=new int [200005];
public static final int inf=0x3f3f3f3f;
public static int n;
public static void main(String args[])
{Scanner cin=new Scanner(System.in);
n=cin.nextInt();
for(int i=1;i<=n;i++)
a[i]=cin.nextInt();
int len=1;
dp1[1]=1;
for(int i=2;i<=n;i++)
{if(a[i-1]<a[i])
dp1[i]=dp1[i-1]+1;
else
dp1[i]=1;
}
dp2[n]=1;
for(int i=n-1;i>=1;i--)
{if(a[i]<a[i+1])
dp2[i]=dp2[i+1]+1;
else
dp2[i]=1;
}
int maxx=0;
for(int i=1;i<n;i++)
{
maxx=Math.max(maxx,dp1[i]+dp2[i]-1);
}
for(int i=2;i<n;i++)
{
if(a[i+1]>a[i-1])
maxx=Math.max(maxx,dp1[i-1]+dp2[i+1]);
}
System.out.println(maxx);
}
} | Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | fbf83655460cfe6d657a0e2696659105 | train_004.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.io.IOException;
import java.math.BigInteger;
import java.util.*;
import java.util.Map.Entry;
public class CF {
public static void main(String[] args) throws IOException{
// TODO Auto-generated method stub
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();
}
int l[]=new int[n];
l[0]=1;
int r[]=new int[n];
int max=1;
for(int i=1;i<n;i++) {
if(a[i]>a[i-1]) {
l[i]=l[i-1]+1;
max=Math.max(max, l[i]);
}else {
l[i]=1;
}
}
r[n-1]=1;
for(int i=n-2;i>=0;i--) {
if(a[i]<a[i+1]) {
r[i]=r[i+1]+1;
}else {
r[i]=1;
}
}
for(int i=1;i<n-1;i++) {
if(a[i-1]<a[i+1]) {
max=Math.max(l[i-1]+r[i+1], max);
}
}
System.out.println(max);
//
// for(int i=0;i<n;i++) {
// System.out.print(l[i]+" ");
// }
// System.out.println();
// for(int i=0;i<n;i++) {
// System.out.print(r[i]+" ");
// }
}
}
| Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | d4d61d8d644a25982232bf9b30b2193b | train_004.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class remEle{
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine().trim());
String[] in = br.readLine().split(" ");
long[] arr = new long[n];
long[] left = new long[n];
Arrays.fill(left , 1);
long[] right = new long[n];
Arrays.fill(right , 1);
for(int i=0;i<n;i++){
arr[i] = Long.parseLong(in[i]);
}
long ans = 1;
for(int i=1;i<n;i++){
if(arr[i] > arr[i - 1]){
left[i] = left[i - 1] + 1;
}
ans = Math.max(ans , left[i]);
}
for(int i= n-2;i>=0;i--){
if(arr[i] < arr[i + 1]){
right[i] = right[i + 1] + 1;
}
}
for(int i=1;i<n-1;i++){
if(arr[i - 1] < arr[i + 1]){
ans = Math.max( ans , left[i - 1] + right[i + 1]);
}
}
System.out.println(ans);
}
} | Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | 03c86e85b58abe2f8e39f2709f2bb4e9 | train_004.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.util.Scanner;
/**
*
* @author Parsa
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = input.nextInt();
}
int maxWithRemove = 0;
int cYR = 1;
int fromLastGap = 1;
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] < arr[i + 1]) {
cYR++;
fromLastGap++;
maxWithRemove = Math.max(maxWithRemove, cYR);
} else {
if (i + 2 < arr.length) {
//arr[i+1] < arr[i]
if (arr[i + 2] > arr[i]) {
maxWithRemove = Math.max(maxWithRemove, cYR);
cYR = fromLastGap + 1;
fromLastGap = 1;
i = i + 1;
} else if (arr[i + 2] > arr[i + 1]) {
if(i-1 >= 0) {
if (arr[i + 1] > arr[i - 1]) {
maxWithRemove = Math.max(maxWithRemove, cYR);
cYR = fromLastGap + 1;
fromLastGap = 2;
i = i + 1;
} else {
maxWithRemove = Math.max(maxWithRemove, cYR);
cYR = 1;
fromLastGap = 1;
i = i;
}
} else {
cYR = 1;
fromLastGap = 1;
}
} else {
maxWithRemove = Math.max(maxWithRemove, cYR);
cYR = 1;
fromLastGap = 1;
i = i + 1;
}
} else {
maxWithRemove = Math.max(maxWithRemove, cYR);
i = n; //break
}
}
}
maxWithRemove = Math.max(maxWithRemove, cYR);
if(n == 0)
System.out.println("0");
else
System.out.println(maxWithRemove);
}
} | Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | 1440d70fd8e385f2ec6e3499baae100a | train_004.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Rd in = new Rd();
PrintWriter out = new PrintWriter(System.out);
int N = in.nextInt();
int[] nums = in.nextIntArray(N);
int[] leftToRight = new int[N];
int[] rightToLeft = new int[N];
Arrays.fill(leftToRight, 1);
Arrays.fill(rightToLeft, 1);
for (int i = 1; i < N; i++) {
if (nums[i] > nums[i - 1]) {
leftToRight[i] = leftToRight[i - 1] + 1;
}
}
for (int i = N - 2; i >= 0; i--) {
if (nums[i + 1] > nums [i]) {
rightToLeft[i] = rightToLeft[i + 1] + 1;
}
}
int max = 1;
for (int i = 0; i < N; i++) {
max = Math.max(max, leftToRight[i]);
}
for (int i = 1; i < N - 1; i++) {
if (nums[i - 1] < nums[i + 1]) {
max = Math.max(max, leftToRight[i - 1] + rightToLeft[i + 1]);
}
}
out.println(max);
out.flush();
}
static class Rd {
BufferedReader br;
StringTokenizer st;
public Rd() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw null;
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
int[] nextIntArray(int n) {
int r[] = new int[n];
for (int i = 0; i < n; i++) r[i] = nextInt();
return r;
}
long[] nextLongArray(int n) {
long r[] = new long[n];
for (int i = 0; i < n; i++) r[i] = nextLong();
return r;
}
char[][] grid(int r, int c) {
char res[][] = new char[r][c];
for (int i = 0; i < r; i++) {
char l[] = next().toCharArray();
for (int j = 0; j < c; j++) {
res[i][j] = l[j];
}
}
return res;
}
}
} | Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | f9751d6ef9793fda256f5852e788c4d8 | train_004.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
/**
* Pick questions that you love and solve them with love, try to get AC in one go with cleanest code
* Just one thing to keep in mind these questions should be out of your reach, which make you step out of comfort zone
* Try to pick them from different topics
* CP is a sport, enjoy it. Don't make it pressure cooker or job
* ****Use pen and paper************* check few examples analyze them, some not given in sample also analyze then code
* Use pen and paper. Solve on paper then code.
* If there is some reasoning e.g. sequence/paths, try printing first 100 elements or 100 answers using brute and observe.
* *********Read question with extreme caution. Mistake is happening here which costs time, WA and easy problem not getting solved.*********
* Sometimes we make question complex due to misunderstanding.
* Prefix sum and suffix sum is highly usable concept, look for it.
* Think of cleanest approach. If too many if else are coming then its indication of WA.
* Solve 1-2 more questions than you solved during contest.
*/
public class Codeforces {
public static void main(String args[]) throws IOException {
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();
}
int lf[] = new int[n];
Arrays.fill(lf, 1);
for (int i=1;i<n;i++) {
if (a[i]>a[i-1]) lf[i] = lf[i-1]+1;
}
int rg[] = new int[n];
Arrays.fill(rg, 1);
for (int i=n-2;i>=0;i--) {
if (a[i]<a[i+1]) rg[i] = rg[i+1] + 1;
}
int ans = 1;
for (int i=0;i<n;i++) {
int max = lf[i];
if (i+2<n && a[i]<a[i+2]) max = max + rg[i+2];
ans = Math.max(ans, max);
}
System.out.println(ans);
in.close();
}
static class Pair {
Integer x;
Integer y;
private Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (o == null || !(o instanceof Pair))
return false;
Pair cor = (Pair)o;
return x.equals(cor.x) && y.equals(cor.y);
}
@Override
public int hashCode() {
int result = 17;
return result;
}
static class PairComparatorX implements Comparator<Pair> {
@Override
public int compare(Pair o1, Pair o2) {
return o1.x.compareTo(o2.x);
}
}
static class PairComparatorY implements Comparator<Pair> {
@Override
public int compare(Pair o1, Pair o2) {
return o1.y.compareTo(o2.y);
}
}
}
private static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
StringTokenizer st;
BufferedReader br;
// public static void main(String args[]) throws IOException {
// Reader in = new Reader();
// int n = in.nextInt();
// String s[] = new String[n];
// for (int i=0;i<n;i++) s[i] = in.next();
// for (int i=0;i<n;i++) System.out.println(s[i]);
//
// }
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
br = new BufferedReader(new InputStreamReader(System.in));
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public String readLine() throws IOException {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
} | Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | faeb2525212d3f3b79a2e6ed474e8660 | train_004.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.util.*;
public class RemoveOneElement {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long arr[] = new long[n];
for(int i=0;i<n;i++) {
arr[i] = sc.nextLong();
}
int l[] = new int[n];
Arrays.fill(l, 1);
int max = 1;
for(int i=1;i<n;i++) {
if(arr[i-1]<arr[i]) {
l[i] = l[i-1]+1;
max = Math.max(l[i], max);
}
}
int r[] = new int[n];
Arrays.fill(r, 1);
for(int i=n-2;i>=0;i--) {
if(arr[i+1]>arr[i]) {
r[i] = r[i+1]+1;
}
}
for(int i=1;i<n-1;i++) {
if(arr[i-1]<arr[i+1]) {
max = Math.max(max, l[i-1]+r[i+1]);
}
}
System.out.println(max);
// int dp[][] = new int[n][2];
// for(int d[]: dp) {
// Arrays.fill(d, -1);
// }
// System.out.println(helper(arr, 0, 0, dp, -1));
}
// public static int helper(long arr[], int pos, int removed, int dp[][], long prev) {
// if(pos==arr.length) {
// return 0;
// }
// if(dp[pos][removed]!=-1) {
// return dp[pos][removed];
// }
// int take = 0;
// int skip = 0;
// int start = 0;
// if(arr[pos]>prev) {
// if(removed==0) {
// skip += helper(arr, pos+1, 1, dp, prev);
// }
// take += 1 + helper(arr, pos+1, removed, dp, arr[pos]);
// return dp[pos][removed] = Math.max(start, take);
// } else {
// if(removed==0) {
// skip += helper(arr, pos+1, 1, dp, prev);
// }
// take += helper(arr, pos+1, removed, dp, arr[pos]);
// return dp[pos][removed] = Math.max(start, take);
// }
// }
}
| Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | b6c72e7d8c419b6a9c80082cf3f5a2ef | train_004.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in))){
int n = Integer.parseInt(br.readLine());
int numbers[] = new int[n];
String s[] = br.readLine().split(" ");
for (int i = 0 ; i < n; ++i) {
numbers[i] = Integer.parseInt(s[i]);
}
int l[] = new int[n];
int r[] = new int[n];
l[0] = 1;
r[n-1] = 1;
int ans = 0;
for(int i = 1; i < n; ++i) {
if(numbers[i]>numbers[i-1]) {
l[i] = l[i-1]+1;
ans = Math.max(ans, l[i]);
}
else
l[i] = 1;
}
for(int i = n-1 ; i > 0; --i) {
if(numbers[i-1]<numbers[i])
r[i-1] = r[i] + 1;
else
r[i-1] = 1;
}
for(int i = 1; i <= n-2; ++i) {
if(numbers[i+1]-numbers[i-1] > 0)
ans = Math.max(ans, l[i-1]+r[i+1]);
}
System.out.println(Math.max(ans, r[0]));
}
catch(Exception e) {
e.printStackTrace();
}
}
}
| Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | e95acf024d1e9203fe2f862fa4570853 | train_004.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 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();
int[] a = new int[n];
for(int i = 0; i < n; i++) {
a[i] = sc.nextInt();
}
int[] l = new int[n];
int[] r = new int[n];
Arrays.fill(l, 1);
Arrays.fill(r, 1);
for(int i = 1;i < n; i++) {
if(a[i]>a[i-1]) {
l[i]+=l[i-1];
}
}
for(int i = n-2; i >= 0; i--) {
if(a[i]<a[i+1]) {
r[i]+=r[i+1];
}
}
int max = 0;
for(int i = 0; i < n; i++) {
max = Math.max(max, l[i]);
}
for(int i = 0; i < n-2; i++) {
if(a[i]<a[i+2]) {
max = Math.max(max, l[i]+r[i+2]);
}
}
out.println(max);
}
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 | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | 2118cf7936fe48f2615374db5663f3ab | train_004.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public final class CodeForces {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] arr = new int[n];
for(int i=0; i<n; i++)
arr[i] = in.nextInt();
System.out.println(maxSub(arr, n));
in.close();
}
private static int maxSub(int[] arr, int n) {
int[] left = new int[n];
int[] right = new int[n];
Arrays.fill(left, 1);
Arrays.fill(right, 1);
for(int i=1; i<n; i++) {
if(arr[i] > arr[i-1])
left[i] = left[i-1] + 1;
}
for(int i=n-2; i>=0; i--) {
if(arr[i] < arr[i+1])
right[i] = right[i+1] + 1;
}
int max = 1;
for(int i=0; i<n; i++) {
max = Math.max(max, left[i]);
if(i != 0 && i != n-1) {
if(arr[i+1] > arr[i-1])
max = Math.max(max, left[i-1] + right[i+1]);
}
}
return max;
}
} | Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | ba20c06f1e6374f1453278b957a24a7a | train_004.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes |
import java.util.*;
import java.lang.*;
import java.lang.reflect.Array;
import java.io.*;
import java.math.*;
import java.text.DecimalFormat;
public class Prac{
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
}
catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int ni() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nl() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nia(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}
public String rs() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
static PrintWriter w = new PrintWriter(System.out);
static long mod=998244353L;
public static class Key {
private final int x;
private final int y;
public Key(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Key)) return false;
Key key = (Key) o;
return x == key.x && y == key.y;
}
@Override
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
}
static int n;
public static void main (String[] args)throws IOException{
InputReader sc=new InputReader(System.in);
int n=sc.ni();
int arr[]=new int[n+1];
for(int i=1;i<=n;i++)arr[i]=sc.ni();
int ans=0;
int dp[][]=new int[n+1][2];
for(int i=1;i<=n;i++){
if(arr[i]>arr[i-1]){
dp[i][0]=dp[i-1][0]+1;
dp[i][1]=dp[i-1][1]+1;
}
else{
dp[i][0]=1;
}
if(i>1&&arr[i]>arr[i-2]){
dp[i][1]=Math.max(dp[i][1],dp[i-2][0]+1);
//dp[i][0]=dp[i-1][1];
}
else{
dp[i][1]=Math.max(dp[i][1], 1);
}
//w.println(dp[i][0]+" "+dp[i][1]);
ans=Math.max(ans,Math.max(dp[i][0],dp[i][1]));
}
w.println(ans);
w.close();
}
}
| Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | 86163415d61d6e6df4205caaba742a89 | train_004.jsonl | 1576157700 | You are given an array $$$a$$$ consisting of $$$n$$$ integers.You can remove at most one element from this array. Thus, the final length of the array is $$$n-1$$$ or $$$n$$$.Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.Recall that the contiguous subarray $$$a$$$ with indices from $$$l$$$ to $$$r$$$ is $$$a[l \dots r] = a_l, a_{l + 1}, \dots, a_r$$$. The subarray $$$a[l \dots r]$$$ is called strictly increasing if $$$a_l < a_{l+1} < \dots < a_r$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class DTask {
public static void main(String[] args) {
MyInputReader in = new MyInputReader(System.in);
int n = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
int[][] dp = new int[n][2];
for (int i = 0; i < n; i++) {
dp[i][0] = 1;
dp[i][1] = 1;
}
for (int i = n - 2; i >= 0; i--) {
if (arr[i] < arr[i + 1]) {
dp[i][0] = dp[i + 1][0] + 1;
}
}
for (int i = 1; i < n; i++) {
if (arr[i] > arr[i - 1]) {
dp[i][1] = dp[i - 1][1] + 1;
}
}
int ans = 0;
for (int i = 0; i < n; i++) {
ans = Math.max(ans, dp[i][0]);
}
for (int i = 1; i < n - 1; i++) {
if (arr[i - 1] < arr[i + 1]) {
ans = Math.max(ans, dp[i - 1][1] + dp[i + 1][0]);
}
}
System.out.println(ans);
}
public static class MyInputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public MyInputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["5\n1 2 5 3 4", "2\n1 2", "7\n6 5 4 3 2 4 3"] | 2 seconds | ["4", "2", "2"] | NoteIn the first example, you can delete $$$a_3=5$$$. Then the resulting array will be equal to $$$[1, 2, 3, 4]$$$ and the length of its largest increasing subarray will be equal to $$$4$$$. | Java 8 | standard input | [
"dp",
"brute force"
] | 87b8dccfc0e5a63cd209c37cf8aebef0 | The first line of the input contains one integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in $$$a$$$. The second line of the input contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 10^9$$$), where $$$a_i$$$ is the $$$i$$$-th element of $$$a$$$. | 1,500 | Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array $$$a$$$ after removing at most one element. | standard output | |
PASSED | 5205bd849fc86f564f2de11dcf90b686 | train_004.jsonl | 1483107300 | A string t is called nice if a string "2017" occurs in t as a subsequence but a string "2016" doesn't occur in t as a subsequence. For example, strings "203434107" and "9220617" are nice, while strings "20016", "1234" and "20167" aren't nice.The ugliness of a string is the minimum possible number of characters to remove, in order to obtain a nice string. If it's impossible to make a string nice by removing characters, its ugliness is - 1.Limak has a string s of length n, with characters indexed 1 through n. He asks you q queries. In the i-th query you should compute and print the ugliness of a substring (continuous subsequence) of s starting at the index ai and ending at the index bi (inclusive). | 256 megabytes | import java.io.*;
import java.util.*;
public class CF750 {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
static final int INF = 1_00_000_000;
static int[][][] cache = new int[10][6][6];
{
for (char c = '0'; c <= '9'; c++) {
int[][] dp = cache[c - '0'];
for (int i = 0; i < 6; i++)
for (int j = i; j < 6; j++) {
dp[i][j] = i == j ? 0 : -INF;
}
if (c == '2') {
dp[0][1] = 1;
} else {
dp[0][0] = 1;
}
if (c == '0') {
dp[1][2] = 1;
} else {
dp[1][1] = 1;
}
if (c == '1') {
dp[2][3] = 1;
} else {
dp[2][2] = 1;
}
if (c == '6') {
dp[3][5] = 1;
} else if (c == '7') {
dp[3][4] = 1;
} else {
dp[3][3] = 1;
}
if (c == '6') {
dp[4][5] = 1;
} else {
dp[4][4] = 1;
}
}
}
static class Node {
int l, r;
Node left, right;
int[][] dp;
public Node(int l, int r, String s) {
this.l = l;
this.r = r;
if (r - l > 1) {
int mid = (l + r) >> 1;
left = new Node(l, mid, s);
right = new Node(mid, r, s);
dp = combine(left.dp, right.dp);
} else {
dp = cache[s.charAt(l) - '0'];
}
}
static int[][] combine(int[][] a, int[][] b) {
if (a == null) {
return b;
}
if (b == null) {
return a;
}
int[][] c = new int[6][6];
for (int i = 0; i < 6; i++) {
for (int j = i; j < 6; j++) {
c[i][j] = -INF;
for (int k = i; k <= j; k++) {
c[i][j] = Math.max(c[i][j], a[i][k] + b[k][j]);
}
}
}
return c;
}
int[][] go(int ql, int qr) {
if (l >= qr || ql >= r) {
return null;
}
if (ql <= l && r <= qr) {
return dp;
}
return combine(left.go(ql, qr), right.go(ql, qr));
}
}
void solve() throws IOException {
int n = nextInt();
int q = nextInt();
String s = nextToken();
Node root = new Node(0, n, s);
while (q-- > 0) {
int l = nextInt() - 1;
int r = nextInt();
int[][] dp = root.go(l, r);
// System.err.println(Arrays.deepToString(dp));
if (dp[0][4] < 0) {
out.println(-1);
} else {
out.println(r - l - dp[0][4]);
}
}
}
CF750() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new CF750();
}
String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return null;
}
}
return st.nextToken();
}
String nextString() {
try {
return br.readLine();
} catch (IOException e) {
eof = true;
return null;
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
} | Java | ["8 3\n20166766\n1 8\n1 7\n2 8", "15 5\n012016662091670\n3 4\n1 14\n4 15\n1 13\n10 15", "4 2\n1234\n2 4\n1 2"] | 3 seconds | ["4\n3\n-1", "-1\n2\n1\n-1\n-1", "-1\n-1"] | NoteIn the first sample: In the first query, ugliness("20166766") = 4 because all four sixes must be removed. In the second query, ugliness("2016676") = 3 because all three sixes must be removed. In the third query, ugliness("0166766") = - 1 because it's impossible to remove some digits to get a nice string. In the second sample: In the second query, ugliness("01201666209167") = 2. It's optimal to remove the first digit '2' and the last digit '6', what gives a string "010166620917", which is nice. In the third query, ugliness("016662091670") = 1. It's optimal to remove the last digit '6', what gives a nice string "01666209170". | Java 8 | standard input | [
"dp",
"divide and conquer",
"data structures",
"matrices"
] | cf5e72a35509c6ee1a3073c0e514f6bf | The first line of the input contains two integers n and q (4 ≤ n ≤ 200 000, 1 ≤ q ≤ 200 000) — the length of the string s and the number of queries respectively. The second line contains a string s of length n. Every character is one of digits '0'–'9'. The i-th of next q lines contains two integers ai and bi (1 ≤ ai ≤ bi ≤ n), describing a substring in the i-th query. | 2,600 | For each query print the ugliness of the given substring. | standard output | |
PASSED | 4f05c3db79df949d2450eb50b8eaee28 | train_004.jsonl | 1483107300 | A string t is called nice if a string "2017" occurs in t as a subsequence but a string "2016" doesn't occur in t as a subsequence. For example, strings "203434107" and "9220617" are nice, while strings "20016", "1234" and "20167" aren't nice.The ugliness of a string is the minimum possible number of characters to remove, in order to obtain a nice string. If it's impossible to make a string nice by removing characters, its ugliness is - 1.Limak has a string s of length n, with characters indexed 1 through n. He asks you q queries. In the i-th query you should compute and print the ugliness of a substring (continuous subsequence) of s starting at the index ai and ending at the index bi (inclusive). | 256 megabytes |
import java.io.*;
import java.math.*;
import java.util.*;
import static java.util.Arrays.*;
public class E {
private static final int mod = (int)1e9+7;
final Random random = new Random(0);
final IOFast io = new IOFast();
/// MAIN CODE
public void run() throws IOException {
// int TEST_CASE = Integer.parseInt(new String(io.nextLine()).trim());
int TEST_CASE = 1;
while(TEST_CASE-- != 0) {
int n = io.nextInt();
int q = io.nextInt();
char[] cs = io.next();
// int n = 200000;
// int q = 200000;
// char[] cs = new char[200000];
// for (int i = 0; i < cs.length; i++) cs[i] = (char)('0' + random.nextInt(10));
Seg2 seg = new Seg2(n);
for (int i = 0; i < cs.length; i++) {
seg.update(i, cs[i] - '0');
}
for (int i = 0; i < q; i++) {
// [l,r)
int l = io.nextInt() - 1;
int r = io.nextInt();
io.out.println(seg.get(l, r));
}
}
}
static int lowerBound(List<Integer> p, int l) {
int ret = Collections.binarySearch(p, l);
if (ret < 0) { ret = -ret - 1; }
return ret;
}
static int lowerBound2(List<Integer> p, int l) {
int ret = Collections.binarySearch(p, l);
if (ret < 0) { ret = -ret - 2; }
return ret;
}
static final int INF = 1<<29;
static class Seg2 {
final int n;
final int[][][] seg;
public Seg2(final int n) {
this.n = Integer.highestOneBit(n) << 1;
seg = new int[this.n << 1][5][5];
for (int[][] s : seg) {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
s[i][j] = segId[i][j];
}
}
}
}
static int[][] segId = new int[][]{
new int[]{ 0, INF, INF, INF, INF, }, // ""
new int[]{ INF, 0, INF, INF, INF, }, // "2"
new int[]{ INF, INF, 0, INF, INF, }, // "20"
new int[]{ INF, INF, INF, 0, INF, }, // "201"
new int[]{ INF, INF, INF, INF, 0, }, // "2017"
};
static int[][] seg2 = new int[][]{
new int[]{ 1, INF, INF, INF, INF, }, // ""
new int[]{ 0, 0, INF, INF, INF, }, // "2"
new int[]{ INF, INF, 0, INF, INF, }, // "20"
new int[]{ INF, INF, INF, 0, INF, }, // "201"
new int[]{ INF, INF, INF, INF, 0, }, // "2017"
};
static int[][] seg0 = new int[][]{
new int[]{ 0, INF, INF, INF, INF, }, // ""
new int[]{ INF, 1, INF, INF, INF, }, // "2"
new int[]{ INF, 0, 0, INF, INF, }, // "20"
new int[]{ INF, INF, INF, 0, INF, }, // "201"
new int[]{ INF, INF, INF, INF, 0, }, // "2017"
};
static int[][] seg1 = new int[][]{
new int[]{ 0, INF, INF, INF, INF, }, // ""
new int[]{ INF, 0, INF, INF, INF, }, // "2"
new int[]{ INF, INF, 1, INF, INF, }, // "20"
new int[]{ INF, INF, 0, 0, INF, }, // "201"
new int[]{ INF, INF, INF, INF, 0, }, // "2017"
};
static int[][] seg7 = new int[][]{
new int[]{ 0, INF, INF, INF, INF, }, // ""
new int[]{ INF, 0, INF, INF, INF, }, // "2"
new int[]{ INF, INF, 0, INF, INF, }, // "20"
new int[]{ INF, INF, INF, 1, INF, }, // "201"
new int[]{ INF, INF, INF, 0, 0, }, // "2017"
};
static int[][] seg6 = new int[][]{
new int[]{ 0, INF, INF, INF, INF, }, // ""
new int[]{ INF, 0, INF, INF, INF, }, // "2"
new int[]{ INF, INF, 0, INF, INF, }, // "20"
new int[]{ INF, INF, INF, 1, INF, }, // "201"
new int[]{ INF, INF, INF, INF, 1, }, // "2017"
};
int[][] tmpVec = new int[5][1];
int get(int l, int r) {
// dump(get(l, r, 0, 0, n));
// dump(mulmat(vec, get(l, r, 0, 0, n)));
// int ans = mulmat(vec, get(l, r, 0, 0, n))[4][0];
int[][] vec = new int[][]{
new int[]{0,},
new int[]{INF,},
new int[]{INF,},
new int[]{INF,},
new int[]{INF,},
};
int ans = get(l, r, 0, 0, n, vec)[4][0];
if (ans >= INF) ans = -1;
return ans;
}
int[][] get(int l, int r, int k, int curL, int curR, int[][] vec) {
if(curR <= l || curL >= r) return vec;
if(l <= curL && curR <= r) {
mulmat(vec, seg[k], tmpVec);
int[][] tmp = vec; vec = tmpVec; tmpVec = tmp;
return vec;
}
final int curM = (curL + curR) / 2;
return get(l, r, 2 * k + 2, curM, curR, get(l, r, 2 * k + 1, curL, curM, vec));
}
int[][] tmpMat = new int[5][5];
void update(int i, int v) {
i += n - 1;
switch(v) {
case 2: seg[i] = seg2; break;
case 0: seg[i] = seg0; break;
case 1: seg[i] = seg1; break;
case 7: seg[i] = seg7; break;
case 6: seg[i] = seg6; break;
default: seg[i] = segId; break;
}
while(i != 0) {
i = (i - 1) / 2;
mulmat(seg[2*i+1], seg[2*i+2], tmpMat);
int[][] tmp = seg[i]; seg[i] = tmpMat; tmpMat = tmp;
}
}
}
// sum(A[i][k] * B[k][j]) -> min(A[i][k] + B[k][j])
// long
// a [n,v] * b [v,m] => c[n,m]
// static int[][] mulmat(int[][] a, int[][] b) {
static int[][] mulmat(int[][] b, int[][] a, int[][] res) {
assert(a[0].length == b.length);
final int n = a.length;
final int v = b.length;
final int m = b[0].length;
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
res[i][j] = INF;
}
}
for(int i = 0; i < n; i++) {
for(int k = 0; k < v; k++) {
final int aa = a[i][k];
for(int j = 0; j < m; j++) {
res[i][j] = Math.min(res[i][j], aa + b[k][j]);
}
}
}
return res;
}
/// TEMPLATE
static int gcd(int n, int r) { return r == 0 ? n : gcd(r, n%r); }
static long gcd(long n, long r) { return r == 0 ? n : gcd(r, n%r); }
static <T> void swap(T[] x, int i, int j) { T t = x[i]; x[i] = x[j]; x[j] = t; }
static void swap(int[] x, int i, int j) { int t = x[i]; x[i] = x[j]; x[j] = t; }
void printArrayLn(int[] xs) { for(int i = 0; i < xs.length; i++) io.out.print(xs[i] + (i==xs.length-1?"\n":" ")); }
void printArrayLn(long[] xs) { for(int i = 0; i < xs.length; i++) io.out.print(xs[i] + (i==xs.length-1?"\n":" ")); }
static void dump(Object... o) { System.err.println(Arrays.deepToString(o)); }
void main() throws IOException {
// IOFast.setFileIO("rle-size.in", "rle-size.out");
try { run(); }
catch (EndOfFileRuntimeException e) { }
io.out.flush();
}
public static void main(String[] args) throws IOException { new E().main(); }
static class EndOfFileRuntimeException extends RuntimeException {
private static final long serialVersionUID = -8565341110209207657L; }
static
public class IOFast {
private BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
private PrintWriter out = new PrintWriter(System.out);
void setFileIn(String ins) throws IOException { in.close(); in = new BufferedReader(new FileReader(ins)); }
void setFileOut(String outs) throws IOException { out.flush(); out.close(); out = new PrintWriter(new FileWriter(outs)); }
void setFileIO(String ins, String outs) throws IOException { setFileIn(ins); setFileOut(outs); }
private static int pos, readLen;
private static final char[] buffer = new char[1024 * 8];
private static char[] str = new char[500*8*2];
private static boolean[] isDigit = new boolean[256];
private static boolean[] isSpace = new boolean[256];
private static boolean[] isLineSep = new boolean[256];
static { for(int i = 0; i < 10; i++) { isDigit['0' + i] = true; } isDigit['-'] = true; isSpace[' '] = isSpace['\r'] = isSpace['\n'] = isSpace['\t'] = true; isLineSep['\r'] = isLineSep['\n'] = true; }
public int read() throws IOException { if(pos >= readLen) { pos = 0; readLen = in.read(buffer); if(readLen <= 0) { throw new EndOfFileRuntimeException(); } } return buffer[pos++]; }
public int nextInt() throws IOException { int len = 0; str[len++] = nextChar(); len = reads(len, isSpace); int i = 0; int ret = 0; if(str[0] == '-') { i = 1; } for(; i < len; i++) ret = ret * 10 + str[i] - '0'; if(str[0] == '-') { ret = -ret; } return ret; }
public long nextLong() throws IOException { int len = 0; str[len++] = nextChar(); len = reads(len, isSpace); int i = 0; long ret = 0; if(str[0] == '-') { i = 1; } for(; i < len; i++) ret = ret * 10 + str[i] - '0'; if(str[0] == '-') { ret = -ret; } return ret; }
public char nextChar() throws IOException { while(true) { final int c = read(); if(!isSpace[c]) { return (char)c; } } }
int reads(int len, boolean[] accept) throws IOException { try { while(true) { final int c = read(); if(accept[c]) { break; } if(str.length == len) { char[] rep = new char[str.length * 3 / 2]; System.arraycopy(str, 0, rep, 0, str.length); str = rep; } str[len++] = (char)c; } } catch(EndOfFileRuntimeException e) { ; } return len; }
int reads(char[] cs, int len, boolean[] accept) throws IOException { try { while(true) { final int c = read(); if(accept[c]) { break; } cs[len++] = (char)c; } } catch(EndOfFileRuntimeException e) { ; } return len; }
public char[] nextLine() throws IOException { int len = 0; str[len++] = nextChar(); len = reads(len, isLineSep); try { if(str[len-1] == '\r') { len--; read(); } } catch(EndOfFileRuntimeException e) { ; } return Arrays.copyOf(str, len); }
public String nextString() throws IOException { return new String(next()); }
public char[] next() throws IOException { int len = 0; str[len++] = nextChar(); len = reads(len, isSpace); return Arrays.copyOf(str, len); }
// public int next(char[] cs) throws IOException { int len = 0; cs[len++] = nextChar(); len = reads(cs, len, isSpace); return len; }
public double nextDouble() throws IOException { return Double.parseDouble(nextString()); }
public long[] nextLongArray(final int n) throws IOException { final long[] res = new long[n]; for(int i = 0; i < n; i++) { res[i] = nextLong(); } return res; }
public int[] nextIntArray(final int n) throws IOException { final int[] res = new int[n]; for(int i = 0; i < n; i++) { res[i] = nextInt(); } return res; }
public int[][] nextIntArray2D(final int n, final int k) throws IOException { final int[][] res = new int[n][]; for(int i = 0; i < n; i++) { res[i] = nextIntArray(k); } return res; }
public int[][] nextIntArray2DWithIndex(final int n, final int k) throws IOException { final int[][] res = new int[n][k+1]; for(int i = 0; i < n; i++) { for(int j = 0; j < k; j++) { res[i][j] = nextInt(); } res[i][k] = i; } return res; }
public double[] nextDoubleArray(final int n) throws IOException { final double[] res = new double[n]; for(int i = 0; i < n; i++) { res[i] = nextDouble(); } return res; }
}
}
| Java | ["8 3\n20166766\n1 8\n1 7\n2 8", "15 5\n012016662091670\n3 4\n1 14\n4 15\n1 13\n10 15", "4 2\n1234\n2 4\n1 2"] | 3 seconds | ["4\n3\n-1", "-1\n2\n1\n-1\n-1", "-1\n-1"] | NoteIn the first sample: In the first query, ugliness("20166766") = 4 because all four sixes must be removed. In the second query, ugliness("2016676") = 3 because all three sixes must be removed. In the third query, ugliness("0166766") = - 1 because it's impossible to remove some digits to get a nice string. In the second sample: In the second query, ugliness("01201666209167") = 2. It's optimal to remove the first digit '2' and the last digit '6', what gives a string "010166620917", which is nice. In the third query, ugliness("016662091670") = 1. It's optimal to remove the last digit '6', what gives a nice string "01666209170". | Java 8 | standard input | [
"dp",
"divide and conquer",
"data structures",
"matrices"
] | cf5e72a35509c6ee1a3073c0e514f6bf | The first line of the input contains two integers n and q (4 ≤ n ≤ 200 000, 1 ≤ q ≤ 200 000) — the length of the string s and the number of queries respectively. The second line contains a string s of length n. Every character is one of digits '0'–'9'. The i-th of next q lines contains two integers ai and bi (1 ≤ ai ≤ bi ≤ n), describing a substring in the i-th query. | 2,600 | For each query print the ugliness of the given substring. | standard output | |
PASSED | 3c9930601b32a597daa2706c820280a2 | train_004.jsonl | 1483107300 | A string t is called nice if a string "2017" occurs in t as a subsequence but a string "2016" doesn't occur in t as a subsequence. For example, strings "203434107" and "9220617" are nice, while strings "20016", "1234" and "20167" aren't nice.The ugliness of a string is the minimum possible number of characters to remove, in order to obtain a nice string. If it's impossible to make a string nice by removing characters, its ugliness is - 1.Limak has a string s of length n, with characters indexed 1 through n. He asks you q queries. In the i-th query you should compute and print the ugliness of a substring (continuous subsequence) of s starting at the index ai and ending at the index bi (inclusive). | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
/*
Прокрастинирую
*/
public class Main {
static FastReader in;
static PrintWriter out;
static Random rand = new Random();
static final int INF = (int) (1e9 + 10), MOD = (int) (1e9 + 7), LOGN = 20;
static final long IINF = (long) (2e18 + 10);
static final int N = (int) (1e6 + 6);
static class SegTree {
int sz;
int[][][] t;
int[][] merge(int[][] m1, int[][] m2) {
if (m1 == null) return m2;
if (m2 == null) return m1;
int[][] m = new int[5][5];
for (int i = 0; i < 5; i++) {
for (int j = i; j < 5; j++) {
m[i][j] = INF;
for (int k = i; k <= j; k++) {
if (m1[i][k] == INF || m2[k][j] == INF) continue;
m[i][j] = Math.min(m[i][j], m1[i][k] + m2[k][j]);
}
}
}
return m;
}
void build(char[] s) {
sz = s.length;
t = new int[sz * 4][5][5];
build(0, 0, sz - 1, s);
}
void build(int v, int tl, int tr, char[] s) {
if (tl == tr) {
t[v] = new int[5][5];
for (int i = 0; i < 5; i++) {
for (int j = i; j < 5; j++) {
t[v][i][j] = INF;
}
t[v][i][i] = 0;
}
if (s[tl] == '2') {
t[v][0][0] = 1;
t[v][0][1] = 0;
} else if (s[tl] == '0') {
t[v][1][1] = 1;
t[v][1][2] = 0;
} else if (s[tl] == '1') {
t[v][2][2] = 1;
t[v][2][3] = 0;
} else if (s[tl] == '7') {
t[v][3][3] = 1;
t[v][3][4] = 0;
} else if (s[tl] == '6') {
t[v][3][3] = 1;
t[v][4][4] = 1;
}
return;
}
int tm = (tl + tr) / 2;
build(v * 2 + 1, tl, tm, s);
build(v * 2 + 2, tm + 1, tr, s);
t[v] = merge(t[v * 2 + 1], t[v * 2 + 2]);
}
int[][] query(int v, int tl, int tr, int l, int r) {
if (r < tl || l > tr) return null;
if (l <= tl && tr <= r) {
return t[v];
}
int tm = (tl + tr) / 2;
int[][] m1 = query(v * 2 + 1, tl, tm, l, r);
int[][] m2 = query(v * 2 + 2, tm + 1, tr, l, r);
return merge(m1, m2);
}
int[][] query(int l, int r) {
return query(0, 0, sz - 1, l, r);
}
}
static void solve() {
int n = in.nextInt();
int q = in.nextInt();
char[] s = in.next().toCharArray();
SegTree st = new SegTree();
st.build(s);
for (int i = 0; i < q; i++) {
int l = in.nextInt() - 1;
int r = in.nextInt() - 1;
int[][] m = st.query(l, r);
if (m[0][4] == INF) {
out.println(-1);
} else {
out.println(m[0][4]);
}
}
}
public static void main(String[] args) throws FileNotFoundException, InterruptedException {
in = new FastReader(System.in);
// in = new FastReader(new FileInputStream("input.txt"));
out = new PrintWriter(System.out);
// out = new PrintWriter(new FileOutputStream("output.txt"));
int tests = 1;
// tests = in.nextInt();
while (tests-- > 0) {
solve();
}
// out.flush();
out.close();
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
FastReader(InputStream is) {
br = new BufferedReader(new InputStreamReader(is));
}
Integer nextInt() {
return Integer.parseInt(next());
}
Long nextLong() {
return Long.parseLong(next());
}
Double nextDouble() {
return Double.parseDouble(next());
}
String next() {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(nextLine());
}
return st.nextToken();
}
String nextLine() {
String s = "";
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
}
} | Java | ["8 3\n20166766\n1 8\n1 7\n2 8", "15 5\n012016662091670\n3 4\n1 14\n4 15\n1 13\n10 15", "4 2\n1234\n2 4\n1 2"] | 3 seconds | ["4\n3\n-1", "-1\n2\n1\n-1\n-1", "-1\n-1"] | NoteIn the first sample: In the first query, ugliness("20166766") = 4 because all four sixes must be removed. In the second query, ugliness("2016676") = 3 because all three sixes must be removed. In the third query, ugliness("0166766") = - 1 because it's impossible to remove some digits to get a nice string. In the second sample: In the second query, ugliness("01201666209167") = 2. It's optimal to remove the first digit '2' and the last digit '6', what gives a string "010166620917", which is nice. In the third query, ugliness("016662091670") = 1. It's optimal to remove the last digit '6', what gives a nice string "01666209170". | Java 8 | standard input | [
"dp",
"divide and conquer",
"data structures",
"matrices"
] | cf5e72a35509c6ee1a3073c0e514f6bf | The first line of the input contains two integers n and q (4 ≤ n ≤ 200 000, 1 ≤ q ≤ 200 000) — the length of the string s and the number of queries respectively. The second line contains a string s of length n. Every character is one of digits '0'–'9'. The i-th of next q lines contains two integers ai and bi (1 ≤ ai ≤ bi ≤ n), describing a substring in the i-th query. | 2,600 | For each query print the ugliness of the given substring. | standard output | |
PASSED | 350111d43083ab83ef0310d3a27b58e5 | train_004.jsonl | 1483107300 | A string t is called nice if a string "2017" occurs in t as a subsequence but a string "2016" doesn't occur in t as a subsequence. For example, strings "203434107" and "9220617" are nice, while strings "20016", "1234" and "20167" aren't nice.The ugliness of a string is the minimum possible number of characters to remove, in order to obtain a nice string. If it's impossible to make a string nice by removing characters, its ugliness is - 1.Limak has a string s of length n, with characters indexed 1 through n. He asks you q queries. In the i-th query you should compute and print the ugliness of a substring (continuous subsequence) of s starting at the index ai and ending at the index bi (inclusive). | 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.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Jialin Ouyang (Jialin.Ouyang@gmail.com)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
QuickScanner in = new QuickScanner(inputStream);
QuickWriter out = new QuickWriter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
static class TaskE {
static int INF = 1000000000;
static int MAX_STATE = 4;
static int[][][] TRANSFORM = new int[][][]{
//0 1 2 3
{{0, 1, 3, 4, 5, 6, 7, 8, 9}, {2}, {}, {}}, // 0
{{}, {1, 2, 3, 4, 5, 6, 7, 8, 9}, {0}, {}}, // 1
{{}, {}, {0, 2, 3, 4, 5, 6, 7, 8, 9}, {1}}, // 2
{{}, {}, {}, {0, 1, 2, 3, 4, 5, 7, 8, 9}}, // 3
};
int n;
int q;
int[] last7;
int[] cnt6;
int[][] transform;
char[] s;
public void solve(int testNumber, QuickScanner in, QuickWriter out) {
transform = new int[MAX_STATE][MAX_STATE];
for (int i = 0; i < MAX_STATE; ++i)
for (int j = i; j < MAX_STATE; ++j) {
int mask = 0;
for (int digit : TRANSFORM[i][j]) {
mask |= 1 << digit;
}
transform[i][j] = mask;
}
n = in.nextInt();
q = in.nextInt();
s = new char[n];
in.next(s);
init();
SimpleITree itree = new SimpleITree(n);
for (int i = 0; i < q; ++i) {
int lower = in.nextInt() - 1;
int upper = in.nextInt() - 1;
if (lower < last7[upper]) {
int res = itree.calc(lower, last7[upper]);
res += cnt6[upper] - cnt6[last7[upper] - 1];
out.println(res >= INF ? -1 : res);
} else {
out.println(-1);
}
}
}
void init() {
last7 = new int[n];
cnt6 = new int[n];
int last7Pos = -1;
for (int i = 0; i < n; ++i) {
if (s[i] == '7') {
last7Pos = i;
} else if (s[i] == '6') {
cnt6[i] = 1;
}
if (i > 0) cnt6[i] += cnt6[i - 1];
last7[i] = last7Pos;
}
}
class SimpleITree extends AbstractSimpleIntervalTree {
int[][][] minCost;
int[] resCost = new int[MAX_STATE];
int[] tmpCost = new int[MAX_STATE];
public SimpleITree(int leafCapacity) {
super(leafCapacity);
}
public void createSubclass(int nodeCapacity) {
minCost = new int[MAX_STATE][MAX_STATE][nodeCapacity];
for (int i = 0; i < MAX_STATE; ++i)
for (int j = i; j < MAX_STATE; ++j) {
Arrays.fill(minCost[i][j], INF);
}
}
public void initLeaf(int nodeIdx, int idx) {
for (int i = 0; i < MAX_STATE; ++i) {
minCost[i][i][nodeIdx] = 1;
for (int j = i; j < MAX_STATE; ++j)
if ((transform[i][j] & (1 << (s[idx] - '0'))) > 0) {
minCost[i][j][nodeIdx] = 0;
}
}
}
public void merge(int nodeIdx, int leftNodeIdx, int rightNodeIdx) {
for (int i = 0; i < MAX_STATE; ++i)
for (int j = i; j < MAX_STATE; ++j)
if (minCost[i][j][leftNodeIdx] != INF) {
for (int k = j; k < MAX_STATE; ++k) {
minCost[i][k][nodeIdx] = Math.min(
minCost[i][k][nodeIdx], minCost[i][j][leftNodeIdx] + minCost[j][k][rightNodeIdx]);
}
}
}
int calc(int lower, int upper) {
Arrays.fill(resCost, INF);
resCost[0] = 0;
calcRange(lower, upper);
return resCost[3];
}
public void calcAppend(int nodeIdx, int lower, int upper) {
Arrays.fill(tmpCost, INF);
for (int i = 0; i < MAX_STATE; ++i)
for (int j = i; j < MAX_STATE; ++j) {
tmpCost[j] = Math.min(tmpCost[j], resCost[i] + minCost[i][j][nodeIdx]);
}
for (int i = 0; i < MAX_STATE; ++i) resCost[i] = tmpCost[i];
}
}
}
static class QuickWriter {
private final PrintWriter writer;
public QuickWriter(OutputStream outputStream) {
this.writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public QuickWriter(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.print('\n');
}
public void close() {
writer.close();
}
}
static interface IntCollection {
}
static class QuickScanner {
private static final int BUFFER_SIZE = 1024;
private InputStream stream;
private byte[] buffer;
private int currentPosition;
private int numberOfChars;
public QuickScanner(InputStream stream) {
this.stream = stream;
this.buffer = new byte[BUFFER_SIZE];
this.currentPosition = 0;
this.numberOfChars = 0;
}
public int next(char[] s) {
return next(s, 0);
}
public int next(char[] s, int startIdx) {
int b = nextNonSpaceChar();
int res = 0;
do {
s[startIdx++] = (char) b;
b = nextChar();
++res;
} while (!isSpaceChar(b));
return res;
}
public int nextInt() {
int c = nextNonSpaceChar();
boolean positive = true;
if (c == '-') {
positive = false;
c = nextChar();
}
int res = 0;
do {
if (c < '0' || '9' < c) throw new RuntimeException();
res = res * 10 + c - '0';
c = nextChar();
} while (!isSpaceChar(c));
return positive ? res : -res;
}
public int nextNonSpaceChar() {
int res = nextChar();
for (; isSpaceChar(res) || res < 0; res = nextChar()) ;
return res;
}
public int nextChar() {
if (numberOfChars == -1) {
throw new RuntimeException();
}
if (currentPosition >= numberOfChars) {
currentPosition = 0;
try {
numberOfChars = stream.read(buffer);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (numberOfChars <= 0) {
return -1;
}
}
return buffer[currentPosition++];
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\t' || isEndOfLineChar(c);
}
public boolean isEndOfLineChar(int c) {
return c == '\n' || c == '\r' || c < 0;
}
}
static abstract class AbstractSimpleIntervalTree {
private int n;
private int[] lower;
private int[] upper;
private IntArrayList calcLeftIdx;
private IntArrayList calcRightIdx;
public abstract void createSubclass(int nodeCapacity);
public abstract void initLeaf(int nodeIdx, int idx);
public abstract void merge(int nodeIdx, int leftNodeIdx, int rightNodeIdx);
public abstract void calcAppend(int nodeIdx, int lower, int upper);
public AbstractSimpleIntervalTree(int leafCapacity) {
calcLeftIdx = new IntArrayList();
calcRightIdx = new IntArrayList();
int leafCapacity2 = leafCapacity << 1;
lower = new int[leafCapacity2];
upper = new int[leafCapacity2];
createSubclass(leafCapacity2);
init(leafCapacity);
}
public void init(int n) {
this.n = n;
for (int i = 0; i < n; ++i) {
lower[n + i] = i;
upper[n + i] = i + 1;
initLeaf(n + i, i);
}
for (int i = n - 1; i > 0; --i) {
lower[i] = lower[i << 1];
upper[i] = upper[(i << 1) | 1];
merge(i, i << 1, (i << 1) | 1);
}
}
public void calcRange(int lower, int upper) {
calcLeftIdx.clear();
calcRightIdx.clear();
for (lower += n, upper += n; lower < upper; lower >>= 1, upper >>= 1) {
if ((lower & 1) > 0) calcLeftIdx.add(lower++);
if ((upper & 1) > 0) calcRightIdx.add(--upper);
}
for (int i = 0; i < calcLeftIdx.size; ++i) {
int idx = calcLeftIdx.get(i);
calcAppend(idx, this.lower[idx], this.upper[idx]);
}
for (int i = calcRightIdx.size - 1; i >= 0; --i) {
int idx = calcRightIdx.get(i);
calcAppend(idx, this.lower[idx], this.upper[idx]);
}
}
}
static class IntArrayUtils {
public static String toString(int[] values, int fromIdx, int toIdx) {
StringBuilder sb = new StringBuilder("[");
for (int i = fromIdx; i < toIdx; ++i) {
if (i != fromIdx) sb.append(", ");
sb.append(values[i]);
}
return sb.append("]").toString();
}
}
static class IntArrayList implements IntCollection {
private static int[] EMPTY = {};
public int[] values;
public int size;
public IntArrayList() {
values = EMPTY;
clear();
}
public IntArrayList(int capacity) {
values = new int[Integer.highestOneBit(capacity) << 1];
clear();
}
public void clear() {
size = 0;
}
public void add(int value) {
ensureCapacity(size + 1);
values[size++] = value;
}
public int get(int idx) {
if (idx >= size) throw new ArrayIndexOutOfBoundsException();
return values[idx];
}
public String toString() {
return IntArrayUtils.toString(values, 0, size);
}
protected void ensureCapacity(int capacity) {
if (capacity <= values.length) return;
int[] newValues = new int[Integer.highestOneBit(capacity) << 1];
for (int i = 0; i < values.length; ++i) {
newValues[i] = values[i];
}
values = newValues;
}
}
}
| Java | ["8 3\n20166766\n1 8\n1 7\n2 8", "15 5\n012016662091670\n3 4\n1 14\n4 15\n1 13\n10 15", "4 2\n1234\n2 4\n1 2"] | 3 seconds | ["4\n3\n-1", "-1\n2\n1\n-1\n-1", "-1\n-1"] | NoteIn the first sample: In the first query, ugliness("20166766") = 4 because all four sixes must be removed. In the second query, ugliness("2016676") = 3 because all three sixes must be removed. In the third query, ugliness("0166766") = - 1 because it's impossible to remove some digits to get a nice string. In the second sample: In the second query, ugliness("01201666209167") = 2. It's optimal to remove the first digit '2' and the last digit '6', what gives a string "010166620917", which is nice. In the third query, ugliness("016662091670") = 1. It's optimal to remove the last digit '6', what gives a nice string "01666209170". | Java 8 | standard input | [
"dp",
"divide and conquer",
"data structures",
"matrices"
] | cf5e72a35509c6ee1a3073c0e514f6bf | The first line of the input contains two integers n and q (4 ≤ n ≤ 200 000, 1 ≤ q ≤ 200 000) — the length of the string s and the number of queries respectively. The second line contains a string s of length n. Every character is one of digits '0'–'9'. The i-th of next q lines contains two integers ai and bi (1 ≤ ai ≤ bi ≤ n), describing a substring in the i-th query. | 2,600 | For each query print the ugliness of the given substring. | standard output | |
PASSED | 902703809cbdc00af1c16809830a7183 | train_004.jsonl | 1483107300 | A string t is called nice if a string "2017" occurs in t as a subsequence but a string "2016" doesn't occur in t as a subsequence. For example, strings "203434107" and "9220617" are nice, while strings "20016", "1234" and "20167" aren't nice.The ugliness of a string is the minimum possible number of characters to remove, in order to obtain a nice string. If it's impossible to make a string nice by removing characters, its ugliness is - 1.Limak has a string s of length n, with characters indexed 1 through n. He asks you q queries. In the i-th query you should compute and print the ugliness of a substring (continuous subsequence) of s starting at the index ai and ending at the index bi (inclusive). | 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.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Jialin Ouyang (Jialin.Ouyang@gmail.com)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
QuickScanner in = new QuickScanner(inputStream);
QuickWriter out = new QuickWriter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
static class TaskE {
static int INF = 1000000000;
static int MAX_STATE = 5;
static int[][][] TRANSFORM = new int[][][]{
//0 1 2 3 4
{{0, 1, 3, 4, 5, 6, 7, 8, 9}, {2}, {}, {}, {}}, // 0
{{}, {1, 2, 3, 4, 5, 6, 7, 8, 9}, {0}, {}, {}}, // 1
{{}, {}, {0, 2, 3, 4, 5, 6, 7, 8, 9}, {1}, {}}, // 2
{{}, {}, {}, {0, 1, 2, 3, 4, 5, 8, 9}, {7}}, // 3
{{}, {}, {}, {}, {0, 1, 2, 3, 4, 5, 7, 8, 9}}, // 4
// //0 1 2 3 4 5
// {{0, 1, 3, 4, 5, 6, 7, 8, 9}, {2}, {}, {}, {}, {}}, // 0
// {{}, {1, 2, 3, 4, 5, 6, 7, 8, 9}, {0}, {}, {}, {}}, // 1
// {{}, {}, {0, 2, 3, 4, 5, 6, 7, 8, 9}, {1}, {}, {}}, // 2
// {{}, {}, {}, {0, 1, 2, 3, 4, 5, 8, 9}, {7}, {6}}, // 3
// {{}, {}, {}, {}, {0, 1, 2, 3, 4, 5, 7, 8, 9}, {6}}, // 4
// {{}, {}, {}, {}, {}, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}}, // 5
};
int n;
int q;
int[][] transform;
char[] s;
public void solve(int testNumber, QuickScanner in, QuickWriter out) {
transform = new int[MAX_STATE][MAX_STATE];
for (int i = 0; i < MAX_STATE; ++i)
for (int j = i; j < MAX_STATE; ++j) {
int mask = 0;
for (int digit : TRANSFORM[i][j]) {
mask |= 1 << digit;
}
transform[i][j] = mask;
}
n = in.nextInt();
q = in.nextInt();
s = new char[n];
in.next(s);
// initLast();
ITree itree = new ITree(n);
for (int i = 0; i < q; ++i) {
int lower = in.nextInt() - 1;
int upper = in.nextInt() - 1;
// if (lower <= last2017[upper] && last2016[upper] < lower) {
// out.println(0);
// } else {
out.println(itree.calc(lower, upper + 1));
// }
}
}
class ITree extends AbstractIntervalTree {
int[][][] minCost;
int[] resCost = new int[MAX_STATE];
int[] tmpCost = new int[MAX_STATE];
public ITree(int leafCapacity) {
super(leafCapacity);
}
public void createSubclass(int nodeCapacity) {
// minCost = new int[nodeCapacity][MAX_STATE][MAX_STATE];
// for (int i = 0; i < nodeCapacity; ++i) {
// init(minCost[i]);
// }
minCost = new int[MAX_STATE][MAX_STATE][nodeCapacity];
for (int i = 0; i < MAX_STATE; ++i)
for (int j = i; j < MAX_STATE; ++j) {
Arrays.fill(minCost[i][j], INF);
}
}
public void initLeaf(int nodeIdx, int idx) {
// for (int i = 0; i < MAX_STATE; ++i) {
// minCost[nodeIdx][i][i] = 1;
// for (int j = i; j < MAX_STATE; ++j) if ((transform[i][j] & (1 << (s[idx] - '0'))) > 0) {
// minCost[nodeIdx][i][j] = 0;
// }
// }
for (int i = 0; i < MAX_STATE; ++i) {
minCost[i][i][nodeIdx] = 1;
for (int j = i; j < MAX_STATE; ++j)
if ((transform[i][j] & (1 << (s[idx] - '0'))) > 0) {
minCost[i][j][nodeIdx] = 0;
}
}
}
public void merge(int nodeIdx, int leftNodeIdx, int rightNodeIdx) {
// for (int i = 0; i < MAX_STATE; ++i) for (int j = i; j < MAX_STATE; ++j) if (minCost[leftNodeIdx][i][j] != INF) {
// for (int k = j; k < MAX_STATE; ++k) {
// minCost[nodeIdx][i][k] = Math.min(
// minCost[nodeIdx][i][k], minCost[leftNodeIdx][i][j] + minCost[rightNodeIdx][j][k]);
// }
// }
for (int i = 0; i < MAX_STATE; ++i)
for (int j = i; j < MAX_STATE; ++j)
if (minCost[i][j][leftNodeIdx] != INF) {
for (int k = j; k < MAX_STATE; ++k) {
minCost[i][k][nodeIdx] = Math.min(
minCost[i][k][nodeIdx], minCost[i][j][leftNodeIdx] + minCost[j][k][rightNodeIdx]);
}
}
}
int calc(int lower, int upper) {
Arrays.fill(resCost, INF);
resCost[0] = 0;
calcRange(lower, upper);
return resCost[4] == INF ? -1 : resCost[4];
}
public void calcAppend(int nodeIdx, int lower, int upper) {
Arrays.fill(tmpCost, INF);
for (int i = 0; i < MAX_STATE; ++i)
for (int j = i; j < MAX_STATE; ++j) {
// tmpCost[i][k] = Math.min(tmpCost[i][k], resCost[i][j] + minCost[nodeIdx][j][k]);
tmpCost[j] = Math.min(tmpCost[j], resCost[i] + minCost[i][j][nodeIdx]);
}
for (int i = 0; i < MAX_STATE; ++i) resCost[i] = tmpCost[i];
}
public void pushLazyPropagation(int fromNodeIdx, int toNodeIdx) {
}
public void clearLazyPropagation(int nodeIdx) {
}
}
}
static class QuickWriter {
private final PrintWriter writer;
public QuickWriter(OutputStream outputStream) {
this.writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public QuickWriter(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.print('\n');
}
public void close() {
writer.close();
}
}
static class QuickScanner {
private static final int BUFFER_SIZE = 1024;
private InputStream stream;
private byte[] buffer;
private int currentPosition;
private int numberOfChars;
public QuickScanner(InputStream stream) {
this.stream = stream;
this.buffer = new byte[BUFFER_SIZE];
this.currentPosition = 0;
this.numberOfChars = 0;
}
public int next(char[] s) {
return next(s, 0);
}
public int next(char[] s, int startIdx) {
int b = nextNonSpaceChar();
int res = 0;
do {
s[startIdx++] = (char) b;
b = nextChar();
++res;
} while (!isSpaceChar(b));
return res;
}
public int nextInt() {
int c = nextNonSpaceChar();
boolean positive = true;
if (c == '-') {
positive = false;
c = nextChar();
}
int res = 0;
do {
if (c < '0' || '9' < c) throw new RuntimeException();
res = res * 10 + c - '0';
c = nextChar();
} while (!isSpaceChar(c));
return positive ? res : -res;
}
public int nextNonSpaceChar() {
int res = nextChar();
for (; isSpaceChar(res) || res < 0; res = nextChar()) ;
return res;
}
public int nextChar() {
if (numberOfChars == -1) {
throw new RuntimeException();
}
if (currentPosition >= numberOfChars) {
currentPosition = 0;
try {
numberOfChars = stream.read(buffer);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (numberOfChars <= 0) {
return -1;
}
}
return buffer[currentPosition++];
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\t' || isEndOfLineChar(c);
}
public boolean isEndOfLineChar(int c) {
return c == '\n' || c == '\r' || c < 0;
}
}
static abstract class AbstractIntervalTree {
private int n;
private int left;
private int right;
public abstract void createSubclass(int nodeCapacity);
public abstract void initLeaf(int nodeIdx, int idx);
public abstract void merge(int nodeIdx, int leftNodeIdx, int rightNodeIdx);
public abstract void calcAppend(int nodeIdx, int lower, int upper);
public abstract void pushLazyPropagation(int fromNodeIdx, int toNodeIdx);
public abstract void clearLazyPropagation(int nodeIdx);
public AbstractIntervalTree(int leafCapacity) {
createSubclass(leafCapacity << 2);
init(leafCapacity);
}
public void init(int n) {
this.n = n;
init(0, 0, n);
}
public void calcRange(int lower, int upper) {
left = lower;
right = upper;
calc(0, 0, n);
}
private void init(int nodeIdx, int lower, int upper) {
if (lower + 1 == upper) {
initLeaf(nodeIdx, lower);
return;
}
int medium = (lower + upper) >> 1;
init(toLeft(nodeIdx), lower, medium);
init(toRight(nodeIdx), medium, upper);
merge(nodeIdx, toLeft(nodeIdx), toRight(nodeIdx));
}
private void calc(int nodeIdx, int lower, int upper) {
if (left <= lower && upper <= right) {
calcAppend(nodeIdx, lower, upper);
return;
}
pushLazyPropagation(nodeIdx);
int medium = (lower + upper) >> 1;
if (left < medium) {
calc(toLeft(nodeIdx), lower, medium);
}
if (medium < right) {
calc(toRight(nodeIdx), medium, upper);
}
merge(nodeIdx, toLeft(nodeIdx), toRight(nodeIdx));
}
private void pushLazyPropagation(int nodeIdx) {
pushLazyPropagation(nodeIdx, toLeft(nodeIdx));
pushLazyPropagation(nodeIdx, toRight(nodeIdx));
clearLazyPropagation(nodeIdx);
}
private int toLeft(int nodeIdx) {
return (nodeIdx << 1) | 1;
}
private int toRight(int nodeIdx) {
return (nodeIdx + 1) << 1;
}
}
}
| Java | ["8 3\n20166766\n1 8\n1 7\n2 8", "15 5\n012016662091670\n3 4\n1 14\n4 15\n1 13\n10 15", "4 2\n1234\n2 4\n1 2"] | 3 seconds | ["4\n3\n-1", "-1\n2\n1\n-1\n-1", "-1\n-1"] | NoteIn the first sample: In the first query, ugliness("20166766") = 4 because all four sixes must be removed. In the second query, ugliness("2016676") = 3 because all three sixes must be removed. In the third query, ugliness("0166766") = - 1 because it's impossible to remove some digits to get a nice string. In the second sample: In the second query, ugliness("01201666209167") = 2. It's optimal to remove the first digit '2' and the last digit '6', what gives a string "010166620917", which is nice. In the third query, ugliness("016662091670") = 1. It's optimal to remove the last digit '6', what gives a nice string "01666209170". | Java 8 | standard input | [
"dp",
"divide and conquer",
"data structures",
"matrices"
] | cf5e72a35509c6ee1a3073c0e514f6bf | The first line of the input contains two integers n and q (4 ≤ n ≤ 200 000, 1 ≤ q ≤ 200 000) — the length of the string s and the number of queries respectively. The second line contains a string s of length n. Every character is one of digits '0'–'9'. The i-th of next q lines contains two integers ai and bi (1 ≤ ai ≤ bi ≤ n), describing a substring in the i-th query. | 2,600 | For each query print the ugliness of the given substring. | standard output | |
PASSED | 54ca5536747fed70d2729ac0ce30b8e5 | train_004.jsonl | 1483107300 | A string t is called nice if a string "2017" occurs in t as a subsequence but a string "2016" doesn't occur in t as a subsequence. For example, strings "203434107" and "9220617" are nice, while strings "20016", "1234" and "20167" aren't nice.The ugliness of a string is the minimum possible number of characters to remove, in order to obtain a nice string. If it's impossible to make a string nice by removing characters, its ugliness is - 1.Limak has a string s of length n, with characters indexed 1 through n. He asks you q queries. In the i-th query you should compute and print the ugliness of a substring (continuous subsequence) of s starting at the index ai and ending at the index bi (inclusive). | 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.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Jialin Ouyang (Jialin.Ouyang@gmail.com)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
QuickScanner in = new QuickScanner(inputStream);
QuickWriter out = new QuickWriter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
static class TaskE {
static int INF = 1000000000;
static int MAX_STATE = 5;
static int[][][] TRANSFORM = new int[][][]{
//0 1 2 3 4
{{0, 1, 3, 4, 5, 6, 7, 8, 9}, {2}, {}, {}, {}}, // 0
{{}, {1, 2, 3, 4, 5, 6, 7, 8, 9}, {0}, {}, {}}, // 1
{{}, {}, {0, 2, 3, 4, 5, 6, 7, 8, 9}, {1}, {}}, // 2
{{}, {}, {}, {0, 1, 2, 3, 4, 5, 8, 9}, {7}}, // 3
{{}, {}, {}, {}, {0, 1, 2, 3, 4, 5, 7, 8, 9}}, // 4
// //0 1 2 3 4 5
// {{0, 1, 3, 4, 5, 6, 7, 8, 9}, {2}, {}, {}, {}, {}}, // 0
// {{}, {1, 2, 3, 4, 5, 6, 7, 8, 9}, {0}, {}, {}, {}}, // 1
// {{}, {}, {0, 2, 3, 4, 5, 6, 7, 8, 9}, {1}, {}, {}}, // 2
// {{}, {}, {}, {0, 1, 2, 3, 4, 5, 8, 9}, {7}, {6}}, // 3
// {{}, {}, {}, {}, {0, 1, 2, 3, 4, 5, 7, 8, 9}, {6}}, // 4
// {{}, {}, {}, {}, {}, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}}, // 5
};
int n;
int q;
int[] last2;
int[] last20;
int[] last201;
int[] last2016;
int[] last2017;
int[][] transform;
char[] s;
public void solve(int testNumber, QuickScanner in, QuickWriter out) {
transform = new int[MAX_STATE][MAX_STATE];
for (int i = 0; i < MAX_STATE; ++i)
for (int j = i; j < MAX_STATE; ++j) {
int mask = 0;
for (int digit : TRANSFORM[i][j]) {
mask |= 1 << digit;
}
transform[i][j] = mask;
}
n = in.nextInt();
q = in.nextInt();
s = new char[n];
in.next(s);
initLast();
ITree itree = new ITree(n);
for (int i = 0; i < q; ++i) {
int lower = in.nextInt() - 1;
int upper = in.nextInt() - 1;
if (lower <= last2017[upper] && last2016[upper] < lower) {
out.println(0);
} else {
out.println(itree.calc(lower, upper + 1));
}
}
}
void initLast() {
last2 = new int[n];
last20 = new int[n];
last201 = new int[n];
last2016 = new int[n];
last2017 = new int[n];
calcLast(last2, '2', null);
calcLast(last20, '0', last2);
calcLast(last201, '1', last20);
calcLast(last2016, '6', last201);
calcLast(last2017, '7', last201);
}
void calcLast(int[] last, char digit, int[] prevLast) {
int lastDigit = -1;
for (int i = 0; i < n; ++i) {
if (s[i] == digit) lastDigit = i;
if (lastDigit < 0) {
last[i] = -1;
} else if (prevLast == null) {
last[i] = lastDigit;
} else {
last[i] = prevLast[lastDigit];
}
}
}
class ITree extends AbstractIntervalTree {
int[][][] minCost;
int[][] resCost = new int[MAX_STATE][MAX_STATE];
int[][] tmpCost = new int[MAX_STATE][MAX_STATE];
public ITree(int leafCapacity) {
super(leafCapacity);
}
public void createSubclass(int nodeCapacity) {
// minCost = new int[nodeCapacity][MAX_STATE][MAX_STATE];
// for (int i = 0; i < nodeCapacity; ++i) {
// init(minCost[i]);
// }
minCost = new int[MAX_STATE][MAX_STATE][nodeCapacity];
for (int i = 0; i < MAX_STATE; ++i)
for (int j = i; j < MAX_STATE; ++j) {
Arrays.fill(minCost[i][j], INF);
}
}
public void initLeaf(int nodeIdx, int idx) {
// for (int i = 0; i < MAX_STATE; ++i) {
// minCost[nodeIdx][i][i] = 1;
// for (int j = i; j < MAX_STATE; ++j) if ((transform[i][j] & (1 << (s[idx] - '0'))) > 0) {
// minCost[nodeIdx][i][j] = 0;
// }
// }
for (int i = 0; i < MAX_STATE; ++i) {
minCost[i][i][nodeIdx] = 1;
for (int j = i; j < MAX_STATE; ++j)
if ((transform[i][j] & (1 << (s[idx] - '0'))) > 0) {
minCost[i][j][nodeIdx] = 0;
}
}
}
public void merge(int nodeIdx, int leftNodeIdx, int rightNodeIdx) {
// for (int i = 0; i < MAX_STATE; ++i) for (int j = i; j < MAX_STATE; ++j) if (minCost[leftNodeIdx][i][j] != INF) {
// for (int k = j; k < MAX_STATE; ++k) {
// minCost[nodeIdx][i][k] = Math.min(
// minCost[nodeIdx][i][k], minCost[leftNodeIdx][i][j] + minCost[rightNodeIdx][j][k]);
// }
// }
for (int i = 0; i < MAX_STATE; ++i)
for (int j = i; j < MAX_STATE; ++j)
if (minCost[i][j][leftNodeIdx] != INF) {
for (int k = j; k < MAX_STATE; ++k) {
minCost[i][k][nodeIdx] = Math.min(
minCost[i][k][nodeIdx], minCost[i][j][leftNodeIdx] + minCost[j][k][rightNodeIdx]);
}
}
}
int calc(int lower, int upper) {
init(resCost);
resCost[0][0] = 0;
calcRange(lower, upper);
return resCost[0][4] == INF ? -1 : resCost[0][4];
}
public void calcAppend(int nodeIdx, int lower, int upper) {
init(tmpCost);
for (int i = 0; i < MAX_STATE; ++i)
for (int j = i; j < MAX_STATE; ++j)
if (resCost[i][j] != INF) {
for (int k = j; k < MAX_STATE; ++k) {
// tmpCost[i][k] = Math.min(tmpCost[i][k], resCost[i][j] + minCost[nodeIdx][j][k]);
tmpCost[i][k] = Math.min(tmpCost[i][k], resCost[i][j] + minCost[j][k][nodeIdx]);
}
}
for (int i = 0; i < MAX_STATE; ++i)
for (int j = i; j < MAX_STATE; ++j) {
resCost[i][j] = tmpCost[i][j];
}
}
void init(int[][] cost) {
for (int i = 0; i < MAX_STATE; ++i)
for (int j = i; j < MAX_STATE; ++j) {
cost[i][j] = INF;
}
}
public void pushLazyPropagation(int fromNodeIdx, int toNodeIdx) {
}
public void clearLazyPropagation(int nodeIdx) {
}
}
}
static class QuickWriter {
private final PrintWriter writer;
public QuickWriter(OutputStream outputStream) {
this.writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public QuickWriter(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.print('\n');
}
public void close() {
writer.close();
}
}
static class QuickScanner {
private static final int BUFFER_SIZE = 1024;
private InputStream stream;
private byte[] buffer;
private int currentPosition;
private int numberOfChars;
public QuickScanner(InputStream stream) {
this.stream = stream;
this.buffer = new byte[BUFFER_SIZE];
this.currentPosition = 0;
this.numberOfChars = 0;
}
public int next(char[] s) {
return next(s, 0);
}
public int next(char[] s, int startIdx) {
int b = nextNonSpaceChar();
int res = 0;
do {
s[startIdx++] = (char) b;
b = nextChar();
++res;
} while (!isSpaceChar(b));
return res;
}
public int nextInt() {
int c = nextNonSpaceChar();
boolean positive = true;
if (c == '-') {
positive = false;
c = nextChar();
}
int res = 0;
do {
if (c < '0' || '9' < c) throw new RuntimeException();
res = res * 10 + c - '0';
c = nextChar();
} while (!isSpaceChar(c));
return positive ? res : -res;
}
public int nextNonSpaceChar() {
int res = nextChar();
for (; isSpaceChar(res) || res < 0; res = nextChar()) ;
return res;
}
public int nextChar() {
if (numberOfChars == -1) {
throw new RuntimeException();
}
if (currentPosition >= numberOfChars) {
currentPosition = 0;
try {
numberOfChars = stream.read(buffer);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (numberOfChars <= 0) {
return -1;
}
}
return buffer[currentPosition++];
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\t' || isEndOfLineChar(c);
}
public boolean isEndOfLineChar(int c) {
return c == '\n' || c == '\r' || c < 0;
}
}
static abstract class AbstractIntervalTree {
private int n;
private int left;
private int right;
public abstract void createSubclass(int nodeCapacity);
public abstract void initLeaf(int nodeIdx, int idx);
public abstract void merge(int nodeIdx, int leftNodeIdx, int rightNodeIdx);
public abstract void calcAppend(int nodeIdx, int lower, int upper);
public abstract void pushLazyPropagation(int fromNodeIdx, int toNodeIdx);
public abstract void clearLazyPropagation(int nodeIdx);
public AbstractIntervalTree(int leafCapacity) {
createSubclass(leafCapacity << 2);
init(leafCapacity);
}
public void init(int n) {
this.n = n;
init(0, 0, n);
}
public void calcRange(int lower, int upper) {
left = lower;
right = upper;
calc(0, 0, n);
}
private void init(int nodeIdx, int lower, int upper) {
if (lower + 1 == upper) {
initLeaf(nodeIdx, lower);
return;
}
int medium = (lower + upper) >> 1;
init(toLeft(nodeIdx), lower, medium);
init(toRight(nodeIdx), medium, upper);
merge(nodeIdx, toLeft(nodeIdx), toRight(nodeIdx));
}
private void calc(int nodeIdx, int lower, int upper) {
if (left <= lower && upper <= right) {
calcAppend(nodeIdx, lower, upper);
return;
}
pushLazyPropagation(nodeIdx);
int medium = (lower + upper) >> 1;
if (left < medium) {
calc(toLeft(nodeIdx), lower, medium);
}
if (medium < right) {
calc(toRight(nodeIdx), medium, upper);
}
merge(nodeIdx, toLeft(nodeIdx), toRight(nodeIdx));
}
private void pushLazyPropagation(int nodeIdx) {
pushLazyPropagation(nodeIdx, toLeft(nodeIdx));
pushLazyPropagation(nodeIdx, toRight(nodeIdx));
clearLazyPropagation(nodeIdx);
}
private int toLeft(int nodeIdx) {
return (nodeIdx << 1) | 1;
}
private int toRight(int nodeIdx) {
return (nodeIdx + 1) << 1;
}
}
}
| Java | ["8 3\n20166766\n1 8\n1 7\n2 8", "15 5\n012016662091670\n3 4\n1 14\n4 15\n1 13\n10 15", "4 2\n1234\n2 4\n1 2"] | 3 seconds | ["4\n3\n-1", "-1\n2\n1\n-1\n-1", "-1\n-1"] | NoteIn the first sample: In the first query, ugliness("20166766") = 4 because all four sixes must be removed. In the second query, ugliness("2016676") = 3 because all three sixes must be removed. In the third query, ugliness("0166766") = - 1 because it's impossible to remove some digits to get a nice string. In the second sample: In the second query, ugliness("01201666209167") = 2. It's optimal to remove the first digit '2' and the last digit '6', what gives a string "010166620917", which is nice. In the third query, ugliness("016662091670") = 1. It's optimal to remove the last digit '6', what gives a nice string "01666209170". | Java 8 | standard input | [
"dp",
"divide and conquer",
"data structures",
"matrices"
] | cf5e72a35509c6ee1a3073c0e514f6bf | The first line of the input contains two integers n and q (4 ≤ n ≤ 200 000, 1 ≤ q ≤ 200 000) — the length of the string s and the number of queries respectively. The second line contains a string s of length n. Every character is one of digits '0'–'9'. The i-th of next q lines contains two integers ai and bi (1 ≤ ai ≤ bi ≤ n), describing a substring in the i-th query. | 2,600 | For each query print the ugliness of the given substring. | standard output | |
PASSED | 57bb0ff86b46e5f674d810a22fe24f5c | train_004.jsonl | 1483107300 | A string t is called nice if a string "2017" occurs in t as a subsequence but a string "2016" doesn't occur in t as a subsequence. For example, strings "203434107" and "9220617" are nice, while strings "20016", "1234" and "20167" aren't nice.The ugliness of a string is the minimum possible number of characters to remove, in order to obtain a nice string. If it's impossible to make a string nice by removing characters, its ugliness is - 1.Limak has a string s of length n, with characters indexed 1 through n. He asks you q queries. In the i-th query you should compute and print the ugliness of a substring (continuous subsequence) of s starting at the index ai and ending at the index bi (inclusive). | 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.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Jialin Ouyang (Jialin.Ouyang@gmail.com)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
QuickScanner in = new QuickScanner(inputStream);
QuickWriter out = new QuickWriter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
static class TaskE {
static int INF = 1000000000;
static int MAX_STATE = 4;
static int[][][] TRANSFORM = new int[][][]{
//0 1 2 3
{{0, 1, 3, 4, 5, 6, 7, 8, 9}, {2}, {}, {}}, // 0
{{}, {1, 2, 3, 4, 5, 6, 7, 8, 9}, {0}, {}}, // 1
{{}, {}, {0, 2, 3, 4, 5, 6, 7, 8, 9}, {1}}, // 2
{{}, {}, {}, {0, 1, 2, 3, 4, 5, 7, 8, 9}}, // 3
// //0 1 2 3 4
// {{0, 1, 3, 4, 5, 6, 7, 8, 9}, {2}, {}, {}, {}}, // 0
// {{}, {1, 2, 3, 4, 5, 6, 7, 8, 9}, {0}, {}, {}}, // 1
// {{}, {}, {0, 2, 3, 4, 5, 6, 7, 8, 9}, {1}, {}}, // 2
// {{}, {}, {}, {0, 1, 2, 3, 4, 5, 8, 9}, {7}}, // 3
// {{}, {}, {}, {}, {0, 1, 2, 3, 4, 5, 7, 8, 9}}, // 4
};
int n;
int q;
int[] last7;
int[] cnt6;
int[][] transform;
char[] s;
public void solve(int testNumber, QuickScanner in, QuickWriter out) {
transform = new int[MAX_STATE][MAX_STATE];
for (int i = 0; i < MAX_STATE; ++i)
for (int j = i; j < MAX_STATE; ++j) {
int mask = 0;
for (int digit : TRANSFORM[i][j]) {
mask |= 1 << digit;
}
transform[i][j] = mask;
}
n = in.nextInt();
q = in.nextInt();
s = new char[n];
in.next(s);
init();
ITree itree = new ITree(n);
for (int i = 0; i < q; ++i) {
int lower = in.nextInt() - 1;
int upper = in.nextInt() - 1;
if (lower < last7[upper]) {
int res = itree.calc(lower, last7[upper]);
res += cnt6[upper] - cnt6[last7[upper] - 1];
out.println(res >= INF ? -1 : res);
} else {
out.println(-1);
}
}
}
void init() {
last7 = new int[n];
cnt6 = new int[n];
int last7Pos = -1;
for (int i = 0; i < n; ++i) {
if (s[i] == '7') {
last7Pos = i;
} else if (s[i] == '6') {
cnt6[i] = 1;
}
if (i > 0) cnt6[i] += cnt6[i - 1];
last7[i] = last7Pos;
}
}
class ITree extends AbstractIntervalTree {
int[][][] minCost;
int[] resCost = new int[MAX_STATE];
int[] tmpCost = new int[MAX_STATE];
public ITree(int leafCapacity) {
super(leafCapacity);
}
public void createSubclass(int nodeCapacity) {
minCost = new int[MAX_STATE][MAX_STATE][nodeCapacity];
for (int i = 0; i < MAX_STATE; ++i)
for (int j = i; j < MAX_STATE; ++j) {
Arrays.fill(minCost[i][j], INF);
}
}
public void initLeaf(int nodeIdx, int idx) {
for (int i = 0; i < MAX_STATE; ++i) {
minCost[i][i][nodeIdx] = 1;
for (int j = i; j < MAX_STATE; ++j)
if ((transform[i][j] & (1 << (s[idx] - '0'))) > 0) {
minCost[i][j][nodeIdx] = 0;
}
}
}
public void merge(int nodeIdx, int leftNodeIdx, int rightNodeIdx) {
for (int i = 0; i < MAX_STATE; ++i)
for (int j = i; j < MAX_STATE; ++j)
if (minCost[i][j][leftNodeIdx] != INF) {
for (int k = j; k < MAX_STATE; ++k) {
minCost[i][k][nodeIdx] = Math.min(
minCost[i][k][nodeIdx], minCost[i][j][leftNodeIdx] + minCost[j][k][rightNodeIdx]);
}
}
}
int calc(int lower, int upper) {
Arrays.fill(resCost, INF);
resCost[0] = 0;
calcRange(lower, upper);
return resCost[3];
}
public void calcAppend(int nodeIdx, int lower, int upper) {
Arrays.fill(tmpCost, INF);
for (int i = 0; i < MAX_STATE; ++i)
for (int j = i; j < MAX_STATE; ++j) {
tmpCost[j] = Math.min(tmpCost[j], resCost[i] + minCost[i][j][nodeIdx]);
}
for (int i = 0; i < MAX_STATE; ++i) resCost[i] = tmpCost[i];
}
public void pushLazyPropagation(int fromNodeIdx, int toNodeIdx) {
}
public void clearLazyPropagation(int nodeIdx) {
}
}
}
static class QuickWriter {
private final PrintWriter writer;
public QuickWriter(OutputStream outputStream) {
this.writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public QuickWriter(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.print('\n');
}
public void close() {
writer.close();
}
}
static class QuickScanner {
private static final int BUFFER_SIZE = 1024;
private InputStream stream;
private byte[] buffer;
private int currentPosition;
private int numberOfChars;
public QuickScanner(InputStream stream) {
this.stream = stream;
this.buffer = new byte[BUFFER_SIZE];
this.currentPosition = 0;
this.numberOfChars = 0;
}
public int next(char[] s) {
return next(s, 0);
}
public int next(char[] s, int startIdx) {
int b = nextNonSpaceChar();
int res = 0;
do {
s[startIdx++] = (char) b;
b = nextChar();
++res;
} while (!isSpaceChar(b));
return res;
}
public int nextInt() {
int c = nextNonSpaceChar();
boolean positive = true;
if (c == '-') {
positive = false;
c = nextChar();
}
int res = 0;
do {
if (c < '0' || '9' < c) throw new RuntimeException();
res = res * 10 + c - '0';
c = nextChar();
} while (!isSpaceChar(c));
return positive ? res : -res;
}
public int nextNonSpaceChar() {
int res = nextChar();
for (; isSpaceChar(res) || res < 0; res = nextChar()) ;
return res;
}
public int nextChar() {
if (numberOfChars == -1) {
throw new RuntimeException();
}
if (currentPosition >= numberOfChars) {
currentPosition = 0;
try {
numberOfChars = stream.read(buffer);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (numberOfChars <= 0) {
return -1;
}
}
return buffer[currentPosition++];
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\t' || isEndOfLineChar(c);
}
public boolean isEndOfLineChar(int c) {
return c == '\n' || c == '\r' || c < 0;
}
}
static abstract class AbstractIntervalTree {
private int n;
private int left;
private int right;
public abstract void createSubclass(int nodeCapacity);
public abstract void initLeaf(int nodeIdx, int idx);
public abstract void merge(int nodeIdx, int leftNodeIdx, int rightNodeIdx);
public abstract void calcAppend(int nodeIdx, int lower, int upper);
public abstract void pushLazyPropagation(int fromNodeIdx, int toNodeIdx);
public abstract void clearLazyPropagation(int nodeIdx);
public AbstractIntervalTree(int leafCapacity) {
createSubclass(leafCapacity << 2);
init(leafCapacity);
}
public void init(int n) {
this.n = n;
init(0, 0, n);
}
public void calcRange(int lower, int upper) {
left = lower;
right = upper;
calc(0, 0, n);
}
private void init(int nodeIdx, int lower, int upper) {
if (lower + 1 == upper) {
initLeaf(nodeIdx, lower);
return;
}
int medium = (lower + upper) >> 1;
init(toLeft(nodeIdx), lower, medium);
init(toRight(nodeIdx), medium, upper);
merge(nodeIdx, toLeft(nodeIdx), toRight(nodeIdx));
}
private void calc(int nodeIdx, int lower, int upper) {
if (left <= lower && upper <= right) {
calcAppend(nodeIdx, lower, upper);
return;
}
pushLazyPropagation(nodeIdx);
int medium = (lower + upper) >> 1;
if (left < medium) {
calc(toLeft(nodeIdx), lower, medium);
}
if (medium < right) {
calc(toRight(nodeIdx), medium, upper);
}
merge(nodeIdx, toLeft(nodeIdx), toRight(nodeIdx));
}
private void pushLazyPropagation(int nodeIdx) {
pushLazyPropagation(nodeIdx, toLeft(nodeIdx));
pushLazyPropagation(nodeIdx, toRight(nodeIdx));
clearLazyPropagation(nodeIdx);
}
private int toLeft(int nodeIdx) {
return (nodeIdx << 1) | 1;
}
private int toRight(int nodeIdx) {
return (nodeIdx + 1) << 1;
}
}
}
| Java | ["8 3\n20166766\n1 8\n1 7\n2 8", "15 5\n012016662091670\n3 4\n1 14\n4 15\n1 13\n10 15", "4 2\n1234\n2 4\n1 2"] | 3 seconds | ["4\n3\n-1", "-1\n2\n1\n-1\n-1", "-1\n-1"] | NoteIn the first sample: In the first query, ugliness("20166766") = 4 because all four sixes must be removed. In the second query, ugliness("2016676") = 3 because all three sixes must be removed. In the third query, ugliness("0166766") = - 1 because it's impossible to remove some digits to get a nice string. In the second sample: In the second query, ugliness("01201666209167") = 2. It's optimal to remove the first digit '2' and the last digit '6', what gives a string "010166620917", which is nice. In the third query, ugliness("016662091670") = 1. It's optimal to remove the last digit '6', what gives a nice string "01666209170". | Java 8 | standard input | [
"dp",
"divide and conquer",
"data structures",
"matrices"
] | cf5e72a35509c6ee1a3073c0e514f6bf | The first line of the input contains two integers n and q (4 ≤ n ≤ 200 000, 1 ≤ q ≤ 200 000) — the length of the string s and the number of queries respectively. The second line contains a string s of length n. Every character is one of digits '0'–'9'. The i-th of next q lines contains two integers ai and bi (1 ≤ ai ≤ bi ≤ n), describing a substring in the i-th query. | 2,600 | For each query print the ugliness of the given substring. | standard output | |
PASSED | 23a5037e321295aa735388f181ed8bcd | train_004.jsonl | 1483107300 | A string t is called nice if a string "2017" occurs in t as a subsequence but a string "2016" doesn't occur in t as a subsequence. For example, strings "203434107" and "9220617" are nice, while strings "20016", "1234" and "20167" aren't nice.The ugliness of a string is the minimum possible number of characters to remove, in order to obtain a nice string. If it's impossible to make a string nice by removing characters, its ugliness is - 1.Limak has a string s of length n, with characters indexed 1 through n. He asks you q queries. In the i-th query you should compute and print the ugliness of a substring (continuous subsequence) of s starting at the index ai and ending at the index bi (inclusive). | 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.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Jialin Ouyang (Jialin.Ouyang@gmail.com)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
QuickScanner in = new QuickScanner(inputStream);
QuickWriter out = new QuickWriter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
static class TaskE {
static int INF = 1000000000;
static int MAX_STATE = 5;
static int[][][] TRANSFORM = new int[][][]{
//0 1 2 3 4
{{0, 1, 3, 4, 5, 6, 7, 8, 9}, {2}, {}, {}, {}}, // 0
{{}, {1, 2, 3, 4, 5, 6, 7, 8, 9}, {0}, {}, {}}, // 1
{{}, {}, {0, 2, 3, 4, 5, 6, 7, 8, 9}, {1}, {}}, // 2
{{}, {}, {}, {0, 1, 2, 3, 4, 5, 8, 9}, {7}}, // 3
{{}, {}, {}, {}, {0, 1, 2, 3, 4, 5, 7, 8, 9}}, // 4
// //0 1 2 3 4 5
// {{0, 1, 3, 4, 5, 6, 7, 8, 9}, {2}, {}, {}, {}, {}}, // 0
// {{}, {1, 2, 3, 4, 5, 6, 7, 8, 9}, {0}, {}, {}, {}}, // 1
// {{}, {}, {0, 2, 3, 4, 5, 6, 7, 8, 9}, {1}, {}, {}}, // 2
// {{}, {}, {}, {0, 1, 2, 3, 4, 5, 8, 9}, {7}, {6}}, // 3
// {{}, {}, {}, {}, {0, 1, 2, 3, 4, 5, 7, 8, 9}, {6}}, // 4
// {{}, {}, {}, {}, {}, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}}, // 5
};
int n;
int q;
int[][] transform;
char[] s;
public void solve(int testNumber, QuickScanner in, QuickWriter out) {
transform = new int[MAX_STATE][MAX_STATE];
for (int i = 0; i < MAX_STATE; ++i)
for (int j = i; j < MAX_STATE; ++j) {
int mask = 0;
for (int digit : TRANSFORM[i][j]) {
mask |= 1 << digit;
}
transform[i][j] = mask;
}
n = in.nextInt();
q = in.nextInt();
s = new char[n];
in.next(s);
// initLast();
ITree itree = new ITree(n);
for (int i = 0; i < q; ++i) {
int lower = in.nextInt() - 1;
int upper = in.nextInt() - 1;
// if (lower <= last2017[upper] && last2016[upper] < lower) {
// out.println(0);
// } else {
out.println(itree.calc(lower, upper + 1));
// }
}
}
class ITree extends AbstractIntervalTree {
int[][][] minCost;
int[][] resCost = new int[MAX_STATE][MAX_STATE];
int[][] tmpCost = new int[MAX_STATE][MAX_STATE];
public ITree(int leafCapacity) {
super(leafCapacity);
}
public void createSubclass(int nodeCapacity) {
// minCost = new int[nodeCapacity][MAX_STATE][MAX_STATE];
// for (int i = 0; i < nodeCapacity; ++i) {
// init(minCost[i]);
// }
minCost = new int[MAX_STATE][MAX_STATE][nodeCapacity];
for (int i = 0; i < MAX_STATE; ++i)
for (int j = i; j < MAX_STATE; ++j) {
Arrays.fill(minCost[i][j], INF);
}
}
public void initLeaf(int nodeIdx, int idx) {
// for (int i = 0; i < MAX_STATE; ++i) {
// minCost[nodeIdx][i][i] = 1;
// for (int j = i; j < MAX_STATE; ++j) if ((transform[i][j] & (1 << (s[idx] - '0'))) > 0) {
// minCost[nodeIdx][i][j] = 0;
// }
// }
for (int i = 0; i < MAX_STATE; ++i) {
minCost[i][i][nodeIdx] = 1;
for (int j = i; j < MAX_STATE; ++j)
if ((transform[i][j] & (1 << (s[idx] - '0'))) > 0) {
minCost[i][j][nodeIdx] = 0;
}
}
}
public void merge(int nodeIdx, int leftNodeIdx, int rightNodeIdx) {
// for (int i = 0; i < MAX_STATE; ++i) for (int j = i; j < MAX_STATE; ++j) if (minCost[leftNodeIdx][i][j] != INF) {
// for (int k = j; k < MAX_STATE; ++k) {
// minCost[nodeIdx][i][k] = Math.min(
// minCost[nodeIdx][i][k], minCost[leftNodeIdx][i][j] + minCost[rightNodeIdx][j][k]);
// }
// }
for (int i = 0; i < MAX_STATE; ++i)
for (int j = i; j < MAX_STATE; ++j)
if (minCost[i][j][leftNodeIdx] != INF) {
for (int k = j; k < MAX_STATE; ++k) {
minCost[i][k][nodeIdx] = Math.min(
minCost[i][k][nodeIdx], minCost[i][j][leftNodeIdx] + minCost[j][k][rightNodeIdx]);
}
}
}
int calc(int lower, int upper) {
init(resCost);
resCost[0][0] = 0;
calcRange(lower, upper);
return resCost[0][4] == INF ? -1 : resCost[0][4];
}
public void calcAppend(int nodeIdx, int lower, int upper) {
init(tmpCost);
for (int i = 0; i < MAX_STATE; ++i)
for (int j = i; j < MAX_STATE; ++j)
if (resCost[i][j] != INF) {
for (int k = j; k < MAX_STATE; ++k) {
// tmpCost[i][k] = Math.min(tmpCost[i][k], resCost[i][j] + minCost[nodeIdx][j][k]);
tmpCost[i][k] = Math.min(tmpCost[i][k], resCost[i][j] + minCost[j][k][nodeIdx]);
}
}
for (int i = 0; i < MAX_STATE; ++i)
for (int j = i; j < MAX_STATE; ++j) {
resCost[i][j] = tmpCost[i][j];
}
}
void init(int[][] cost) {
for (int i = 0; i < MAX_STATE; ++i)
for (int j = i; j < MAX_STATE; ++j) {
cost[i][j] = INF;
}
}
public void pushLazyPropagation(int fromNodeIdx, int toNodeIdx) {
}
public void clearLazyPropagation(int nodeIdx) {
}
}
}
static class QuickWriter {
private final PrintWriter writer;
public QuickWriter(OutputStream outputStream) {
this.writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public QuickWriter(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.print('\n');
}
public void close() {
writer.close();
}
}
static class QuickScanner {
private static final int BUFFER_SIZE = 1024;
private InputStream stream;
private byte[] buffer;
private int currentPosition;
private int numberOfChars;
public QuickScanner(InputStream stream) {
this.stream = stream;
this.buffer = new byte[BUFFER_SIZE];
this.currentPosition = 0;
this.numberOfChars = 0;
}
public int next(char[] s) {
return next(s, 0);
}
public int next(char[] s, int startIdx) {
int b = nextNonSpaceChar();
int res = 0;
do {
s[startIdx++] = (char) b;
b = nextChar();
++res;
} while (!isSpaceChar(b));
return res;
}
public int nextInt() {
int c = nextNonSpaceChar();
boolean positive = true;
if (c == '-') {
positive = false;
c = nextChar();
}
int res = 0;
do {
if (c < '0' || '9' < c) throw new RuntimeException();
res = res * 10 + c - '0';
c = nextChar();
} while (!isSpaceChar(c));
return positive ? res : -res;
}
public int nextNonSpaceChar() {
int res = nextChar();
for (; isSpaceChar(res) || res < 0; res = nextChar()) ;
return res;
}
public int nextChar() {
if (numberOfChars == -1) {
throw new RuntimeException();
}
if (currentPosition >= numberOfChars) {
currentPosition = 0;
try {
numberOfChars = stream.read(buffer);
} catch (Exception e) {
throw new RuntimeException(e);
}
if (numberOfChars <= 0) {
return -1;
}
}
return buffer[currentPosition++];
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\t' || isEndOfLineChar(c);
}
public boolean isEndOfLineChar(int c) {
return c == '\n' || c == '\r' || c < 0;
}
}
static abstract class AbstractIntervalTree {
private int n;
private int left;
private int right;
public abstract void createSubclass(int nodeCapacity);
public abstract void initLeaf(int nodeIdx, int idx);
public abstract void merge(int nodeIdx, int leftNodeIdx, int rightNodeIdx);
public abstract void calcAppend(int nodeIdx, int lower, int upper);
public abstract void pushLazyPropagation(int fromNodeIdx, int toNodeIdx);
public abstract void clearLazyPropagation(int nodeIdx);
public AbstractIntervalTree(int leafCapacity) {
createSubclass(leafCapacity << 2);
init(leafCapacity);
}
public void init(int n) {
this.n = n;
init(0, 0, n);
}
public void calcRange(int lower, int upper) {
left = lower;
right = upper;
calc(0, 0, n);
}
private void init(int nodeIdx, int lower, int upper) {
if (lower + 1 == upper) {
initLeaf(nodeIdx, lower);
return;
}
int medium = (lower + upper) >> 1;
init(toLeft(nodeIdx), lower, medium);
init(toRight(nodeIdx), medium, upper);
merge(nodeIdx, toLeft(nodeIdx), toRight(nodeIdx));
}
private void calc(int nodeIdx, int lower, int upper) {
if (left <= lower && upper <= right) {
calcAppend(nodeIdx, lower, upper);
return;
}
pushLazyPropagation(nodeIdx);
int medium = (lower + upper) >> 1;
if (left < medium) {
calc(toLeft(nodeIdx), lower, medium);
}
if (medium < right) {
calc(toRight(nodeIdx), medium, upper);
}
merge(nodeIdx, toLeft(nodeIdx), toRight(nodeIdx));
}
private void pushLazyPropagation(int nodeIdx) {
pushLazyPropagation(nodeIdx, toLeft(nodeIdx));
pushLazyPropagation(nodeIdx, toRight(nodeIdx));
clearLazyPropagation(nodeIdx);
}
private int toLeft(int nodeIdx) {
return (nodeIdx << 1) | 1;
}
private int toRight(int nodeIdx) {
return (nodeIdx + 1) << 1;
}
}
}
| Java | ["8 3\n20166766\n1 8\n1 7\n2 8", "15 5\n012016662091670\n3 4\n1 14\n4 15\n1 13\n10 15", "4 2\n1234\n2 4\n1 2"] | 3 seconds | ["4\n3\n-1", "-1\n2\n1\n-1\n-1", "-1\n-1"] | NoteIn the first sample: In the first query, ugliness("20166766") = 4 because all four sixes must be removed. In the second query, ugliness("2016676") = 3 because all three sixes must be removed. In the third query, ugliness("0166766") = - 1 because it's impossible to remove some digits to get a nice string. In the second sample: In the second query, ugliness("01201666209167") = 2. It's optimal to remove the first digit '2' and the last digit '6', what gives a string "010166620917", which is nice. In the third query, ugliness("016662091670") = 1. It's optimal to remove the last digit '6', what gives a nice string "01666209170". | Java 8 | standard input | [
"dp",
"divide and conquer",
"data structures",
"matrices"
] | cf5e72a35509c6ee1a3073c0e514f6bf | The first line of the input contains two integers n and q (4 ≤ n ≤ 200 000, 1 ≤ q ≤ 200 000) — the length of the string s and the number of queries respectively. The second line contains a string s of length n. Every character is one of digits '0'–'9'. The i-th of next q lines contains two integers ai and bi (1 ≤ ai ≤ bi ≤ n), describing a substring in the i-th query. | 2,600 | For each query print the ugliness of the given substring. | standard output | |
PASSED | 8c6f0db08c4e593925dbbd8455a6bb69 | train_004.jsonl | 1483107300 | A string t is called nice if a string "2017" occurs in t as a subsequence but a string "2016" doesn't occur in t as a subsequence. For example, strings "203434107" and "9220617" are nice, while strings "20016", "1234" and "20167" aren't nice.The ugliness of a string is the minimum possible number of characters to remove, in order to obtain a nice string. If it's impossible to make a string nice by removing characters, its ugliness is - 1.Limak has a string s of length n, with characters indexed 1 through n. He asks you q queries. In the i-th query you should compute and print the ugliness of a substring (continuous subsequence) of s starting at the index ai and ending at the index bi (inclusive). | 256 megabytes | import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException
{
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(1, in, out);
out.close();
}
static class Task {
static final int STATES = 5;
static final int inf = (int)1e9;
int t[][][];
String number;
boolean first;
int[][] tmp;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int q = in.nextInt();
number = in.nextToken();
t = new int[4 * n + 1][STATES][STATES];
build(1 , 0 , n - 1);
int[][] res = new int[STATES][STATES];
tmp = new int[STATES][STATES];
for(int cc = 0; cc < q; cc ++ ){
int l = in.nextInt() - 1;
int r = in.nextInt() - 1;
first = false;
query(1, 0 , n - 1, l, r, res);
int sol = res[0][4];
if(sol >= inf)sol = -1;
out.println(sol);
}
}
void merge(int[][] res, int[][] a , int[][] b){
for(int[] x: res)Arrays.fill(x, inf);
for(int i = 0; i < STATES; i++ )
for(int j = 0; j < STATES; j++)
for(int k = 0; k < STATES; k++)
res[i][j] = Math.min(res[i][j], a[i][k] + b[k][j]);
}
private void build(int v, int b, int e) {
if(b == e){
create(v , number.charAt(b) - '0');
return;
}
int mid = (b + e) >> 1;
build(2 * v , b , mid);
build(2 * v + 1 , mid + 1 , e);
merge(t[v] , t[2 * v], t[2 * v + 1]);
}
public void query(int v , int b , int e , int l , int r, int[][] res)
{
if(b >= l && e <= r){
if(!first){
for( int i = 0; i < STATES; i++)
System.arraycopy(t[v][i], 0, res[i], 0, STATES);
first = true;
}
else
{
merge(tmp , res , t[v]);
for( int i = 0; i < STATES; i++)
System.arraycopy(tmp[i], 0, res[i], 0, STATES);
}
return;
}
int m = (b + e) >> 1;
if(m >= r) {
query(2 * v , b , m , l, r, res);
} else if(m < l) {
query(2 * v + 1, m + 1 , e , l, r, res);
} else {
query(2 * v , b , m , l, r, res);
query(2 * v + 1, m + 1 , e , l, r, res);
}
}
private void create(int v, int digit) {
int[][] mat = t[v];
for(int[] x: mat)Arrays.fill(x, inf);
for( int src = 0; src < STATES; src++ ){
int dst = src;
if (digit == 2) {
if (src == 0) dst = 1;
} else if (digit == 0) {
if (src == 1) dst = 2;
} else if (digit == 1) {
if (src == 2) dst = 3;
} else if (digit == 7) {
if (src == 3) dst = 4;
} else if (digit == 6) {
//
if (src == 3 || src == 4){
mat[src][src] = 1;
continue;
}
}
mat[src][dst] = 0;
if (dst != src)
mat[src][src] = 1;
}
}
}
static class InputReader {
BufferedReader in;
StringTokenizer tok;
public InputReader(InputStream stream){
in = new BufferedReader(new InputStreamReader(stream), 32768);
tok = null;
}
String nextToken()
{
String line = "";
while(tok == null || !tok.hasMoreTokens()) {
try {
if((line = in.readLine()) != null)
tok = new StringTokenizer(line);
else
return null;
} catch (IOException e) {
//e.printStackTrace();
return null;
}
}
return tok.nextToken();
}
int nextInt(){
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
| Java | ["8 3\n20166766\n1 8\n1 7\n2 8", "15 5\n012016662091670\n3 4\n1 14\n4 15\n1 13\n10 15", "4 2\n1234\n2 4\n1 2"] | 3 seconds | ["4\n3\n-1", "-1\n2\n1\n-1\n-1", "-1\n-1"] | NoteIn the first sample: In the first query, ugliness("20166766") = 4 because all four sixes must be removed. In the second query, ugliness("2016676") = 3 because all three sixes must be removed. In the third query, ugliness("0166766") = - 1 because it's impossible to remove some digits to get a nice string. In the second sample: In the second query, ugliness("01201666209167") = 2. It's optimal to remove the first digit '2' and the last digit '6', what gives a string "010166620917", which is nice. In the third query, ugliness("016662091670") = 1. It's optimal to remove the last digit '6', what gives a nice string "01666209170". | Java 8 | standard input | [
"dp",
"divide and conquer",
"data structures",
"matrices"
] | cf5e72a35509c6ee1a3073c0e514f6bf | The first line of the input contains two integers n and q (4 ≤ n ≤ 200 000, 1 ≤ q ≤ 200 000) — the length of the string s and the number of queries respectively. The second line contains a string s of length n. Every character is one of digits '0'–'9'. The i-th of next q lines contains two integers ai and bi (1 ≤ ai ≤ bi ≤ n), describing a substring in the i-th query. | 2,600 | For each query print the ugliness of the given substring. | standard output | |
PASSED | eaaa1133e2fd9711cdc92c1ff46636f2 | train_004.jsonl | 1483107300 | A string t is called nice if a string "2017" occurs in t as a subsequence but a string "2016" doesn't occur in t as a subsequence. For example, strings "203434107" and "9220617" are nice, while strings "20016", "1234" and "20167" aren't nice.The ugliness of a string is the minimum possible number of characters to remove, in order to obtain a nice string. If it's impossible to make a string nice by removing characters, its ugliness is - 1.Limak has a string s of length n, with characters indexed 1 through n. He asks you q queries. In the i-th query you should compute and print the ugliness of a substring (continuous subsequence) of s starting at the index ai and ending at the index bi (inclusive). | 256 megabytes | import java.io.*;
import java.util.*;
public class CF {
FastScanner in;
PrintWriter out;
ArrayList<Integer>[] start;
int[] left, right;
String ask = "2016";
void go(int l, int r) {
if (l == r) {
return;
}
int m = (l + r + 1) >> 1;
go(l, m - 1);
go(m, r);
int prevId = n;
for (int pos = m; pos <= r; pos++) {
for (int i = 0; i < 4; i++) {
for (int j = i; j < 4; j++) {
dpRight[i][j][pos] = Integer.MAX_VALUE;
if (s[pos] != ask.charAt(j)) {
dpRight[i][j][pos] = dpRight[i][j][prevId];
} else {
if (dpRight[i][j][prevId] != Integer.MAX_VALUE) {
dpRight[i][j][pos] = dpRight[i][j][prevId] + 1;
}
}
if (i != j
&& dpRight[i][j - 1][prevId] != Integer.MAX_VALUE) {
if (ask.charAt(j - 1) == s[pos]) {
dpRight[i][j][pos] = Math.min(dpRight[i][j][pos],
dpRight[i][j - 1][prevId]);
}
}
}
}
prevId = pos;
}
prevId = n;
for (int pos = m - 1; pos >= l; pos--) {
for (int i = 0; i < 4; i++) {
for (int j = i; j < 4; j++) {
dpLeft[i][j][pos] = Integer.MAX_VALUE;
if (s[pos] != ask.charAt(i)) {
dpLeft[i][j][pos] = dpLeft[i][j][prevId];
} else {
if (dpLeft[i][j][prevId] != Integer.MAX_VALUE) {
dpLeft[i][j][pos] = dpLeft[i][j][prevId] + 1;
}
if (i != j
&& dpLeft[i + 1][j][prevId] != Integer.MAX_VALUE) {
dpLeft[i][j][pos] = Math.min(dpLeft[i][j][pos],
dpLeft[i + 1][j][prevId]);
}
}
}
}
for (int id : start[pos]) {
int ri = right[id];
if (ri >= m && ri <= r) {
int best = Integer.MAX_VALUE;
for (int inter = 0; inter < 4; inter++) {
if (dpLeft[0][inter][pos] != Integer.MAX_VALUE) {
if (dpRight[inter][3][ri] != Integer.MAX_VALUE) {
best = Math.min(best, dpLeft[0][inter][pos]
+ dpRight[inter][3][ri]);
}
}
}
if (best == Integer.MAX_VALUE) {
ans[id] = -1;
} else {
ans[id] += best;
}
}
}
prevId = pos;
}
}
char[] s;
int n;
int[][][] dpLeft;
int[][][] dpRight;
int[] ans;
void solve() {
n = in.nextInt();
int q = in.nextInt();
s = in.next().toCharArray();
dpLeft = new int[4][4][n + 1];
dpRight = new int[4][4][n + 1];
left = new int[q];
right = new int[q];
start = new ArrayList[n];
int[] last7 = new int[n];
int[] cnt6 = new int[n + 1];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
dpRight[i][j][n] = i == j ? 0 : Integer.MAX_VALUE;
dpLeft[i][j][n] = i == j ? 0 : Integer.MAX_VALUE;
}
}
for (int i = 0; i < n; i++) {
cnt6[i + 1] = cnt6[i];
if (s[i] == '6') {
cnt6[i + 1]++;
}
if (s[i] == '7') {
last7[i] = i;
} else {
last7[i] = i == 0 ? -1 : (last7[i - 1]);
}
}
ans = new int[q];
for (int i = 0; i < n; i++) {
start[i] = new ArrayList<Integer>();
}
for (int i = 0; i < q; i++) {
left[i] = in.nextInt() - 1;
right[i] = in.nextInt() - 1;
int pr = last7[right[i]];
if (pr <= left[i]) {
ans[i] = -1;
} else {
ans[i] = cnt6[right[i] + 1] - cnt6[pr];
right[i] = pr;
start[left[i]].add(i);
}
}
go(0, n - 1);
for (int x : ans) {
out.println(x);
}
}
void run() {
try {
in = new FastScanner(new File("object.in"));
out = new PrintWriter(new File("object.out"));
solve();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
void runIO() {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
public static void main(String[] args) {
new CF().runIO();
}
} | Java | ["8 3\n20166766\n1 8\n1 7\n2 8", "15 5\n012016662091670\n3 4\n1 14\n4 15\n1 13\n10 15", "4 2\n1234\n2 4\n1 2"] | 3 seconds | ["4\n3\n-1", "-1\n2\n1\n-1\n-1", "-1\n-1"] | NoteIn the first sample: In the first query, ugliness("20166766") = 4 because all four sixes must be removed. In the second query, ugliness("2016676") = 3 because all three sixes must be removed. In the third query, ugliness("0166766") = - 1 because it's impossible to remove some digits to get a nice string. In the second sample: In the second query, ugliness("01201666209167") = 2. It's optimal to remove the first digit '2' and the last digit '6', what gives a string "010166620917", which is nice. In the third query, ugliness("016662091670") = 1. It's optimal to remove the last digit '6', what gives a nice string "01666209170". | Java 8 | standard input | [
"dp",
"divide and conquer",
"data structures",
"matrices"
] | cf5e72a35509c6ee1a3073c0e514f6bf | The first line of the input contains two integers n and q (4 ≤ n ≤ 200 000, 1 ≤ q ≤ 200 000) — the length of the string s and the number of queries respectively. The second line contains a string s of length n. Every character is one of digits '0'–'9'. The i-th of next q lines contains two integers ai and bi (1 ≤ ai ≤ bi ≤ n), describing a substring in the i-th query. | 2,600 | For each query print the ugliness of the given substring. | standard output | |
PASSED | 16c08bbc822d8d8392ff3618c1a8c0e9 | train_004.jsonl | 1483107300 | A string t is called nice if a string "2017" occurs in t as a subsequence but a string "2016" doesn't occur in t as a subsequence. For example, strings "203434107" and "9220617" are nice, while strings "20016", "1234" and "20167" aren't nice.The ugliness of a string is the minimum possible number of characters to remove, in order to obtain a nice string. If it's impossible to make a string nice by removing characters, its ugliness is - 1.Limak has a string s of length n, with characters indexed 1 through n. He asks you q queries. In the i-th query you should compute and print the ugliness of a substring (continuous subsequence) of s starting at the index ai and ending at the index bi (inclusive). | 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);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
static class TaskE {
final int inf = (int) 1e9;
int n;
char[] str;
int[] tree;
int[] ans;
final String s2017 = "2017";
private void getAns(int v, int tl, int tr, int l, int r) {
if (l > r) {
return;
}
if (tl == l && tr == r) {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
ans[index(v, i, j)] = tree[index(v, i, j)];
}
}
} else {
int tm = (tl + tr) >>> 1;
if (r <= tm) {
getAns(v + v + 1, tl, tm, l, Math.min(r, tm));
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
ans[index(v, i, j)] = ans[index(v + v + 1, i, j)];
}
}
} else if (tm + 1 <= l) {
getAns(v + v + 2, tm + 1, tr, Math.max(l, tm + 1), r);
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
ans[index(v, i, j)] = ans[index(v + v + 2, i, j)];
}
}
} else {
getAns(v + v + 1, tl, tm, l, Math.min(r, tm));
getAns(v + v + 2, tm + 1, tr, Math.max(l, tm + 1), r);
unit(ans, v + v + 1, v + v + 2, v);
}
}
}
private void init() {
int nodeCount = Math.max(1, Integer.highestOneBit(n) << 2);
tree = new int[nodeCount * 5 * 5];
Arrays.fill(tree, inf);
build(0, 0, n - 1);
ans = new int[nodeCount * 5 * 5];
}
private void build(int v, int tl, int tr) {
if (tl == tr) {
for (int i = 0; i < 4; i++) {
if (str[tl] == s2017.charAt(i)) {
tree[index(v, i, i)] = 1;
tree[index(v, i, i + 1)] = 0;
} else if (3 <= i && str[tl] == '6') {
tree[index(v, i, i)] = 1;
} else {
tree[index(v, i, i)] = 0;
}
}
tree[index(v, 4, 4)] = str[tl] == '6' ? 1 : 0;
} else {
int tm = (tl + tr) >>> 1;
build(v + v + 1, tl, tm);
build(v + v + 2, tm + 1, tr);
unit(tree, v + v + 1, v + v + 2, v);
}
}
int index(int v, int i, int j) {
int res = ((v << 2) + v) + i;
return (res << 2) + res + j;
}
private void unit(int[] dp, int vl, int vr, int v) {
for (int i = 0; i < 5; i++) {
for (int j = i; j < 5; j++) {
int res = inf;
for (int k = i; k <= j; k++) {
res = Math.min(res, dp[index(vl, i, k)] + dp[index(vr, k, j)]);
}
dp[index(v, i, j)] = res;
}
}
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.readInt();
int q = in.readInt();
str = IOUtils.readCharArray(in, n);
// ExtendedRandom rnd = new ExtendedRandom(228);
// n = 200_000;
// int q = 200_000;
// str = rnd.nextCharArray(n, "0123456789".toCharArray());
init();
for (int iter = 0; iter < q; iter++) {
int l = in.readInt() - 1;
int r = in.readInt() - 1;
// int l = rnd.nextInt(0, n);
// int r = rnd.nextInt(l, n);
getAns(0, 0, n - 1, l, r);
int answer = ans[index(0, 0, 4)];
out.printLine(answer == inf ? -1 : answer);
}
}
}
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 char readCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class IOUtils {
public static char[] readCharArray(InputReader in, int size) {
char[] array = new char[size];
for (int i = 0; i < size; i++) {
array[i] = in.readCharacter();
}
return array;
}
}
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 printLine(int i) {
writer.println(i);
}
}
}
| Java | ["8 3\n20166766\n1 8\n1 7\n2 8", "15 5\n012016662091670\n3 4\n1 14\n4 15\n1 13\n10 15", "4 2\n1234\n2 4\n1 2"] | 3 seconds | ["4\n3\n-1", "-1\n2\n1\n-1\n-1", "-1\n-1"] | NoteIn the first sample: In the first query, ugliness("20166766") = 4 because all four sixes must be removed. In the second query, ugliness("2016676") = 3 because all three sixes must be removed. In the third query, ugliness("0166766") = - 1 because it's impossible to remove some digits to get a nice string. In the second sample: In the second query, ugliness("01201666209167") = 2. It's optimal to remove the first digit '2' and the last digit '6', what gives a string "010166620917", which is nice. In the third query, ugliness("016662091670") = 1. It's optimal to remove the last digit '6', what gives a nice string "01666209170". | Java 8 | standard input | [
"dp",
"divide and conquer",
"data structures",
"matrices"
] | cf5e72a35509c6ee1a3073c0e514f6bf | The first line of the input contains two integers n and q (4 ≤ n ≤ 200 000, 1 ≤ q ≤ 200 000) — the length of the string s and the number of queries respectively. The second line contains a string s of length n. Every character is one of digits '0'–'9'. The i-th of next q lines contains two integers ai and bi (1 ≤ ai ≤ bi ≤ n), describing a substring in the i-th query. | 2,600 | For each query print the ugliness of the given substring. | standard output | |
PASSED | e692d72dd6ad21aa1e9caa6cc4cd32cb | train_004.jsonl | 1483107300 | A string t is called nice if a string "2017" occurs in t as a subsequence but a string "2016" doesn't occur in t as a subsequence. For example, strings "203434107" and "9220617" are nice, while strings "20016", "1234" and "20167" aren't nice.The ugliness of a string is the minimum possible number of characters to remove, in order to obtain a nice string. If it's impossible to make a string nice by removing characters, its ugliness is - 1.Limak has a string s of length n, with characters indexed 1 through n. He asks you q queries. In the i-th query you should compute and print the ugliness of a substring (continuous subsequence) of s starting at the index ai and ending at the index bi (inclusive). | 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);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
static class TaskE {
final int inf = (int) 1e9;
int n;
char[] str;
int[] tree;
int[] ans;
final String s2017 = "2017";
private void getAns(int v, int tl, int tr, int l, int r) {
if (l > r) {
return;
}
if (tl == l && tr == r) {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
ans[index(v, i, j)] = tree[index(v, i, j)];
}
}
} else {
int tm = (tl + tr) >>> 1;
if (r <= tm) {
getAns(v + v + 1, tl, tm, l, Math.min(r, tm));
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
ans[index(v, i, j)] = ans[index(v + v + 1, i, j)];
}
}
} else if (tm + 1 <= l) {
getAns(v + v + 2, tm + 1, tr, Math.max(l, tm + 1), r);
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
ans[index(v, i, j)] = ans[index(v + v + 2, i, j)];
}
}
} else {
getAns(v + v + 1, tl, tm, l, Math.min(r, tm));
getAns(v + v + 2, tm + 1, tr, Math.max(l, tm + 1), r);
unit(ans, v + v + 1, v + v + 2, v);
}
}
}
private void init() {
int nodeCount = Math.max(1, Integer.highestOneBit(n) << 2);
tree = new int[nodeCount * 5 * 5];
Arrays.fill(tree, inf);
build(0, 0, n - 1);
ans = new int[nodeCount * 5 * 5];
}
private void build(int v, int tl, int tr) {
if (tl == tr) {
for (int i = 0; i < 4; i++) {
if (str[tl] == s2017.charAt(i)) {
tree[index(v, i, i)] = 1;
tree[index(v, i, i + 1)] = 0;
} else if (3 <= i && str[tl] == '6') {
tree[index(v, i, i)] = 1;
} else {
tree[index(v, i, i)] = 0;
}
}
tree[index(v, 4, 4)] = str[tl] == '6' ? 1 : 0;
} else {
int tm = (tl + tr) >>> 1;
build(v + v + 1, tl, tm);
build(v + v + 2, tm + 1, tr);
unit(tree, v + v + 1, v + v + 2, v);
}
}
int index(int v, int i, int j) {
int res = (((v << 2) + v) + i);
return ((res << 2) + res) + j;
}
private void unit(int[] dp, int vl, int vr, int v) {
for (int i = 0; i < 5; i++) {
for (int j = i; j < 5; j++) {
int res = inf;
for (int k = i; k <= j; k++) {
res = Math.min(res, dp[index(vl, i, k)] + dp[index(vr, k, j)]);
}
dp[index(v, i, j)] = res;
}
}
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.readInt();
int q = in.readInt();
str = IOUtils.readCharArray(in, n);
// ExtendedRandom rnd = new ExtendedRandom(228);
// n = 200_000;
// int q = 200_000;
// str = rnd.nextCharArray(n, "0123456789".toCharArray());
init();
for (int iter = 0; iter < q; iter++) {
int l = in.readInt() - 1;
int r = in.readInt() - 1;
// int l = rnd.nextInt(0, n);
// int r = rnd.nextInt(l, n);
getAns(0, 0, n - 1, l, r);
int answer = ans[index(0, 0, 4)];
out.printLine(answer == inf ? -1 : answer);
}
}
}
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 char readCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class IOUtils {
public static char[] readCharArray(InputReader in, int size) {
char[] array = new char[size];
for (int i = 0; i < size; i++) {
array[i] = in.readCharacter();
}
return array;
}
}
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 printLine(int i) {
writer.println(i);
}
}
}
| Java | ["8 3\n20166766\n1 8\n1 7\n2 8", "15 5\n012016662091670\n3 4\n1 14\n4 15\n1 13\n10 15", "4 2\n1234\n2 4\n1 2"] | 3 seconds | ["4\n3\n-1", "-1\n2\n1\n-1\n-1", "-1\n-1"] | NoteIn the first sample: In the first query, ugliness("20166766") = 4 because all four sixes must be removed. In the second query, ugliness("2016676") = 3 because all three sixes must be removed. In the third query, ugliness("0166766") = - 1 because it's impossible to remove some digits to get a nice string. In the second sample: In the second query, ugliness("01201666209167") = 2. It's optimal to remove the first digit '2' and the last digit '6', what gives a string "010166620917", which is nice. In the third query, ugliness("016662091670") = 1. It's optimal to remove the last digit '6', what gives a nice string "01666209170". | Java 8 | standard input | [
"dp",
"divide and conquer",
"data structures",
"matrices"
] | cf5e72a35509c6ee1a3073c0e514f6bf | The first line of the input contains two integers n and q (4 ≤ n ≤ 200 000, 1 ≤ q ≤ 200 000) — the length of the string s and the number of queries respectively. The second line contains a string s of length n. Every character is one of digits '0'–'9'. The i-th of next q lines contains two integers ai and bi (1 ≤ ai ≤ bi ≤ n), describing a substring in the i-th query. | 2,600 | For each query print the ugliness of the given substring. | standard output | |
PASSED | 2f8def30e5ad1efbee8fb8d09f3d04ff | train_004.jsonl | 1483107300 | A string t is called nice if a string "2017" occurs in t as a subsequence but a string "2016" doesn't occur in t as a subsequence. For example, strings "203434107" and "9220617" are nice, while strings "20016", "1234" and "20167" aren't nice.The ugliness of a string is the minimum possible number of characters to remove, in order to obtain a nice string. If it's impossible to make a string nice by removing characters, its ugliness is - 1.Limak has a string s of length n, with characters indexed 1 through n. He asks you q queries. In the i-th query you should compute and print the ugliness of a substring (continuous subsequence) of s starting at the index ai and ending at the index bi (inclusive). | 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);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
static class TaskE {
final int inf = (int) 1e9;
int n;
char[] str;
int[] tree;
int[] ans;
private void getAns(int v, int tl, int tr, int l, int r) {
if (l > r) {
return;
}
if (tl == l && tr == r) {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
ans[index(v, i, j)] = tree[index(v, i, j)];
}
}
} else {
int tm = (tl + tr) >>> 1;
if (r <= tm) {
getAns(v + v + 1, tl, tm, l, Math.min(r, tm));
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
ans[index(v, i, j)] = ans[index(v + v + 1, i, j)];
}
}
} else if (tm + 1 <= l) {
getAns(v + v + 2, tm + 1, tr, Math.max(l, tm + 1), r);
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
ans[index(v, i, j)] = ans[index(v + v + 2, i, j)];
}
}
} else {
getAns(v + v + 1, tl, tm, l, Math.min(r, tm));
getAns(v + v + 2, tm + 1, tr, Math.max(l, tm + 1), r);
unit(ans, v + v + 1, v + v + 2, v);
}
}
}
private void init() {
int nodeCount = Math.max(1, Integer.highestOneBit(n) << 2);
tree = new int[nodeCount * 5 * 5];
Arrays.fill(tree, inf);
build(0, 0, n - 1);
ans = new int[nodeCount * 5 * 5];
}
private void build(int v, int tl, int tr) {
if (tl == tr) {
String s2017 = "2017";
for (int i = 0; i < 4; i++) {
if (str[tl] == s2017.charAt(i)) {
tree[index(v, i, i)] = 1;
tree[index(v, i, i + 1)] = 0;
} else if (3 <= i && str[tl] == '6') {
tree[index(v, i, i)] = 1;
} else {
tree[index(v, i, i)] = 0;
}
}
tree[index(v, 4, 4)] = str[tl] == '6' ? 1 : 0;
} else {
int tm = (tl + tr) >>> 1;
build(v + v + 1, tl, tm);
build(v + v + 2, tm + 1, tr);
unit(tree, v + v + 1, v + v + 2, v);
}
}
int index(int v, int i, int j) {
int res = (((v << 2) + v) + i);
return ((res << 2) + res) + j;
}
private void unit(int[] dp, int vl, int vr, int v) {
for (int i = 0; i < 5; i++) {
for (int j = i; j < 5; j++) {
int res = inf;
for (int k = i; k <= j; k++) {
res = Math.min(res, dp[index(vl, i, k)] + dp[index(vr, k, j)]);
}
dp[index(v, i, j)] = res;
}
}
}
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.readInt();
int q = in.readInt();
str = IOUtils.readCharArray(in, n);
// ExtendedRandom rnd = new ExtendedRandom(228);
// n = 200_000;
// int q = 200_000;
// str = rnd.nextCharArray(n, "0123456789".toCharArray());
init();
for (int iter = 0; iter < q; iter++) {
int l = in.readInt() - 1;
int r = in.readInt() - 1;
// int l = rnd.nextInt(0, n);
// int r = rnd.nextInt(l, n);
getAns(0, 0, n - 1, l, r);
int answer = ans[index(0, 0, 4)];
out.printLine(answer == inf ? -1 : answer);
}
}
}
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 char readCharacter() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
return (char) c;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class IOUtils {
public static char[] readCharArray(InputReader in, int size) {
char[] array = new char[size];
for (int i = 0; i < size; i++) {
array[i] = in.readCharacter();
}
return array;
}
}
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 printLine(int i) {
writer.println(i);
}
}
}
| Java | ["8 3\n20166766\n1 8\n1 7\n2 8", "15 5\n012016662091670\n3 4\n1 14\n4 15\n1 13\n10 15", "4 2\n1234\n2 4\n1 2"] | 3 seconds | ["4\n3\n-1", "-1\n2\n1\n-1\n-1", "-1\n-1"] | NoteIn the first sample: In the first query, ugliness("20166766") = 4 because all four sixes must be removed. In the second query, ugliness("2016676") = 3 because all three sixes must be removed. In the third query, ugliness("0166766") = - 1 because it's impossible to remove some digits to get a nice string. In the second sample: In the second query, ugliness("01201666209167") = 2. It's optimal to remove the first digit '2' and the last digit '6', what gives a string "010166620917", which is nice. In the third query, ugliness("016662091670") = 1. It's optimal to remove the last digit '6', what gives a nice string "01666209170". | Java 8 | standard input | [
"dp",
"divide and conquer",
"data structures",
"matrices"
] | cf5e72a35509c6ee1a3073c0e514f6bf | The first line of the input contains two integers n and q (4 ≤ n ≤ 200 000, 1 ≤ q ≤ 200 000) — the length of the string s and the number of queries respectively. The second line contains a string s of length n. Every character is one of digits '0'–'9'. The i-th of next q lines contains two integers ai and bi (1 ≤ ai ≤ bi ≤ n), describing a substring in the i-th query. | 2,600 | For each query print the ugliness of the given substring. | standard output | |
PASSED | 40eb984197f12d58bec1ac1ce2bded6d | train_004.jsonl | 1433595600 | The Looksery company, consisting of n staff members, is planning another big party. Every employee has his phone number and the phone numbers of his friends in the phone book. Everyone who comes to the party, sends messages to his contacts about how cool it is. At the same time everyone is trying to spend as much time on the fun as possible, so they send messages to everyone without special thinking, moreover, each person even sends a message to himself or herself.Igor and Max, Looksery developers, started a dispute on how many messages each person gets. Igor indicates n numbers, the i-th of which indicates how many messages, in his view, the i-th employee is going to take. If Igor guesses correctly at least one of these numbers, he wins, otherwise Max wins.You support Max in this debate, so you need, given the contact lists of the employees, to determine whether there is a situation where Igor loses. Specifically, you need to determine which employees should come to the party, and which should not, so after all the visitors send messages to their contacts, each employee received a number of messages that is different from what Igor stated. | 256 megabytes | /* package whatever; // 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 Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int a[][] = new int[m][m];
for(int i = 0;i<m;i++){
String s = sc.next();
for(int j = 0;j<m;j++){
a[i][j]=s.charAt(j)-'0';
}
}
int b[] = new int[m];
for(int i = 0;i<m;i++){
b[i]=sc.nextInt();
}
int c[] = new int[m];
for(int i = 0;i<m;i++){
c[i]=0;
}
while(true){
boolean ok = false;
for(int i = 0;i<m;i++){
if(c[i]==0&&b[i]<=0){
ok = true;
c[i]=1;
for(int j = 0;j<m;j++){
b[j]-=a[i][j];
}
}
}
if(!ok){
break;
}
}
int sum = 0;
for(int i = 0;i<m;i++){
sum+=c[i];
}
System.out.println(sum);
for(int i = 0;i<m;i++){
if(c[i]==1){
System.out.print((i+1) + " ");
}
}
}
} | Java | ["3\n101\n010\n001\n0 1 2", "1\n1\n1", "4\n1111\n0101\n1110\n0001\n1 0 1 0"] | 1 second | ["1\n1", "0", "4\n1 2 3 4"] | NoteIn the first sample Igor supposes that the first employee will receive 0 messages. Since he isn't contained in any other contact list he must come to the party in order to receive one message from himself. If he is the only who come to the party then he will receive 1 message, the second employee will receive 0 messages and the third will also receive 1 message. Thereby Igor won't guess any number.In the second sample if the single employee comes to the party he receives 1 message and Igor wins, so he shouldn't do it.In the third sample the first employee will receive 2 messages, the second — 3, the third — 2, the fourth — 3. | Java 7 | standard input | [
"constructive algorithms",
"dfs and similar",
"greedy",
"graphs"
] | 794b0ac038e4e32f35f754e9278424d3 | The first line contains a single integer n (1 ≤ n ≤ 100) — the number of employees of company Looksery. Next n lines contain the description of the contact lists of the employees. The i-th of these lines contains a string of length n, consisting of digits zero and one, specifying the contact list of the i-th employee. If the j-th character of the i-th string equals 1, then the j-th employee is in the i-th employee's contact list, otherwise he isn't. It is guaranteed that the i-th character of the i-th line is always equal to 1. The last line contains n space-separated integers: a1, a2, ..., an (0 ≤ ai ≤ n), where ai represents the number of messages that the i-th employee should get according to Igor. | 2,300 | In the first line print a single integer m — the number of employees who should come to the party so that Igor loses the dispute. In the second line print m space-separated integers — the numbers of these employees in an arbitrary order. If Igor wins the dispute in any case, print -1. If there are multiple possible solutions, print any of them. | standard output | |
PASSED | 9fc6e869857b9757cbdf4da8d4421a54 | train_004.jsonl | 1433595600 | The Looksery company, consisting of n staff members, is planning another big party. Every employee has his phone number and the phone numbers of his friends in the phone book. Everyone who comes to the party, sends messages to his contacts about how cool it is. At the same time everyone is trying to spend as much time on the fun as possible, so they send messages to everyone without special thinking, moreover, each person even sends a message to himself or herself.Igor and Max, Looksery developers, started a dispute on how many messages each person gets. Igor indicates n numbers, the i-th of which indicates how many messages, in his view, the i-th employee is going to take. If Igor guesses correctly at least one of these numbers, he wins, otherwise Max wins.You support Max in this debate, so you need, given the contact lists of the employees, to determine whether there is a situation where Igor loses. Specifically, you need to determine which employees should come to the party, and which should not, so after all the visitors send messages to their contacts, each employee received a number of messages that is different from what Igor stated. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class Main
{
void run() throws NumberFormatException, IOException
{
int n = nextInt();
boolean[] cool = new boolean[n];
String[] s = new String[n];
int[] deg = new int[n];
for( int i = 0; i < n; i++ ){
s[i] = nextToken();
for( int j = 0; j < n; j++ ){
if(s[i].charAt(j) == '1')
deg[i]++;
}
}
int[] a = new int[n];
for( int i = 0; i < n; i++)
a[i] = nextInt();
int[] q = new int[n];
int qr = 0;
int[] add = new int[n];
int r = (int)1e9;
for( int i = 0; i < n; i++)
{
r = Math.min(r, a[i]);
if(a[i] == 0){
q[qr++] = i;
cool[i] = true;
for( int j = 0; j < n; j++ ){
if(s[i].charAt(j) == '1')
add[j]++;
}
}
}
// for( int i = 0; i < n; i++ )
// out.print(add[i] + " ");
//.println();
if(r > 0){
out.println(0);
return;
}
while(true){
boolean found = false;
for( int i = 0; i < n; i++){
if(add[i] == a[i]){
q[qr++] = i;
for( int j = 0; j < n; j++ )
if(s[i].charAt(j) == '1')
add[j]++;
found = true;
break;
}
}
if(!found)break;
}
for( int i = 0; i < n; i++)
if(add[i] == a[i]){
out.println(-1);
return;
}
out.println(qr);
for( int i = 0; i < qr; i++ )
out.print(q[i] + 1 + " ");
out.println();
}
BufferedReader in;
PrintStream out;
StringTokenizer tok;
public Main() throws NumberFormatException, IOException
{
in = new BufferedReader(new InputStreamReader(System.in));
out = System.out;
run();
}
public static void main(String[] args) throws NumberFormatException, IOException
{
new Main();
}
String nextToken() throws IOException
{
String line = "";
while(tok == null || !tok.hasMoreTokens()) {
if((line = in.readLine()) != null)
tok = new StringTokenizer(line);
else
return null;
}
return tok.nextToken();
}
int nextInt() throws NumberFormatException, IOException
{
return Integer.parseInt(nextToken());
}
long nextLong() throws NumberFormatException, IOException
{
return Long.parseLong(nextToken());
}
double nextDouble() throws NumberFormatException, IOException
{
return Double.parseDouble(nextToken());
}
} | Java | ["3\n101\n010\n001\n0 1 2", "1\n1\n1", "4\n1111\n0101\n1110\n0001\n1 0 1 0"] | 1 second | ["1\n1", "0", "4\n1 2 3 4"] | NoteIn the first sample Igor supposes that the first employee will receive 0 messages. Since he isn't contained in any other contact list he must come to the party in order to receive one message from himself. If he is the only who come to the party then he will receive 1 message, the second employee will receive 0 messages and the third will also receive 1 message. Thereby Igor won't guess any number.In the second sample if the single employee comes to the party he receives 1 message and Igor wins, so he shouldn't do it.In the third sample the first employee will receive 2 messages, the second — 3, the third — 2, the fourth — 3. | Java 7 | standard input | [
"constructive algorithms",
"dfs and similar",
"greedy",
"graphs"
] | 794b0ac038e4e32f35f754e9278424d3 | The first line contains a single integer n (1 ≤ n ≤ 100) — the number of employees of company Looksery. Next n lines contain the description of the contact lists of the employees. The i-th of these lines contains a string of length n, consisting of digits zero and one, specifying the contact list of the i-th employee. If the j-th character of the i-th string equals 1, then the j-th employee is in the i-th employee's contact list, otherwise he isn't. It is guaranteed that the i-th character of the i-th line is always equal to 1. The last line contains n space-separated integers: a1, a2, ..., an (0 ≤ ai ≤ n), where ai represents the number of messages that the i-th employee should get according to Igor. | 2,300 | In the first line print a single integer m — the number of employees who should come to the party so that Igor loses the dispute. In the second line print m space-separated integers — the numbers of these employees in an arbitrary order. If Igor wins the dispute in any case, print -1. If there are multiple possible solutions, print any of them. | standard output | |
PASSED | 2341e66600836dc07d7965551da79356 | train_004.jsonl | 1433595600 | The Looksery company, consisting of n staff members, is planning another big party. Every employee has his phone number and the phone numbers of his friends in the phone book. Everyone who comes to the party, sends messages to his contacts about how cool it is. At the same time everyone is trying to spend as much time on the fun as possible, so they send messages to everyone without special thinking, moreover, each person even sends a message to himself or herself.Igor and Max, Looksery developers, started a dispute on how many messages each person gets. Igor indicates n numbers, the i-th of which indicates how many messages, in his view, the i-th employee is going to take. If Igor guesses correctly at least one of these numbers, he wins, otherwise Max wins.You support Max in this debate, so you need, given the contact lists of the employees, to determine whether there is a situation where Igor loses. Specifically, you need to determine which employees should come to the party, and which should not, so after all the visitors send messages to their contacts, each employee received a number of messages that is different from what Igor stated. | 256 megabytes | import java.io.IOException;
import java.io.InputStreamReader;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.io.PrintStream;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Nipuna Samarasekara
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, FastScanner in, FastPrinter out) {
int n=in.nextInt();
int[][] a=new int[n][n];
for (int i = 0; i < n; i++) {
String s=in.next();
for (int j = 0; j < n; j++) {
if (s.charAt(j)=='1')a[i][j]=1;
}
}
int[] rr= in.readIntArray(n);
ArrayList<Integer> ans= new ArrayList<>();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (rr[j]==0){ans.add(j);
for (int k = 0; k < n; k++) {
rr[k]-=a[j][k];
}
}
}
}
out.println(ans.size());
for (Integer an : ans) {
out.print((an+1) + " ");
}
out.println();
}
}
class FastScanner extends BufferedReader {
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try {
int ret = super.read();
return ret;
} catch (IOException e) {
throw new InputMismatchException();
}
}
public String next() {
StringBuilder sb = new StringBuilder();
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
if (c < 0) {
return null;
}
while (c >= 0 && !isWhiteSpace(c)) {
sb.appendCodePoint(c);
c = read();
}
return sb.toString();
}
static boolean isWhiteSpace(int c) {
return c >= 0 && c <= 32;
}
public int nextInt() {
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int ret = 0;
while (c >= 0 && !isWhiteSpace(c)) {
if (c < '0' || c > '9') {
throw new NumberFormatException("digit expected " + (char) c
+ " found");
}
ret = ret * 10 + c - '0';
c = read();
}
return ret * sgn;
}
public String readLine() {
try {
return super.readLine();
} catch (IOException e) {
return null;
}
}
public int[] readIntArray(int n) {
int[] ret = new int[n];
for (int i = 0; i < n; i++) {
ret[i] = nextInt();
}
return ret;
}
}
class FastPrinter extends PrintWriter {
public FastPrinter(OutputStream out) {
super(out);
}
}
| Java | ["3\n101\n010\n001\n0 1 2", "1\n1\n1", "4\n1111\n0101\n1110\n0001\n1 0 1 0"] | 1 second | ["1\n1", "0", "4\n1 2 3 4"] | NoteIn the first sample Igor supposes that the first employee will receive 0 messages. Since he isn't contained in any other contact list he must come to the party in order to receive one message from himself. If he is the only who come to the party then he will receive 1 message, the second employee will receive 0 messages and the third will also receive 1 message. Thereby Igor won't guess any number.In the second sample if the single employee comes to the party he receives 1 message and Igor wins, so he shouldn't do it.In the third sample the first employee will receive 2 messages, the second — 3, the third — 2, the fourth — 3. | Java 7 | standard input | [
"constructive algorithms",
"dfs and similar",
"greedy",
"graphs"
] | 794b0ac038e4e32f35f754e9278424d3 | The first line contains a single integer n (1 ≤ n ≤ 100) — the number of employees of company Looksery. Next n lines contain the description of the contact lists of the employees. The i-th of these lines contains a string of length n, consisting of digits zero and one, specifying the contact list of the i-th employee. If the j-th character of the i-th string equals 1, then the j-th employee is in the i-th employee's contact list, otherwise he isn't. It is guaranteed that the i-th character of the i-th line is always equal to 1. The last line contains n space-separated integers: a1, a2, ..., an (0 ≤ ai ≤ n), where ai represents the number of messages that the i-th employee should get according to Igor. | 2,300 | In the first line print a single integer m — the number of employees who should come to the party so that Igor loses the dispute. In the second line print m space-separated integers — the numbers of these employees in an arbitrary order. If Igor wins the dispute in any case, print -1. If there are multiple possible solutions, print any of them. | standard output | |
PASSED | 989bbf0c20cd7b548d123fd3506eb3f5 | train_004.jsonl | 1433595600 | The Looksery company, consisting of n staff members, is planning another big party. Every employee has his phone number and the phone numbers of his friends in the phone book. Everyone who comes to the party, sends messages to his contacts about how cool it is. At the same time everyone is trying to spend as much time on the fun as possible, so they send messages to everyone without special thinking, moreover, each person even sends a message to himself or herself.Igor and Max, Looksery developers, started a dispute on how many messages each person gets. Igor indicates n numbers, the i-th of which indicates how many messages, in his view, the i-th employee is going to take. If Igor guesses correctly at least one of these numbers, he wins, otherwise Max wins.You support Max in this debate, so you need, given the contact lists of the employees, to determine whether there is a situation where Igor loses. Specifically, you need to determine which employees should come to the party, and which should not, so after all the visitors send messages to their contacts, each employee received a number of messages that is different from what Igor stated. | 256 megabytes | /*
*
* @author Mukesh Singh
*
*/
import java.io.*;
import java.util.*;
import java.text.DecimalFormat;
@SuppressWarnings("unchecked")
public class AB {
//solve test cases
void solve() throws Exception {
int n = in.nextInt() ;
String[]ar = new String[n];
for(int i = 0 ; i < n ; ++i) ar[i] = in.nextToken() ;
int[]count = new int[n];
for(int i = 0 ; i < n ; ++i ) count[i] = in.nextInt() ;
LinkedList<Integer> res = new LinkedList<>();
for(int t = 0 ; t < n ; ++t ){
for(int i = 0 ; i < n ; ++i ){
if(count[i] == 0 ){
for(int j = 0 ; j < n ; ++j )
if(ar[i].charAt(j)=='1') count[j] -= 1 ;
res.addLast(i+1);
}
}
}
System.out.println(res.size());
for(int a : res )System.out.print(a+" ");
System.out.println();
}
//@ main function
public static void main(String[] args) throws Exception {
new AB();
}
InputReader in;
PrintStream out ;
DecimalFormat df ;
AB() {
try {
File defaultInput = new File("file.in");
if (defaultInput.exists())
in = new InputReader("file.in");
else
in = new InputReader();
defaultInput = new File("file.out");
if (defaultInput.exists())
out = new PrintStream(new FileOutputStream("file.out"));
else
out = new PrintStream(System.out);
df = new DecimalFormat("######0.00");
solve();
out.close();
}
catch (Exception e) {
e.printStackTrace();
System.exit(261);
}
}
class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
InputReader() {
reader = new BufferedReader(new InputStreamReader(System.in));
}
InputReader(String fileName) throws FileNotFoundException {
reader = new BufferedReader(new FileReader(new File(fileName)));
}
String readLine() throws IOException {
return reader.readLine();
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(readLine());
return tokenizer.nextToken();
}
boolean hasMoreTokens() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String s = readLine();
if (s == null)
return false;
tokenizer = new StringTokenizer(s);
}
return true;
}
int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(nextToken());
}
}
}
| Java | ["3\n101\n010\n001\n0 1 2", "1\n1\n1", "4\n1111\n0101\n1110\n0001\n1 0 1 0"] | 1 second | ["1\n1", "0", "4\n1 2 3 4"] | NoteIn the first sample Igor supposes that the first employee will receive 0 messages. Since he isn't contained in any other contact list he must come to the party in order to receive one message from himself. If he is the only who come to the party then he will receive 1 message, the second employee will receive 0 messages and the third will also receive 1 message. Thereby Igor won't guess any number.In the second sample if the single employee comes to the party he receives 1 message and Igor wins, so he shouldn't do it.In the third sample the first employee will receive 2 messages, the second — 3, the third — 2, the fourth — 3. | Java 7 | standard input | [
"constructive algorithms",
"dfs and similar",
"greedy",
"graphs"
] | 794b0ac038e4e32f35f754e9278424d3 | The first line contains a single integer n (1 ≤ n ≤ 100) — the number of employees of company Looksery. Next n lines contain the description of the contact lists of the employees. The i-th of these lines contains a string of length n, consisting of digits zero and one, specifying the contact list of the i-th employee. If the j-th character of the i-th string equals 1, then the j-th employee is in the i-th employee's contact list, otherwise he isn't. It is guaranteed that the i-th character of the i-th line is always equal to 1. The last line contains n space-separated integers: a1, a2, ..., an (0 ≤ ai ≤ n), where ai represents the number of messages that the i-th employee should get according to Igor. | 2,300 | In the first line print a single integer m — the number of employees who should come to the party so that Igor loses the dispute. In the second line print m space-separated integers — the numbers of these employees in an arbitrary order. If Igor wins the dispute in any case, print -1. If there are multiple possible solutions, print any of them. | standard output | |
PASSED | c2c9cb0e4b0de6dc9ac66b3aef985971 | train_004.jsonl | 1433595600 | The Looksery company, consisting of n staff members, is planning another big party. Every employee has his phone number and the phone numbers of his friends in the phone book. Everyone who comes to the party, sends messages to his contacts about how cool it is. At the same time everyone is trying to spend as much time on the fun as possible, so they send messages to everyone without special thinking, moreover, each person even sends a message to himself or herself.Igor and Max, Looksery developers, started a dispute on how many messages each person gets. Igor indicates n numbers, the i-th of which indicates how many messages, in his view, the i-th employee is going to take. If Igor guesses correctly at least one of these numbers, he wins, otherwise Max wins.You support Max in this debate, so you need, given the contact lists of the employees, to determine whether there is a situation where Igor loses. Specifically, you need to determine which employees should come to the party, and which should not, so after all the visitors send messages to their contacts, each employee received a number of messages that is different from what Igor stated. | 256 megabytes | import java.util.*;
import java.io.*;
public class cf549B {
static InputReader in = new InputReader();
static String str;
static String[] arr;
public static void main(String[] args) throws Exception {
int n = Integer.parseInt(in.readLine());
char[][] mat = new char[n][n];
for(int i = 0; i < n; i++) {
mat[i] = in.readLine().toCharArray();
}
arr = in.readLine().split(" ");
int[] a = new int[arr.length];
for(int ii = 0; ii < arr.length; ii++) {
a[ii] = Integer.parseInt(arr[ii]);
}
boolean works = true;
ArrayList<Integer> list = new ArrayList<Integer>();
boolean[] hV = new boolean[n];
while(works && list.size() != n) {
int select = -1;
for(int i = 0; i < n; i++) {
if(a[i] == 0 && !hV[i]) {
select = i;
}
}
if(select == -1) {
works = false;
} else {
hV[select] = true;
list.add(select + 1);
for(int i = 0; i < n; i++) {
if(mat[select][i] == '1') {
a[i]--;
}
}
}
}
for(int i = 0; i < n; i++) {
if(a[i] == 0) {
System.out.println(-1);
return;
}
}
System.out.println(list.size());
for(int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + (i == list.size() - 1 ? "\n" : " "));
}
}
static class InputReader {
BufferedReader br;
public InputReader() {
try {
br = new BufferedReader(new FileReader("cf549B.in"));
} catch(Exception e) {
br = new BufferedReader(new InputStreamReader(System.in));
}
}
public String readLine() throws Exception {
return br.readLine();
}
}
} | Java | ["3\n101\n010\n001\n0 1 2", "1\n1\n1", "4\n1111\n0101\n1110\n0001\n1 0 1 0"] | 1 second | ["1\n1", "0", "4\n1 2 3 4"] | NoteIn the first sample Igor supposes that the first employee will receive 0 messages. Since he isn't contained in any other contact list he must come to the party in order to receive one message from himself. If he is the only who come to the party then he will receive 1 message, the second employee will receive 0 messages and the third will also receive 1 message. Thereby Igor won't guess any number.In the second sample if the single employee comes to the party he receives 1 message and Igor wins, so he shouldn't do it.In the third sample the first employee will receive 2 messages, the second — 3, the third — 2, the fourth — 3. | Java 7 | standard input | [
"constructive algorithms",
"dfs and similar",
"greedy",
"graphs"
] | 794b0ac038e4e32f35f754e9278424d3 | The first line contains a single integer n (1 ≤ n ≤ 100) — the number of employees of company Looksery. Next n lines contain the description of the contact lists of the employees. The i-th of these lines contains a string of length n, consisting of digits zero and one, specifying the contact list of the i-th employee. If the j-th character of the i-th string equals 1, then the j-th employee is in the i-th employee's contact list, otherwise he isn't. It is guaranteed that the i-th character of the i-th line is always equal to 1. The last line contains n space-separated integers: a1, a2, ..., an (0 ≤ ai ≤ n), where ai represents the number of messages that the i-th employee should get according to Igor. | 2,300 | In the first line print a single integer m — the number of employees who should come to the party so that Igor loses the dispute. In the second line print m space-separated integers — the numbers of these employees in an arbitrary order. If Igor wins the dispute in any case, print -1. If there are multiple possible solutions, print any of them. | standard output | |
PASSED | 6f9b1e131dd95ce48914ff18a40cbdc6 | train_004.jsonl | 1433595600 | The Looksery company, consisting of n staff members, is planning another big party. Every employee has his phone number and the phone numbers of his friends in the phone book. Everyone who comes to the party, sends messages to his contacts about how cool it is. At the same time everyone is trying to spend as much time on the fun as possible, so they send messages to everyone without special thinking, moreover, each person even sends a message to himself or herself.Igor and Max, Looksery developers, started a dispute on how many messages each person gets. Igor indicates n numbers, the i-th of which indicates how many messages, in his view, the i-th employee is going to take. If Igor guesses correctly at least one of these numbers, he wins, otherwise Max wins.You support Max in this debate, so you need, given the contact lists of the employees, to determine whether there is a situation where Igor loses. Specifically, you need to determine which employees should come to the party, and which should not, so after all the visitors send messages to their contacts, each employee received a number of messages that is different from what Igor stated. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
* @author Pavel Mavrin
*/
public class B {
private void solve() throws IOException {
int n = nextInt();
boolean[][] a = new boolean[n][n];
for (int i = 0; i < n; i++) {
String s = next();
for (int j = 0; j < n; j++) {
a[i][j] = s.charAt(j) == '1';
}
}
int[] b = new int[n];
for (int i = 0; i < n; i++) {
b[i] = nextInt();
}
int[] c = new int[n];
boolean[] z = new boolean[n];
int res = 0;
while (true) {
boolean ok = true;
for (int i = 0; i < n; i++) {
if (c[i] == b[i]) {
z[i] = true;
for (int j = 0; j < n; j++) {
if (a[i][j]) c[j]++;
}
ok = false;
res++;
}
}
if (ok) break;
}
out.println(res);
for (int i = 0; i < n; i++) {
if (z[i]) out.print((i + 1) + " ");
}
}
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
PrintWriter out = new PrintWriter(System.out);
String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
public static void main(String[] args) throws IOException {
new B().run();
}
private void run() throws IOException {
solve();
out.close();
}
}
| Java | ["3\n101\n010\n001\n0 1 2", "1\n1\n1", "4\n1111\n0101\n1110\n0001\n1 0 1 0"] | 1 second | ["1\n1", "0", "4\n1 2 3 4"] | NoteIn the first sample Igor supposes that the first employee will receive 0 messages. Since he isn't contained in any other contact list he must come to the party in order to receive one message from himself. If he is the only who come to the party then he will receive 1 message, the second employee will receive 0 messages and the third will also receive 1 message. Thereby Igor won't guess any number.In the second sample if the single employee comes to the party he receives 1 message and Igor wins, so he shouldn't do it.In the third sample the first employee will receive 2 messages, the second — 3, the third — 2, the fourth — 3. | Java 7 | standard input | [
"constructive algorithms",
"dfs and similar",
"greedy",
"graphs"
] | 794b0ac038e4e32f35f754e9278424d3 | The first line contains a single integer n (1 ≤ n ≤ 100) — the number of employees of company Looksery. Next n lines contain the description of the contact lists of the employees. The i-th of these lines contains a string of length n, consisting of digits zero and one, specifying the contact list of the i-th employee. If the j-th character of the i-th string equals 1, then the j-th employee is in the i-th employee's contact list, otherwise he isn't. It is guaranteed that the i-th character of the i-th line is always equal to 1. The last line contains n space-separated integers: a1, a2, ..., an (0 ≤ ai ≤ n), where ai represents the number of messages that the i-th employee should get according to Igor. | 2,300 | In the first line print a single integer m — the number of employees who should come to the party so that Igor loses the dispute. In the second line print m space-separated integers — the numbers of these employees in an arbitrary order. If Igor wins the dispute in any case, print -1. If there are multiple possible solutions, print any of them. | standard output | |
PASSED | 74580ec225d8fdf9e41610268d5c1c16 | train_004.jsonl | 1433595600 | The Looksery company, consisting of n staff members, is planning another big party. Every employee has his phone number and the phone numbers of his friends in the phone book. Everyone who comes to the party, sends messages to his contacts about how cool it is. At the same time everyone is trying to spend as much time on the fun as possible, so they send messages to everyone without special thinking, moreover, each person even sends a message to himself or herself.Igor and Max, Looksery developers, started a dispute on how many messages each person gets. Igor indicates n numbers, the i-th of which indicates how many messages, in his view, the i-th employee is going to take. If Igor guesses correctly at least one of these numbers, he wins, otherwise Max wins.You support Max in this debate, so you need, given the contact lists of the employees, to determine whether there is a situation where Igor loses. Specifically, you need to determine which employees should come to the party, and which should not, so after all the visitors send messages to their contacts, each employee received a number of messages that is different from what Igor stated. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String [] args)throws Exception{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
int deg[]=new int[n];
String array[]=new String[n];
for(int i=0;i<n;i++){
array[i]=br.readLine();
}
Queue<Integer>q=new LinkedList<Integer>();
StringTokenizer st=new StringTokenizer(br.readLine());
for(int i=0;i<n;i++){
deg[i]=Integer.parseInt(st.nextToken());
if(deg[i]==0){
q.add(i);
}
}
int ans=0;
ArrayList<Integer>list=new ArrayList<Integer>();
int finDeg[]=new int[n];
while(!q.isEmpty()){
int a=q.remove();
if(finDeg[a] > deg[a])continue;
ans++;
list.add(a+1);
for(int i=0;i<n;i++){
if(array[a].charAt(i)=='1')
finDeg[i]++;
if(finDeg[i]==deg[i])q.add(i);
}
}
System.out.println(ans);
for(int temp:list)
System.out.print(temp+" ");
}
} | Java | ["3\n101\n010\n001\n0 1 2", "1\n1\n1", "4\n1111\n0101\n1110\n0001\n1 0 1 0"] | 1 second | ["1\n1", "0", "4\n1 2 3 4"] | NoteIn the first sample Igor supposes that the first employee will receive 0 messages. Since he isn't contained in any other contact list he must come to the party in order to receive one message from himself. If he is the only who come to the party then he will receive 1 message, the second employee will receive 0 messages and the third will also receive 1 message. Thereby Igor won't guess any number.In the second sample if the single employee comes to the party he receives 1 message and Igor wins, so he shouldn't do it.In the third sample the first employee will receive 2 messages, the second — 3, the third — 2, the fourth — 3. | Java 7 | standard input | [
"constructive algorithms",
"dfs and similar",
"greedy",
"graphs"
] | 794b0ac038e4e32f35f754e9278424d3 | The first line contains a single integer n (1 ≤ n ≤ 100) — the number of employees of company Looksery. Next n lines contain the description of the contact lists of the employees. The i-th of these lines contains a string of length n, consisting of digits zero and one, specifying the contact list of the i-th employee. If the j-th character of the i-th string equals 1, then the j-th employee is in the i-th employee's contact list, otherwise he isn't. It is guaranteed that the i-th character of the i-th line is always equal to 1. The last line contains n space-separated integers: a1, a2, ..., an (0 ≤ ai ≤ n), where ai represents the number of messages that the i-th employee should get according to Igor. | 2,300 | In the first line print a single integer m — the number of employees who should come to the party so that Igor loses the dispute. In the second line print m space-separated integers — the numbers of these employees in an arbitrary order. If Igor wins the dispute in any case, print -1. If there are multiple possible solutions, print any of them. | standard output | |
PASSED | 0d999895d9c84b984e50b8057079aa93 | train_004.jsonl | 1433595600 | The Looksery company, consisting of n staff members, is planning another big party. Every employee has his phone number and the phone numbers of his friends in the phone book. Everyone who comes to the party, sends messages to his contacts about how cool it is. At the same time everyone is trying to spend as much time on the fun as possible, so they send messages to everyone without special thinking, moreover, each person even sends a message to himself or herself.Igor and Max, Looksery developers, started a dispute on how many messages each person gets. Igor indicates n numbers, the i-th of which indicates how many messages, in his view, the i-th employee is going to take. If Igor guesses correctly at least one of these numbers, he wins, otherwise Max wins.You support Max in this debate, so you need, given the contact lists of the employees, to determine whether there is a situation where Igor loses. Specifically, you need to determine which employees should come to the party, and which should not, so after all the visitors send messages to their contacts, each employee received a number of messages that is different from what Igor stated. | 256 megabytes | import java.io.*;
import java.awt.geom.Point2D;
import java.text.*;
import java.math.*;
import java.util.*;
public class Main implements Runnable {
final String filename = "";
public void solve() throws Exception {
int n = iread();
boolean[][] mat = new boolean[n][n];
for (int i = 0; i < n; i++) {
String s = readword();
for (int j = 0; j < n; j++)
mat[i][j] = s.charAt(j) == '1';
}
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = iread();
}
int[] deg = new int[n];
int[] Z = new int[n];
int cnt = 0;
while (true) {
boolean flag = false;
for (int i = 0; i < n; i++) {
if (deg[i] == a[i]) {
Z[cnt++] = i+1;
flag = true;
for (int j = 0; j < n; j++)
if (mat[i][j])
deg[j]++;
}
}
if (!flag)
break;
}
out.write(cnt + "\n");
for (int i = 0; i < cnt; i++) {
if (i > 0)
out.write(" ");
out.write(Z[i] + "");
}
out.write("\n");
}
public void run() {
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new BufferedWriter(new OutputStreamWriter(System.out));
// in = new BufferedReader(new FileReader(filename+".in"));
// out = new BufferedWriter(new FileWriter(filename+".out"));
solve();
out.flush();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
public int iread() throws Exception {
return Integer.parseInt(readword());
}
public double dread() throws Exception {
return Double.parseDouble(readword());
}
public long lread() throws Exception {
return Long.parseLong(readword());
}
BufferedReader in;
BufferedWriter out;
public String readword() throws IOException {
StringBuilder b = new StringBuilder();
int c;
c = in.read();
while (c >= 0 && c <= ' ')
c = in.read();
if (c < 0)
return "";
while (c > ' ') {
b.append((char) c);
c = in.read();
}
return b.toString();
}
public static void main(String[] args) {
try {
Locale.setDefault(Locale.US);
} catch (Exception e) {
}
// new Thread(new Main()).start();
new Thread(null, new Main(), "1", 1 << 25).start();
}
}
| Java | ["3\n101\n010\n001\n0 1 2", "1\n1\n1", "4\n1111\n0101\n1110\n0001\n1 0 1 0"] | 1 second | ["1\n1", "0", "4\n1 2 3 4"] | NoteIn the first sample Igor supposes that the first employee will receive 0 messages. Since he isn't contained in any other contact list he must come to the party in order to receive one message from himself. If he is the only who come to the party then he will receive 1 message, the second employee will receive 0 messages and the third will also receive 1 message. Thereby Igor won't guess any number.In the second sample if the single employee comes to the party he receives 1 message and Igor wins, so he shouldn't do it.In the third sample the first employee will receive 2 messages, the second — 3, the third — 2, the fourth — 3. | Java 7 | standard input | [
"constructive algorithms",
"dfs and similar",
"greedy",
"graphs"
] | 794b0ac038e4e32f35f754e9278424d3 | The first line contains a single integer n (1 ≤ n ≤ 100) — the number of employees of company Looksery. Next n lines contain the description of the contact lists of the employees. The i-th of these lines contains a string of length n, consisting of digits zero and one, specifying the contact list of the i-th employee. If the j-th character of the i-th string equals 1, then the j-th employee is in the i-th employee's contact list, otherwise he isn't. It is guaranteed that the i-th character of the i-th line is always equal to 1. The last line contains n space-separated integers: a1, a2, ..., an (0 ≤ ai ≤ n), where ai represents the number of messages that the i-th employee should get according to Igor. | 2,300 | In the first line print a single integer m — the number of employees who should come to the party so that Igor loses the dispute. In the second line print m space-separated integers — the numbers of these employees in an arbitrary order. If Igor wins the dispute in any case, print -1. If there are multiple possible solutions, print any of them. | standard output | |
PASSED | 5e1de196e702d7e8b0e6753e69d199c5 | train_004.jsonl | 1433595600 | The Looksery company, consisting of n staff members, is planning another big party. Every employee has his phone number and the phone numbers of his friends in the phone book. Everyone who comes to the party, sends messages to his contacts about how cool it is. At the same time everyone is trying to spend as much time on the fun as possible, so they send messages to everyone without special thinking, moreover, each person even sends a message to himself or herself.Igor and Max, Looksery developers, started a dispute on how many messages each person gets. Igor indicates n numbers, the i-th of which indicates how many messages, in his view, the i-th employee is going to take. If Igor guesses correctly at least one of these numbers, he wins, otherwise Max wins.You support Max in this debate, so you need, given the contact lists of the employees, to determine whether there is a situation where Igor loses. Specifically, you need to determine which employees should come to the party, and which should not, so after all the visitors send messages to their contacts, each employee received a number of messages that is different from what Igor stated. | 256 megabytes | import java.util.*;
import java.io.*;
public class b {
public static void main(String[] args) throws IOException
{
PrintWriter out = new PrintWriter(System.out);
input.init(System.in);
int n = input.nextInt();
boolean[][] g = new boolean[n][n];
for(int i = 0; i<n; i++)
{
String s = input.next();
for(int j = 0; j<n; j++)
{
g[i][j] = s.charAt(j) == '1';
}
}
int[] as = new int[n];
for(int i = 0; i<n; i++) as[i] = input.nextInt();
boolean z = false;
for(int x: as) if(x == 0) z = true;
if(!z)
{
out.println(0);
out.close();
return;
}
Queue<Integer> q = new LinkedList<Integer>();
int[] ms = new int[n];
for(int i = 0; i<n; i++)
{
if(ms[i] == as[i])
{
q.add(i);
ms[i]++;
}
}
ArrayList<Integer> res = new ArrayList<Integer>();
while(!q.isEmpty())
{
int at = q.poll();
res.add(at);
for(int j = 0; j<n; j++)
{
if(at == j) continue;
if(g[at][j])
{
ms[j]++;
if(as[j] == ms[j])
{
ms[j]++;
q.add(j);
}
}
}
}
Collections.sort(res);
out.println(res.size());
for(int x : res) out.println(x+1);
out.close();
}
public static class input {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
static long nextLong() throws IOException {
return Long.parseLong( next() );
}
}
}
| Java | ["3\n101\n010\n001\n0 1 2", "1\n1\n1", "4\n1111\n0101\n1110\n0001\n1 0 1 0"] | 1 second | ["1\n1", "0", "4\n1 2 3 4"] | NoteIn the first sample Igor supposes that the first employee will receive 0 messages. Since he isn't contained in any other contact list he must come to the party in order to receive one message from himself. If he is the only who come to the party then he will receive 1 message, the second employee will receive 0 messages and the third will also receive 1 message. Thereby Igor won't guess any number.In the second sample if the single employee comes to the party he receives 1 message and Igor wins, so he shouldn't do it.In the third sample the first employee will receive 2 messages, the second — 3, the third — 2, the fourth — 3. | Java 7 | standard input | [
"constructive algorithms",
"dfs and similar",
"greedy",
"graphs"
] | 794b0ac038e4e32f35f754e9278424d3 | The first line contains a single integer n (1 ≤ n ≤ 100) — the number of employees of company Looksery. Next n lines contain the description of the contact lists of the employees. The i-th of these lines contains a string of length n, consisting of digits zero and one, specifying the contact list of the i-th employee. If the j-th character of the i-th string equals 1, then the j-th employee is in the i-th employee's contact list, otherwise he isn't. It is guaranteed that the i-th character of the i-th line is always equal to 1. The last line contains n space-separated integers: a1, a2, ..., an (0 ≤ ai ≤ n), where ai represents the number of messages that the i-th employee should get according to Igor. | 2,300 | In the first line print a single integer m — the number of employees who should come to the party so that Igor loses the dispute. In the second line print m space-separated integers — the numbers of these employees in an arbitrary order. If Igor wins the dispute in any case, print -1. If there are multiple possible solutions, print any of them. | standard output | |
PASSED | 0152ccd5fb64a23bf95e4c2d7e662845 | train_004.jsonl | 1433595600 | The Looksery company, consisting of n staff members, is planning another big party. Every employee has his phone number and the phone numbers of his friends in the phone book. Everyone who comes to the party, sends messages to his contacts about how cool it is. At the same time everyone is trying to spend as much time on the fun as possible, so they send messages to everyone without special thinking, moreover, each person even sends a message to himself or herself.Igor and Max, Looksery developers, started a dispute on how many messages each person gets. Igor indicates n numbers, the i-th of which indicates how many messages, in his view, the i-th employee is going to take. If Igor guesses correctly at least one of these numbers, he wins, otherwise Max wins.You support Max in this debate, so you need, given the contact lists of the employees, to determine whether there is a situation where Igor loses. Specifically, you need to determine which employees should come to the party, and which should not, so after all the visitors send messages to their contacts, each employee received a number of messages that is different from what Igor stated. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
static int n;
static HashMap<Long,Integer> hm;
public static void main( String args[]) throws Exception{
IO io = new IO();
io.init();
//------------------------------------------
int n = io.nextInt();
int[][] array = new int[n][n];
for( int i = 0 ; i < n ; ++i ){
String temp = io.nextToken();
for( int j = 0 ; j < n ; ++j ){
array[i][j] = temp.charAt(j) - '0';
}
}
int[] target = new int[n];
for( int i = 0 ; i < n; ++i){
target[i] = io.nextInt();
}
boolean[] invited = new boolean[n];
int counter = 0 ;
for( int i : target ){
if( i == 0 ) counter++;
}
while( counter > 0 ){ // atleast one zero
int temp = -1;
for( int i = 0 ; i < n ; ++i ){
if( target[i] == 0 ){
temp = i ;
break;
}
}
invited[temp] = true;
for( int i = 0 ; i < n ; ++i ){
if( array[temp][i] == 1 ){
target[i]--;
}
}
counter = 0 ;
for( int i : target ){
if( i == 0 ) counter++;
}
}
int ans = 0 ;
for( boolean b : invited)
if( b ) ans++;
io.println(ans );
for( int i = 0 ; i < n ; ++i){
if( invited[i])
io.print( (i+1) + " ");
}
//-------------------------------------------
io.destroy();
}
static class IO{
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void init() {
try {
reader = new BufferedReader(new InputStreamReader(System.in),8*1024);
writer = new PrintWriter(System.out);
} catch (Exception e) {
e.printStackTrace();
System.exit(261);
}
}
void destroy() {
writer.close();
System.exit(0);
}
void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
void println(Object... objects) {
print(objects);
writer.println();
}
String nextLine() throws IOException {
return reader.readLine();
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(nextLine());
return tokenizer.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(nextToken());
}
}
}
/*
*/
| Java | ["3\n101\n010\n001\n0 1 2", "1\n1\n1", "4\n1111\n0101\n1110\n0001\n1 0 1 0"] | 1 second | ["1\n1", "0", "4\n1 2 3 4"] | NoteIn the first sample Igor supposes that the first employee will receive 0 messages. Since he isn't contained in any other contact list he must come to the party in order to receive one message from himself. If he is the only who come to the party then he will receive 1 message, the second employee will receive 0 messages and the third will also receive 1 message. Thereby Igor won't guess any number.In the second sample if the single employee comes to the party he receives 1 message and Igor wins, so he shouldn't do it.In the third sample the first employee will receive 2 messages, the second — 3, the third — 2, the fourth — 3. | Java 7 | standard input | [
"constructive algorithms",
"dfs and similar",
"greedy",
"graphs"
] | 794b0ac038e4e32f35f754e9278424d3 | The first line contains a single integer n (1 ≤ n ≤ 100) — the number of employees of company Looksery. Next n lines contain the description of the contact lists of the employees. The i-th of these lines contains a string of length n, consisting of digits zero and one, specifying the contact list of the i-th employee. If the j-th character of the i-th string equals 1, then the j-th employee is in the i-th employee's contact list, otherwise he isn't. It is guaranteed that the i-th character of the i-th line is always equal to 1. The last line contains n space-separated integers: a1, a2, ..., an (0 ≤ ai ≤ n), where ai represents the number of messages that the i-th employee should get according to Igor. | 2,300 | In the first line print a single integer m — the number of employees who should come to the party so that Igor loses the dispute. In the second line print m space-separated integers — the numbers of these employees in an arbitrary order. If Igor wins the dispute in any case, print -1. If there are multiple possible solutions, print any of them. | standard output | |
PASSED | c3c951faa2ab686bece99198d9a81bab | train_004.jsonl | 1433595600 | The Looksery company, consisting of n staff members, is planning another big party. Every employee has his phone number and the phone numbers of his friends in the phone book. Everyone who comes to the party, sends messages to his contacts about how cool it is. At the same time everyone is trying to spend as much time on the fun as possible, so they send messages to everyone without special thinking, moreover, each person even sends a message to himself or herself.Igor and Max, Looksery developers, started a dispute on how many messages each person gets. Igor indicates n numbers, the i-th of which indicates how many messages, in his view, the i-th employee is going to take. If Igor guesses correctly at least one of these numbers, he wins, otherwise Max wins.You support Max in this debate, so you need, given the contact lists of the employees, to determine whether there is a situation where Igor loses. Specifically, you need to determine which employees should come to the party, and which should not, so after all the visitors send messages to their contacts, each employee received a number of messages that is different from what Igor stated. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Main {
public static void main(String[] args)throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String in;
boolean[][] adj = new boolean[n+1][n+1];
for(int i=1;i<=n;i++){
in = br.readLine();
for(int j=1;j<=n;j++){
if(in.charAt(j-1)=='1')
adj[i][j]=true;
}
}
int[] arr = new int[n+1] , temp = new int[n+1],res = new int[n+1];
ArrayList<Integer> list = new ArrayList<Integer>();
String[] in2 = br.readLine().split(" ");
for(int i=0;i<n;i++){
arr[i+1]=Integer.parseInt(in2[i]);
temp[i+1]=arr[i+1];
}
while(true){
boolean flag=true;
for(int i=1;i<=n;i++){
if(temp[i]==0){
flag=false;break;
}
}
if(flag)break;
for(int i=1;i<=n;i++){
if(temp[i]==-1)continue;
if(temp[i]==0){
temp[i]=-1;
list.add(i);
for(int j=1;j<=n;j++){
if(adj[i][j]){
res[j]++;
temp[j]--;
}
}
}
}
}
boolean flag=false;
for(int i=1;i<=n;i++){
if(res[i]==arr[i]){
flag=true;break;
}
}
if(flag)
System.out.println(-1);
else{
System.out.println(list.size());
for(int i=0;i<list.size();i++)
System.out.print(list.get(i)+" ");
System.out.println();
}
}
} | Java | ["3\n101\n010\n001\n0 1 2", "1\n1\n1", "4\n1111\n0101\n1110\n0001\n1 0 1 0"] | 1 second | ["1\n1", "0", "4\n1 2 3 4"] | NoteIn the first sample Igor supposes that the first employee will receive 0 messages. Since he isn't contained in any other contact list he must come to the party in order to receive one message from himself. If he is the only who come to the party then he will receive 1 message, the second employee will receive 0 messages and the third will also receive 1 message. Thereby Igor won't guess any number.In the second sample if the single employee comes to the party he receives 1 message and Igor wins, so he shouldn't do it.In the third sample the first employee will receive 2 messages, the second — 3, the third — 2, the fourth — 3. | Java 7 | standard input | [
"constructive algorithms",
"dfs and similar",
"greedy",
"graphs"
] | 794b0ac038e4e32f35f754e9278424d3 | The first line contains a single integer n (1 ≤ n ≤ 100) — the number of employees of company Looksery. Next n lines contain the description of the contact lists of the employees. The i-th of these lines contains a string of length n, consisting of digits zero and one, specifying the contact list of the i-th employee. If the j-th character of the i-th string equals 1, then the j-th employee is in the i-th employee's contact list, otherwise he isn't. It is guaranteed that the i-th character of the i-th line is always equal to 1. The last line contains n space-separated integers: a1, a2, ..., an (0 ≤ ai ≤ n), where ai represents the number of messages that the i-th employee should get according to Igor. | 2,300 | In the first line print a single integer m — the number of employees who should come to the party so that Igor loses the dispute. In the second line print m space-separated integers — the numbers of these employees in an arbitrary order. If Igor wins the dispute in any case, print -1. If there are multiple possible solutions, print any of them. | standard output | |
PASSED | 6ca0cce4f33c7687de56cde3fef76acb | train_004.jsonl | 1433595600 | The Looksery company, consisting of n staff members, is planning another big party. Every employee has his phone number and the phone numbers of his friends in the phone book. Everyone who comes to the party, sends messages to his contacts about how cool it is. At the same time everyone is trying to spend as much time on the fun as possible, so they send messages to everyone without special thinking, moreover, each person even sends a message to himself or herself.Igor and Max, Looksery developers, started a dispute on how many messages each person gets. Igor indicates n numbers, the i-th of which indicates how many messages, in his view, the i-th employee is going to take. If Igor guesses correctly at least one of these numbers, he wins, otherwise Max wins.You support Max in this debate, so you need, given the contact lists of the employees, to determine whether there is a situation where Igor loses. Specifically, you need to determine which employees should come to the party, and which should not, so after all the visitors send messages to their contacts, each employee received a number of messages that is different from what Igor stated. | 256 megabytes |
import java.util.*;
import java.io.*;
public class B
{
public static void main(String[] args)
{
PrintWriter out = new PrintWriter(System.out);
new B(new FastScanner(), out);
out.close();
}
public B(FastScanner in, PrintWriter out)
{
int N = in.nextInt();
boolean[][] sendMessage = new boolean[N][N];
for (int i=0; i<N; i++)
{
String s = in.next();
for (int j=0; j<N; j++)
{
sendMessage[i][j] = s.charAt(j)=='1';
}
}
int[] guess = new int[N];
for (int i=0; i<N; i++)
guess[i] = in.nextInt();
int[] numMessages = new int[N];
TreeSet<Integer> res = new TreeSet<Integer>();
while (true)
{
int cur = -1;
for (int i=0; i<N; i++)
if (guess[i] == numMessages[i])
{
cur = i;
break;
}
if (cur == -1) break;
res.add(cur);
for (int i=0; i<N; i++)
if (sendMessage[cur][i])
numMessages[i]++;
}
out.println(res.size());
for (int r : res)
{
out.print(r+1);
out.print(' ');
}
out.println();
}
}
class FastScanner{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public FastScanner()
{
stream = System.in;
}
int read()
{
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars){
curChar = 0;
try{
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
boolean isSpaceChar(int c)
{
return c==' '||c=='\n'||c=='\r'||c=='\t'||c==-1;
}
boolean isEndline(int c)
{
return c=='\n'||c=='\r'||c==-1;
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String next(){
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do{
res.appendCodePoint(c);
c = read();
}while(!isSpaceChar(c));
return res.toString();
}
String nextLine(){
int c = read();
while (isEndline(c))
c = read();
StringBuilder res = new StringBuilder();
do{
res.appendCodePoint(c);
c = read();
}while(!isEndline(c));
return res.toString();
}
}
| Java | ["3\n101\n010\n001\n0 1 2", "1\n1\n1", "4\n1111\n0101\n1110\n0001\n1 0 1 0"] | 1 second | ["1\n1", "0", "4\n1 2 3 4"] | NoteIn the first sample Igor supposes that the first employee will receive 0 messages. Since he isn't contained in any other contact list he must come to the party in order to receive one message from himself. If he is the only who come to the party then he will receive 1 message, the second employee will receive 0 messages and the third will also receive 1 message. Thereby Igor won't guess any number.In the second sample if the single employee comes to the party he receives 1 message and Igor wins, so he shouldn't do it.In the third sample the first employee will receive 2 messages, the second — 3, the third — 2, the fourth — 3. | Java 7 | standard input | [
"constructive algorithms",
"dfs and similar",
"greedy",
"graphs"
] | 794b0ac038e4e32f35f754e9278424d3 | The first line contains a single integer n (1 ≤ n ≤ 100) — the number of employees of company Looksery. Next n lines contain the description of the contact lists of the employees. The i-th of these lines contains a string of length n, consisting of digits zero and one, specifying the contact list of the i-th employee. If the j-th character of the i-th string equals 1, then the j-th employee is in the i-th employee's contact list, otherwise he isn't. It is guaranteed that the i-th character of the i-th line is always equal to 1. The last line contains n space-separated integers: a1, a2, ..., an (0 ≤ ai ≤ n), where ai represents the number of messages that the i-th employee should get according to Igor. | 2,300 | In the first line print a single integer m — the number of employees who should come to the party so that Igor loses the dispute. In the second line print m space-separated integers — the numbers of these employees in an arbitrary order. If Igor wins the dispute in any case, print -1. If there are multiple possible solutions, print any of them. | standard output | |
PASSED | 862c66f2a0af9e6b63cbf50857bed8df | train_004.jsonl | 1433595600 | The Looksery company, consisting of n staff members, is planning another big party. Every employee has his phone number and the phone numbers of his friends in the phone book. Everyone who comes to the party, sends messages to his contacts about how cool it is. At the same time everyone is trying to spend as much time on the fun as possible, so they send messages to everyone without special thinking, moreover, each person even sends a message to himself or herself.Igor and Max, Looksery developers, started a dispute on how many messages each person gets. Igor indicates n numbers, the i-th of which indicates how many messages, in his view, the i-th employee is going to take. If Igor guesses correctly at least one of these numbers, he wins, otherwise Max wins.You support Max in this debate, so you need, given the contact lists of the employees, to determine whether there is a situation where Igor loses. Specifically, you need to determine which employees should come to the party, and which should not, so after all the visitors send messages to their contacts, each employee received a number of messages that is different from what Igor stated. | 256 megabytes | import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
String[] contacts = new String[n];
for (int i = 0; i < n; i++) {
contacts[i] = in.nextToken();
}
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
int[] gotMessages = new int[n];
boolean[] party = new boolean[n];
all:
while (true) {
for (int i = 0; i < n; i++) {
if (a[i] == gotMessages[i]) {
party[i] = true;
for (int j = 0; j < n; j++) {
if (contacts[i].charAt(j) == '1') {
++gotMessages[j];
}
}
continue all;
}
}
break;
}
int count = 0;
for (int i = 0; i < n; i++) {
if (party[i]) {
++count;
}
}
out.println(count);
for (int i = 0; i < n; i++) {
if (party[i]) {
out.print((i+1)+" ");
}
}
out.println();
}
}
class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream));
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
}
| Java | ["3\n101\n010\n001\n0 1 2", "1\n1\n1", "4\n1111\n0101\n1110\n0001\n1 0 1 0"] | 1 second | ["1\n1", "0", "4\n1 2 3 4"] | NoteIn the first sample Igor supposes that the first employee will receive 0 messages. Since he isn't contained in any other contact list he must come to the party in order to receive one message from himself. If he is the only who come to the party then he will receive 1 message, the second employee will receive 0 messages and the third will also receive 1 message. Thereby Igor won't guess any number.In the second sample if the single employee comes to the party he receives 1 message and Igor wins, so he shouldn't do it.In the third sample the first employee will receive 2 messages, the second — 3, the third — 2, the fourth — 3. | Java 7 | standard input | [
"constructive algorithms",
"dfs and similar",
"greedy",
"graphs"
] | 794b0ac038e4e32f35f754e9278424d3 | The first line contains a single integer n (1 ≤ n ≤ 100) — the number of employees of company Looksery. Next n lines contain the description of the contact lists of the employees. The i-th of these lines contains a string of length n, consisting of digits zero and one, specifying the contact list of the i-th employee. If the j-th character of the i-th string equals 1, then the j-th employee is in the i-th employee's contact list, otherwise he isn't. It is guaranteed that the i-th character of the i-th line is always equal to 1. The last line contains n space-separated integers: a1, a2, ..., an (0 ≤ ai ≤ n), where ai represents the number of messages that the i-th employee should get according to Igor. | 2,300 | In the first line print a single integer m — the number of employees who should come to the party so that Igor loses the dispute. In the second line print m space-separated integers — the numbers of these employees in an arbitrary order. If Igor wins the dispute in any case, print -1. If there are multiple possible solutions, print any of them. | standard output | |
PASSED | 7e0d6921890b97c9f9215e6aa3ac4944 | train_004.jsonl | 1433595600 | The Looksery company, consisting of n staff members, is planning another big party. Every employee has his phone number and the phone numbers of his friends in the phone book. Everyone who comes to the party, sends messages to his contacts about how cool it is. At the same time everyone is trying to spend as much time on the fun as possible, so they send messages to everyone without special thinking, moreover, each person even sends a message to himself or herself.Igor and Max, Looksery developers, started a dispute on how many messages each person gets. Igor indicates n numbers, the i-th of which indicates how many messages, in his view, the i-th employee is going to take. If Igor guesses correctly at least one of these numbers, he wins, otherwise Max wins.You support Max in this debate, so you need, given the contact lists of the employees, to determine whether there is a situation where Igor loses. Specifically, you need to determine which employees should come to the party, and which should not, so after all the visitors send messages to their contacts, each employee received a number of messages that is different from what Igor stated. | 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 B_LC_2015 {
public static long MOD = 1000000007;
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();
boolean[][] map = new boolean[n][n];
for (int i = 0; i < n; i++) {
String line = in.next();
for (int j = 0; j < n; j++) {
map[i][j] = line.charAt(j) == '1';
}
}
Point[] data = new Point[n];
for (int i = 0; i < n; i++) {
data[i] = new Point(i, in.nextInt());
}
Arrays.sort(data, new Comparator<Point>(){
@Override
public int compare(Point o1, Point o2) {
// TODO Auto-generated method stub
return o1.y - o2.y;
}});
int[] count = new int[n];
boolean[] check = new boolean[n];
boolean ok = true;
int total = 0;
while (ok) {
boolean found = false;
for (Point p : data) {
if (count[p.x] == p.y) {
found = true;
total++;
if (!check[p.x]) {
check[p.x] = true;
for (int j = 0; j < n; j++) {
if (map[p.x][j]) {
count[j]++;
}
}
}else{
ok = false;
for(Point q : data){
if(map[q.x][q.y] && !check[q.x]){
check[p.x] = true;
total++;
ok = true;
for (int j = 0; j < n; j++) {
if (map[q.x][j]) {
count[j]++;
}
}
break;
}
}
}
break;
}
}
if (!found) {
break;
}
}
if(!ok){
out.println(-1);
}else{
out.println(total);
for(int i = 0; i < n; i++){
if(check[i]){
out.print((i + 1) + " ");
}
}
}
out.close();
}
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 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\n101\n010\n001\n0 1 2", "1\n1\n1", "4\n1111\n0101\n1110\n0001\n1 0 1 0"] | 1 second | ["1\n1", "0", "4\n1 2 3 4"] | NoteIn the first sample Igor supposes that the first employee will receive 0 messages. Since he isn't contained in any other contact list he must come to the party in order to receive one message from himself. If he is the only who come to the party then he will receive 1 message, the second employee will receive 0 messages and the third will also receive 1 message. Thereby Igor won't guess any number.In the second sample if the single employee comes to the party he receives 1 message and Igor wins, so he shouldn't do it.In the third sample the first employee will receive 2 messages, the second — 3, the third — 2, the fourth — 3. | Java 7 | standard input | [
"constructive algorithms",
"dfs and similar",
"greedy",
"graphs"
] | 794b0ac038e4e32f35f754e9278424d3 | The first line contains a single integer n (1 ≤ n ≤ 100) — the number of employees of company Looksery. Next n lines contain the description of the contact lists of the employees. The i-th of these lines contains a string of length n, consisting of digits zero and one, specifying the contact list of the i-th employee. If the j-th character of the i-th string equals 1, then the j-th employee is in the i-th employee's contact list, otherwise he isn't. It is guaranteed that the i-th character of the i-th line is always equal to 1. The last line contains n space-separated integers: a1, a2, ..., an (0 ≤ ai ≤ n), where ai represents the number of messages that the i-th employee should get according to Igor. | 2,300 | In the first line print a single integer m — the number of employees who should come to the party so that Igor loses the dispute. In the second line print m space-separated integers — the numbers of these employees in an arbitrary order. If Igor wins the dispute in any case, print -1. If there are multiple possible solutions, print any of them. | standard output | |
PASSED | 6e48f665cbaf9b20951d29f03d77a576 | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int q = in.nextInt();
int onePos = 1, twoPos = 2;
for (int i = 0; i < q; i++) {
int type = in.nextInt();
if (type == 1) {
int x = in.nextInt();
onePos += x;
twoPos += x;
} else {
if (onePos % 2 == 0) onePos--;
else onePos++;
if (twoPos % 2 == 0) twoPos--;
else twoPos++;
}
while (onePos <= 0) onePos += n;
while (twoPos <= 0) twoPos += n;
while (onePos > n) onePos -= n;
while (twoPos > n) twoPos -= n;
}
int ans[] = new int[n];
for (int i = 0; i < n; i += 2) {
ans[(i + onePos - 1) % n] = i + 1;
ans[(i + twoPos - 1) % n] = i + 2;
}
for (int i = 0; i < n; i++) {
out.print(ans[i] + " ");
}
}
}
static class InputReader {
private BufferedReader reader;
private StringTokenizer stt;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
return null;
}
}
public String next() {
while (stt == null || !stt.hasMoreTokens()) {
stt = new StringTokenizer(nextLine());
}
return stt.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | 4a5705e034364ce6217d7d0803bf7723 | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | //brute force on even and odd then apply to all
import java.util.*;
import java.io.*;
public class main
{
public static void main(String args[]) throws Exception
{
InputReader in=new InputReader();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
int n = in.nextInt();
int q = in.nextInt();
long odd = 0;
long even = 0;
while (q > 0) {
int t = in.nextInt();
if (t == 1) {
int val = in.nextInt();
odd += val;
even += val;
} else {
if (odd % 2 == 0)
odd += 1;
else
odd = odd - 1;
if (even % 2 == 0)
even += -1;
else
even += 1;
}
q--;
}
int ans[] = new int[n + 1];
for (int i = 1; i <= n; i++) {
if (i % 2 == 0) {
long ind = i + ((even) % n);
if (ind <= 0) {
ind += n;
}
if (ind > n) {
ind = ind - n;
}
ans[(int) ind] = i;
} else {
long ind = i + ((odd) % n);
if (ind <= 0) {
ind += n;
}
if (ind > n) {
ind = ind - n;
}
ans[(int) ind] = i;
}
}
for(int i=0;i<n;i++)
{
out.write(Integer.toString(ans[i+1])+" ");
}
out.flush();
out.close();
}
static class InputReader
{
BufferedReader in;
int j=0;
String[] line;
public InputReader()
{
try{
in = new BufferedReader(new InputStreamReader(System.in));
line = in.readLine().split(" ");
}
catch(Exception e)
{
}
}
public int nextInt()
{
if(j<line.length)
{
return Integer.parseInt(line[j++]);
}
else
{
try{
line = in.readLine().split(" ");
}
catch(Exception e){
}
j=0;
return Integer.parseInt(line[j++]);
}
}
}
} | Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | abe2c7bfbc9ceea8f915c6e1c5512ca1 | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | /**
* Built using VSCode,Custom Python and Bash files
* @author Siddhraj Sisodiya
*/
import java.io.*;
import java.util.*;
import java.math.*;
public class Main
{
public static void main(String[] args)
{
OutputWriter out = new OutputWriter(new PrintWriter(System.out));
Task solver = new Task();
solver.solve(new InputReader(System.in),out);
out.close();
}
}
class Task
{
Merge merge;
Task()
{
merge=new Merge();
}
public void solve(InputReader in,OutputWriter out)
{
int n = in.nextInt(),q=in.nextInt();
int a1=0,a2=1;
while(q-->0)
{
int type = in.nextInt();
if(type==1)
{
int x=in.nextInt();
a1+=x;
a2+=x;
a1=a1%n;
a2=a2%n;
if(a1<0)
{
a1+=n;
}
if(a2<0)
{
a2+=n;
}
}
else
{
if(a1%2==1)
{
a1--;
}
else
{
a1++;
}
if(a2%2==1)
{
a2--;
}
else
{
a2++;
}
}
}
int ans[]=new int[n];
Arrays.fill(ans,-1);
int count=1;
while(count<n)
{
ans[a1]=count;
count+=2;
a1+=2;
a1=a1%n;
}
count=2;
while(count<=n)
{
ans[a2]=count;
count+=2;
a2+=2;
a2=a2%n;
}
for (int i = 0; i < n ; i++)
{
out.prints(ans[i]);
}
}
}
class Merge
{
public void sort(int a[])
{
ArrayList<Integer> arr=new ArrayList<>();
for(int i=0;i<a.length;i++)
{
arr.add(a[i]);
}
Collections.sort(arr);
for(int i=0;i<a.length;i++)
{
a[i]=arr.get(i);
}
}
public void sort(long a[])
{
ArrayList<Long> arr=new ArrayList<>();
for(int i=0;i<a.length;i++)
{
arr.add(a[i]);
}
Collections.sort(arr);
for(int i=0;i<a.length;i++)
{
a[i]=arr.get(i);
}
}
}
class Pair implements Comparable<Pair>
{
Integer s;
Integer l;
Pair(int s,int l)
{
this.s=s;
this.l=l;
}
public int compareTo(Pair p)
{
return Integer.compare(this.l,p.l);
}
}
class OutputWriter
{
StringBuilder line;
PrintWriter out;
public OutputWriter(PrintWriter out)
{
this.out=out;
line=new StringBuilder();
}
public void print(int n)
{
line.append(n);
}
public void prints(int n)
{
line.append(n).append(' ');
}
public void println(int n)
{
line.append(n).append('\n');
}
public void close()
{
out.println(line);
out.flush();
}
}
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[] nextIntArray(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[] nextLongArray(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[] nextDoubleArray(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);
}
} | Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | 0309ca72ec69753610f4637d3ccc88a2 | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | /**
* Built using VSCode,Custom Python and Bash files
* @author Siddhraj Sisodiya
*/
import java.io.*;
import java.util.*;
import java.math.*;
public class Main
{
public static void main(String[] args)
{
InputStream inputStream = System.in;
InputReader in = new InputReader(inputStream);
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(in,out);
out.flush();
}
static class Task
{
Merge merge;
Task()
{
merge=new Merge();
}
public void solve(InputReader in,PrintWriter out)
{
int n = in.nextInt(),q=in.nextInt();
int a1=0,a2=1;
while(q-->0)
{
int type = in.nextInt();
if(type==1)
{
int x=in.nextInt();
a1+=x;
a2+=x;
a1=a1%n;
a2=a2%n;
if(a1<0)
{
a1+=n;
}
if(a2<0)
{
a2+=n;
}
}
else
{
if(a1%2==1)
{
a1--;
}
else
{
a1++;
}
if(a2%2==1)
{
a2--;
}
else
{
a2++;
}
}
}
int ans[]=new int[n];
Arrays.fill(ans,-1);
int count=1;
while(count<n)
{
ans[a1]=count;
count+=2;
a1+=2;
a1=a1%n;
}
count=2;
while(count<=n)
{
ans[a2]=count;
count+=2;
a2+=2;
a2=a2%n;
}
StringBuilder line = new StringBuilder();
for (int i = 0; i < n ; i++)
{
line.append(ans[i]).append(' ');
}
out.println(line);
}
}
static class Merge
{
public void sort(int a[])
{
ArrayList<Integer> arr=new ArrayList<>();
for(int i=0;i<a.length;i++)
{
arr.add(a[i]);
}
Collections.sort(arr);
for(int i=0;i<a.length;i++)
{
a[i]=arr.get(i);
}
}
public void sort(long a[])
{
ArrayList<Long> arr=new ArrayList<>();
for(int i=0;i<a.length;i++)
{
arr.add(a[i]);
}
Collections.sort(arr);
for(int i=0;i<a.length;i++)
{
a[i]=arr.get(i);
}
}
}
static class Pair implements Comparable<Pair>
{
Integer s;
Integer l;
Pair(int s,int l)
{
this.s=s;
this.l=l;
}
public int compareTo(Pair p)
{
return Integer.compare(this.l,p.l);
}
}
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 | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | 40df516483f9333a268e75e099d17f65 | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class main
{
public static void main(String args[])
{
InputStream inputStream = System.in;
InputReader in = new InputReader(inputStream);
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
int n = in.nextInt(),q=in.nextInt();
int a1=0,a2=1;
while(q-->0)
{
int type = in.nextInt();
if(type==1)
{
int x=in.nextInt();
a1+=x;
a2+=x;
a1=a1%n;
a2=a2%n;
if(a1<0)
{
a1+=n;
}
if(a2<0)
{
a2+=n;
}
}
else
{
if(a1%2==1)
{
a1--;
}
else
{
a1++;
}
if(a2%2==1)
{
a2--;
}
else
{
a2++;
}
}
}
int ans[]=new int[n];
Arrays.fill(ans,-1);
int count=1;
while(count<n)
{
ans[a1]=count;
count+=2;
a1+=2;
a1=a1%n;
}
count=2;
while(count<=n)
{
ans[a2]=count;
count+=2;
a2+=2;
a2=a2%n;
}
StringBuilder line = new StringBuilder();
for (int i = 0; i < n ; i++)
{
line.append(' ').append(ans[i]);
}
out.println(line.substring(1));
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 | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | bbba90533a98c3c721444bbe8c3c2d1f | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | import java.io.*;
import java.util.*;
public class main
{
public static void main(String args[])
{
InputReader in=new InputReader();
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
int n = in.nextInt(),q=in.nextInt();
int a1=0,a2=1;
while(q-->0)
{
int type = in.nextInt();
if(type==1)
{
int x=in.nextInt();
a1+=x;
a2+=x;
a1=a1%n;
a2=a2%n;
if(a1<0)
{
a1+=n;
}
if(a2<0)
{
a2+=n;
}
}
else
{
if(a1%2==1)
{
a1--;
}
else
{
a1++;
}
if(a2%2==1)
{
a2--;
}
else
{
a2++;
}
}
}
int ans[]=new int[n];
Arrays.fill(ans,-1);
int count=1;
while(count<n)
{
ans[a1]=count;
count+=2;
a1+=2;
a1=a1%n;
}
count=2;
while(count<=n)
{
ans[a2]=count;
count+=2;
a2+=2;
a2=a2%n;
}
for(int i=0;i<n;i++)
{
out.print(ans[i]+" ");
}
out.close();
}
static class InputReader
{
BufferedReader in;
int j=0;
String[] line;
public InputReader()
{
try{
in = new BufferedReader(new InputStreamReader(System.in));
line = in.readLine().split(" ");
}
catch(Exception e)
{
}
}
public int nextInt()
{
if(j<line.length)
{
return Integer.parseInt(line[j++]);
}
else
{
try{
line = in.readLine().split(" ");
}
catch(Exception e){
}
j=0;
return Integer.parseInt(line[j++]);
}
}
}
} | Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | 8c97b8d09bb02cfbbda8ebc482f73c02 | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class main
{
public static void main(String args[])
{
InputStream inputStream = System.in;
InputReader in = new InputReader(inputStream);
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
int n = in.nextInt(),q=in.nextInt();
int a1=0,a2=1;
while(q-->0)
{
int type = in.nextInt();
if(type==1)
{
int x=in.nextInt();
a1+=x;
a2+=x;
a1=a1%n;
a2=a2%n;
if(a1<0)
{
a1+=n;
}
if(a2<0)
{
a2+=n;
}
}
else
{
if(a1%2==1)
{
a1--;
}
else
{
a1++;
}
if(a2%2==1)
{
a2--;
}
else
{
a2++;
}
}
}
int ans[]=new int[n];
Arrays.fill(ans,-1);
int count=1;
while(count<n)
{
ans[a1]=count;
count+=2;
a1+=2;
a1=a1%n;
}
count=2;
while(count<=n)
{
ans[a2]=count;
count+=2;
a2+=2;
a2=a2%n;
}
StringBuilder line = new StringBuilder();
for (int i = 0; i < n ; i++)
{
line.append(' ').append(ans[i]);
}
out.println(line.substring(1));
out.flush();
}
static class InputReader
{
//private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars == -1)
{
throw new InputMismatchException();
}
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
{
return -1;
}
}
return buf[curChar++];
}
public int peek()
{
if (numChars == -1)
{
return -1;
}
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
} catch (IOException e)
{
return -1;
}
if (numChars <= 0)
{
return -1;
}
}
return buf[curChar];
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
StringBuilder res = new StringBuilder();
do
{
if (Character.isValidCodePoint(c))
{
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
{
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0()
{
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1)
{
if (c != '\r')
{
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine()
{
String s = readLine0();
while (s.trim().length() == 0)
{
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines)
{
if (ignoreEmptyLines)
{
return readLine();
} else
{
return readLine0();
}
}
public BigInteger readBigInteger()
{
try
{
return new BigInteger(nextString());
} catch (NumberFormatException e)
{
throw new InputMismatchException();
}
}
public char nextCharacter()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
return (char) c;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
{
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
{
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted()
{
int value;
while (isSpaceChar(value = peek()) && value != -1)
{
read();
}
return value == -1;
}
public String next()
{
return nextString();
}
public SpaceCharFilter getFilter()
{
return filter;
}
public void setFilter(SpaceCharFilter filter)
{
this.filter = filter;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
public int[] nextIntArray(int n)
{
int[] array=new int[n];
for(int i=0;i<n;++i)array[i]=nextInt();
return array;
}
public int[] nextIntArray(Integer n)
{
int[] array=new int[n];
for(int i=0;i<n;++i)array[i]=nextInt();
return array;
}
public Integer[] nextIntegerArray(int n)
{
Integer[] array=new Integer[n];
for(int i=0;i<n;++i)array[i]=nextInt();
return array;
}
public Integer[] nextIntegerArray(Integer n)
{
Integer[] array=new Integer[n];
for(int i=0;i<n;++i)array[i]=nextInt();
return array;
}
public int[] nextSortedIntArray(int n)
{
int array[]=nextIntArray(n);
Arrays.sort(array);
return array;
}
public int[] nextSumIntArray(int n)
{
int[] array=new int[n];
array[0]=nextInt();
for(int i=1;i<n;++i)array[i]=array[i-1]+nextInt();
return array;
}
public long[] nextLongArray(int n)
{
long[] array=new long[n];
for(int i=0;i<n;++i)array[i]=nextLong();
return array;
}
public long[] nextSumLongArray(int n)
{
long[] array=new long[n];
array[0]=nextInt();
for(int i=1;i<n;++i)array[i]=array[i-1]+nextInt();
return array;
}
public long[] nextSortedLongArray(int n)
{
long array[]=nextLongArray(n);
Arrays.sort(array);
return array;
}
}
} | Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | 405858bef465d5824b1d50acce4a9aaa | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | /**
* Built using VSCode,Custom Python and Bash files
* @author Siddhraj Sisodiya
*/
import java.io.*;
import java.util.*;
import java.math.*;
public class Main
{
public static void main(String[] args)
{
InputStream inputStream = System.in;
InputReader in = new InputReader(inputStream);
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(in,out);
out.flush();
}
static class Task
{
Merge merge;
Task()
{
merge=new Merge();
}
public void solve(InputReader in,PrintWriter out)
{
int n = in.nextInt(),q=in.nextInt();
int a1=0,a2=1;
while(q-->0)
{
int type = in.nextInt();
if(type==1)
{
int x=in.nextInt();
a1+=x;
a2+=x;
a1=a1%n;
a2=a2%n;
if(a1<0)
{
a1+=n;
}
if(a2<0)
{
a2+=n;
}
}
else
{
if(a1%2==1)
{
a1--;
}
else
{
a1++;
}
if(a2%2==1)
{
a2--;
}
else
{
a2++;
}
}
}
int ans[]=new int[n];
Arrays.fill(ans,-1);
int count=1;
while(count<n)
{
ans[a1]=count;
count+=2;
a1+=2;
a1=a1%n;
}
count=2;
while(count<=n)
{
ans[a2]=count;
count+=2;
a2+=2;
a2=a2%n;
}
for (int i = 0; i < n ; i++)
{
out.print(ans[i]+" ");
}
}
}
static class Merge
{
public void sort(int a[])
{
ArrayList<Integer> arr=new ArrayList<>();
for(int i=0;i<a.length;i++)
{
arr.add(a[i]);
}
Collections.sort(arr);
for(int i=0;i<a.length;i++)
{
a[i]=arr.get(i);
}
}
public void sort(long a[])
{
ArrayList<Long> arr=new ArrayList<>();
for(int i=0;i<a.length;i++)
{
arr.add(a[i]);
}
Collections.sort(arr);
for(int i=0;i<a.length;i++)
{
a[i]=arr.get(i);
}
}
}
static class Pair implements Comparable<Pair>
{
Integer s;
Integer l;
Pair(int s,int l)
{
this.s=s;
this.l=l;
}
public int compareTo(Pair p)
{
return Integer.compare(this.l,p.l);
}
}
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 | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | b04ebfb5924fe195e26dac4bf12872c8 | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class B
{
public static void main(String[] args)
{
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int q = in.nextInt();
int zero = 0;
int one = 1;
for (int i = 0; i < q ; i++)
{
int type = in.nextInt();
if (type == 1)
{
int x = (in.nextInt() + n) % n;
zero = (zero + x) % n;
one = (one + x) % n;
}
else
{
zero ^= 1;
one ^= 1;
}
}
int[] ans = new int[n];
for (int i = 0 ; i < n / 2 ; i++)
{
ans[(zero+i*2)%n] = i * 2 + 1;
ans[(one+i*2)%n] = i * 2 + 2;
}
StringBuilder line = new StringBuilder();
for (int i = 0; i < n ; i++)
{
line.append(' ').append(ans[i]);
}
out.println(line.substring(1));
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 | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | 238329f8358909d89414b3a3a2bc7396 | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | /**
* Built using VSCode,Custom Python and Bash files
* @author Siddhraj Sisodiya
*/
import java.io.*;
import java.util.*;
import java.math.*;
public class Main
{
public static void main(String[] args)
{
InputStream inputStream = System.in;
InputReader in = new InputReader(inputStream);
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task(in,out);
solver.solve();
}
static class Task
{
InputReader in;
PrintWriter out;
Merge merge;
long m=1000000007;
long temp=1;
Task(InputReader in,PrintWriter out)
{
this.in=in;
this.out=out;
merge=new Merge();
}
public void solve()
{
int n = in.nextInt(),q=in.nextInt();
int a1=0,a2=1;
while(q-->0)
{
int type = in.nextInt();
if(type==1)
{
int x=in.nextInt();
a1+=x;
a2+=x;
a1=a1%n;
a2=a2%n;
if(a1<0)
{
a1+=n;
}
if(a2<0)
{
a2+=n;
}
}
else
{
if(a1%2==1)
{
a1--;
}
else
{
a1++;
}
if(a2%2==1)
{
a2--;
}
else
{
a2++;
}
}
}
int ans[]=new int[n];
Arrays.fill(ans,-1);
int count=1;
while(count<n)
{
ans[a1]=count;
count+=2;
a1+=2;
a1=a1%n;
}
count=2;
while(count<=n)
{
ans[a2]=count;
count+=2;
a2+=2;
a2=a2%n;
}
for(int i=0;i<n;i++)
{
out.print(ans[i]+" ");
}
out.close();
}
}
static class Merge
{
public void sort(int a[])
{
ArrayList<Integer> arr=new ArrayList<>();
for(int i=0;i<a.length;i++)
{
arr.add(a[i]);
}
Collections.sort(arr);
for(int i=0;i<a.length;i++)
{
a[i]=arr.get(i);
}
}
public void sort(long a[])
{
ArrayList<Long> arr=new ArrayList<>();
for(int i=0;i<a.length;i++)
{
arr.add(a[i]);
}
Collections.sort(arr);
for(int i=0;i<a.length;i++)
{
a[i]=arr.get(i);
}
}
}
static class Pair implements Comparable<Pair>
{
Integer s;
Integer l;
Pair(int s,int l)
{
this.s=s;
this.l=l;
}
public int compareTo(Pair p)
{
return Integer.compare(this.l,p.l);
}
}
static class InputReader
{
//private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars == -1)
{
throw new InputMismatchException();
}
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
{
return -1;
}
}
return buf[curChar++];
}
public int peek()
{
if (numChars == -1)
{
return -1;
}
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
} catch (IOException e)
{
return -1;
}
if (numChars <= 0)
{
return -1;
}
}
return buf[curChar];
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
StringBuilder res = new StringBuilder();
do
{
if (Character.isValidCodePoint(c))
{
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
{
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0()
{
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1)
{
if (c != '\r')
{
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine()
{
String s = readLine0();
while (s.trim().length() == 0)
{
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines)
{
if (ignoreEmptyLines)
{
return readLine();
} else
{
return readLine0();
}
}
public BigInteger readBigInteger()
{
try
{
return new BigInteger(nextString());
} catch (NumberFormatException e)
{
throw new InputMismatchException();
}
}
public char nextCharacter()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
return (char) c;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
{
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
{
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted()
{
int value;
while (isSpaceChar(value = peek()) && value != -1)
{
read();
}
return value == -1;
}
public String next()
{
return nextString();
}
public SpaceCharFilter getFilter()
{
return filter;
}
public void setFilter(SpaceCharFilter filter)
{
this.filter = filter;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
public int[] nextIntArray(int n)
{
int[] array=new int[n];
for(int i=0;i<n;++i)array[i]=nextInt();
return array;
}
public int[] nextIntArray(Integer n)
{
int[] array=new int[n];
for(int i=0;i<n;++i)array[i]=nextInt();
return array;
}
public Integer[] nextIntegerArray(int n)
{
Integer[] array=new Integer[n];
for(int i=0;i<n;++i)array[i]=nextInt();
return array;
}
public Integer[] nextIntegerArray(Integer n)
{
Integer[] array=new Integer[n];
for(int i=0;i<n;++i)array[i]=nextInt();
return array;
}
public int[] nextSortedIntArray(int n)
{
int array[]=nextIntArray(n);
Arrays.sort(array);
return array;
}
public int[] nextSumIntArray(int n)
{
int[] array=new int[n];
array[0]=nextInt();
for(int i=1;i<n;++i)array[i]=array[i-1]+nextInt();
return array;
}
public long[] nextLongArray(int n)
{
long[] array=new long[n];
for(int i=0;i<n;++i)array[i]=nextLong();
return array;
}
public long[] nextSumLongArray(int n)
{
long[] array=new long[n];
array[0]=nextInt();
for(int i=1;i<n;++i)array[i]=array[i-1]+nextInt();
return array;
}
public long[] nextSortedLongArray(int n)
{
long array[]=nextLongArray(n);
Arrays.sort(array);
return array;
}
}
} | Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | 736ad747c6833ddecc1872639b59d970 | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | /**
* Built using VSCode,Custom Python and Bash files
* @author Siddhraj Sisodiya
*/
import java.io.*;
import java.util.*;
import java.math.*;
public class Main
{
public static void main(String[] args)
{
OutputWriter out = new OutputWriter(new PrintWriter(System.out));
Task solver = new Task();
solver.solve(new InputReader(System.in),out);
out.close();
}
}
class Task
{
Merge merge;
Task()
{
merge=new Merge();
}
public void solve(InputReader in,OutputWriter out)
{
int n = in.nextInt(),q=in.nextInt();
int a1=0,a2=1;
while(q-->0)
{
int type = in.nextInt();
if(type==1)
{
int x=in.nextInt();
a1+=x;
a2+=x;
a1=a1%n;
a2=a2%n;
if(a1<0)
{
a1+=n;
}
if(a2<0)
{
a2+=n;
}
}
else
{
if(a1%2==1)
{
a1--;
}
else
{
a1++;
}
if(a2%2==1)
{
a2--;
}
else
{
a2++;
}
}
}
int ans[]=new int[n];
Arrays.fill(ans,-1);
int count=1;
while(count<n)
{
ans[a1]=count;
count+=2;
a1+=2;
a1=a1%n;
}
count=2;
while(count<=n)
{
ans[a2]=count;
count+=2;
a2+=2;
a2=a2%n;
}
for (int i = 0; i < n ; i++)
{
out.printf("%d ",ans[i]);
}
}
//here out is inbuild function keep in mind and never use float
}
class Merge
{
public void sort(int a[])
{
ArrayList<Integer> arr=new ArrayList<>();
for(int i=0;i<a.length;i++)
{
arr.add(a[i]);
}
Collections.sort(arr);
for(int i=0;i<a.length;i++)
{
a[i]=arr.get(i);
}
}
public void sort(long a[])
{
ArrayList<Long> arr=new ArrayList<>();
for(int i=0;i<a.length;i++)
{
arr.add(a[i]);
}
Collections.sort(arr);
for(int i=0;i<a.length;i++)
{
a[i]=arr.get(i);
}
}
public void sort(double a[])
{
ArrayList<Double> arr=new ArrayList<>();
for(int i=0;i<a.length;i++)
{
arr.add(a[i]);
}
Collections.sort(arr);
for(int i=0;i<a.length;i++)
{
a[i]=arr.get(i);
}
}
}
class Pair implements Comparable<Pair>
{
Integer s;
Integer l;
Pair(int s,int l)
{
this.s=s;
this.l=l;
}
public int compareTo(Pair p)
{
return Integer.compare(this.l,p.l);
}
}
class OutputWriter
{
StringBuilder line;
PrintWriter out;
public OutputWriter(PrintWriter out)
{
this.out=out;
line=new StringBuilder();
}
public void print(int n)
{
line.append(n);
}
public void prints(int n)
{
line.append(n).append(' ');
}
public void println(int n)
{
line.append(n).append('\n');
}
public void print(long n)
{
line.append(n);
}
public void prints(long n)
{
line.append(n).append(' ');
}
public void println(long n)
{
line.append(n).append('\n');
}
public void print(double n)
{
line.append(n);
}
public void prints(double n)
{
line.append(n).append(' ');
}
public void println(double n)
{
line.append(n).append('\n');
}
public void print(String n)
{
line.append(n);
}
public void prints(String n)
{
line.append(n).append(' ');
}
public void println(String n)
{
line.append(n).append('\n');
}
public void print(char n)
{
line.append(n);
}
public void prints(char n)
{
line.append(n).append(' ');
}
public void println(char n)
{
line.append(n).append('\n');
}
public void printf(String str,Object... o)
{
line.append(String.format(str, o));
}
public void close()
{
out.print(line);
out.flush();
}
}
class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int[] nextIntArray(int n)
{
int[] ret = new int[n];
for (int i = 0; i < n; i++)
{
ret[i] = nextInt();
}
return ret;
}
public 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;
}
public long[] nextLongArray(int n)
{
long[] ret = new long[n];
for (int i = 0; i < n; i++)
{
ret[i] = nextLong();
}
return ret;
}
public 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;
}
public double[] nextDoubleArray(int n)
{
double[] ret = new double[n];
for (int i = 0; i < n; i++)
{
ret[i] = nextDouble();
}
return ret;
}
public 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);
}
} | Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | d2faf2358dfae5820ac81fc54a9cd2fb | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | /**
* Built using VSCode,Custom Python and Bash files
* @author Siddhraj Sisodiya
*/
import java.io.*;
import java.util.*;
import java.math.*;
public class Main
{
public static void main(String[] args)
{
OutputWriter out = new OutputWriter(new PrintWriter(System.out));
Task solver = new Task();
solver.solve(new InputReader(System.in),out);
out.close();
}
}
class Task
{
Merge merge;
Task()
{
merge=new Merge();
}
public void solve(InputReader in,OutputWriter out)
{
int n = in.nextInt(),q=in.nextInt();
int a1=0,a2=1;
while(q-->0)
{
int type = in.nextInt();
if(type==1)
{
int x=in.nextInt();
a1+=x;
a2+=x;
a1=a1%n;
a2=a2%n;
if(a1<0)
{
a1+=n;
}
if(a2<0)
{
a2+=n;
}
}
else
{
if(a1%2==1)
{
a1--;
}
else
{
a1++;
}
if(a2%2==1)
{
a2--;
}
else
{
a2++;
}
}
}
int ans[]=new int[n];
Arrays.fill(ans,-1);
int count=1;
while(count<n)
{
ans[a1]=count;
count+=2;
a1+=2;
a1=a1%n;
}
count=2;
while(count<=n)
{
ans[a2]=count;
count+=2;
a2+=2;
a2=a2%n;
}
for (int i = 0; i < n ; i++)
{
out.print(ans[i]+" ");
}
}
//here out is inbuild function keep in mind and never use float
}
class Merge
{
public void sort(int a[])
{
ArrayList<Integer> arr=new ArrayList<>();
for(int i=0;i<a.length;i++)
{
arr.add(a[i]);
}
Collections.sort(arr);
for(int i=0;i<a.length;i++)
{
a[i]=arr.get(i);
}
}
public void sort(long a[])
{
ArrayList<Long> arr=new ArrayList<>();
for(int i=0;i<a.length;i++)
{
arr.add(a[i]);
}
Collections.sort(arr);
for(int i=0;i<a.length;i++)
{
a[i]=arr.get(i);
}
}
public void sort(double a[])
{
ArrayList<Double> arr=new ArrayList<>();
for(int i=0;i<a.length;i++)
{
arr.add(a[i]);
}
Collections.sort(arr);
for(int i=0;i<a.length;i++)
{
a[i]=arr.get(i);
}
}
}
class Pair implements Comparable<Pair>
{
Integer s;
Integer l;
Pair(int s,int l)
{
this.s=s;
this.l=l;
}
public int compareTo(Pair p)
{
return Integer.compare(this.l,p.l);
}
}
class OutputWriter
{
StringBuilder line;
PrintWriter out;
public OutputWriter(PrintWriter out)
{
this.out=out;
line=new StringBuilder();
}
public void print(int n)
{
line.append(n);
}
public void prints(int n)
{
line.append(n).append(' ');
}
public void println(int n)
{
line.append(n).append('\n');
}
public void print(long n)
{
line.append(n);
}
public void prints(long n)
{
line.append(n).append(' ');
}
public void println(long n)
{
line.append(n).append('\n');
}
public void print(double n)
{
line.append(n);
}
public void prints(double n)
{
line.append(n).append(' ');
}
public void println(double n)
{
line.append(n).append('\n');
}
public void print(String n)
{
line.append(n);
}
public void prints(String n)
{
line.append(n).append(' ');
}
public void println(String n)
{
line.append(n).append('\n');
}
public void print(char n)
{
line.append(n);
}
public void prints(char n)
{
line.append(n).append(' ');
}
public void println(char n)
{
line.append(n).append('\n');
}
public void close()
{
out.print(line);
out.flush();
}
}
class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int[] nextIntArray(int n)
{
int[] ret = new int[n];
for (int i = 0; i < n; i++)
{
ret[i] = nextInt();
}
return ret;
}
public 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;
}
public long[] nextLongArray(int n)
{
long[] ret = new long[n];
for (int i = 0; i < n; i++)
{
ret[i] = nextLong();
}
return ret;
}
public 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;
}
public double[] nextDoubleArray(int n)
{
double[] ret = new double[n];
for (int i = 0; i < n; i++)
{
ret[i] = nextDouble();
}
return ret;
}
public 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);
}
} | Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | 65a99a15bf35351b2a9a1113a0e3ef12 | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class main
{
public static void main(String args[])
{
InputStream inputStream = System.in;
InputReader in = new InputReader(inputStream);
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
int n = in.nextInt(),q=in.nextInt();
int a1=0,a2=1;
while(q-->0)
{
int type = in.nextInt();
if(type==1)
{
int x=in.nextInt();
a1+=x;
a2+=x;
a1=a1%n;
a2=a2%n;
if(a1<0)
{
a1+=n;
}
if(a2<0)
{
a2+=n;
}
}
else
{
if(a1%2==1)
{
a1--;
}
else
{
a1++;
}
if(a2%2==1)
{
a2--;
}
else
{
a2++;
}
}
}
int ans[]=new int[n];
Arrays.fill(ans,-1);
int count=1;
while(count<n)
{
ans[a1]=count;
count+=2;
a1+=2;
a1=a1%n;
}
count=2;
while(count<=n)
{
ans[a2]=count;
count+=2;
a2+=2;
a2=a2%n;
}
for(int i=0;i<n;i++)
{
out.print(ans[i]+" ");
}
out.close();
}
static class InputReader
{
//private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars == -1)
{
throw new InputMismatchException();
}
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
{
return -1;
}
}
return buf[curChar++];
}
public int peek()
{
if (numChars == -1)
{
return -1;
}
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
} catch (IOException e)
{
return -1;
}
if (numChars <= 0)
{
return -1;
}
}
return buf[curChar];
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
StringBuilder res = new StringBuilder();
do
{
if (Character.isValidCodePoint(c))
{
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
{
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0()
{
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1)
{
if (c != '\r')
{
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine()
{
String s = readLine0();
while (s.trim().length() == 0)
{
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines)
{
if (ignoreEmptyLines)
{
return readLine();
} else
{
return readLine0();
}
}
public BigInteger readBigInteger()
{
try
{
return new BigInteger(nextString());
} catch (NumberFormatException e)
{
throw new InputMismatchException();
}
}
public char nextCharacter()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
return (char) c;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
{
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
{
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted()
{
int value;
while (isSpaceChar(value = peek()) && value != -1)
{
read();
}
return value == -1;
}
public String next()
{
return nextString();
}
public SpaceCharFilter getFilter()
{
return filter;
}
public void setFilter(SpaceCharFilter filter)
{
this.filter = filter;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
public int[] nextIntArray(int n)
{
int[] array=new int[n];
for(int i=0;i<n;++i)array[i]=nextInt();
return array;
}
public int[] nextIntArray(Integer n)
{
int[] array=new int[n];
for(int i=0;i<n;++i)array[i]=nextInt();
return array;
}
public Integer[] nextIntegerArray(int n)
{
Integer[] array=new Integer[n];
for(int i=0;i<n;++i)array[i]=nextInt();
return array;
}
public Integer[] nextIntegerArray(Integer n)
{
Integer[] array=new Integer[n];
for(int i=0;i<n;++i)array[i]=nextInt();
return array;
}
public int[] nextSortedIntArray(int n)
{
int array[]=nextIntArray(n);
Arrays.sort(array);
return array;
}
public int[] nextSumIntArray(int n)
{
int[] array=new int[n];
array[0]=nextInt();
for(int i=1;i<n;++i)array[i]=array[i-1]+nextInt();
return array;
}
public long[] nextLongArray(int n)
{
long[] array=new long[n];
for(int i=0;i<n;++i)array[i]=nextLong();
return array;
}
public long[] nextSumLongArray(int n)
{
long[] array=new long[n];
array[0]=nextInt();
for(int i=1;i<n;++i)array[i]=array[i-1]+nextInt();
return array;
}
public long[] nextSortedLongArray(int n)
{
long array[]=nextLongArray(n);
Arrays.sort(array);
return array;
}
}
} | Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | 859be845c17c620b77f000ceaa955c4e | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | //brute force on even and odd then apply to all
import java.util.*;
import java.io.*;
public class main
{
public static void main(String args[]) throws Exception
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
String[] str =in.readLine().split(" ");
int n = Integer.parseInt(str[0]);
int q = Integer.parseInt(str[1]);
int a1=0,a2=1;
while(q-->0)
{
String[] s =in.readLine().split(" ");
int type = Integer.parseInt(s[0]);
if(type==1)
{
int x=Integer.parseInt(s[1]);
a1+=x;
a2+=x;
a1=a1%n;
a2=a2%n;
if(a1<0)
{
a1+=n;
}
if(a2<0)
{
a2+=n;
}
}
else
{
if(a1%2==1)
{
a1--;
}
else
{
a1++;
}
if(a2%2==1)
{
a2--;
}
else
{
a2++;
}
}
}
int ans[]=new int[n];
Arrays.fill(ans,-1);
int count=1;
while(count<n)
{
ans[a1]=count;
count+=2;
a1+=2;
a1=a1%n;
}
count=2;
while(count<=n)
{
ans[a2]=count;
count+=2;
a2+=2;
a2=a2%n;
}
for(int i=0;i<n;i++)
{
out.write(Integer.toString(ans[i])+" ");
}
out.flush();
out.close();
}
} | Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | b8de7249f8f8868af837570ac109e741 | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | /**
* Built using VSCode,Custom Python and Bash files
* @author Siddhraj Sisodiya
*/
import java.io.*;
import java.util.*;
import java.math.*;
public class Main
{
public static void main(String[] args)
{
OutputWriter out = new OutputWriter(new PrintWriter(System.out));
Task solver = new Task();
solver.solve(new InputReader(System.in),out);
out.close();
}
}
class Task
{
Merge merge;
Task()
{
merge=new Merge();
}
public void solve(InputReader in,OutputWriter out)
{
int n = in.nextInt(),q=in.nextInt();
int a1=0,a2=1;
while(q-->0)
{
int type = in.nextInt();
if(type==1)
{
int x=in.nextInt();
a1+=x;
a2+=x;
a1=a1%n;
a2=a2%n;
if(a1<0)
{
a1+=n;
}
if(a2<0)
{
a2+=n;
}
}
else
{
if(a1%2==1)
{
a1--;
}
else
{
a1++;
}
if(a2%2==1)
{
a2--;
}
else
{
a2++;
}
}
}
int ans[]=new int[n];
Arrays.fill(ans,-1);
int count=1;
while(count<n)
{
ans[a1]=count;
count+=2;
a1+=2;
a1=a1%n;
}
count=2;
while(count<=n)
{
ans[a2]=count;
count+=2;
a2+=2;
a2=a2%n;
}
for (int i = 0; i < n ; i++)
{
out.prints(ans[i]);
}
}
}
class Merge
{
public void sort(int a[])
{
ArrayList<Integer> arr=new ArrayList<>();
for(int i=0;i<a.length;i++)
{
arr.add(a[i]);
}
Collections.sort(arr);
for(int i=0;i<a.length;i++)
{
a[i]=arr.get(i);
}
}
public void sort(long a[])
{
ArrayList<Long> arr=new ArrayList<>();
for(int i=0;i<a.length;i++)
{
arr.add(a[i]);
}
Collections.sort(arr);
for(int i=0;i<a.length;i++)
{
a[i]=arr.get(i);
}
}
}
class Pair implements Comparable<Pair>
{
Integer s;
Integer l;
Pair(int s,int l)
{
this.s=s;
this.l=l;
}
public int compareTo(Pair p)
{
return Integer.compare(this.l,p.l);
}
}
class OutputWriter
{
StringBuilder line;
PrintWriter out;
public OutputWriter(PrintWriter out)
{
this.out=out;
line=new StringBuilder();
}
public void print(int n)
{
line.append(n);
}
public void prints(int n)
{
line.append(n).append(' ');
}
public void println(int n)
{
line.append(n).append('\n');
}
public void print(long n)
{
line.append(n);
}
public void prints(long n)
{
line.append(n).append(' ');
}
public void println(long n)
{
line.append(n).append('\n');
}
public void print(double n)
{
line.append(n);
}
public void prints(double n)
{
line.append(n).append(' ');
}
public void println(double n)
{
line.append(n).append('\n');
}
public void print(String n)
{
line.append(n);
}
public void prints(String n)
{
line.append(n).append(' ');
}
public void println(String n)
{
line.append(n).append('\n');
}
public void print(char n)
{
line.append(n);
}
public void prints(char n)
{
line.append(n).append(' ');
}
public void println(char n)
{
line.append(n).append('\n');
}
public void close()
{
out.println(line);
out.flush();
}
}
class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int[] nextIntArray(int n)
{
int[] ret = new int[n];
for (int i = 0; i < n; i++)
{
ret[i] = nextInt();
}
return ret;
}
public 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;
}
public long[] nextLongArray(int n)
{
long[] ret = new long[n];
for (int i = 0; i < n; i++)
{
ret[i] = nextLong();
}
return ret;
}
public 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;
}
public double[] nextDoubleArray(int n)
{
double[] ret = new double[n];
for (int i = 0; i < n; i++)
{
ret[i] = nextDouble();
}
return ret;
}
public 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);
}
} | Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | b640c6f7c03f3ff19c45c64cfb9df093 | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class main
{
public static void main(String args[])
{
InputStream inputStream = System.in;
InputReader in = new InputReader(inputStream);
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
int n = in.nextInt(),q=in.nextInt();
int a1=0,a2=1;
while(q-->0)
{
int type = in.nextInt();
if(type==1)
{
int x=in.nextInt();
a1+=x;
a2+=x;
a1=a1%n;
a2=a2%n;
if(a1<0)
{
a1+=n;
}
if(a2<0)
{
a2+=n;
}
}
else
{
if(a1%2==1)
{
a1--;
}
else
{
a1++;
}
if(a2%2==1)
{
a2--;
}
else
{
a2++;
}
}
}
int ans[]=new int[n];
Arrays.fill(ans,-1);
int count=1;
while(count<n)
{
ans[a1]=count;
count+=2;
a1+=2;
a1=a1%n;
}
count=2;
while(count<=n)
{
ans[a2]=count;
count+=2;
a2+=2;
a2=a2%n;
}
StringBuilder line = new StringBuilder();
for (int i = 0; i < n ; i++)
{
line.append(ans[i]).append(' ');
}
out.println(line);
out.close();
}
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 | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | 31f473c98a9b04c0caab74b6d1fdfaa1 | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | /**
* Built using VSCode,Custom Python and Bash files
* @author Siddhraj Sisodiya
*/
import java.io.*;
import java.util.*;
import java.math.*;
public class Main
{
public static void main(String[] args)
{
InputStream inputStream = System.in;
InputReader in = new InputReader(inputStream);
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(in,out);
out.flush();
}
static class Task
{
Merge merge;
Task()
{
merge=new Merge();
}
public void solve(InputReader in,PrintWriter out)
{
int n = in.nextInt(),q=in.nextInt();
int a1=0,a2=1;
while(q-->0)
{
int type = in.nextInt();
if(type==1)
{
int x=in.nextInt();
a1+=x;
a2+=x;
a1=a1%n;
a2=a2%n;
if(a1<0)
{
a1+=n;
}
if(a2<0)
{
a2+=n;
}
}
else
{
if(a1%2==1)
{
a1--;
}
else
{
a1++;
}
if(a2%2==1)
{
a2--;
}
else
{
a2++;
}
}
}
int ans[]=new int[n];
Arrays.fill(ans,-1);
int count=1;
while(count<n)
{
ans[a1]=count;
count+=2;
a1+=2;
a1=a1%n;
}
count=2;
while(count<=n)
{
ans[a2]=count;
count+=2;
a2+=2;
a2=a2%n;
}
StringBuilder line = new StringBuilder();
for (int i = 0; i < n ; i++)
{
line.append(ans[i]).append(' ');
}
out.println(line);
}
}
static class Merge
{
public void sort(int a[])
{
ArrayList<Integer> arr=new ArrayList<>();
for(int i=0;i<a.length;i++)
{
arr.add(a[i]);
}
Collections.sort(arr);
for(int i=0;i<a.length;i++)
{
a[i]=arr.get(i);
}
}
public void sort(long a[])
{
ArrayList<Long> arr=new ArrayList<>();
for(int i=0;i<a.length;i++)
{
arr.add(a[i]);
}
Collections.sort(arr);
for(int i=0;i<a.length;i++)
{
a[i]=arr.get(i);
}
}
}
static class Pair implements Comparable<Pair>
{
Integer s;
Integer l;
Pair(int s,int l)
{
this.s=s;
this.l=l;
}
public int compareTo(Pair p)
{
return Integer.compare(this.l,p.l);
}
}
static class InputReader
{
//private boolean finished = false;
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars == -1)
{
throw new InputMismatchException();
}
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
{
return -1;
}
}
return buf[curChar++];
}
public int peek()
{
if (numChars == -1)
{
return -1;
}
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
} catch (IOException e)
{
return -1;
}
if (numChars <= 0)
{
return -1;
}
}
return buf[curChar];
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String nextString()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
StringBuilder res = new StringBuilder();
do
{
if (Character.isValidCodePoint(c))
{
res.appendCodePoint(c);
}
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
{
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c)
{
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private String readLine0()
{
StringBuilder buf = new StringBuilder();
int c = read();
while (c != '\n' && c != -1)
{
if (c != '\r')
{
buf.appendCodePoint(c);
}
c = read();
}
return buf.toString();
}
public String readLine()
{
String s = readLine0();
while (s.trim().length() == 0)
{
s = readLine0();
}
return s;
}
public String readLine(boolean ignoreEmptyLines)
{
if (ignoreEmptyLines)
{
return readLine();
} else
{
return readLine0();
}
}
public BigInteger readBigInteger()
{
try
{
return new BigInteger(nextString());
} catch (NumberFormatException e)
{
throw new InputMismatchException();
}
}
public char nextCharacter()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
return (char) c;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
{
c = read();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
{
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
{
return res * Math.pow(10, nextInt());
}
if (c < '0' || c > '9')
{
throw new InputMismatchException();
}
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean isExhausted()
{
int value;
while (isSpaceChar(value = peek()) && value != -1)
{
read();
}
return value == -1;
}
public String next()
{
return nextString();
}
public SpaceCharFilter getFilter()
{
return filter;
}
public void setFilter(SpaceCharFilter filter)
{
this.filter = filter;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
public int[] nextIntArray(int n)
{
int[] array=new int[n];
for(int i=0;i<n;++i)array[i]=nextInt();
return array;
}
public int[] nextIntArray(Integer n)
{
int[] array=new int[n];
for(int i=0;i<n;++i)array[i]=nextInt();
return array;
}
public Integer[] nextIntegerArray(int n)
{
Integer[] array=new Integer[n];
for(int i=0;i<n;++i)array[i]=nextInt();
return array;
}
public Integer[] nextIntegerArray(Integer n)
{
Integer[] array=new Integer[n];
for(int i=0;i<n;++i)array[i]=nextInt();
return array;
}
public int[] nextSortedIntArray(int n)
{
int array[]=nextIntArray(n);
Arrays.sort(array);
return array;
}
public int[] nextSumIntArray(int n)
{
int[] array=new int[n];
array[0]=nextInt();
for(int i=1;i<n;++i)array[i]=array[i-1]+nextInt();
return array;
}
public long[] nextLongArray(int n)
{
long[] array=new long[n];
for(int i=0;i<n;++i)array[i]=nextLong();
return array;
}
public long[] nextSumLongArray(int n)
{
long[] array=new long[n];
array[0]=nextInt();
for(int i=1;i<n;++i)array[i]=array[i-1]+nextInt();
return array;
}
public long[] nextSortedLongArray(int n)
{
long array[]=nextLongArray(n);
Arrays.sort(array);
return array;
}
}
} | Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | 7ba14ea4dc7167b1cf0fcb75db764a51 | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | /**
* Built using VSCode,Custom Python and Bash files
* @author Siddhraj Sisodiya
*/
import java.io.*;
import java.util.*;
import java.math.*;
public class Main
{
public static void main(String[] args)
{
InputStream inputStream = System.in;
InputReader in = new InputReader(inputStream);
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(in,out);
out.flush();
}
static class Task
{
Merge merge;
Task()
{
merge=new Merge();
}
public void solve(InputReader in,PrintWriter out)
{
Output outer=new Output(out);
int n = in.nextInt(),q=in.nextInt();
int a1=0,a2=1;
while(q-->0)
{
int type = in.nextInt();
if(type==1)
{
int x=in.nextInt();
a1+=x;
a2+=x;
a1=a1%n;
a2=a2%n;
if(a1<0)
{
a1+=n;
}
if(a2<0)
{
a2+=n;
}
}
else
{
if(a1%2==1)
{
a1--;
}
else
{
a1++;
}
if(a2%2==1)
{
a2--;
}
else
{
a2++;
}
}
}
int ans[]=new int[n];
Arrays.fill(ans,-1);
int count=1;
while(count<n)
{
ans[a1]=count;
count+=2;
a1+=2;
a1=a1%n;
}
count=2;
while(count<=n)
{
ans[a2]=count;
count+=2;
a2+=2;
a2=a2%n;
}
for (int i = 0; i < n ; i++)
{
outer.print(ans[i]);
}
outer.close();
}
}
static class Output
{
StringBuilder line;
PrintWriter out;
public Output(PrintWriter out)
{
this.out=out;
line=new StringBuilder();
}
public void print(int n)
{
line.append(n).append(' ');
}
public void close()
{
out.println(line);
}
}
static class Merge
{
public void sort(int a[])
{
ArrayList<Integer> arr=new ArrayList<>();
for(int i=0;i<a.length;i++)
{
arr.add(a[i]);
}
Collections.sort(arr);
for(int i=0;i<a.length;i++)
{
a[i]=arr.get(i);
}
}
public void sort(long a[])
{
ArrayList<Long> arr=new ArrayList<>();
for(int i=0;i<a.length;i++)
{
arr.add(a[i]);
}
Collections.sort(arr);
for(int i=0;i<a.length;i++)
{
a[i]=arr.get(i);
}
}
}
static class Pair implements Comparable<Pair>
{
Integer s;
Integer l;
Pair(int s,int l)
{
this.s=s;
this.l=l;
}
public int compareTo(Pair p)
{
return Integer.compare(this.l,p.l);
}
}
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 | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | e3b880bbad79cd98315dc3732c21d14d | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | /**
* Built using VSCode,Custom Python and Bash files
* @author Siddhraj Sisodiya
*/
import java.io.*;
import java.util.*;
import java.math.*;
public class Main
{
public static void main(String[] args)
{
InputReader in = new InputReader(System.in);
Output out = new Output(new PrintWriter(System.out));
Task solver = new Task();
solver.solve(in,out);
out.close();
}
static class Task
{
Merge merge;
Task()
{
merge=new Merge();
}
public void solve(InputReader in,Output out)
{
int n = in.nextInt(),q=in.nextInt();
int a1=0,a2=1;
while(q-->0)
{
int type = in.nextInt();
if(type==1)
{
int x=in.nextInt();
a1+=x;
a2+=x;
a1=a1%n;
a2=a2%n;
if(a1<0)
{
a1+=n;
}
if(a2<0)
{
a2+=n;
}
}
else
{
if(a1%2==1)
{
a1--;
}
else
{
a1++;
}
if(a2%2==1)
{
a2--;
}
else
{
a2++;
}
}
}
int ans[]=new int[n];
Arrays.fill(ans,-1);
int count=1;
while(count<n)
{
ans[a1]=count;
count+=2;
a1+=2;
a1=a1%n;
}
count=2;
while(count<=n)
{
ans[a2]=count;
count+=2;
a2+=2;
a2=a2%n;
}
for (int i = 0; i < n ; i++)
{
out.prints(ans[i]);
}
}
}
static class Merge
{
public void sort(int a[])
{
ArrayList<Integer> arr=new ArrayList<>();
for(int i=0;i<a.length;i++)
{
arr.add(a[i]);
}
Collections.sort(arr);
for(int i=0;i<a.length;i++)
{
a[i]=arr.get(i);
}
}
public void sort(long a[])
{
ArrayList<Long> arr=new ArrayList<>();
for(int i=0;i<a.length;i++)
{
arr.add(a[i]);
}
Collections.sort(arr);
for(int i=0;i<a.length;i++)
{
a[i]=arr.get(i);
}
}
}
static class Pair implements Comparable<Pair>
{
Integer s;
Integer l;
Pair(int s,int l)
{
this.s=s;
this.l=l;
}
public int compareTo(Pair p)
{
return Integer.compare(this.l,p.l);
}
}
static class Output
{
StringBuilder line;
PrintWriter out;
public Output(PrintWriter out)
{
this.out=out;
line=new StringBuilder();
}
public void print(int n)
{
line.append(n);
}
public void prints(int n)
{
line.append(n).append(' ');
}
public void close()
{
out.println(line);
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 | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | 745a945e485fd8f5e37b5f54e6332e2d | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | //brute force on even and odd then apply to all
import java.util.*;
import java.io.*;
public class main
{
public static void main(String args[]) throws Exception
{
InputReader in=new InputReader();
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
int n = in.nextInt(),q=in.nextInt();
int a1=0,a2=1;
while(q-->0)
{
int type = in.nextInt();
if(type==1)
{
int x=in.nextInt();
a1+=x;
a2+=x;
a1=a1%n;
a2=a2%n;
if(a1<0)
{
a1+=n;
}
if(a2<0)
{
a2+=n;
}
}
else
{
if(a1%2==1)
{
a1--;
}
else
{
a1++;
}
if(a2%2==1)
{
a2--;
}
else
{
a2++;
}
}
}
int ans[]=new int[n];
Arrays.fill(ans,-1);
int count=1;
while(count<n)
{
ans[a1]=count;
count+=2;
a1+=2;
a1=a1%n;
}
count=2;
while(count<=n)
{
ans[a2]=count;
count+=2;
a2+=2;
a2=a2%n;
}
for(int i=0;i<n;i++)
{
out.write(Integer.toString(ans[i])+" ");
}
out.flush();
out.close();
}
static class InputReader
{
BufferedReader in;
int j=0;
String[] line;
public InputReader()
{
try{
in = new BufferedReader(new InputStreamReader(System.in));
line = in.readLine().split(" ");
}
catch(Exception e)
{
}
}
public int nextInt()
{
if(j<line.length)
{
return Integer.parseInt(line[j++]);
}
else
{
try{
line = in.readLine().split(" ");
}
catch(Exception e){
}
j=0;
return Integer.parseInt(line[j++]);
}
}
}
} | Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | 59e5bd9b90ef4a5ac6c0558841798b0c | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class main
{
public static void main(String args[])
{
InputStream inputStream = System.in;
InputReader in = new InputReader(inputStream);
OutputStream outputStream = System.out;
PrintWriter out = new PrintWriter(outputStream);
int n = in.nextInt(),q=in.nextInt();
int a1=0,a2=1;
while(q-->0)
{
int type = in.nextInt();
if(type==1)
{
int x=in.nextInt();
a1+=x;
a2+=x;
a1=a1%n;
a2=a2%n;
if(a1<0)
{
a1+=n;
}
if(a2<0)
{
a2+=n;
}
}
else
{
if(a1%2==1)
{
a1--;
}
else
{
a1++;
}
if(a2%2==1)
{
a2--;
}
else
{
a2++;
}
}
}
int ans[]=new int[n];
Arrays.fill(ans,-1);
int count=1;
while(count<n)
{
ans[a1]=count;
count+=2;
a1+=2;
a1=a1%n;
}
count=2;
while(count<=n)
{
ans[a2]=count;
count+=2;
a2+=2;
a2=a2%n;
}
StringBuilder line = new StringBuilder();
for (int i = 0; i < n ; i++)
{
line.append(ans[i]).append(' ');
}
out.println(line);
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 | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | e669107f6e641fb23e855f602c8ed02d | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String [] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int q = Integer.parseInt(st.nextToken());
int array[] = new int[n];
int x = 0;
long ones = 1,twos = 2;
for(int i = 1;i <= q;i++){
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
x = Integer.MAX_VALUE;
if(a == 1)
x = Integer.parseInt(st.nextToken());
if(x != Integer.MAX_VALUE)
ones += x;
else if((ones & 1) == 0)--ones;
else ++ones;
if(x != Integer.MAX_VALUE)
twos += x;
else if((twos & 1) == 0)--twos;
else ++twos;
// System.out.println(ones);
}
ones %= n;twos %= n;
if(ones < 0)ones += n;
if(twos < 0)twos += n;
int odd = 1,even = 2;
for(int i = 1;i <= n/2;i++){
array[(int)ones] = odd;
array[(int)twos] = even;
odd += 2;even += 2;
ones += 2;
twos += 2;
if(ones >= n)ones -= n;
if(twos >= n)twos -= n;
}
StringBuilder sb = new StringBuilder();
for(int i = 1;i < n;i++)
sb.append(array[i] + " ");
System.out.print(sb);
System.out.print(array[0]);
}
} | Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | 06a90eb74d78c0a5c31dfe70c4f26bf4 | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Andrey Rechitsky (arechitsky@gmail.com)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, FastScanner in, FastPrinter out) {
int n = in.nextInt();
int q = in.nextInt();
long x = 0;
long even = 0;
boolean iseven = true;
for (int i = 0; i < q; i++) {
int t = in.nextInt();
if (t == 1) {
int d = in.nextInt();
x += d;
iseven ^= d % 2 != 0;
} else {
if (iseven) even++;
else even--;
iseven = !iseven;
}
}
int[] ans = new int[n];
for (int i = 0; i < n; i++) {
long tmp = i + x;
if (i % 2 == 0) {
tmp += even;
} else {
tmp -= even;
}
tmp %= n;
tmp += n;
tmp %= n;
ans[(int) tmp] = i;
}
for (int a : ans) {
out.print(a + 1);
out.print(' ');
}
out.printLine();
}
}
static class FastPrinter {
private final PrintWriter writer;
public FastPrinter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public FastPrinter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void printLine() {
writer.println();
}
public void print(long i) {
writer.print(i);
}
public void print(char c) {
writer.print(c);
}
}
static class FastScanner {
private BufferedReader reader;
private StringTokenizer st;
public FastScanner(InputStream stream) {
this.reader = new BufferedReader(new InputStreamReader(stream));
this.st = new StringTokenizer("");
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
while (!st.hasMoreTokens()) {
st = new StringTokenizer(readLine());
}
return st.nextToken();
}
private String readLine() {
String line = tryReadLine();
if (line == null) throw new InputMismatchException();
return line;
}
private String tryReadLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new InputMismatchException();
}
}
}
}
| Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | 79b361a8a61dbd3c1778d776f27bec90 | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | import java.io.*;
import java.util.StringTokenizer;
public class C2 {
FastScanner in;
PrintWriter out;
void solve() {
int n = in.nextInt(), q = in.nextInt();
int[] a1 = new int[n / 2], a2 = new int[n / 2];
for (int i = 0; i < n / 2; i++) {
a1[i] = 2 * i;
a2[i] = 2 * i + 1;
}
int shift1 = 0, shift2 = 0;
for (int i = 0; i < q; i++) {
int t = in.nextInt();
if (t == 1) {
int s = -in.nextInt();
if (s < 0) {
s = n + s;
}
if (s % 2 != 0) {
int[] tmpA = a1;
a1 = a2;
a2 = tmpA;
int tmp = shift1;
shift1 = shift2;
shift2 = tmp;
shift2++;
}
shift1 = (shift1 + s / 2) % (n / 2);
shift2 = (shift2 + s / 2) % (n / 2);
} else {
int[] tmpA = a1;
a1 = a2;
a2 = tmpA;
int tmp = shift1;
shift1 = shift2;
shift2 = tmp;
}
}
for (int i = 0; i < n / 2; i++) {
out.print((a1[(shift1 + i) % (n / 2)] + 1) + " ");
out.print((a2[(shift2 + i) % (n / 2)] + 1) + " ");
}
}
void runIO() {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
public static void main(String[] args) {
new C2().runIO();
}
} | Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | dbe67fa26fb112b5bef81f7630026df1 | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
/**
* Created by WiNDWAY on 5/13/16.
*/
public class Codeforces_VKCup_2016_round_2_LittleArtemAndDance {
public static void main(String[] args) {
FScanner input = new FScanner();
out = new PrintWriter(new BufferedOutputStream(System.out), true);
int boys = input.nextInt();
int commands = input.nextInt();
int firstBoyIndex = 0;
int secondBoyIndex = 1;
int[] boysArray = new int[boys];
for (int i = 0; i < commands; i++) {
int order = input.nextInt();
if (order == 2) {
if (firstBoyIndex % 2 == 0) {
firstBoyIndex++;
} else {
firstBoyIndex--;
}
if (secondBoyIndex % 2 == 0) {
secondBoyIndex++;
} else {
secondBoyIndex--;
}
} else if (order == 1) {
int move = input.nextInt();
firstBoyIndex += move;
secondBoyIndex += move;
if (firstBoyIndex >= boys) {
firstBoyIndex -= boys;
} else if (firstBoyIndex < 0) {
firstBoyIndex += boys;
}
if (secondBoyIndex >= boys) {
secondBoyIndex -= boys;
} else if (secondBoyIndex < 0) {
secondBoyIndex += boys;
}
}
}
Arrays.fill(boysArray, -1);
boysArray[firstBoyIndex] = 1;
boysArray[secondBoyIndex] = 2;
int oddBoyCounter = 1;
int oddBoyValue = 3;
int oddBoyIndex = firstBoyIndex + 2;
if (oddBoyIndex >= boys) {
oddBoyIndex -= boys;
}
while (oddBoyCounter < boys / 2) {
boysArray[oddBoyIndex] = oddBoyValue;
oddBoyValue += 2;
oddBoyCounter++;
oddBoyIndex += 2;
if (oddBoyIndex >= boys) {
oddBoyIndex -= boys;
}
}
int evenBoyCounter = 1;
int evenBoyValue = 4;
int evenBoyIndex = secondBoyIndex + 2;
if (evenBoyIndex >= boys) {
evenBoyIndex -= boys;
}
while (evenBoyCounter < boys / 2) {
boysArray[evenBoyIndex] = evenBoyValue;
evenBoyValue += 2;
evenBoyCounter++;
evenBoyIndex += 2;
if (evenBoyIndex >= boys) {
evenBoyIndex -= boys;
}
}
for (int i = 0; i < boys; i++) {
out.print(i == 0 ? boysArray[i] : " " + boysArray[i]);
}
out.close();
}
public static PrintWriter out;
public static class FScanner {
BufferedReader br;
StringTokenizer st;
public FScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
private 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 double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | f98576efd62b5bec9bc01e200a51c17d | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | import java.io.*;
import java.util.StringTokenizer;
/**
* @author Aydar Gizatullin a.k.a. lightning95, aydar.gizatullin@gmail.com
* Created on 4/24/16.
*/
public class ProbC {
private RW rw;
private String FILE_NAME = "file";
public static void main(String[] args) {
new ProbC().run();
}
private void run() {
rw = new RW(FILE_NAME + ".in", FILE_NAME + ".out");
solve();
rw.close();
}
private class RW {
private StringTokenizer st;
private PrintWriter out;
private BufferedReader br;
private boolean eof;
RW(String inputFile, String outputFile) {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new OutputStreamWriter(System.out));
File f = new File(inputFile);
if (f.exists() && f.canRead()) {
try {
br = new BufferedReader(new FileReader(inputFile));
out = new PrintWriter(new FileWriter(outputFile));
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String nextLine() {
String s = "";
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
private String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
eof = true;
return "-1";
}
}
return st.nextToken();
}
private int nextInt() {
return Integer.parseInt(next());
}
private void println() {
out.println();
}
private void println(Object o) {
out.println(o);
}
private void print(Object o) {
out.print(o);
}
private void close() {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
out.close();
}
}
private void solve() {
int n = rw.nextInt();
int q = rw.nextInt();
int f = 0;
int s = 1;
int t = 2;
for (int i = 0; i < q; ++i) {
int tip = rw.nextInt();
if (tip == 1) {
int x = (n + rw.nextInt()) % n;
f = (f + x) % n;
s = (s + x) % n;
t = (t + x) % n;
} else {
f = f + (f % 2 == 0 ? 1 : -1);
s = s + (s % 2 == 0 ? 1 : -1);
t = t + (t % 2 == 0 ? 1 : -1);
}
}
int[] a = new int[n];
int x = (n + t - f) % n;
for (int i = f, p = -1; a[i] == 0; i = (i + x) % n) {
a[i] = (p += 2);
}
for (int i = s, p = 0; a[i] == 0; i = (i + x) % n) {
a[i] = (p += 2);
}
for (int i= 0; i < n; ++i){
rw.print(a[i] + " ");
}
rw.println();
}
}
| Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | 135e38efbac383e010a5b15622272334 | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | import java.util.*;
import java.io.*;
public class Tmpl {
FastScanner in;
PrintWriter out;
public void solve() throws IOException {
int n = in.nextInt();
int q = in.nextInt();
int a = 0;
int b = 0;
for (int i = 0; i < q; i++) {
if (in.nextInt() == 1) {
int x = in.nextInt();
a += x;
b += x;
} else {
if (a % 2 == 0) {
a++;
} else {
a--;
}
if (b % 2 == 0) {
b--;
} else {
b++;
}
}
a %= n;
b %= n;
}
int[] ans = new int[n];
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
int x = ((i + a) % n + n) % n;
ans[x] = i+1;
} else {
int x = ((i + b) % n + n) % n;
ans[x] = i+1;
}
}
for ( int i = 0; i < n; i++){
out.print(ans[i]+" ");
}
}
public void run() {
try {
in = new FastScanner(new InputStreamReader(System.in));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
System.out)));
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStreamReader isr) {
br = new BufferedReader(isr);
}
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());
}
}
public static void main(String[] arg) {
new Tmpl().run();
}
} | Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | 6a3b0329763105842b3462433104337d | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | import java.io.*;
import java.util.*;
public final class artem_and_dance
{
static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
static FastScanner sc=new FastScanner(br);
static PrintWriter out=new PrintWriter(System.out);
static ArrayList<Integer>[] al;
@SuppressWarnings("unchecked")
public static void main(String args[]) throws Exception
{
long n=sc.nextInt(),q=sc.nextInt();al=new ArrayList[2];boolean b1=true;
for(int i=0;i<2;i++)
{
al[i]=new ArrayList<Integer>();
}
for(int i=0;i<n;i+=2)
{
al[0].add(i);
}
for(int i=1;i<n;i+=2)
{
al[1].add(i);
}
long sum1=0,sum2=0,val=0;
while(q>0)
{
int t=sc.nextInt();
if(t==1)
{
int x=sc.nextInt();sum1+=x;sum2+=x;val+=x;
}
else
{
if(val%2==0)
{
sum1++;sum2--;val++;
}
else
{
sum1--;sum2++;val--;
}
}
q--;
}
int[] res=new int[(int)n];
for(int i=0;i<al[0].size();i++)
{
long curr=al[0].get(i);curr=(curr+sum1)%n;long low=0,high=(long)(4e6);
while(low<high)
{
long mid=(low+high)>>1;
if(curr+(n*mid)>=0)
{
high=mid;
}
else
{
low=mid+1;
}
}
curr=(curr+(n*low))%n;res[(int)curr]=i*2;
}
for(int i=0;i<al[1].size();i++)
{
long curr=al[1].get(i);curr=(curr+sum2)%n;long low=0,high=(long)(4e6);
while(low<high)
{
long mid=(low+high)>>1;
if(curr+(n*mid)>=0)
{
high=mid;
}
else
{
low=mid+1;
}
}
curr=(curr+(n*low))%n;
res[(int)curr]=(i*2)+1;
}
for(int i=0;i<n;i++)
{
out.print((res[i]+1)+" ");
}
out.println("");out.close();
}
}
class FastScanner
{
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
public String next() throws Exception {
return nextToken().toString();
}
public int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
public long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
public double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
} | Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | aaa996187f4b7ea94288daa15a789fb7 | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | import java.io.*;
import java.util.*;
public class C {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
void solve() throws IOException {
int n = nextInt();
int q = nextInt();
int p0 = 0;
int p1 = 1;
while (q-- > 0) {
int type = nextInt();
if (type == 1) {
int shift = nextInt();
p0 = (p0 + shift + n) % n;
p1 = (p1 + shift + n) % n;
} else {
p0 ^= 1;
p1 ^= 1;
}
}
int[] ans = new int[n];
for (int i = 0, j = p0; i < n; i += 2) {
ans[j] = i;
j = (j + 2) % n;
}
for (int i = 1, j = p1; i < n; i += 2) {
ans[j] = i;
j = (j + 2) % n;
}
for (int x : ans) {
out.print(x + 1 + " ");
}
out.println();
}
C() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new C();
}
String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return null;
}
}
return st.nextToken();
}
String nextString() {
try {
return br.readLine();
} catch (IOException e) {
eof = true;
return null;
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
} | Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | f0bf5783854ccfa022619eb11c07fb2c | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int n = in.readInt();
int q = in.readInt();
long firstPos = 0;
long secondPos = 1;
for (int i = 0; i < q; i++) {
switch (in.readInt()) {
case 1:
long d = in.readLong();
firstPos += d;
secondPos += d;
break;
case 2:
if (firstPos % 2 == 0) {
firstPos++;
} else {
firstPos--;
}
if (secondPos % 2 == 0) {
secondPos++;
} else {
secondPos--;
}
break;
}
}
while (firstPos < 0 || secondPos < 0) {
firstPos += n;
secondPos += n;
}
firstPos %= n;
secondPos %= n;
int[] ans = new int[n];
for (int i = 0; i < n / 2; i++) {
ans[(int) ((firstPos + i * 2) % n)] = i * 2 + 1;
ans[(int) (secondPos + i * 2) % n] = i * 2 + 2;
}
out.print(ans);
}
}
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(int[] array) {
for (int i = 0; i < array.length; i++) {
if (i != 0) {
writer.print(' ');
}
writer.print(array[i]);
}
}
public void close() {
writer.close();
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | 7d0b33948b8f352fca94c0e4bfff9abf | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | import java.io.*;
import java.util.StringTokenizer;
public class C {
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void solve() throws IOException {
int t = 1;
while (t-- > 0) {
solveTest();
}
}
void solveTest() throws IOException {
int n = readInt();
int q = readInt();
long odd = 0;
long even = 0;
boolean swap = false;
for (int i = 0; i < q; i++) {
int t = readInt();
if (t == 1) {
int d = readInt();
odd += d;
even += d;
if (Math.abs(d) % 2 != 0) {
swap = !swap;
}
} else {
if (swap) {
odd--;
even++;
} else {
odd++;
even--;
}
swap = !swap;
}
}
if (odd < 0) {
odd = odd + n * 10000000l;
}
if (even < 0) {
even = even + n * 10000000l;
}
odd %= n;
even %= n;
int[] x = new int[n];
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
// odd
x[(int) ((i + odd) % n)] = i;
} else {
x[(int) ((i + even) % n)] = i;
}
}
for(int i = 0; i < n; i++) {
out.print(++x[i] + " ");
}
}
void init() throws FileNotFoundException {
if (ONLINE_JUDGE) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
int[] readArr(int n) throws IOException {
int[] res = new int[n];
for (int i = 0; i < n; i++) {
res[i] = readInt();
}
return res;
}
long[] readArrL(int n) throws IOException {
long[] res = new long[n];
for (int i = 0; i < n; i++) {
res[i] = readLong();
}
return res;
}
public static void main(String[] args) {
new C().run();
}
public void run() {
try {
long t1 = System.currentTimeMillis();
init();
solve();
out.close();
long t2 = System.currentTimeMillis();
System.err.println("Time = " + (t2 - t1));
} catch (Exception e) {
e.printStackTrace(System.err);
System.exit(-1);
}
}
} | Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | e72ed44a200e3761aa0b5fff5cf6451c | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | import java.io.*;
import java.util.Stack;
import java.util.StringTokenizer;
public class TaskC {
StringTokenizer st;
BufferedReader in;
PrintWriter out;
public static void main(String[] args) throws IOException {
TaskC taskC = new TaskC();
taskC.open();
taskC.solve();
taskC.close();
}
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String str = in.readLine();
if (str == null) return null;
else st = new StringTokenizer(str);
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
private void close() {
out.close();
}
private void solve() throws IOException {
int n = nextInt(), q = nextInt();
Stack<Boolean> swaps = new Stack<>();
int pos = 0;
for (int i = 0; i < q; i++) {
if (nextInt() == 1) {
pos = (pos + nextInt() + n) % n;
} else {
boolean oddSwap = pos % 2 == 1;
if (!swaps.isEmpty() && swaps.peek() == oddSwap) swaps.pop();
else swaps.add(oddSwap);
}
}
int[] answ = new int[n];
int sz = swaps.size();
if (!swaps.isEmpty() && swaps.firstElement()) sz = -sz;
for (int i = 0; i < n; i++) {
int posI = (i + sz + n) % n;
answ[posI] = i;
sz = -sz;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
sb.append(answ[(i-pos+n)%n]+1);
sb.append(' ');
}
out.println(sb);
}
private void open() {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(new BufferedOutputStream(System.out));
}
} | Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | 0ee30e89590632459fce35939c26ad06 | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | import java.util.Arrays;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Igor Kraskevich
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
}
class TaskC {
public void solve(int testNumber, FastScanner in, PrintWriter out) {
int n = in.nextInt();
int q = in.nextInt();
int swaps = 0;
long dEven = 0;
long dOdd = 0;
for (int i = 0; i < q; i++) {
int t = in.nextInt();
if (t == 1) {
long x = -in.nextInt();
x = (x + n) % n;
if (x % 2 == 0) {
dEven += x / 2;
dOdd += x / 2;
} else {
dEven += x / 2 + 1;
dOdd += x / 2;
swaps++;
long temp = dOdd;
dOdd = dEven;
dEven = temp;
}
} else {
swaps++;
long temp = dOdd;
dOdd = dEven;
dEven = temp;
}
}
int[] res = new int[n];
for (int i = 0; i < n / 2; i++) {
res[2 * i] = (int) ((dEven + i) * 2 % n);
res[2 * i + 1] = (int) (((dOdd + i) * 2 + 1) % n);
}
if (swaps % 2 == 1) {
for (int i = 0; i < n; i++)
if (i % 2 == 0)
res[i]++;
else
res[i]--;
}
for (int i = 0; i < n; i++)
out.print(res[i] + 1 + " ");
out.println();
}
}
class FastScanner {
private StringTokenizer tokenizer;
private BufferedReader reader;
public FastScanner(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String line = null;
try {
line = reader.readLine();
} catch (IOException e) {
}
if (line == null)
return null;
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
| Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | 0463a431f004ffb66931376e027afc2e | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
import java.util.HashMap;
public class Main
{
static class Reader
{
private InputStream mIs;private byte[] buf = new byte[1024];private int curChar,numChars;public Reader() { this(System.in); }public Reader(InputStream is) { mIs = is;}
public int read() {if (numChars == -1) throw new InputMismatchException();if (curChar >= numChars) {curChar = 0;try { numChars = mIs.read(buf);} catch (IOException e) { throw new InputMismatchException();}if (numChars <= 0) return -1; }return buf[curChar++];}
public String nextLine(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isEndOfLine(c));return res.toString() ;}
public String s(){int c = read();while (isSpaceChar(c)) c = read();StringBuilder res = new StringBuilder();do {res.appendCodePoint(c);c = read();}while (!isSpaceChar(c));return res.toString();}
public long l(){int c = read();while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }long res = 0; do{ if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read();}while(!isSpaceChar(c));return res * sgn;}
public int i(){int c = read() ;while (isSpaceChar(c)) c = read();int sgn = 1;if (c == '-') { sgn = -1 ; c = read() ; }int res = 0;do{if (c < '0' || c > '9') throw new InputMismatchException();res *= 10 ; res += c - '0' ; c = read() ;}while(!isSpaceChar(c));return res * sgn;}
public double d() throws IOException {return Double.parseDouble(s()) ;}
public boolean isSpaceChar(int c) { return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1; }
public boolean isEndOfLine(int c) { return c == '\n' || c == '\r' || c == -1; }
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void main(String args[])
{
Reader sc=new Reader();
PrintWriter out=new PrintWriter(System.out);
int n=sc.i();
int q=sc.i();
int pos1=1;
int pos2=2;
while(q-->0)
{
int qe=sc.i();
if(qe==2)
{
if(pos1%2==1)
pos1++;
else
pos1--;
if(pos2%2==1)
pos2++;
else
pos2--;
}
else
{
int val=sc.i();
if(val>0)
{
pos1+=val;
pos1%=n;
if(pos1==0)
pos1=n;
pos2+=val;
pos2%=n;
if(pos2==0)
pos2=n;
}
else
{
pos1+=val;
pos1+=n;
pos1%=n;
if(pos1==0)
pos1=n;
pos2+=val;
pos2+=n;
pos2%=n;
if(pos2==0)
pos2=n;
}
}
}
int arr[]=new int[n];
int counter=1;
pos1--;
while(counter!=n+1)
{
arr[pos1]=counter;
counter+=2;
pos1+=2;
pos1%=n;
}
counter=2;
pos2--;
while(counter!=n+2)
{
arr[pos2]=counter;
counter+=2;
pos2+=2;
pos2%=n;
}
for(int i=0;i<n;i++)
out.print(arr[i]+" ");
out.println();
out.flush();
}
} | Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | 89e3a0d0c82b6f2e20ab7bcf30c988f3 | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | import java.util.*;
import java.io.*;
public class C {
FastScanner in;
PrintWriter out;
boolean systemIO = true;
public void solve() {
int n = in.nextInt();
int q = in.nextInt();
int[] a = new int[n];
if (n == 2) {
int one = 0;
for (int i = 0; i < q; i++) {
if (in.nextInt() == 1) {
int x = in.nextInt();
one = (one + 2 * n + x) % n;
} else {
if (one % 2 == 0) {
one++;
} else {
one--;
}
}
}
if (one == 1) {
out.print("2 1");
} else {
out.println("1 2");
}
return;
}
int one = 0;
int two = 1;
int tree = 2;
for (int i = 0; i < q; i++) {
if (in.nextInt() == 1) {
int x = in.nextInt();
one = (one + 2 * n + x) % n;
two = (two + 2 * n + x) % n;
tree = (tree + 2 * n + x) % n;
} else {
if (one % 2 == 0) {
one++;
} else {
one--;
}
if (two % 2 == 0) {
two++;
} else {
two--;
}
if (tree % 2 == 0) {
tree++;
} else {
tree--;
}
}
}
a[one] = 1;
a[two] = 2;
a[tree] = 3;
int dx = two - one;
int dy = tree - one;
one = tree;
a[(tree + dx + 2 * n) % n] = 4;
two = (tree + dx + 2 * n) % n;
for (int i = 5; i <= a.length; i += 2) {
one = (one + dy + 2 * n) % n;
a[one] = i;
two = (two + dy + 2 * n) % n;
a[two] = i + 1;
}
for (int i = 0; i < a.length; i++) {
out.print(a[i] + " ");
}
}
public void run() {
try {
if (systemIO) {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
} else {
in = new FastScanner(new File("segments.in"));
out = new PrintWriter(new File("segments.out"));
}
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
return null;
}
}
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());
}
}
// AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
public static void main(String[] arg) {
new C().run();
}
} | Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | 90797b09980f6e575b1d79da7792ebf6 | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | import javafx.geometry.Pos;
import javafx.util.Pair;
import java.io.*;
import java.lang.reflect.Array;
import java.math.BigInteger;
import java.security.cert.PolicyNode;
import java.util.*;
import java.util.jar.Pack200;
public class Solution {
BufferedReader in;
PrintWriter out;
StringTokenizer st;
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
final int inf = Integer.MAX_VALUE / 2;
final double eps = 0.0000000001;
int rd() throws IOException {
return Integer.parseInt(nextToken());
}
long rdl() throws IOException {
return Long.parseLong(nextToken());
}
void solve() throws IOException {
//1 2 3 4 5 6
//2 1 4 3 6 5
//5 2 1 4 3 6
//2 5 4 1 6 3
//6 3 2 5 4 1
//3 6 5 2 1 4
//5 4 1 6 3 2
int n = rd();
int q = rd();
int pos1 = 0;
int pos2 = 1;
int posn = n;
for (int i = 0; i < q; i++){
int x = rd();
if (x == 2){
if (pos1 % 2 == 0){
pos1 ++;
} else {
pos1 --;
}
if (pos2 % 2 == 0){
pos2 ++;
} else {
pos2 --;
}
} else {
int y = rd();
if (y < 0){
y = n + y;
}
pos1 = (pos1 + y) % n ;
pos2 = (pos2 + y) % n;
posn = (posn + y) % n;
}
}
int[] a = new int[n];
for (int i = 1; i < n; i += 2){
a[(pos1 + i - 1) % n] = i;
}
for (int i = 2; i <= n; i += 2){
a[(pos2 + i - 2) % n] = i;
}
for (int i = 0; i < n; i++){
out.print(a[i] + " ");
}
}
void run() throws IOException {
try {
// in = new BufferedReader(new FileReader("notation.in"));
// out = new PrintWriter("notation.out");
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
Locale.setDefault(Locale.UK);
solve();
} catch (Exception e) {
e.printStackTrace();//To change body of catch statement use File | Settings | File Templates.
} finally {
out.close();
}
}
public static void main(String Args[]) throws IOException {
new Solution().run();
}
} | Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | 9c6f7d9136022e99b566eeca564cc4ee | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | import java.io.*;
import java.util.Scanner;
import java.util.StringTokenizer;
public class D {
public static void main(String[] args) throws Exception{
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tok = new StringTokenizer(input.readLine());
int n = Integer.parseInt(tok.nextToken());
int q = Integer.parseInt(tok.nextToken());
boolean z = true;
int odd = 0;
int even = 0;
int t;
int x;
for(int i = 0; i < q; i++){
tok = new StringTokenizer(input.readLine());
t = Integer.parseInt(tok.nextToken());
if(t == 1){
x = Integer.parseInt(tok.nextToken());
odd = (odd + n + x) % n;
even = (even + n + x) % n;
if((z && even % 2 == 1) || (!z && even % 2 == 0)){
z = !z;
}
}
else{
if(z){
even = (even - 1 + n) % n;
odd = (odd + 1) % n;
}
else{
even = (even + 1) % n;
odd = (odd - 1 + n) % n;
}
z = !z;
}
}
PrintStream output = new PrintStream(new BufferedOutputStream(System.out));
int ans = 0;
StringBuilder s = new StringBuilder(8 * n);
for(int i = 1; i <= n; i++){
ans = i - even;
if(ans < 1)
ans += n;
if(ans % 2 == 0){
s.append(ans + " ");
}
else{
ans = i - odd;
if(ans < 1)
ans += n;
s.append(ans + " ");
}
}
output.println(s);
output.close();
}
}
| Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | 45c60b24f3f329b387f06eb7262a9c08 | train_004.jsonl | 1461515700 | Little Artem is fond of dancing. Most of all dances Artem likes rueda — Cuban dance that is danced by pairs of boys and girls forming a circle and dancing together.More detailed, there are n pairs of boys and girls standing in a circle. Initially, boy number 1 dances with a girl number 1, boy number 2 dances with a girl number 2 and so on. Girls are numbered in the clockwise order. During the dance different moves are announced and all pairs perform this moves. While performing moves boys move along the circle, while girls always stay at their initial position. For the purpose of this problem we consider two different types of moves: Value x and some direction are announced, and all boys move x positions in the corresponding direction. Boys dancing with even-indexed girls swap positions with boys who are dancing with odd-indexed girls. That is the one who was dancing with the girl 1 swaps with the one who was dancing with the girl number 2, while the one who was dancing with girl number 3 swaps with the one who was dancing with the girl number 4 and so one. It's guaranteed that n is even. Your task is to determine the final position of each boy. | 256 megabytes | import java.util.*;
import java.io.*;
public class C {
FastScanner in;
PrintWriter out;
public void solve() throws IOException {
int n = in.nextInt();
int[] now = new int[2];
now[0] = 0;
now[1] = 1;
long[] dif = new long[2];
int q = in.nextInt();
for (int i = 0; i < q; i++) {
int t = in.nextInt();
if (t == 1) {
long x = in.nextInt();
dif[0] += x;
dif[1] += x;
if (x % 2 != 0) {
int tmp = now[0];
now[0] = now[1];
now[1] = tmp;
}
} else {
for (int x = 0; x < 2; x++) {
if (now[x] == 0) {
dif[x]++;
} else {
dif[x]--;
}
}
int tmp = now[0];
now[0] = now[1];
now[1] = tmp;
}
}
int[] a = new int[n];
for (int i = 0; i < n; i++) {
long x = (long) i + dif[i % 2];
x %= n;
x += n;
x %= n;
a[(int) x] = i + 1;
}
Arrays.stream(a).forEach(i -> out.print(i + " "));
out.println();
}
public void run() {
try {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
Locale.setDefault(Locale.US);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
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());
}
}
public static void main(String[] arg) {
new C().run();
}
} | Java | ["6 3\n1 2\n2\n1 2", "2 3\n1 1\n2\n1 -2", "4 2\n2\n1 3"] | 2 seconds | ["4 3 6 5 2 1", "1 2", "1 4 3 2"] | null | Java 8 | standard input | [
"constructive algorithms",
"implementation",
"brute force"
] | e30ac55354792bdad2ef41aba8838806 | The first line of the input contains two integers n and q (2 ≤ n ≤ 1 000 000, 1 ≤ q ≤ 2 000 000) — the number of couples in the rueda and the number of commands to perform, respectively. It's guaranteed that n is even. Next q lines contain the descriptions of the commands. Each command has type as the integer 1 or 2 first. Command of the first type is given as x ( - n ≤ x ≤ n), where 0 ≤ x ≤ n means all boys moves x girls in clockwise direction, while - x means all boys move x positions in counter-clockwise direction. There is no other input for commands of the second type. | 1,800 | Output n integers, the i-th of them should be equal to the index of boy the i-th girl is dancing with after performing all q moves. | standard output | |
PASSED | 920f5b23088d188517c6eb72b0ef4bfc | train_004.jsonl | 1402241400 | Valera loves his garden, where n fruit trees grow.This year he will enjoy a great harvest! On the i-th tree bi fruit grow, they will ripen on a day number ai. Unfortunately, the fruit on the tree get withered, so they can only be collected on day ai and day ai + 1 (all fruits that are not collected in these two days, become unfit to eat).Valera is not very fast, but there are some positive points. Valera is ready to work every day. In one day, Valera can collect no more than v fruits. The fruits may be either from the same tree, or from different ones. What is the maximum amount of fruit Valera can collect for all time, if he operates optimally well? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
// http://codeforces.com/contest/441/problem/B
public class ValeraAndFruits {
public static void main(String[] args) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
String input;
while ((input = reader.readLine()) != null && input.length() > 0) {
StringTokenizer data = new StringTokenizer(input);
int treesNumber = Integer.parseInt(data.nextToken());
int limitPerDay = Integer.parseInt(data.nextToken());
int[] fruits = new int[3002];
for (int i = 0; i < treesNumber; i++) {
data = new StringTokenizer(reader.readLine());
int index = Integer.parseInt(data.nextToken());
int value = Integer.parseInt(data.nextToken());
fruits[index] += value;
}
int total = 0;
int yesterdayFruits = 0;
for (int i = 0; i < fruits.length; i++) {
if ((yesterdayFruits + fruits[i]) <= limitPerDay) {
total += yesterdayFruits + fruits[i];
yesterdayFruits = 0;
} else {
total += limitPerDay;
int fruitsLeft = Math.max(limitPerDay - yesterdayFruits, 0);
yesterdayFruits = fruits[i] - fruitsLeft;
}
}
System.out.println(total);
}
}
}
} | Java | ["2 3\n1 5\n2 3", "5 10\n3 20\n2 20\n1 20\n4 20\n5 20"] | 1 second | ["8", "60"] | NoteIn the first sample, in order to obtain the optimal answer, you should act as follows. On the first day collect 3 fruits from the 1-st tree. On the second day collect 1 fruit from the 2-nd tree and 2 fruits from the 1-st tree. On the third day collect the remaining fruits from the 2-nd tree. In the second sample, you can only collect 60 fruits, the remaining fruit will simply wither. | Java 7 | standard input | [
"implementation",
"greedy"
] | 848ead2b878f9fd8547e1d442e2f85ff | The first line contains two space-separated integers n and v (1 ≤ n, v ≤ 3000) — the number of fruit trees in the garden and the number of fruits that Valera can collect in a day. Next n lines contain the description of trees in the garden. The i-th line contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ 3000) — the day the fruits ripen on the i-th tree and the number of fruits on the i-th tree. | 1,400 | Print a single integer — the maximum number of fruit that Valera can collect. | standard output | |
PASSED | add6da1a2d6258149a3e086eb9373c6d | train_004.jsonl | 1402241400 | Valera loves his garden, where n fruit trees grow.This year he will enjoy a great harvest! On the i-th tree bi fruit grow, they will ripen on a day number ai. Unfortunately, the fruit on the tree get withered, so they can only be collected on day ai and day ai + 1 (all fruits that are not collected in these two days, become unfit to eat).Valera is not very fast, but there are some positive points. Valera is ready to work every day. In one day, Valera can collect no more than v fruits. The fruits may be either from the same tree, or from different ones. What is the maximum amount of fruit Valera can collect for all time, if he operates optimally well? | 256 megabytes | //package R252;
import java.io.*;
import java.util.Arrays;
import java.util.Comparator;
public class R252B {
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
String linea;
String[] Datos;
while((linea = in.readLine()) != null && linea.length() != 0){
Datos = linea.split(" ");
int n = Integer.parseInt(Datos[0]);
int v = Integer.parseInt(Datos[1]);
arbol[] a = new arbol[n];
for (int i = 0; i <n; i++) {
Datos = in.readLine().split(" ");
a[i] = new arbol(Integer.parseInt(Datos[0]), Integer.parseInt(Datos[1]));
}
Arrays.sort(a, new arbol.Order_byDays());
// for (arbol i: a)
// System.out.println(i.days + " / " + i.fruits);
int max = 0;
for (arbol i: a)
if (i.getDays() > max) max = i.getDays();
// System.out.println("Max: " + max);
int days = 0, sum, total = 0;
while (days <= max) {
days += 1;
sum = 0;
// System.out.println("Day: " + days);
for (int i = 0; i < n; i++) {
if (a[i].days > days) break;
// System.out.println("i: " + i);
if (a[i].days == days || a[i].days == days -1) {
// System.out.println(a[i].days + " / " + a[i].fruits);
if (sum + a[i].getFruits() <= v) {
sum += a[i].getFruits();
a[i].setFruits(0);
}
else {
if (sum > v) {
break;
}
else {
// System.out.println("Aquí");
a[i].setFruits(a[i].getFruits() - (v -sum));
sum += v - sum;
// System.out.println(a[i].days + " / " + a[i].getFruits());
break;
}
}
// System.out.println(a[i].days + " / " + a[i].fruits);
}
}
// System.out.println("==================================");
total += sum;
// System.out.println("Suma: " + sum + " / Total: " + total);
}
System.out.println(total);
}
}
public static class arbol implements Comparable<arbol> {
private int days;
private int fruits;
public arbol (int d, int f) {
this.days = d;
this.fruits = f;
}
public int getDays() {
return this.days;
}
public int getFruits() {
return this.fruits;
}
public void setDays(int days) {
this.days = days;
}
public void setFruits(int fruits) {
this.fruits = fruits;
}
@Override
public int compareTo(arbol arg0) {
throw new UnsupportedOperationException("Not supported yet.");
}
public static class Order_byDays implements Comparator<arbol> {
public int compare(arbol a1, arbol a2) {
return (int) (a1.days- a2.days);
}
};
}
}
| Java | ["2 3\n1 5\n2 3", "5 10\n3 20\n2 20\n1 20\n4 20\n5 20"] | 1 second | ["8", "60"] | NoteIn the first sample, in order to obtain the optimal answer, you should act as follows. On the first day collect 3 fruits from the 1-st tree. On the second day collect 1 fruit from the 2-nd tree and 2 fruits from the 1-st tree. On the third day collect the remaining fruits from the 2-nd tree. In the second sample, you can only collect 60 fruits, the remaining fruit will simply wither. | Java 7 | standard input | [
"implementation",
"greedy"
] | 848ead2b878f9fd8547e1d442e2f85ff | The first line contains two space-separated integers n and v (1 ≤ n, v ≤ 3000) — the number of fruit trees in the garden and the number of fruits that Valera can collect in a day. Next n lines contain the description of trees in the garden. The i-th line contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ 3000) — the day the fruits ripen on the i-th tree and the number of fruits on the i-th tree. | 1,400 | Print a single integer — the maximum number of fruit that Valera can collect. | standard output | |
PASSED | 49715c36a7a060c8ba7f6ef5309f5d2b | train_004.jsonl | 1402241400 | Valera loves his garden, where n fruit trees grow.This year he will enjoy a great harvest! On the i-th tree bi fruit grow, they will ripen on a day number ai. Unfortunately, the fruit on the tree get withered, so they can only be collected on day ai and day ai + 1 (all fruits that are not collected in these two days, become unfit to eat).Valera is not very fast, but there are some positive points. Valera is ready to work every day. In one day, Valera can collect no more than v fruits. The fruits may be either from the same tree, or from different ones. What is the maximum amount of fruit Valera can collect for all time, if he operates optimally well? | 256 megabytes | //package R252;
import java.io.*;
import java.util.Arrays;
public class R252B {
public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(isr);
String linea;
String[] Datos;
while((linea = in.readLine()) != null && linea.length() != 0){
Datos = linea.split(" ");
int n = Integer.parseInt(Datos[0]);
int v = Integer.parseInt(Datos[1]);
arbol[] a = new arbol[n];
for (int i = 0; i <n; i++) {
Datos = in.readLine().split(" ");
a[i] = new arbol(Integer.parseInt(Datos[0]), Integer.parseInt(Datos[1]));
}
Arrays.sort(a);
int max = 0;
for (arbol i: a)
if (i.getDays() > max) max = i.getDays();
int days = 0, sum, total = 0;
while (days <= max) {
days += 1;
sum = 0;
for (int i = 0; i < n; i++) {
if (a[i].days > days) break;
if (a[i].days == days || a[i].days == days -1) {
if (sum + a[i].getFruits() <= v) {
sum += a[i].getFruits();
a[i].setFruits(0);
}
else {
if (sum > v) {
break;
}
else {
a[i].setFruits(a[i].getFruits() - (v -sum));
sum += v - sum;
break;
}
}
}
}
total += sum;
}
System.out.println(total);
}
}
public static class arbol implements Comparable<arbol> {
private int days;
private int fruits;
public arbol (int d, int f) {
this.days = d;
this.fruits = f;
}
public int getDays() {
return this.days;
}
public int getFruits() {
return this.fruits;
}
public void setDays(int days) {
this.days = days;
}
public void setFruits(int fruits) {
this.fruits = fruits;
}
@Override
public int compareTo(arbol arg0) {
return this.days - arg0.days;
}
}
}
| Java | ["2 3\n1 5\n2 3", "5 10\n3 20\n2 20\n1 20\n4 20\n5 20"] | 1 second | ["8", "60"] | NoteIn the first sample, in order to obtain the optimal answer, you should act as follows. On the first day collect 3 fruits from the 1-st tree. On the second day collect 1 fruit from the 2-nd tree and 2 fruits from the 1-st tree. On the third day collect the remaining fruits from the 2-nd tree. In the second sample, you can only collect 60 fruits, the remaining fruit will simply wither. | Java 7 | standard input | [
"implementation",
"greedy"
] | 848ead2b878f9fd8547e1d442e2f85ff | The first line contains two space-separated integers n and v (1 ≤ n, v ≤ 3000) — the number of fruit trees in the garden and the number of fruits that Valera can collect in a day. Next n lines contain the description of trees in the garden. The i-th line contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ 3000) — the day the fruits ripen on the i-th tree and the number of fruits on the i-th tree. | 1,400 | Print a single integer — the maximum number of fruit that Valera can collect. | standard output | |
PASSED | 2d46b0600126fa50a6c0b0624fb31eb7 | train_004.jsonl | 1402241400 | Valera loves his garden, where n fruit trees grow.This year he will enjoy a great harvest! On the i-th tree bi fruit grow, they will ripen on a day number ai. Unfortunately, the fruit on the tree get withered, so they can only be collected on day ai and day ai + 1 (all fruits that are not collected in these two days, become unfit to eat).Valera is not very fast, but there are some positive points. Valera is ready to work every day. In one day, Valera can collect no more than v fruits. The fruits may be either from the same tree, or from different ones. What is the maximum amount of fruit Valera can collect for all time, if he operates optimally well? | 256 megabytes | import java.util.Scanner;
public class ValeraAndFruits {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int v = sc.nextInt();
int b[] = new int[3001];
int r = 0;
int d = 0;
for (int i = 0; i < b.length; i++)
b[i] = 0;
for (int i = 1; i <= n; i++) {
b[sc.nextInt()] += sc.nextInt();
}
for (int i = 1; i < b.length; i++) {
if (b[i - 1] >= v) {
r += v;
} else {
d = v - b[i - 1];
r += b[i - 1];
if (b[i] >= d) {
b[i] -= d;
r += d;
} else {
r += b[i];
b[i] = 0;
}
}
}
if (b[b.length - 1] >= v) {
r += v;
} else {
r += b[b.length - 1];
}
System.out.println(r);
}
}
| Java | ["2 3\n1 5\n2 3", "5 10\n3 20\n2 20\n1 20\n4 20\n5 20"] | 1 second | ["8", "60"] | NoteIn the first sample, in order to obtain the optimal answer, you should act as follows. On the first day collect 3 fruits from the 1-st tree. On the second day collect 1 fruit from the 2-nd tree and 2 fruits from the 1-st tree. On the third day collect the remaining fruits from the 2-nd tree. In the second sample, you can only collect 60 fruits, the remaining fruit will simply wither. | Java 7 | standard input | [
"implementation",
"greedy"
] | 848ead2b878f9fd8547e1d442e2f85ff | The first line contains two space-separated integers n and v (1 ≤ n, v ≤ 3000) — the number of fruit trees in the garden and the number of fruits that Valera can collect in a day. Next n lines contain the description of trees in the garden. The i-th line contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ 3000) — the day the fruits ripen on the i-th tree and the number of fruits on the i-th tree. | 1,400 | Print a single integer — the maximum number of fruit that Valera can collect. | standard output | |
PASSED | 7953d5c79a6356b2f06ddef21eb4c0bb | train_004.jsonl | 1402241400 | Valera loves his garden, where n fruit trees grow.This year he will enjoy a great harvest! On the i-th tree bi fruit grow, they will ripen on a day number ai. Unfortunately, the fruit on the tree get withered, so they can only be collected on day ai and day ai + 1 (all fruits that are not collected in these two days, become unfit to eat).Valera is not very fast, but there are some positive points. Valera is ready to work every day. In one day, Valera can collect no more than v fruits. The fruits may be either from the same tree, or from different ones. What is the maximum amount of fruit Valera can collect for all time, if he operates optimally well? | 256 megabytes | import java.util.Scanner;
public class ValeraAndFruits {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int v = sc.nextInt();
int b[] = new int[3002];
int r = 0;
int d = 0;
for (int i = 0; i < b.length; i++)
b[i] = 0;
for (int i = 1; i <= n; i++) {
b[sc.nextInt()] += sc.nextInt();
}
for (int i = 1; i < b.length; i++) {
if (b[i - 1] >= v) {
r += v;
} else {
d = v - b[i - 1];
r += b[i - 1];
if (b[i] >= d) {
b[i] -= d;
r += d;
} else {
r += b[i];
b[i] = 0;
}
}
}
System.out.println(r);
}
}
| Java | ["2 3\n1 5\n2 3", "5 10\n3 20\n2 20\n1 20\n4 20\n5 20"] | 1 second | ["8", "60"] | NoteIn the first sample, in order to obtain the optimal answer, you should act as follows. On the first day collect 3 fruits from the 1-st tree. On the second day collect 1 fruit from the 2-nd tree and 2 fruits from the 1-st tree. On the third day collect the remaining fruits from the 2-nd tree. In the second sample, you can only collect 60 fruits, the remaining fruit will simply wither. | Java 7 | standard input | [
"implementation",
"greedy"
] | 848ead2b878f9fd8547e1d442e2f85ff | The first line contains two space-separated integers n and v (1 ≤ n, v ≤ 3000) — the number of fruit trees in the garden and the number of fruits that Valera can collect in a day. Next n lines contain the description of trees in the garden. The i-th line contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ 3000) — the day the fruits ripen on the i-th tree and the number of fruits on the i-th tree. | 1,400 | Print a single integer — the maximum number of fruit that Valera can collect. | standard output | |
PASSED | 803c124e6260df4d9b0fcf414568540b | train_004.jsonl | 1402241400 | Valera loves his garden, where n fruit trees grow.This year he will enjoy a great harvest! On the i-th tree bi fruit grow, they will ripen on a day number ai. Unfortunately, the fruit on the tree get withered, so they can only be collected on day ai and day ai + 1 (all fruits that are not collected in these two days, become unfit to eat).Valera is not very fast, but there are some positive points. Valera is ready to work every day. In one day, Valera can collect no more than v fruits. The fruits may be either from the same tree, or from different ones. What is the maximum amount of fruit Valera can collect for all time, if he operates optimally well? | 256 megabytes | import java.util.Scanner;
public class ValeraAndFruits {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int treeNum = sc.nextInt();
int maxColl = sc.nextInt();
int max = 3000;
int[] sum = new int[max+2];
//����sum����Ŷ�Ӧ�������ݶ�Ӧ��������ˮ��
//0�ŵ�Ԫ������
for(int i=1;i<=treeNum;i++){
sum[sc.nextInt()] += sc.nextInt();
}
sc.close();
// for(int i=1;i<sum.length;i++){
// System.out.print(sum[i]+" ");
// }
int left = 0;
for(int i=1;i<sum.length-1;i++){
if(left > 0){
if(left >= maxColl){
left = sum[i];
sum[i] = maxColl;
}
else{
if(sum[i]+left > maxColl){
left = sum[i] +left - maxColl;
sum[i] = maxColl;
}
else{
sum[i] = sum[i] + left;
left = 0;
}
}
}
else{
if(sum[i] > maxColl){
left = sum[i] - maxColl;
sum[i] = maxColl;
}
else{
left = 0;
}
}
if(i == max){
if(left > 0){
if(left > maxColl){
sum[max+1] = maxColl;
}
else{
sum[max+1] = left;
}
}
else{
sum[max+1] = 0;
}
// System.out.println(sum[treeNum+1]);
// System.out.println(left);
}
}
// System.out.println(sum[treeNum+1]);
// for(int i=1;i<sum.length;i++){
// System.out.print(sum[i]+" ");
// }
// System.out.println();
int sumAll = 0;
for(int i=1;i<sum.length;i++){
sumAll += sum[i];
}
System.out.println(sumAll);
}
}
| Java | ["2 3\n1 5\n2 3", "5 10\n3 20\n2 20\n1 20\n4 20\n5 20"] | 1 second | ["8", "60"] | NoteIn the first sample, in order to obtain the optimal answer, you should act as follows. On the first day collect 3 fruits from the 1-st tree. On the second day collect 1 fruit from the 2-nd tree and 2 fruits from the 1-st tree. On the third day collect the remaining fruits from the 2-nd tree. In the second sample, you can only collect 60 fruits, the remaining fruit will simply wither. | Java 7 | standard input | [
"implementation",
"greedy"
] | 848ead2b878f9fd8547e1d442e2f85ff | The first line contains two space-separated integers n and v (1 ≤ n, v ≤ 3000) — the number of fruit trees in the garden and the number of fruits that Valera can collect in a day. Next n lines contain the description of trees in the garden. The i-th line contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ 3000) — the day the fruits ripen on the i-th tree and the number of fruits on the i-th tree. | 1,400 | Print a single integer — the maximum number of fruit that Valera can collect. | standard output | |
PASSED | 166723c5b4a81d859ac4d3fccb3f4e89 | train_004.jsonl | 1402241400 | Valera loves his garden, where n fruit trees grow.This year he will enjoy a great harvest! On the i-th tree bi fruit grow, they will ripen on a day number ai. Unfortunately, the fruit on the tree get withered, so they can only be collected on day ai and day ai + 1 (all fruits that are not collected in these two days, become unfit to eat).Valera is not very fast, but there are some positive points. Valera is ready to work every day. In one day, Valera can collect no more than v fruits. The fruits may be either from the same tree, or from different ones. What is the maximum amount of fruit Valera can collect for all time, if he operates optimally well? | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class Vtora {
/**
* @param args
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int v = in.nextInt();
Item[] items = new Item[n];
for (int i = 0; i < n; i++) {
items[i] = new Item();
items[i].a = in.nextInt();
items[i].b = in.nextInt();
}
Arrays.sort(items);
// System.out.println(Arrays.toString(items));
int total = 0;
int days[] = new int[3010];
for (int i = 0; i < n; i++) {
if (days[items[i].a] < v) {
int x = Math.min(v - days[items[i].a], items[i].b);
days[items[i].a] += x;
items[i].b -= x;
}
if (items[i].b > 0 && days[items[i].a + 1] < v) {
int x = Math.min(v - days[items[i].a + 1], items[i].b);
days[items[i].a + 1] += x;
items[i].b -= x;
}
}
for (int i = 0; i < days.length; i++) {
total += days[i];
}
System.out.println(total);
}
}
class Item implements Comparable<Item> {
int a;
int b;
public Item() {
}
public Item(int aa, int bb) {
a = aa;
b = bb;
}
@Override
public int compareTo(Item other) {
return a - other.a;
}
@Override
public String toString() {
return a + " " + b;
}
}
| Java | ["2 3\n1 5\n2 3", "5 10\n3 20\n2 20\n1 20\n4 20\n5 20"] | 1 second | ["8", "60"] | NoteIn the first sample, in order to obtain the optimal answer, you should act as follows. On the first day collect 3 fruits from the 1-st tree. On the second day collect 1 fruit from the 2-nd tree and 2 fruits from the 1-st tree. On the third day collect the remaining fruits from the 2-nd tree. In the second sample, you can only collect 60 fruits, the remaining fruit will simply wither. | Java 7 | standard input | [
"implementation",
"greedy"
] | 848ead2b878f9fd8547e1d442e2f85ff | The first line contains two space-separated integers n and v (1 ≤ n, v ≤ 3000) — the number of fruit trees in the garden and the number of fruits that Valera can collect in a day. Next n lines contain the description of trees in the garden. The i-th line contains two space-separated integers ai and bi (1 ≤ ai, bi ≤ 3000) — the day the fruits ripen on the i-th tree and the number of fruits on the i-th tree. | 1,400 | Print a single integer — the maximum number of fruit that Valera can collect. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.