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 | 5ef180811624d277b2bd22766f87d768 | train_003.jsonl | 1604228700 | The new academic year has started, and Berland's university has $$$n$$$ first-year students. They are divided into $$$k$$$ academic groups, however, some of the groups might be empty. Among the students, there are $$$m$$$ pairs of acquaintances, and each acquaintance pair might be both in a common group or be in two different groups.Alice is the curator of the first years, she wants to host an entertaining game to make everyone know each other. To do that, she will select two different academic groups and then divide the students of those groups into two teams. The game requires that there are no acquaintance pairs inside each of the teams.Alice wonders how many pairs of groups she can select, such that it'll be possible to play a game after that. All students of the two selected groups must take part in the game.Please note, that the teams Alice will form for the game don't need to coincide with groups the students learn in. Moreover, teams may have different sizes (or even be empty). | 512 megabytes | import static java.lang.Math.*;
import static java.util.Arrays.*;
import java.util.*;
import java.util.ArrayList;
import java.util.stream.*;
public class C {
@SuppressWarnings("unchecked")
public Object solve () {
N = sc.nextInt();
int M = sc.nextInt(), K = sc.nextInt();
C = dec(sc.nextInts());
int [][] E = dec(sc.nextInts(M));
for (int [] e : E)
if (C[e[0]] > C[e[1]]) {
int x = e[0], y = e[1];
e[0] = y; e[1] = x;
}
Comparator<int[]> C0 = (a, b) -> C[a[0]] - C[b[0]];
Comparator<int[]> C1 = (a, b) -> C[a[1]] - C[b[1]];
sort(E, C0.thenComparing(C1));
G = graph(N, E);
D = new int [N]; fill(D, -1);
boolean [] Q = new boolean [K]; fill(Q, true);
for (int i : rep(N))
if (Q[C[i]])
if (D[i] == -1)
if (!dfs1(i, -1, i))
Q[C[i]] = false;
int J = 0;
for (int i : rep(K))
if (!Q[i])
++J;
long res = 1L * K * (K-1) / 2 - J * (J-1) / 2 - J * (K - J);
for (int i : rep(2))
for (int [] e : E)
if (Q[C[e[i]]])
e[i] = D[e[i]];
C = copyOf(C, 2*N);
for (int i : rep(N))
C[i+N] = C[i];
H = new List [2*N];
F = new int [2*N];
for (int p = 0, q = 0; q < M; ) {
int u = C[E[p][0]], v = C[E[p][1]];
while (q < M && u == C[E[q][0]] && v == C[E[q][1]])
++q;
if (Q[u] && Q[v] && u != v) {
for (int i : rep(p, q)) {
int x = E[i][0], y = E[i][1];
if (H[x] == null)
H[x] = new ArrayList<>();
if (H[x].isEmpty())
H[x].add(p(x));
if (H[y] == null)
H[y] = new ArrayList<>();
if (H[y].isEmpty())
H[y].add(p(y));
H[x].add(y); H[y].add(x);
}
for (int i : rep(p, q)) {
int x = E[i][0];
if (F[x] == 0)
if (!dfs2(x, -1, -1)) {
--res;
break;
}
}
for (int i : rep(p, q)) {
int x = E[i][0], y = E[i][1];
H[x] = H[y] = null;
F[x] = F[y] = F[p(x)] = F[p(y)] = 0;
}
}
p = q;
}
return res;
}
int N;
int [] C, D, F;
int [][] G;
List<Integer> [] H;
int p (int x) {
return x < N ? x + N : x - N;
}
boolean dfs1 (int s, int p, int v) {
int N = G.length, w = v < N ? v+N : v-N;
if (D[s] == v)
return true;
if (D[s] == w)
return false;
D[s] = v;
for (int j : G[s])
if (j != p && C[j] == C[s])
if (!dfs1(j, s, w))
return false;
return true;
}
boolean dfs2 (int s, int p, int v) {
if (F[s] == v)
return true;
if (F[s] == -v)
return false;
F[s] = v;
if (H[s] != null)
for (int j : H[s])
if (j != p)
if (!dfs2(j, s, -v))
return false;
return true;
}
private static final int CONTEST_TYPE = 1;
private static void init () {
}
private static final int INF = (int) 1e9 + 10;
private static int [] dec (int ... A) { for (int i = 0; i < A.length; ++i) --A[i]; return A; }
private static int [][] dec (int [] ... E) { return dec(E, INF); }
private static int [][] dec (int [][] E, int N) { for (int [] e : E) for (int i = 0; i < e.length && i < N; ++i) --e[i]; return E; }
private static int [][] dup (int [][] E) {
int [][] res = new int [2*E.length][];
for (int i = 0; i < E.length; ++i) {
res[2*i] = E[i].clone();
res[2*i+1] = E[i].clone();
res[2*i+1][0] = E[i][1]; res[2*i+1][1] = E[i][0];
}
return res;
}
private static int [][][] dwgraph (int N, int [][] E) {
int [] D = new int [N];
for (int [] e : E)
++D[e[0]];
int [][][] res = new int [2][N][];
for (int i = 0; i < 2; ++i)
for (int j = 0; j < N; ++j)
res[i][j] = new int [D[j]];
D = new int [N];
for (int [] e : E) {
int x = e[0], y = e[1], z = e.length > 2 ? e[2] : 1;
res[0][x][D[x]] = y;
res[1][x][D[x]] = z;
++D[x];
}
return res;
}
private static int [][] graph (int N, int [][] E) {
return wgraph(N, E)[0];
}
private static int [] rep (int N) { return rep(0, N); }
private static int [] rep (int S, int T) { if (S >= T) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; }
private static int [][][] wgraph (int N, int [][] E) { return dwgraph(N, dup(E)); }
//////////////////////////////////////////////////////////////////////////////////// OFF
private static IOUtils.MyScanner sc = new IOUtils.MyScanner();
private static class IOUtils {
public static class MyScanner {
public String next () { newLine(); return line[index++]; }
public int nextInt () { return Integer.parseInt(next()); }
public String nextLine () { line = null; return readLine(); }
public String [] nextStrings () { return split(nextLine()); }
public int[] nextInts () { return nextStream().mapToInt(Integer::parseInt).toArray(); }
public int[][] nextInts (int N) { return IntStream.range(0, N).mapToObj(i -> nextInts()).toArray(int[][]::new); }
//////////////////////////////////////////////
private boolean eol () { return index == line.length; }
private String readLine () {
try {
return r.readLine();
} catch (Exception e) {
throw new Error (e);
}
}
private final java.io.BufferedReader r;
private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); }
private MyScanner (java.io.BufferedReader r) {
try {
this.r = r;
while (!r.ready())
Thread.sleep(1);
start();
} catch (Exception e) {
throw new Error(e);
}
}
private String [] line;
private int index;
private void newLine () {
if (line == null || eol()) {
line = split(readLine());
index = 0;
}
}
private java.util.stream.Stream<String> nextStream () { return java.util.Arrays.stream(nextStrings()); }
private String [] split (String s) { return s.length() > 0 ? s.split(" ") : new String [0]; }
}
private static String build (Object o, Object ... A) { return buildDelim(" ", o, A); }
private static String buildDelim (String delim, Object o, Object ... A) {
StringBuilder b = new StringBuilder();
append(b, o, delim);
for (Object p : A)
append(b, p, delim);
return b.substring(min(b.length(), delim.length()));
}
//////////////////////////////////////////////////////////////////////////////////
private static java.text.DecimalFormat formatter = new java.text.DecimalFormat("#.#########");
private static void start () { if (t == 0) t = millis(); }
private static void append (java.util.function.Consumer<Object> f, java.util.function.Consumer<Object> g, final Object o) {
if (o.getClass().isArray()) {
int len = java.lang.reflect.Array.getLength(o);
for (int i = 0; i < len; ++i)
f.accept(java.lang.reflect.Array.get(o, i));
}
else if (o instanceof Iterable<?>)
((Iterable<?>)o).forEach(f::accept);
else
g.accept(o instanceof Double ? formatter.format(o) : o);
}
private static void append (final StringBuilder b, Object o, final String delim) {
append(x -> { append(b, x, delim); }, x -> b.append(delim).append(x), o);
}
private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out);
private static void print (Object o, Object ... A) {
String res = build(o, A);
if (DEBUG == 2)
err(res, '(', time(), ')');
if (res.length() > 0)
pw.println(res);
if (DEBUG == 1) {
pw.flush();
System.out.flush();
}
}
private static void err (Object o, Object ... A) { System.err.println(build(o, A)); }
private static int DEBUG;
private static void exit () {
String end = "------------------" + System.lineSeparator() + time();
switch(DEBUG) {
case 1: print(end); break;
case 2: err(end); break;
}
IOUtils.pw.close();
System.out.flush();
System.exit(0);
}
private static long t;
private static long millis () { return System.currentTimeMillis(); }
private static String time () { return "Time: " + (millis() - t) / 1000.0; }
private static void run (int N) {
try { DEBUG = Integer.parseInt(System.getProperties().get("DEBUG").toString()); }
catch (Throwable t) {}
for (int n = 1; n <= N; ++n) {
Object res = new C().solve();
if (res != null) {
@SuppressWarnings("all")
Object o = CONTEST_TYPE == 0 ? "Case #" + n + ": " + build(res) : res;
print(o);
}
}
exit();
}
}
////////////////////////////////////////////////////////////////////////////////////
public static void main (String[] args) {
init();
@SuppressWarnings("all")
int N = CONTEST_TYPE == 1 ? 1 : sc.nextInt();
IOUtils.run(N);
}
}
| Java | ["6 8 3\n1 1 2 2 3 3\n1 3\n1 5\n1 6\n2 5\n2 6\n3 4\n3 5\n5 6", "4 3 3\n1 1 2 2\n1 2\n2 3\n3 4", "4 4 2\n1 1 1 2\n1 2\n2 3\n3 1\n1 4", "5 5 2\n1 2 1 2 1\n1 2\n2 3\n3 4\n4 5\n5 1"] | 3 seconds | ["2", "3", "0", "0"] | NoteThe acquaintances graph for the first example is shown in the picture below (next to each student there is their group number written).In that test we can select the following groups: Select the first and the second groups. For instance, one team can be formed from students $$$1$$$ and $$$4$$$, while other team can be formed from students $$$2$$$ and $$$3$$$. Select the second and the third group. For instance, one team can be formed $$$3$$$ and $$$6$$$, while other team can be formed from students $$$4$$$ and $$$5$$$. We can't select the first and the third group, because there is no way to form the teams for the game. In the second example, we can select any group pair. Please note, that even though the third group has no students, we still can select it (with some other group) for the game. | Java 11 | standard input | [
"data structures",
"dsu",
"dfs and similar",
"graphs"
] | b4332870aac6159d5aaa4ff21f8e9f7f | The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n \le 500\,000$$$; $$$0 \le m \le 500\,000$$$; $$$2 \le k \le 500\,000$$$)Β β the number of students, the number of pairs of acquaintances and the number of groups respectively. The second line contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ equals to the group number of the $$$i$$$-th student. Next $$$m$$$ lines follow. The $$$i$$$-th of them contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$), denoting that students $$$a_i$$$ and $$$b_i$$$ are acquaintances. It's guaranteed, that $$$a_i \neq b_i$$$, and that no (unordered) pair is mentioned more than once. | 2,500 | Print a single integerΒ β the number of ways to choose two different groups such that it's possible to select two teams to play the game. | standard output | |
PASSED | 68d96871c2178b9123de94b7347ad3f4 | train_003.jsonl | 1604228700 | The new academic year has started, and Berland's university has $$$n$$$ first-year students. They are divided into $$$k$$$ academic groups, however, some of the groups might be empty. Among the students, there are $$$m$$$ pairs of acquaintances, and each acquaintance pair might be both in a common group or be in two different groups.Alice is the curator of the first years, she wants to host an entertaining game to make everyone know each other. To do that, she will select two different academic groups and then divide the students of those groups into two teams. The game requires that there are no acquaintance pairs inside each of the teams.Alice wonders how many pairs of groups she can select, such that it'll be possible to play a game after that. All students of the two selected groups must take part in the game.Please note, that the teams Alice will form for the game don't need to coincide with groups the students learn in. Moreover, teams may have different sizes (or even be empty). | 512 megabytes | import static java.lang.Math.*;
import static java.util.Arrays.*;
import java.util.*;
import java.util.ArrayList;
import java.util.stream.*;
public class C {
@SuppressWarnings("unchecked")
public Object solve () {
N = sc.nextInt();
int M = sc.nextInt(), K = sc.nextInt();
C = dec(sc.nextInts());
int [][] E = dec(sc.nextInts(M));
for (int [] e : E)
if (C[e[0]] > C[e[1]]) {
int x = e[0], y = e[1];
e[0] = y; e[1] = x;
}
Comparator<int[]> C0 = (a, b) -> C[a[0]] - C[b[0]];
Comparator<int[]> C1 = (a, b) -> C[a[1]] - C[b[1]];
sort(E, C0.thenComparing(C1));
G = graph(N, E);
D = new int [N]; fill(D, -1);
boolean [] Q = new boolean [K]; fill(Q, true);
for (int i : rep(N))
if (Q[C[i]])
if (D[i] == -1)
if (!dfs1(i, -1, i))
Q[C[i]] = false;
int J = 0;
for (int i : rep(K))
if (!Q[i])
++J;
long res = 1L * K * (K-1) / 2 - J * (J-1) / 2 - J * (K - J);
for (int i : rep(2))
for (int [] e : E)
if (Q[C[e[i]]])
e[i] = D[e[i]];
H = new List [2*N];
F = new int [2*N];
for (int p = 0, q = 0; q < M; ) {
int u = C[E[p][0]%N], v = C[E[p][1]%N];
while (q < M && u == C[E[q][0]%N] && v == C[E[q][1]%N])
++q;
if (Q[u] && Q[v] && u != v) {
for (int i : rep(p, q)) {
int x = E[i][0], y = E[i][1];
if (H[x] == null)
H[x] = new ArrayList<>();
if (H[x].isEmpty())
H[x].add(p(x));
if (H[y] == null)
H[y] = new ArrayList<>();
if (H[y].isEmpty())
H[y].add(p(y));
H[x].add(y); H[y].add(x);
}
for (int i : rep(p, q)) {
int x = E[i][0];
if (F[x] == 0)
if (!dfs2(x, -1, -1)) {
--res;
break;
}
}
for (int i : rep(p, q)) {
int x = E[i][0], y = E[i][1];
H[x].clear(); H[y].clear();
F[x] = F[y] = F[p(x)] = F[p(y)] = 0;
}
}
p = q;
}
return res;
}
int N;
int [] C, D, F;
int [][] G;
List<Integer> [] H;
int p (int x) {
return x < N ? x + N : x - N;
}
boolean dfs1 (int s, int p, int v) {
int N = G.length, w = v < N ? v+N : v-N;
if (D[s] == v)
return true;
if (D[s] == w)
return false;
D[s] = v;
for (int j : G[s])
if (j != p && C[j] == C[s])
if (!dfs1(j, s, w))
return false;
return true;
}
boolean dfs2 (int s, int p, int v) {
if (F[s] == v)
return true;
if (F[s] == -v)
return false;
F[s] = v;
if (H[s] != null)
for (int j : H[s])
if (j != p)
if (!dfs2(j, s, -v))
return false;
return true;
}
private static final int CONTEST_TYPE = 1;
private static void init () {
}
private static final int INF = (int) 1e9 + 10;
private static int [] dec (int ... A) { for (int i = 0; i < A.length; ++i) --A[i]; return A; }
private static int [][] dec (int [] ... E) { return dec(E, INF); }
private static int [][] dec (int [][] E, int N) { for (int [] e : E) for (int i = 0; i < e.length && i < N; ++i) --e[i]; return E; }
private static int [][] dup (int [][] E) {
int [][] res = new int [2*E.length][];
for (int i = 0; i < E.length; ++i) {
res[2*i] = E[i].clone();
res[2*i+1] = E[i].clone();
res[2*i+1][0] = E[i][1]; res[2*i+1][1] = E[i][0];
}
return res;
}
private static int [][][] dwgraph (int N, int [][] E) {
int [] D = new int [N];
for (int [] e : E)
++D[e[0]];
int [][][] res = new int [2][N][];
for (int i = 0; i < 2; ++i)
for (int j = 0; j < N; ++j)
res[i][j] = new int [D[j]];
D = new int [N];
for (int [] e : E) {
int x = e[0], y = e[1], z = e.length > 2 ? e[2] : 1;
res[0][x][D[x]] = y;
res[1][x][D[x]] = z;
++D[x];
}
return res;
}
private static int [][] graph (int N, int [][] E) {
return wgraph(N, E)[0];
}
private static int [] rep (int N) { return rep(0, N); }
private static int [] rep (int S, int T) { if (S >= T) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; }
private static int [][][] wgraph (int N, int [][] E) { return dwgraph(N, dup(E)); }
//////////////////////////////////////////////////////////////////////////////////// OFF
private static IOUtils.MyScanner sc = new IOUtils.MyScanner();
private static class IOUtils {
public static class MyScanner {
public String next () { newLine(); return line[index++]; }
public int nextInt () { return Integer.parseInt(next()); }
public String nextLine () { line = null; return readLine(); }
public String [] nextStrings () { return split(nextLine()); }
public int[] nextInts () { return nextStream().mapToInt(Integer::parseInt).toArray(); }
public int[][] nextInts (int N) { return IntStream.range(0, N).mapToObj(i -> nextInts()).toArray(int[][]::new); }
//////////////////////////////////////////////
private boolean eol () { return index == line.length; }
private String readLine () {
try {
return r.readLine();
} catch (Exception e) {
throw new Error (e);
}
}
private final java.io.BufferedReader r;
private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); }
private MyScanner (java.io.BufferedReader r) {
try {
this.r = r;
while (!r.ready())
Thread.sleep(1);
start();
} catch (Exception e) {
throw new Error(e);
}
}
private String [] line;
private int index;
private void newLine () {
if (line == null || eol()) {
line = split(readLine());
index = 0;
}
}
private java.util.stream.Stream<String> nextStream () { return java.util.Arrays.stream(nextStrings()); }
private String [] split (String s) { return s.length() > 0 ? s.split(" ") : new String [0]; }
}
private static String build (Object o, Object ... A) { return buildDelim(" ", o, A); }
private static String buildDelim (String delim, Object o, Object ... A) {
StringBuilder b = new StringBuilder();
append(b, o, delim);
for (Object p : A)
append(b, p, delim);
return b.substring(min(b.length(), delim.length()));
}
//////////////////////////////////////////////////////////////////////////////////
private static java.text.DecimalFormat formatter = new java.text.DecimalFormat("#.#########");
private static void start () { if (t == 0) t = millis(); }
private static void append (java.util.function.Consumer<Object> f, java.util.function.Consumer<Object> g, final Object o) {
if (o.getClass().isArray()) {
int len = java.lang.reflect.Array.getLength(o);
for (int i = 0; i < len; ++i)
f.accept(java.lang.reflect.Array.get(o, i));
}
else if (o instanceof Iterable<?>)
((Iterable<?>)o).forEach(f::accept);
else
g.accept(o instanceof Double ? formatter.format(o) : o);
}
private static void append (final StringBuilder b, Object o, final String delim) {
append(x -> { append(b, x, delim); }, x -> b.append(delim).append(x), o);
}
private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out);
private static void print (Object o, Object ... A) {
String res = build(o, A);
if (DEBUG == 2)
err(res, '(', time(), ')');
if (res.length() > 0)
pw.println(res);
if (DEBUG == 1) {
pw.flush();
System.out.flush();
}
}
private static void err (Object o, Object ... A) { System.err.println(build(o, A)); }
private static int DEBUG;
private static void exit () {
String end = "------------------" + System.lineSeparator() + time();
switch(DEBUG) {
case 1: print(end); break;
case 2: err(end); break;
}
IOUtils.pw.close();
System.out.flush();
System.exit(0);
}
private static long t;
private static long millis () { return System.currentTimeMillis(); }
private static String time () { return "Time: " + (millis() - t) / 1000.0; }
private static void run (int N) {
try { DEBUG = Integer.parseInt(System.getProperties().get("DEBUG").toString()); }
catch (Throwable t) {}
for (int n = 1; n <= N; ++n) {
Object res = new C().solve();
if (res != null) {
@SuppressWarnings("all")
Object o = CONTEST_TYPE == 0 ? "Case #" + n + ": " + build(res) : res;
print(o);
}
}
exit();
}
}
////////////////////////////////////////////////////////////////////////////////////
public static void main (String[] args) {
init();
@SuppressWarnings("all")
int N = CONTEST_TYPE == 1 ? 1 : sc.nextInt();
IOUtils.run(N);
}
}
| Java | ["6 8 3\n1 1 2 2 3 3\n1 3\n1 5\n1 6\n2 5\n2 6\n3 4\n3 5\n5 6", "4 3 3\n1 1 2 2\n1 2\n2 3\n3 4", "4 4 2\n1 1 1 2\n1 2\n2 3\n3 1\n1 4", "5 5 2\n1 2 1 2 1\n1 2\n2 3\n3 4\n4 5\n5 1"] | 3 seconds | ["2", "3", "0", "0"] | NoteThe acquaintances graph for the first example is shown in the picture below (next to each student there is their group number written).In that test we can select the following groups: Select the first and the second groups. For instance, one team can be formed from students $$$1$$$ and $$$4$$$, while other team can be formed from students $$$2$$$ and $$$3$$$. Select the second and the third group. For instance, one team can be formed $$$3$$$ and $$$6$$$, while other team can be formed from students $$$4$$$ and $$$5$$$. We can't select the first and the third group, because there is no way to form the teams for the game. In the second example, we can select any group pair. Please note, that even though the third group has no students, we still can select it (with some other group) for the game. | Java 11 | standard input | [
"data structures",
"dsu",
"dfs and similar",
"graphs"
] | b4332870aac6159d5aaa4ff21f8e9f7f | The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n \le 500\,000$$$; $$$0 \le m \le 500\,000$$$; $$$2 \le k \le 500\,000$$$)Β β the number of students, the number of pairs of acquaintances and the number of groups respectively. The second line contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ equals to the group number of the $$$i$$$-th student. Next $$$m$$$ lines follow. The $$$i$$$-th of them contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$), denoting that students $$$a_i$$$ and $$$b_i$$$ are acquaintances. It's guaranteed, that $$$a_i \neq b_i$$$, and that no (unordered) pair is mentioned more than once. | 2,500 | Print a single integerΒ β the number of ways to choose two different groups such that it's possible to select two teams to play the game. | standard output | |
PASSED | 0a19926d36f002a2b939a021c98b8a62 | train_003.jsonl | 1604228700 | The new academic year has started, and Berland's university has $$$n$$$ first-year students. They are divided into $$$k$$$ academic groups, however, some of the groups might be empty. Among the students, there are $$$m$$$ pairs of acquaintances, and each acquaintance pair might be both in a common group or be in two different groups.Alice is the curator of the first years, she wants to host an entertaining game to make everyone know each other. To do that, she will select two different academic groups and then divide the students of those groups into two teams. The game requires that there are no acquaintance pairs inside each of the teams.Alice wonders how many pairs of groups she can select, such that it'll be possible to play a game after that. All students of the two selected groups must take part in the game.Please note, that the teams Alice will form for the game don't need to coincide with groups the students learn in. Moreover, teams may have different sizes (or even be empty). | 512 megabytes | import static java.lang.Math.*;
import static java.util.Arrays.*;
import java.util.*;
import java.util.ArrayList;
import java.util.stream.*;
public class C {
@SuppressWarnings("unchecked")
public Object solve () {
N = sc.nextInt();
int M = sc.nextInt(), K = sc.nextInt();
C = dec(sc.nextInts());
int [][] E = dec(sc.nextInts(M));
for (int [] e : E)
if (C[e[0]] > C[e[1]]) {
int x = e[0], y = e[1];
e[0] = y; e[1] = x;
}
Comparator<int[]> C0 = (a, b) -> C[a[0]] - C[b[0]];
Comparator<int[]> C1 = (a, b) -> C[a[1]] - C[b[1]];
sort(E, C0.thenComparing(C1));
G = graph(N, E);
D = new int [N]; fill(D, -1);
boolean [] Q = new boolean [K]; fill(Q, true);
for (int i : rep(N))
if (Q[C[i]])
if (D[i] == -1)
if (!dfs1(i, -1, i))
Q[C[i]] = false;
int J = 0;
for (int i : rep(K))
if (!Q[i])
++J;
long res = 1L * K * (K-1) / 2 - J * (J-1) / 2 - J * (K - J);
for (int i : rep(2))
for (int [] e : E)
if (Q[C[e[i]]])
e[i] = D[e[i]];
C = copyOf(C, 2*N);
for (int i : rep(N))
C[i+N] = C[i];
H = new List [2*N];
F = new int [2*N];
for (int p = 0, q = 0; q < M; ) {
int u = C[E[p][0]], v = C[E[p][1]];
while (q < M && u == C[E[q][0]] && v == C[E[q][1]])
++q;
if (Q[u] && Q[v] && u != v) {
for (int i : rep(p, q)) {
int x = E[i][0], y = E[i][1];
if (H[x] == null)
H[x] = new ArrayList<>();
if (H[x].isEmpty())
H[x].add(p(x));
if (H[y] == null)
H[y] = new ArrayList<>();
if (H[y].isEmpty())
H[y].add(p(y));
H[x].add(y); H[y].add(x);
}
for (int i : rep(p, q)) {
int x = E[i][0];
if (F[x] == 0)
if (!dfs2(x, -1, -1)) {
--res;
break;
}
}
for (int i : rep(p, q)) {
int x = E[i][0], y = E[i][1];
H[x].clear(); H[y].clear();
F[x] = F[y] = F[p(x)] = F[p(y)] = 0;
}
}
p = q;
}
return res;
}
int N;
int [] C, D, F;
int [][] G;
List<Integer> [] H;
int p (int x) {
return x < N ? x + N : x - N;
}
boolean dfs1 (int s, int p, int v) {
int N = G.length, w = v < N ? v+N : v-N;
if (D[s] == v)
return true;
if (D[s] == w)
return false;
D[s] = v;
for (int j : G[s])
if (j != p && C[j] == C[s])
if (!dfs1(j, s, w))
return false;
return true;
}
boolean dfs2 (int s, int p, int v) {
if (F[s] == v)
return true;
if (F[s] == -v)
return false;
F[s] = v;
if (H[s] != null)
for (int j : H[s])
if (j != p)
if (!dfs2(j, s, -v))
return false;
return true;
}
private static final int CONTEST_TYPE = 1;
private static void init () {
}
private static final int INF = (int) 1e9 + 10;
private static int [] dec (int ... A) { for (int i = 0; i < A.length; ++i) --A[i]; return A; }
private static int [][] dec (int [] ... E) { return dec(E, INF); }
private static int [][] dec (int [][] E, int N) { for (int [] e : E) for (int i = 0; i < e.length && i < N; ++i) --e[i]; return E; }
private static int [][] dup (int [][] E) {
int [][] res = new int [2*E.length][];
for (int i = 0; i < E.length; ++i) {
res[2*i] = E[i].clone();
res[2*i+1] = E[i].clone();
res[2*i+1][0] = E[i][1]; res[2*i+1][1] = E[i][0];
}
return res;
}
private static int [][][] dwgraph (int N, int [][] E) {
int [] D = new int [N];
for (int [] e : E)
++D[e[0]];
int [][][] res = new int [2][N][];
for (int i = 0; i < 2; ++i)
for (int j = 0; j < N; ++j)
res[i][j] = new int [D[j]];
D = new int [N];
for (int [] e : E) {
int x = e[0], y = e[1], z = e.length > 2 ? e[2] : 1;
res[0][x][D[x]] = y;
res[1][x][D[x]] = z;
++D[x];
}
return res;
}
private static int [][] graph (int N, int [][] E) {
return wgraph(N, E)[0];
}
private static int [] rep (int N) { return rep(0, N); }
private static int [] rep (int S, int T) { if (S >= T) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; }
private static int [][][] wgraph (int N, int [][] E) { return dwgraph(N, dup(E)); }
//////////////////////////////////////////////////////////////////////////////////// OFF
private static IOUtils.MyScanner sc = new IOUtils.MyScanner();
private static class IOUtils {
public static class MyScanner {
public String next () { newLine(); return line[index++]; }
public int nextInt () { return Integer.parseInt(next()); }
public String nextLine () { line = null; return readLine(); }
public String [] nextStrings () { return split(nextLine()); }
public int[] nextInts () { return nextStream().mapToInt(Integer::parseInt).toArray(); }
public int[][] nextInts (int N) { return IntStream.range(0, N).mapToObj(i -> nextInts()).toArray(int[][]::new); }
//////////////////////////////////////////////
private boolean eol () { return index == line.length; }
private String readLine () {
try {
return r.readLine();
} catch (Exception e) {
throw new Error (e);
}
}
private final java.io.BufferedReader r;
private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); }
private MyScanner (java.io.BufferedReader r) {
try {
this.r = r;
while (!r.ready())
Thread.sleep(1);
start();
} catch (Exception e) {
throw new Error(e);
}
}
private String [] line;
private int index;
private void newLine () {
if (line == null || eol()) {
line = split(readLine());
index = 0;
}
}
private java.util.stream.Stream<String> nextStream () { return java.util.Arrays.stream(nextStrings()); }
private String [] split (String s) { return s.length() > 0 ? s.split(" ") : new String [0]; }
}
private static String build (Object o, Object ... A) { return buildDelim(" ", o, A); }
private static String buildDelim (String delim, Object o, Object ... A) {
StringBuilder b = new StringBuilder();
append(b, o, delim);
for (Object p : A)
append(b, p, delim);
return b.substring(min(b.length(), delim.length()));
}
//////////////////////////////////////////////////////////////////////////////////
private static java.text.DecimalFormat formatter = new java.text.DecimalFormat("#.#########");
private static void start () { if (t == 0) t = millis(); }
private static void append (java.util.function.Consumer<Object> f, java.util.function.Consumer<Object> g, final Object o) {
if (o.getClass().isArray()) {
int len = java.lang.reflect.Array.getLength(o);
for (int i = 0; i < len; ++i)
f.accept(java.lang.reflect.Array.get(o, i));
}
else if (o instanceof Iterable<?>)
((Iterable<?>)o).forEach(f::accept);
else
g.accept(o instanceof Double ? formatter.format(o) : o);
}
private static void append (final StringBuilder b, Object o, final String delim) {
append(x -> { append(b, x, delim); }, x -> b.append(delim).append(x), o);
}
private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out);
private static void print (Object o, Object ... A) {
String res = build(o, A);
if (DEBUG == 2)
err(res, '(', time(), ')');
if (res.length() > 0)
pw.println(res);
if (DEBUG == 1) {
pw.flush();
System.out.flush();
}
}
private static void err (Object o, Object ... A) { System.err.println(build(o, A)); }
private static int DEBUG;
private static void exit () {
String end = "------------------" + System.lineSeparator() + time();
switch(DEBUG) {
case 1: print(end); break;
case 2: err(end); break;
}
IOUtils.pw.close();
System.out.flush();
System.exit(0);
}
private static long t;
private static long millis () { return System.currentTimeMillis(); }
private static String time () { return "Time: " + (millis() - t) / 1000.0; }
private static void run (int N) {
try { DEBUG = Integer.parseInt(System.getProperties().get("DEBUG").toString()); }
catch (Throwable t) {}
for (int n = 1; n <= N; ++n) {
Object res = new C().solve();
if (res != null) {
@SuppressWarnings("all")
Object o = CONTEST_TYPE == 0 ? "Case #" + n + ": " + build(res) : res;
print(o);
}
}
exit();
}
}
////////////////////////////////////////////////////////////////////////////////////
public static void main (String[] args) {
init();
@SuppressWarnings("all")
int N = CONTEST_TYPE == 1 ? 1 : sc.nextInt();
IOUtils.run(N);
}
}
| Java | ["6 8 3\n1 1 2 2 3 3\n1 3\n1 5\n1 6\n2 5\n2 6\n3 4\n3 5\n5 6", "4 3 3\n1 1 2 2\n1 2\n2 3\n3 4", "4 4 2\n1 1 1 2\n1 2\n2 3\n3 1\n1 4", "5 5 2\n1 2 1 2 1\n1 2\n2 3\n3 4\n4 5\n5 1"] | 3 seconds | ["2", "3", "0", "0"] | NoteThe acquaintances graph for the first example is shown in the picture below (next to each student there is their group number written).In that test we can select the following groups: Select the first and the second groups. For instance, one team can be formed from students $$$1$$$ and $$$4$$$, while other team can be formed from students $$$2$$$ and $$$3$$$. Select the second and the third group. For instance, one team can be formed $$$3$$$ and $$$6$$$, while other team can be formed from students $$$4$$$ and $$$5$$$. We can't select the first and the third group, because there is no way to form the teams for the game. In the second example, we can select any group pair. Please note, that even though the third group has no students, we still can select it (with some other group) for the game. | Java 11 | standard input | [
"data structures",
"dsu",
"dfs and similar",
"graphs"
] | b4332870aac6159d5aaa4ff21f8e9f7f | The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n \le 500\,000$$$; $$$0 \le m \le 500\,000$$$; $$$2 \le k \le 500\,000$$$)Β β the number of students, the number of pairs of acquaintances and the number of groups respectively. The second line contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ equals to the group number of the $$$i$$$-th student. Next $$$m$$$ lines follow. The $$$i$$$-th of them contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$), denoting that students $$$a_i$$$ and $$$b_i$$$ are acquaintances. It's guaranteed, that $$$a_i \neq b_i$$$, and that no (unordered) pair is mentioned more than once. | 2,500 | Print a single integerΒ β the number of ways to choose two different groups such that it's possible to select two teams to play the game. | standard output | |
PASSED | ba092dee57ed7fdc3e66138000c4cada | train_003.jsonl | 1604228700 | The new academic year has started, and Berland's university has $$$n$$$ first-year students. They are divided into $$$k$$$ academic groups, however, some of the groups might be empty. Among the students, there are $$$m$$$ pairs of acquaintances, and each acquaintance pair might be both in a common group or be in two different groups.Alice is the curator of the first years, she wants to host an entertaining game to make everyone know each other. To do that, she will select two different academic groups and then divide the students of those groups into two teams. The game requires that there are no acquaintance pairs inside each of the teams.Alice wonders how many pairs of groups she can select, such that it'll be possible to play a game after that. All students of the two selected groups must take part in the game.Please note, that the teams Alice will form for the game don't need to coincide with groups the students learn in. Moreover, teams may have different sizes (or even be empty). | 512 megabytes | import static java.lang.Math.*;
import static java.util.Arrays.*;
import java.util.*;
import java.util.ArrayList;
import java.util.stream.*;
public class C {
@SuppressWarnings("unchecked")
public Object solve () {
N = sc.nextInt();
int M = sc.nextInt(), K = sc.nextInt();
C = dec(sc.nextInts());
int [][] E = dec(sc.nextInts(M));
for (int [] e : E)
if (C[e[0]] > C[e[1]]) {
int x = e[0], y = e[1];
e[0] = y; e[1] = x;
}
sort(E, (a, b) -> {
if (C[a[0]] != C[b[0]])
return C[a[0]] - C[b[0]];
else
return C[a[1]] - C[b[1]];
});
G = graph(N, E);
D = new int [N]; fill(D, -1);
boolean [] Q = new boolean [K]; fill(Q, true);
for (int i : rep(N))
if (Q[C[i]])
if (D[i] == -1)
if (!dfs1(i, -1, i))
Q[C[i]] = false;
int J = 0;
for (int i : rep(K))
if (!Q[i])
++J;
long res = 1L * K * (K-1) / 2 - J * (J-1) / 2 - J * (K - J);
for (int i : rep(2))
for (int [] e : E)
if (Q[C[e[i]]])
e[i] = D[e[i]];
H = new List [2*N];
F = new int [2*N];
for (int p = 0, q = 0; q < M; ) {
int u = C[E[p][0]%N], v = C[E[p][1]%N];
while (q < M && u == C[E[q][0]%N] && v == C[E[q][1]%N])
++q;
if (Q[u] && Q[v] && u != v) {
for (int i : rep(p, q)) {
int x = E[i][0], y = E[i][1];
if (H[x] == null)
H[x] = new ArrayList<>();
if (H[x].isEmpty())
H[x].add(p(x));
if (H[y] == null)
H[y] = new ArrayList<>();
if (H[y].isEmpty())
H[y].add(p(y));
H[x].add(y); H[y].add(x);
}
for (int i : rep(p, q)) {
int x = E[i][0];
if (F[x] == 0)
if (!dfs2(x, -1, -1)) {
--res;
break;
}
}
for (int i : rep(p, q)) {
int x = E[i][0], y = E[i][1];
H[x].clear(); H[y].clear();
F[x] = F[y] = F[p(x)] = F[p(y)] = 0;
}
}
p = q;
}
return res;
}
int N;
int [] C, D, F;
int [][] G;
List<Integer> [] H;
int p (int x) {
return x < N ? x + N : x - N;
}
boolean dfs1 (int s, int p, int v) {
int N = G.length, w = v < N ? v+N : v-N;
if (D[s] == v)
return true;
if (D[s] == w)
return false;
D[s] = v;
for (int j : G[s])
if (j != p && C[j] == C[s])
if (!dfs1(j, s, w))
return false;
return true;
}
boolean dfs2 (int s, int p, int v) {
if (F[s] == v)
return true;
if (F[s] == -v)
return false;
F[s] = v;
if (H[s] != null)
for (int j : H[s])
if (j != p)
if (!dfs2(j, s, -v))
return false;
return true;
}
private static final int CONTEST_TYPE = 1;
private static void init () {
}
private static final int INF = (int) 1e9 + 10;
private static int [] dec (int ... A) { for (int i = 0; i < A.length; ++i) --A[i]; return A; }
private static int [][] dec (int [] ... E) { return dec(E, INF); }
private static int [][] dec (int [][] E, int N) { for (int [] e : E) for (int i = 0; i < e.length && i < N; ++i) --e[i]; return E; }
private static int [][] dup (int [][] E) {
int [][] res = new int [2*E.length][];
for (int i = 0; i < E.length; ++i) {
res[2*i] = E[i].clone();
res[2*i+1] = E[i].clone();
res[2*i+1][0] = E[i][1]; res[2*i+1][1] = E[i][0];
}
return res;
}
private static int [][][] dwgraph (int N, int [][] E) {
int [] D = new int [N];
for (int [] e : E)
++D[e[0]];
int [][][] res = new int [2][N][];
for (int i = 0; i < 2; ++i)
for (int j = 0; j < N; ++j)
res[i][j] = new int [D[j]];
D = new int [N];
for (int [] e : E) {
int x = e[0], y = e[1], z = e.length > 2 ? e[2] : 1;
res[0][x][D[x]] = y;
res[1][x][D[x]] = z;
++D[x];
}
return res;
}
private static int [][] graph (int N, int [][] E) {
return wgraph(N, E)[0];
}
private static int [] rep (int N) { return rep(0, N); }
private static int [] rep (int S, int T) { if (S >= T) return new int [0]; int [] res = new int [T-S]; for (int i = S; i < T; ++i) res[i-S] = i; return res; }
private static int [][][] wgraph (int N, int [][] E) { return dwgraph(N, dup(E)); }
//////////////////////////////////////////////////////////////////////////////////// OFF
private static IOUtils.MyScanner sc = new IOUtils.MyScanner();
private static class IOUtils {
public static class MyScanner {
public String next () { newLine(); return line[index++]; }
public int nextInt () { return Integer.parseInt(next()); }
public String nextLine () { line = null; return readLine(); }
public String [] nextStrings () { return split(nextLine()); }
public int[] nextInts () { return nextStream().mapToInt(Integer::parseInt).toArray(); }
public int[][] nextInts (int N) { return IntStream.range(0, N).mapToObj(i -> nextInts()).toArray(int[][]::new); }
//////////////////////////////////////////////
private boolean eol () { return index == line.length; }
private String readLine () {
try {
return r.readLine();
} catch (Exception e) {
throw new Error (e);
}
}
private final java.io.BufferedReader r;
private MyScanner () { this(new java.io.BufferedReader(new java.io.InputStreamReader(System.in))); }
private MyScanner (java.io.BufferedReader r) {
try {
this.r = r;
while (!r.ready())
Thread.sleep(1);
start();
} catch (Exception e) {
throw new Error(e);
}
}
private String [] line;
private int index;
private void newLine () {
if (line == null || eol()) {
line = split(readLine());
index = 0;
}
}
private java.util.stream.Stream<String> nextStream () { return java.util.Arrays.stream(nextStrings()); }
private String [] split (String s) { return s.length() > 0 ? s.split(" ") : new String [0]; }
}
private static String build (Object o, Object ... A) { return buildDelim(" ", o, A); }
private static String buildDelim (String delim, Object o, Object ... A) {
StringBuilder b = new StringBuilder();
append(b, o, delim);
for (Object p : A)
append(b, p, delim);
return b.substring(min(b.length(), delim.length()));
}
//////////////////////////////////////////////////////////////////////////////////
private static java.text.DecimalFormat formatter = new java.text.DecimalFormat("#.#########");
private static void start () { if (t == 0) t = millis(); }
private static void append (java.util.function.Consumer<Object> f, java.util.function.Consumer<Object> g, final Object o) {
if (o.getClass().isArray()) {
int len = java.lang.reflect.Array.getLength(o);
for (int i = 0; i < len; ++i)
f.accept(java.lang.reflect.Array.get(o, i));
}
else if (o instanceof Iterable<?>)
((Iterable<?>)o).forEach(f::accept);
else
g.accept(o instanceof Double ? formatter.format(o) : o);
}
private static void append (final StringBuilder b, Object o, final String delim) {
append(x -> { append(b, x, delim); }, x -> b.append(delim).append(x), o);
}
private static java.io.PrintWriter pw = new java.io.PrintWriter(System.out);
private static void print (Object o, Object ... A) {
String res = build(o, A);
if (DEBUG == 2)
err(res, '(', time(), ')');
if (res.length() > 0)
pw.println(res);
if (DEBUG == 1) {
pw.flush();
System.out.flush();
}
}
private static void err (Object o, Object ... A) { System.err.println(build(o, A)); }
private static int DEBUG;
private static void exit () {
String end = "------------------" + System.lineSeparator() + time();
switch(DEBUG) {
case 1: print(end); break;
case 2: err(end); break;
}
IOUtils.pw.close();
System.out.flush();
System.exit(0);
}
private static long t;
private static long millis () { return System.currentTimeMillis(); }
private static String time () { return "Time: " + (millis() - t) / 1000.0; }
private static void run (int N) {
try { DEBUG = Integer.parseInt(System.getProperties().get("DEBUG").toString()); }
catch (Throwable t) {}
for (int n = 1; n <= N; ++n) {
Object res = new C().solve();
if (res != null) {
@SuppressWarnings("all")
Object o = CONTEST_TYPE == 0 ? "Case #" + n + ": " + build(res) : res;
print(o);
}
}
exit();
}
}
////////////////////////////////////////////////////////////////////////////////////
public static void main (String[] args) {
init();
@SuppressWarnings("all")
int N = CONTEST_TYPE == 1 ? 1 : sc.nextInt();
IOUtils.run(N);
}
}
| Java | ["6 8 3\n1 1 2 2 3 3\n1 3\n1 5\n1 6\n2 5\n2 6\n3 4\n3 5\n5 6", "4 3 3\n1 1 2 2\n1 2\n2 3\n3 4", "4 4 2\n1 1 1 2\n1 2\n2 3\n3 1\n1 4", "5 5 2\n1 2 1 2 1\n1 2\n2 3\n3 4\n4 5\n5 1"] | 3 seconds | ["2", "3", "0", "0"] | NoteThe acquaintances graph for the first example is shown in the picture below (next to each student there is their group number written).In that test we can select the following groups: Select the first and the second groups. For instance, one team can be formed from students $$$1$$$ and $$$4$$$, while other team can be formed from students $$$2$$$ and $$$3$$$. Select the second and the third group. For instance, one team can be formed $$$3$$$ and $$$6$$$, while other team can be formed from students $$$4$$$ and $$$5$$$. We can't select the first and the third group, because there is no way to form the teams for the game. In the second example, we can select any group pair. Please note, that even though the third group has no students, we still can select it (with some other group) for the game. | Java 11 | standard input | [
"data structures",
"dsu",
"dfs and similar",
"graphs"
] | b4332870aac6159d5aaa4ff21f8e9f7f | The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n \le 500\,000$$$; $$$0 \le m \le 500\,000$$$; $$$2 \le k \le 500\,000$$$)Β β the number of students, the number of pairs of acquaintances and the number of groups respectively. The second line contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ equals to the group number of the $$$i$$$-th student. Next $$$m$$$ lines follow. The $$$i$$$-th of them contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$), denoting that students $$$a_i$$$ and $$$b_i$$$ are acquaintances. It's guaranteed, that $$$a_i \neq b_i$$$, and that no (unordered) pair is mentioned more than once. | 2,500 | Print a single integerΒ β the number of ways to choose two different groups such that it's possible to select two teams to play the game. | standard output | |
PASSED | 306f3d569df8cccf19cafe016339da77 | train_003.jsonl | 1604228700 | The new academic year has started, and Berland's university has $$$n$$$ first-year students. They are divided into $$$k$$$ academic groups, however, some of the groups might be empty. Among the students, there are $$$m$$$ pairs of acquaintances, and each acquaintance pair might be both in a common group or be in two different groups.Alice is the curator of the first years, she wants to host an entertaining game to make everyone know each other. To do that, she will select two different academic groups and then divide the students of those groups into two teams. The game requires that there are no acquaintance pairs inside each of the teams.Alice wonders how many pairs of groups she can select, such that it'll be possible to play a game after that. All students of the two selected groups must take part in the game.Please note, that the teams Alice will form for the game don't need to coincide with groups the students learn in. Moreover, teams may have different sizes (or even be empty). | 512 megabytes | import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.DataInputStream;
import java.io.Flushable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.function.IntUnaryOperator;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
static class TaskAdapter implements Runnable {
@Override
public void run() {
long startTime = System.currentTimeMillis();
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastReader in = new FastReader(inputStream);
Output out = new Output(outputStream);
CTeamBuilding solver = new CTeamBuilding();
solver.solve(1, in, out);
out.close();
System.err.println(System.currentTimeMillis()-startTime+"ms");
}
}
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1<<28);
thread.start();
thread.join();
}
static class CTeamBuilding {
int n;
int m;
int k;
int cmax;
boolean bipartite;
int[] compd;
int[] arr;
int[] other;
int[] bcolor;
boolean[] tvalid;
ArrayList<Integer> cvisited;
ArrayList<Integer>[] graph;
public CTeamBuilding() {
}
public void comp(int u, int cur, int next) {
if(compd[u]!=-1) {
if(compd[u]!=cur) {
tvalid[arr[u]] = false;
}
return;
}
compd[u] = cur;
cmax = Math.max(cmax, cur);
for(int v: graph[u]) {
if(arr[u]==arr[v]) {
comp(v, next, cur);
}
}
}
public void dfs(int u, int cur, int next) {
if(bcolor[u]!=-1) {
if(bcolor[u]!=cur) {
bipartite = false;
}
return;
}
bcolor[u] = cur;
cvisited.add(u);
if(other[u]!=-1) {
dfs(other[u], next, cur);
}
for(int v: graph[u]) {
dfs(v, next, cur);
}
}
public void solve(int kase, InputReader in, Output pw) {
{
n = in.nextInt();
m = in.nextInt();
k = in.nextInt();
arr = in.nextInt(n, o -> o-1);
graph = in.nextUndirectedGraph(n, m);
}
{
compd = new int[n];
Arrays.fill(compd, -1);
tvalid = new boolean[k];
Arrays.fill(tvalid, true);
other = new int[n];
Arrays.fill(other, -1);
cmax = 0;
int curc = 0;
for(int i = 0; i<n; i++) {
if(compd[i]==-1) {
comp(i, curc, curc+1);
if(cmax>curc) {
other[curc] = curc+1;
other[curc+1] = curc;
}
curc = cmax+1;
}
}
}
HashMap<Pair<Integer, Integer>, ArrayList<Pair<Integer, Integer>>> edges = new HashMap<>(m*4);
{
for(int i = 0; i<n; i++) {
int iteam = arr[i];
if(tvalid[iteam]) {
for(int j: graph[i]) {
int jteam = arr[j];
if(tvalid[jteam]&&jteam>iteam) {
edges.computeIfAbsent(new Pair<>(iteam, jteam), o -> new ArrayList<>()).add(new Pair<>(compd[i], compd[j]));
}
}
}
}
}
long cnt = 0;
{
for(int i = 0; i<n; i++) {
graph[i].clear();
}
bcolor = new int[n];
Arrays.fill(bcolor, -1);
HashSet<Pair<Integer, Integer>> tvisited = new HashSet<>(m*2);
cvisited = new ArrayList<>(n);
for(var v: edges.entrySet()) {
ArrayList<Integer> curv = new ArrayList<>();
for(var i: v.getValue()) {
graph[i.a].add(i.b);
graph[i.b].add(i.a);
curv.add(i.a);
curv.add(i.b);
}
bipartite = true;
for(int i: curv) {
if(bcolor[i]==-1) {
dfs(i, 0, 1);
}
}
if(!bipartite) {
cnt++;
// Utilities.Debug.dbg(v.getKey());
}
for(int i: cvisited) {
graph[i].clear();
bcolor[i] = -1;
}
cvisited.clear();
}
}
{
long left = k;
for(int i = 0; i<k; i++) {
if(!tvalid[i]) {
left--;
}
}
// Utilities.Debug.dbg(left, cnt);
pw.println((left)*(left-1)/2-cnt);
}
}
}
static class FastReader implements InputReader {
final private int BUFFER_SIZE = 1<<16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer;
private int bytesRead;
public FastReader(InputStream is) {
din = new DataInputStream(is);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public int nextInt() {
int ret = 0;
byte c = skipToDigit();
boolean neg = (c=='-');
if(neg) {
c = read();
}
do {
ret = ret*10+c-'0';
} while((c = read())>='0'&&c<='9');
if(neg) {
return -ret;
}
return ret;
}
private boolean isDigit(byte b) {
return b>='0'&&b<='9';
}
private byte skipToDigit() {
byte ret;
while(!isDigit(ret = read())&&ret!='-') ;
return ret;
}
private void fillBuffer() {
try {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
}catch(IOException e) {
e.printStackTrace();
throw new InputMismatchException();
}
if(bytesRead==-1) {
buffer[0] = -1;
}
}
private byte read() {
if(bytesRead==-1) {
throw new InputMismatchException();
}else if(bufferPointer==bytesRead) {
fillBuffer();
}
return buffer[bufferPointer++];
}
}
static class Pair<T1, T2> implements Comparable<Pair<T1, T2>> {
public T1 a;
public T2 b;
public Pair(Pair<T1, T2> p) {
this(p.a, p.b);
}
public Pair(T1 a, T2 b) {
this.a = a;
this.b = b;
}
public String toString() {
return a+" "+b;
}
public int hashCode() {
return Objects.hash(a, b);
}
public boolean equals(Object o) {
if(o instanceof Pair) {
Pair p = (Pair) o;
return a.equals(p.a)&&b.equals(p.b);
}
return false;
}
public int compareTo(Pair<T1, T2> p) {
int cmp = ((Comparable<T1>) a).compareTo(p.a);
if(cmp==0) {
return ((Comparable<T2>) b).compareTo(p.b);
}
return cmp;
}
}
static interface InputReader {
int nextInt();
default int[] nextInt(int n, IntUnaryOperator operator) {
int[] ret = new int[n];
for(int i = 0; i<n; i++) {
ret[i] = operator.applyAsInt(nextInt());
}
return ret;
}
default ArrayList<Integer>[] nextUndirectedGraph(int n, int m) {
ArrayList<Integer>[] ret = new ArrayList[n];
for(int i = 0; i<n; i++) {
ret[i] = new ArrayList<>();
}
for(int i = 0; i<m; i++) {
int u = nextInt()-1, v = nextInt()-1;
ret[u].add(v);
ret[v].add(u);
}
return ret;
}
}
static class Utilities {
public static class Debug {
public static final boolean LOCAL = System.getProperty("ONLINE_JUDGE")==null;
private static <T> String ts(T t) {
if(t==null) {
return "null";
}
try {
return ts((Iterable) t);
}catch(ClassCastException e) {
if(t instanceof int[]) {
String s = Arrays.toString((int[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}else if(t instanceof long[]) {
String s = Arrays.toString((long[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}else if(t instanceof char[]) {
String s = Arrays.toString((char[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}else if(t instanceof double[]) {
String s = Arrays.toString((double[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}else if(t instanceof boolean[]) {
String s = Arrays.toString((boolean[]) t);
return "{"+s.substring(1, s.length()-1)+"}";
}
try {
return ts((Object[]) t);
}catch(ClassCastException e1) {
return t.toString();
}
}
}
private static <T> String ts(T[] arr) {
StringBuilder ret = new StringBuilder();
ret.append("{");
boolean first = true;
for(T t: arr) {
if(!first) {
ret.append(", ");
}
first = false;
ret.append(ts(t));
}
ret.append("}");
return ret.toString();
}
private static <T> String ts(Iterable<T> iter) {
StringBuilder ret = new StringBuilder();
ret.append("{");
boolean first = true;
for(T t: iter) {
if(!first) {
ret.append(", ");
}
first = false;
ret.append(ts(t));
}
ret.append("}");
return ret.toString();
}
public static void dbg(Object... o) {
if(LOCAL) {
System.err.print("Line #"+Thread.currentThread().getStackTrace()[2].getLineNumber()+": [");
for(int i = 0; i<o.length; i++) {
if(i!=0) {
System.err.print(", ");
}
System.err.print(ts(o[i]));
}
System.err.println("]");
}
}
}
}
static class Output implements Closeable, Flushable {
public StringBuilder sb;
public OutputStream os;
public int BUFFER_SIZE;
public String lineSeparator;
public Output(OutputStream os) {
this(os, 1<<16);
}
public Output(OutputStream os, int bs) {
BUFFER_SIZE = bs;
sb = new StringBuilder(BUFFER_SIZE);
this.os = new BufferedOutputStream(os, 1<<17);
lineSeparator = System.lineSeparator();
}
public void println(long l) {
println(String.valueOf(l));
}
public void println(String s) {
sb.append(s);
println();
}
public void println() {
sb.append(lineSeparator);
}
private void flushToBuffer() {
try {
os.write(sb.toString().getBytes());
}catch(IOException e) {
e.printStackTrace();
}
sb = new StringBuilder(BUFFER_SIZE);
}
public void flush() {
try {
flushToBuffer();
os.flush();
}catch(IOException e) {
e.printStackTrace();
}
}
public void close() {
flush();
try {
os.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
}
| Java | ["6 8 3\n1 1 2 2 3 3\n1 3\n1 5\n1 6\n2 5\n2 6\n3 4\n3 5\n5 6", "4 3 3\n1 1 2 2\n1 2\n2 3\n3 4", "4 4 2\n1 1 1 2\n1 2\n2 3\n3 1\n1 4", "5 5 2\n1 2 1 2 1\n1 2\n2 3\n3 4\n4 5\n5 1"] | 3 seconds | ["2", "3", "0", "0"] | NoteThe acquaintances graph for the first example is shown in the picture below (next to each student there is their group number written).In that test we can select the following groups: Select the first and the second groups. For instance, one team can be formed from students $$$1$$$ and $$$4$$$, while other team can be formed from students $$$2$$$ and $$$3$$$. Select the second and the third group. For instance, one team can be formed $$$3$$$ and $$$6$$$, while other team can be formed from students $$$4$$$ and $$$5$$$. We can't select the first and the third group, because there is no way to form the teams for the game. In the second example, we can select any group pair. Please note, that even though the third group has no students, we still can select it (with some other group) for the game. | Java 11 | standard input | [
"data structures",
"dsu",
"dfs and similar",
"graphs"
] | b4332870aac6159d5aaa4ff21f8e9f7f | The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n \le 500\,000$$$; $$$0 \le m \le 500\,000$$$; $$$2 \le k \le 500\,000$$$)Β β the number of students, the number of pairs of acquaintances and the number of groups respectively. The second line contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ equals to the group number of the $$$i$$$-th student. Next $$$m$$$ lines follow. The $$$i$$$-th of them contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$), denoting that students $$$a_i$$$ and $$$b_i$$$ are acquaintances. It's guaranteed, that $$$a_i \neq b_i$$$, and that no (unordered) pair is mentioned more than once. | 2,500 | Print a single integerΒ β the number of ways to choose two different groups such that it's possible to select two teams to play the game. | standard output | |
PASSED | 52e6fdc9da47fa8598e021fc014bd503 | train_003.jsonl | 1604228700 | The new academic year has started, and Berland's university has $$$n$$$ first-year students. They are divided into $$$k$$$ academic groups, however, some of the groups might be empty. Among the students, there are $$$m$$$ pairs of acquaintances, and each acquaintance pair might be both in a common group or be in two different groups.Alice is the curator of the first years, she wants to host an entertaining game to make everyone know each other. To do that, she will select two different academic groups and then divide the students of those groups into two teams. The game requires that there are no acquaintance pairs inside each of the teams.Alice wonders how many pairs of groups she can select, such that it'll be possible to play a game after that. All students of the two selected groups must take part in the game.Please note, that the teams Alice will form for the game don't need to coincide with groups the students learn in. Moreover, teams may have different sizes (or even be empty). | 512 megabytes | //package round680;
import java.io.*;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Queue;
public class C {
InputStream is;
FastWriter out;
String INPUT = "";
void solve()
{
int n = ni(), m = ni(), K = ni();
int[] c = na(n);
int[][] es = new int[m][];
for(int i = 0;i < m;i++){
es[i] = new int[]{ni()-1, ni()-1, -1, -1};
es[i][2] = Math.min(c[es[i][0]], c[es[i][1]])-1;
es[i][3] = Math.max(c[es[i][0]], c[es[i][1]])-1;
if(es[i][2] == es[i][3]){
es[i][3] = -1;
}
}
Arrays.sort(es, (x, y) -> {
if (x[2] != y[2]) return x[2] - y[2];
return x[3] - y[3];
});
RestorableDisjointSet2 rds = new RestorableDisjointSet2(2*n, 2*m);
boolean[] ngs = new boolean[K];
long nng = 0;
for(int i = 0;i < m;) {
int j = i;
while (j < m && es[i][2] == es[j][2] && es[i][3] == es[j][3]) j++;
if(es[i][3] == -1){
boolean ng = false;
int h = rds.hp;
for (int k = i; k < j; k++) {
rds.union(es[k][0], es[k][1] + n);
rds.union(es[k][0] + n, es[k][1]);
ng |= rds.equiv(es[k][0], es[k][0] + n);
}
ngs[es[i][2]] = ng;
if(ng)nng++;
rds.revert(h);
}
i = j;
}
long ans = (long)(K-nng)*(K-nng-1)/2;
for(int i = 0;i < m;) {
int j = i;
while (j < m && es[i][2] == es[j][2] && es[i][3] == es[j][3]) j++;
if(es[i][3] == -1){
for (int k = i; k < j; k++) {
rds.union(es[k][0], es[k][1] + n);
rds.union(es[k][0] + n, es[k][1]);
}
}
i = j;
}
for(int i = 0;i < m;){
int j = i;
while(j < m && es[i][2] == es[j][2] && es[i][3] == es[j][3])j++;
if(es[i][3] != -1) {
boolean ng = ngs[es[i][2]] | ngs[es[i][3]];
if(!ng) {
int h = rds.hp;
for (int k = i; k < j; k++) {
rds.union(es[k][0], es[k][1] + n);
rds.union(es[k][0] + n, es[k][1]);
ng |= rds.equiv(es[k][0], es[k][0] + n);
}
if (ng) {
ans--;
}
rds.revert(h);
}
}
i = j;
}
out.println(ans);
}
public static class RestorableDisjointSet2 {
public int[] upper; // minus:num_element(root) plus:root(normal)
private int[] targets;
private int[] histupper;
public int hp = 0;
public RestorableDisjointSet2(int n, int m)
{
upper = new int[n];
Arrays.fill(upper, -1);
targets = new int[2*m];
histupper = new int[2*m];
//
// w = new int[n];
}
public RestorableDisjointSet2(RestorableDisjointSet2 ds)
{
this.upper = Arrays.copyOf(ds.upper, ds.upper.length);
this.histupper = Arrays.copyOf(ds.histupper, ds.histupper.length);
//
this.hp = ds.hp;
}
public int root(int x)
{
return upper[x] < 0 ? x : root(upper[x]);
}
public boolean equiv(int x, int y)
{
return root(x) == root(y);
}
public boolean union(int x, int y)
{
x = root(x);
y = root(y);
if(x != y) {
if(upper[y] < upper[x]) {
int d = x; x = y; y = d;
}
// w[x] += w[y];
record(x); record(y);
upper[x] += upper[y];
//
upper[y] = x;
}
return x == y;
}
public int time() { return hp; }
private void record(int x)
{
targets[hp] = x;
histupper[hp] = upper[x];
//
hp++;
}
public void revert(int to)
{
while(hp > to){
upper[targets[hp-1]] = histupper[hp-1];
//
hp--;
}
}
public int count()
{
int ct = 0;
for(int u : upper){
if(u < 0)ct++;
}
return ct;
}
public int[][] makeUp()
{
int n = upper.length;
int[][] ret = new int[n][];
int[] rp = new int[n];
for(int i = 0;i < n;i++){
if(upper[i] < 0)ret[i] = new int[-upper[i]];
}
for(int i = 0;i < n;i++){
int r = root(i);
ret[r][rp[r]++] = i;
}
return ret;
}
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new FastWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new C().run(); }
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private long[] nal(int n)
{
long[] a = new long[n];
for(int i = 0;i < n;i++)a[i] = nl();
return a;
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[][] nmi(int n, int m) {
int[][] map = new int[n][];
for(int i = 0;i < n;i++)map[i] = na(m);
return map;
}
private int ni() { return (int)nl(); }
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
public static class FastWriter
{
private static final int BUF_SIZE = 1<<13;
private final byte[] buf = new byte[BUF_SIZE];
private final OutputStream out;
private int ptr = 0;
private FastWriter(){out = null;}
public FastWriter(OutputStream os)
{
this.out = os;
}
public FastWriter(String path)
{
try {
this.out = new FileOutputStream(path);
} catch (FileNotFoundException e) {
throw new RuntimeException("FastWriter");
}
}
public FastWriter write(byte b)
{
buf[ptr++] = b;
if(ptr == BUF_SIZE)innerflush();
return this;
}
public FastWriter write(char c)
{
return write((byte)c);
}
public FastWriter write(char[] s)
{
for(char c : s){
buf[ptr++] = (byte)c;
if(ptr == BUF_SIZE)innerflush();
}
return this;
}
public FastWriter write(String s)
{
s.chars().forEach(c -> {
buf[ptr++] = (byte)c;
if(ptr == BUF_SIZE)innerflush();
});
return this;
}
private static int countDigits(int l) {
if (l >= 1000000000) return 10;
if (l >= 100000000) return 9;
if (l >= 10000000) return 8;
if (l >= 1000000) return 7;
if (l >= 100000) return 6;
if (l >= 10000) return 5;
if (l >= 1000) return 4;
if (l >= 100) return 3;
if (l >= 10) return 2;
return 1;
}
public FastWriter write(int x)
{
if(x == Integer.MIN_VALUE){
return write((long)x);
}
if(ptr + 12 >= BUF_SIZE)innerflush();
if(x < 0){
write((byte)'-');
x = -x;
}
int d = countDigits(x);
for(int i = ptr + d - 1;i >= ptr;i--){
buf[i] = (byte)('0'+x%10);
x /= 10;
}
ptr += d;
return this;
}
private static int countDigits(long l) {
if (l >= 1000000000000000000L) return 19;
if (l >= 100000000000000000L) return 18;
if (l >= 10000000000000000L) return 17;
if (l >= 1000000000000000L) return 16;
if (l >= 100000000000000L) return 15;
if (l >= 10000000000000L) return 14;
if (l >= 1000000000000L) return 13;
if (l >= 100000000000L) return 12;
if (l >= 10000000000L) return 11;
if (l >= 1000000000L) return 10;
if (l >= 100000000L) return 9;
if (l >= 10000000L) return 8;
if (l >= 1000000L) return 7;
if (l >= 100000L) return 6;
if (l >= 10000L) return 5;
if (l >= 1000L) return 4;
if (l >= 100L) return 3;
if (l >= 10L) return 2;
return 1;
}
public FastWriter write(long x)
{
if(x == Long.MIN_VALUE){
return write("" + x);
}
if(ptr + 21 >= BUF_SIZE)innerflush();
if(x < 0){
write((byte)'-');
x = -x;
}
int d = countDigits(x);
for(int i = ptr + d - 1;i >= ptr;i--){
buf[i] = (byte)('0'+x%10);
x /= 10;
}
ptr += d;
return this;
}
public FastWriter write(double x, int precision)
{
if(x < 0){
write('-');
x = -x;
}
x += Math.pow(10, -precision)/2;
// if(x < 0){ x = 0; }
write((long)x).write(".");
x -= (long)x;
for(int i = 0;i < precision;i++){
x *= 10;
write((char)('0'+(int)x));
x -= (int)x;
}
return this;
}
public FastWriter writeln(char c){
return write(c).writeln();
}
public FastWriter writeln(int x){
return write(x).writeln();
}
public FastWriter writeln(long x){
return write(x).writeln();
}
public FastWriter writeln(double x, int precision){
return write(x, precision).writeln();
}
public FastWriter write(int... xs)
{
boolean first = true;
for(int x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter write(long... xs)
{
boolean first = true;
for(long x : xs) {
if (!first) write(' ');
first = false;
write(x);
}
return this;
}
public FastWriter writeln()
{
return write((byte)'\n');
}
public FastWriter writeln(int... xs)
{
return write(xs).writeln();
}
public FastWriter writeln(long... xs)
{
return write(xs).writeln();
}
public FastWriter writeln(char[] line)
{
return write(line).writeln();
}
public FastWriter writeln(char[]... map)
{
for(char[] line : map)write(line).writeln();
return this;
}
public FastWriter writeln(String s)
{
return write(s).writeln();
}
private void innerflush()
{
try {
out.write(buf, 0, ptr);
ptr = 0;
} catch (IOException e) {
throw new RuntimeException("innerflush");
}
}
public void flush()
{
innerflush();
try {
out.flush();
} catch (IOException e) {
throw new RuntimeException("flush");
}
}
public FastWriter print(byte b) { return write(b); }
public FastWriter print(char c) { return write(c); }
public FastWriter print(char[] s) { return write(s); }
public FastWriter print(String s) { return write(s); }
public FastWriter print(int x) { return write(x); }
public FastWriter print(long x) { return write(x); }
public FastWriter print(double x, int precision) { return write(x, precision); }
public FastWriter println(char c){ return writeln(c); }
public FastWriter println(int x){ return writeln(x); }
public FastWriter println(long x){ return writeln(x); }
public FastWriter println(double x, int precision){ return writeln(x, precision); }
public FastWriter print(int... xs) { return write(xs); }
public FastWriter print(long... xs) { return write(xs); }
public FastWriter println(int... xs) { return writeln(xs); }
public FastWriter println(long... xs) { return writeln(xs); }
public FastWriter println(char[] line) { return writeln(line); }
public FastWriter println(char[]... map) { return writeln(map); }
public FastWriter println(String s) { return writeln(s); }
public FastWriter println() { return writeln(); }
}
public void trnz(int... o)
{
for(int i = 0;i < o.length;i++)if(o[i] != 0)System.out.print(i+":"+o[i]+" ");
System.out.println();
}
// print ids which are 1
public void trt(long... o)
{
Queue<Integer> stands = new ArrayDeque<>();
for(int i = 0;i < o.length;i++){
for(long x = o[i];x != 0;x &= x-1)stands.add(i<<6|Long.numberOfTrailingZeros(x));
}
System.out.println(stands);
}
public void tf(boolean... r)
{
for(boolean x : r)System.out.print(x?'#':'.');
System.out.println();
}
public void tf(boolean[]... b)
{
for(boolean[] r : b) {
for(boolean x : r)System.out.print(x?'#':'.');
System.out.println();
}
System.out.println();
}
public void tf(long[]... b)
{
if(INPUT.length() != 0) {
for (long[] r : b) {
for (long x : r) {
for (int i = 0; i < 64; i++) {
System.out.print(x << ~i < 0 ? '#' : '.');
}
}
System.out.println();
}
System.out.println();
}
}
public void tf(long... b)
{
if(INPUT.length() != 0) {
for (long x : b) {
for (int i = 0; i < 64; i++) {
System.out.print(x << ~i < 0 ? '#' : '.');
}
}
System.out.println();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
| Java | ["6 8 3\n1 1 2 2 3 3\n1 3\n1 5\n1 6\n2 5\n2 6\n3 4\n3 5\n5 6", "4 3 3\n1 1 2 2\n1 2\n2 3\n3 4", "4 4 2\n1 1 1 2\n1 2\n2 3\n3 1\n1 4", "5 5 2\n1 2 1 2 1\n1 2\n2 3\n3 4\n4 5\n5 1"] | 3 seconds | ["2", "3", "0", "0"] | NoteThe acquaintances graph for the first example is shown in the picture below (next to each student there is their group number written).In that test we can select the following groups: Select the first and the second groups. For instance, one team can be formed from students $$$1$$$ and $$$4$$$, while other team can be formed from students $$$2$$$ and $$$3$$$. Select the second and the third group. For instance, one team can be formed $$$3$$$ and $$$6$$$, while other team can be formed from students $$$4$$$ and $$$5$$$. We can't select the first and the third group, because there is no way to form the teams for the game. In the second example, we can select any group pair. Please note, that even though the third group has no students, we still can select it (with some other group) for the game. | Java 11 | standard input | [
"data structures",
"dsu",
"dfs and similar",
"graphs"
] | b4332870aac6159d5aaa4ff21f8e9f7f | The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n \le 500\,000$$$; $$$0 \le m \le 500\,000$$$; $$$2 \le k \le 500\,000$$$)Β β the number of students, the number of pairs of acquaintances and the number of groups respectively. The second line contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ equals to the group number of the $$$i$$$-th student. Next $$$m$$$ lines follow. The $$$i$$$-th of them contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$), denoting that students $$$a_i$$$ and $$$b_i$$$ are acquaintances. It's guaranteed, that $$$a_i \neq b_i$$$, and that no (unordered) pair is mentioned more than once. | 2,500 | Print a single integerΒ β the number of ways to choose two different groups such that it's possible to select two teams to play the game. | standard output | |
PASSED | 6c63cd5c5a8a7e398d95786cd529f2bb | train_003.jsonl | 1604228700 | The new academic year has started, and Berland's university has $$$n$$$ first-year students. They are divided into $$$k$$$ academic groups, however, some of the groups might be empty. Among the students, there are $$$m$$$ pairs of acquaintances, and each acquaintance pair might be both in a common group or be in two different groups.Alice is the curator of the first years, she wants to host an entertaining game to make everyone know each other. To do that, she will select two different academic groups and then divide the students of those groups into two teams. The game requires that there are no acquaintance pairs inside each of the teams.Alice wonders how many pairs of groups she can select, such that it'll be possible to play a game after that. All students of the two selected groups must take part in the game.Please note, that the teams Alice will form for the game don't need to coincide with groups the students learn in. Moreover, teams may have different sizes (or even be empty). | 512 megabytes | import java.io.*;
import java.util.*;
public class A {
public static void main (String[] args) { new A(); }
ArrayDeque<Edge>[] cAdj;
int[] dfsDepth, dfsTime;
int curTime;
public A() {
FastScanner fs = new FastScanner();
PrintWriter out = new PrintWriter(System.out);
System.err.println("");
int n = fs.nextInt();
int m = fs.nextInt();
int k = fs.nextInt();
long totalBadPairs = 0;
IntList[] comps = new IntList[k];
for(int i = 0; i < k; i++) {
comps[i] = new IntList();
}
int[] id = fs.nextIntArray(n);
for(int i = 0; i < n; i++) {
id[i]--;
comps[id[i]].add(i);
}
IntList[] adj = new IntList[n];
for(int i = 0; i < n; i++) {
adj[i] = new IntList();
}
Edge[] edges = new Edge[m];
HashMap<Long, IntList> candGroups = new HashMap<>();
for(int i = 0; i < m; i++) {
int u = fs.nextInt()-1;
int v = fs.nextInt()-1;
int g1 = id[u];
int g2 = id[v];
edges[i] = new Edge(u, v, g1, g2);
if(g1 == g2) {
adj[u].add(v);
adj[v].add(u);
}
else {
long msk = getMask(g1, g2);
if(!candGroups.containsKey(msk)) {
candGroups.put(msk, new IntList());
}
candGroups.get(msk).add(i);
}
}
boolean[] invalidGroups = new boolean[k];
int[] color = new int[n];
Arrays.fill(color, -1);
int[] parent = new int[n];
cAdj = new ArrayDeque[n];
for(int i = 0; i < n; i++) cAdj[i] = new ArrayDeque<>();
ArrayDeque<Integer> dq = new ArrayDeque<>();
int edgeIdx = 0;
int[] order = new int[n];
for(int i = 0; i < k; i++) {
boolean bad = false;
for(int ii = 0; ii < comps[i].size(); ii++) {
int x = comps[i].get(ii);
if(color[x] != -1) continue;
int ptr = 0;
color[x] = 0;
dq.add(x);
while(!dq.isEmpty()) {
int u = dq.pollFirst();
order[ptr++] = u;
parent[u] = x;
for(int vv = 0; vv < adj[u].size(); vv++) {
int v = adj[u].get(vv);
if(color[v] == -1) {
color[v] = color[u] ^ 1;
dq.add(v);
}
else {
if(color[v] == color[u]) {
bad = true;
}
}
}
}
int fi = -1;
for(int j = 0; j < ptr; j++) {
if(color[order[j]] != color[x]) {
fi = order[j];
break;
}
}
for(int j = 0; j < ptr; j++) {
int who = order[j];
if(color[who] == 1) {
parent[who] = fi;
}
}
if(fi != -1) {
cAdj[x].add(new Edge(x, fi, edgeIdx, -1));
cAdj[fi].add(new Edge(fi, x, edgeIdx, -1));
edgeIdx++;
}
}
invalidGroups[i] = bad;
}
dfsDepth = new int[n];
dfsTime = new int[n];
curTime = 0;
Arrays.fill(dfsDepth, -1);
int AND = (1 << 20) - 1;
for(Map.Entry<Long, IntList> mp : candGroups.entrySet()) {
curTime++;
long msk = mp.getKey();
int g1 = (int)(msk & AND);
int g2 = (int)(msk >> 20);
if(invalidGroups[g1] || invalidGroups[g2]) continue;
boolean bad = false;
IntList list = mp.getValue();
for(int ee = 0; ee < list.size(); ee++) {
int eIdx = list.get(ee);
Edge e = edges[eIdx];
int pu = parent[e.u], pv = parent[e.v];
cAdj[pu].add(new Edge(pu, pv, edgeIdx, -1));
cAdj[pv].add(new Edge(pv, pu, edgeIdx, -1));
edgeIdx++;
}
for(int ee = 0; ee < list.size(); ee++) {
int eIdx = list.get(ee);
Edge e = edges[eIdx];
int pu = parent[e.u];
if(dfsTime[pu] != curTime) {
dfsDepth[pu] = 0;
dfsTime[pu] = curTime;
oddCycle = false;
dfs(pu, -1);
if(oddCycle) {
bad = true;
break;
}
}
}
for(int ee = 0; ee < list.size(); ee++) {
int eIdx = list.get(ee);
Edge e = edges[eIdx];
int pu = parent[e.u], pv = parent[e.v];
cAdj[pu].pollLast();
cAdj[pv].pollLast();
}
if(bad) {
totalBadPairs++;
}
}
long amt = 0;
for(boolean b : invalidGroups) if(!b) amt++;
long total = amt * (amt - 1) / 2;
total -= totalBadPairs;
out.println(total);
out.close();
}
boolean oddCycle;
void dfs(int u, int parEdge) {
for(Edge e : cAdj[u]) {
int v = e.v;
if(e.g1 == parEdge) continue;
if(dfsTime[v] == curTime) {
if(dfsDepth[v] == dfsDepth[u]) {
oddCycle = true;
}
}
else {
dfsTime[v] = curTime;
dfsDepth[v] = dfsDepth[u] ^ 1;
dfs(v, e.g1);
}
}
}
long getMask(int u, int v) {
int mn = Math.min(u, v);
int mx = Math.max(u, v);
long res = mn;
res |= (long)mx << 20;
return res;
}
class Edge {
int u, v, g1, g2;
Edge(int a, int b, int gg, int vv) {
u = a;
v = b;
g1 = gg;
g2 = vv;
}
public String toString() {
return String.format("(%d -> %d) %d", u, v, g1);
}
}
static class IntList {
static int[] EMPTY = {};
int n = 0, a[] = EMPTY;
void add(int v) {
if (n >= a.length)
a = Arrays.copyOf(a, (n << 2) + 8);
a[n++] = v;
}
int get(int idx) { return a[idx]; }
int size() { return n; }
}
class FastScanner {
public int BS = 1<<16;
public char NC = (char)0;
byte[] buf = new byte[BS];
int bId = 0, size = 0;
char c = NC;
double num = 1;
BufferedInputStream in;
public FastScanner() {
in = new BufferedInputStream(System.in, BS);
}
public FastScanner(String s) {
try {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
catch (Exception e) {
in = new BufferedInputStream(System.in, BS);
}
}
public char nextChar(){
while(bId==size) {
try {
size = in.read(buf);
}catch(Exception e) {
return NC;
}
if(size==-1)return NC;
bId=0;
}
return (char)buf[bId++];
}
public int nextInt() {
return (int)nextLong();
}
public long nextLong() {
num=1;
boolean neg = false;
if(c==NC)c=nextChar();
for(;(c<'0' || c>'9'); c = nextChar()) {
if(c=='-')neg=true;
}
long res = 0;
for(; c>='0' && c <='9'; c=nextChar()) {
res = (res<<3)+(res<<1)+c-'0';
num*=10;
}
return neg?-res:res;
}
public double nextDouble() {
double cur = nextLong();
return c!='.' ? cur:cur+nextLong()/num;
}
public String next() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c>32) {
res.append(c);
c=nextChar();
}
return res.toString();
}
public String nextLine() {
StringBuilder res = new StringBuilder();
while(c<=32)c=nextChar();
while(c!='\n') {
res.append(c);
c=nextChar();
}
return res.toString();
}
public boolean hasNext() {
if(c>32)return true;
while(true) {
c=nextChar();
if(c==NC)return false;
else if(c>32)return true;
}
}
public int[] nextIntArray(int n) {
int[] res = new int[n];
for(int i = 0; i < n; i++) res[i] = nextInt();
return res;
}
}
} | Java | ["6 8 3\n1 1 2 2 3 3\n1 3\n1 5\n1 6\n2 5\n2 6\n3 4\n3 5\n5 6", "4 3 3\n1 1 2 2\n1 2\n2 3\n3 4", "4 4 2\n1 1 1 2\n1 2\n2 3\n3 1\n1 4", "5 5 2\n1 2 1 2 1\n1 2\n2 3\n3 4\n4 5\n5 1"] | 3 seconds | ["2", "3", "0", "0"] | NoteThe acquaintances graph for the first example is shown in the picture below (next to each student there is their group number written).In that test we can select the following groups: Select the first and the second groups. For instance, one team can be formed from students $$$1$$$ and $$$4$$$, while other team can be formed from students $$$2$$$ and $$$3$$$. Select the second and the third group. For instance, one team can be formed $$$3$$$ and $$$6$$$, while other team can be formed from students $$$4$$$ and $$$5$$$. We can't select the first and the third group, because there is no way to form the teams for the game. In the second example, we can select any group pair. Please note, that even though the third group has no students, we still can select it (with some other group) for the game. | Java 11 | standard input | [
"data structures",
"dsu",
"dfs and similar",
"graphs"
] | b4332870aac6159d5aaa4ff21f8e9f7f | The first line contains three integers $$$n$$$, $$$m$$$ and $$$k$$$ ($$$1 \le n \le 500\,000$$$; $$$0 \le m \le 500\,000$$$; $$$2 \le k \le 500\,000$$$)Β β the number of students, the number of pairs of acquaintances and the number of groups respectively. The second line contains $$$n$$$ integers $$$c_1, c_2, \dots, c_n$$$ ($$$1 \le c_i \le k$$$), where $$$c_i$$$ equals to the group number of the $$$i$$$-th student. Next $$$m$$$ lines follow. The $$$i$$$-th of them contains two integers $$$a_i$$$ and $$$b_i$$$ ($$$1 \le a_i, b_i \le n$$$), denoting that students $$$a_i$$$ and $$$b_i$$$ are acquaintances. It's guaranteed, that $$$a_i \neq b_i$$$, and that no (unordered) pair is mentioned more than once. | 2,500 | Print a single integerΒ β the number of ways to choose two different groups such that it's possible to select two teams to play the game. | standard output | |
PASSED | 3fca7a15d3f5b5dc6b5eda22feb4a613 | train_003.jsonl | 1269100800 | Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor Β«TextpadΒ» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck! | 64 megabytes | import java.io.*;
import java.util.*;
public class cf5B
{
public static void main (String[] args) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader (System.in));
ArrayList<String> lst = new ArrayList<String>();
String line;
int longest = 0;
int whitespace = 0;
int leftSpace, rightSpace;
boolean swtch = false;
while(br.ready())
{
line = br.readLine();
lst.add(line);
if(line.length() > longest)
longest = line.length();
}
for(int i = 0; i< longest + 2; i++)
{
System.out.print("*");
}
System.out.println();
for(int i = 0; i< lst.size(); i++)
{
whitespace = longest - lst.get(i).length();
rightSpace = leftSpace = whitespace/2;
if(whitespace % 2 != 0)
{
if(!swtch)
rightSpace += 1;
else
leftSpace += 1;
swtch = !swtch;
}
System.out.print("*");
System.out.print(addSpaces(leftSpace));
System.out.print(lst.get(i));
System.out.print(addSpaces(rightSpace));
System.out.println("*");
}
for(int i = 0; i< longest + 2; i++)
{
System.out.print("*");
}
System.out.println();
}
private static String addSpaces(int numSpaces)
{
char[] arr = new char[numSpaces];
Arrays.fill(arr, ' ');
return new String(arr);
}
} | Java | ["This is\n\nCodeforces\nBeta\nRound\n5", "welcome to the\nCodeforces\nBeta\nRound 5\n\nand\ngood luck"] | 1 second | ["************\n* This is *\n* *\n*Codeforces*\n* Beta *\n* Round *\n* 5 *\n************", "****************\n*welcome to the*\n* Codeforces *\n* Beta *\n* Round 5 *\n* *\n* and *\n* good luck *\n****************"] | null | Java 7 | standard input | [
"implementation",
"strings"
] | a017393743ae70a4d8a9d9dc40410653 | The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000. | 1,200 | Format the given text, aligning it center. Frame the whole text with characters Β«*Β» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better. | standard output | |
PASSED | 0785fe973bc3dfad391835da562b6077 | train_003.jsonl | 1269100800 | Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor Β«TextpadΒ» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck! | 64 megabytes | import java.util.LinkedList;
import java.util.Scanner;
/**
* Created by peter.bykov on 13.05.2014.
*/
public class Archive5B {
private static boolean left = false;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
// Scanner s = null;
// try {
// s = new Scanner(new File("C:\\tmp\\codeforces\\5B\\test1.txt"));
// } catch (FileNotFoundException e) {
// e.printStackTrace();
// }
LinkedList<String> text = new LinkedList<String>();
int maxLength = 0;
while (s.hasNextLine()) {
String line = s.nextLine();
if(line.length() > maxLength) {
maxLength = line.length();
}
text.add(line);
}
System.out.println(getInputString(maxLength, null, true));
for (int i = 0; i < text.size(); i++) {
System.out.println(getInputString(maxLength, text.get(i), false));
}
System.out.println(getInputString(maxLength, null, true));
}
private static StringBuffer getInputString(int stringLength, String text, boolean isFrame) {
StringBuffer str = new StringBuffer();
if(text == null) {
if(isFrame) {
for (int i = 0; i < stringLength + 2; i++) {
str.append("*");
}
return str;
} else {
str.append("*");
for (int i = 0; i < stringLength; i++) {
str.append(" ");;
}
str.append("*");
return str;
}
} else {
str.append("*");
int spaceLeft = stringLength - text.length();
if(spaceLeft%2 != 0) {
for (int s = 0; s < spaceLeft/2 + (left?1:0); s++) {
str.append(" ");;
}
str.append(text);;
for (int s = 0; s < spaceLeft/2 + (!left?1:0); s++) {
str.append(" ");;
}
left = !left;
} else {
for (int s = 0; s < spaceLeft/2; s++) {
str.append(" ");;
}
str.append(text);;
for (int s = 0; s < spaceLeft/2; s++) {
str.append(" ");;
}
}
str.append("*");
}
return str;
}
}
| Java | ["This is\n\nCodeforces\nBeta\nRound\n5", "welcome to the\nCodeforces\nBeta\nRound 5\n\nand\ngood luck"] | 1 second | ["************\n* This is *\n* *\n*Codeforces*\n* Beta *\n* Round *\n* 5 *\n************", "****************\n*welcome to the*\n* Codeforces *\n* Beta *\n* Round 5 *\n* *\n* and *\n* good luck *\n****************"] | null | Java 7 | standard input | [
"implementation",
"strings"
] | a017393743ae70a4d8a9d9dc40410653 | The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000. | 1,200 | Format the given text, aligning it center. Frame the whole text with characters Β«*Β» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better. | standard output | |
PASSED | 3ca566c8f76b10470a9b7100c4b99141 | train_003.jsonl | 1269100800 | Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor Β«TextpadΒ» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck! | 64 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
ArrayList<String> al = new ArrayList<String>();
int maxLength = Integer.MIN_VALUE;
while(input.hasNextLine()){
String str = input.nextLine();
maxLength = Math.max(maxLength, str.length());
al.add(str);
//str = input.nextLine();
}
System.out.print("*");
for(int i = 0; i < maxLength;i++)
System.out.print("*");
System.out.println("*");
boolean west = true;
for(String i : al){
System.out.print("*");
int e = maxLength - i.length();
int m = e/2;
int left = m, right = m;
if(e % 2 != 0){
if(west) right += 1;
else left += 1;
west = !west;
}
System.out.print(p(' ',left));
System.out.print(i);
System.out.print(p(' ',right));
System.out.println('*');
}
System.out.print("*");
for(int i = 0; i < maxLength;i++)
System.out.print("*");
System.out.println("*");
}
private static String p(char c, int n) {
char[] a = new char[n];
Arrays.fill(a, c);
return new String(a);
}
} | Java | ["This is\n\nCodeforces\nBeta\nRound\n5", "welcome to the\nCodeforces\nBeta\nRound 5\n\nand\ngood luck"] | 1 second | ["************\n* This is *\n* *\n*Codeforces*\n* Beta *\n* Round *\n* 5 *\n************", "****************\n*welcome to the*\n* Codeforces *\n* Beta *\n* Round 5 *\n* *\n* and *\n* good luck *\n****************"] | null | Java 7 | standard input | [
"implementation",
"strings"
] | a017393743ae70a4d8a9d9dc40410653 | The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000. | 1,200 | Format the given text, aligning it center. Frame the whole text with characters Β«*Β» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better. | standard output | |
PASSED | b5085096b9874216915e0ff90411498f | train_003.jsonl | 1269100800 | Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor Β«TextpadΒ» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck! | 64 megabytes | import java.util.*;
public class B5 {
public static void main(String[] args){
Scanner br = new Scanner(System.in);
int maxLen = 0;
ArrayList<String> ss = new ArrayList<String>();
while(br.hasNextLine()){
String line = br.nextLine();
maxLen = Math.max(maxLen, line.length());
ss.add(line);
}
for(int i = 0;i<maxLen+2;i++){
System.out.print("*");
}
System.out.println();
boolean left = true;
for(String s : ss){
System.out.print("*");
String temp = s;
while(temp.length()+2 <= maxLen){
temp = " "+temp+" ";
}
if(temp.length() < maxLen){
if(left){
temp+=" ";
left = false;
}
else{
temp = " "+temp;
left = true;
}
}
System.out.print(temp);
System.out.print("*");
System.out.println();
}
for(int i = 0;i<maxLen+2;i++){
System.out.print("*");
}
System.out.println();
}
}
| Java | ["This is\n\nCodeforces\nBeta\nRound\n5", "welcome to the\nCodeforces\nBeta\nRound 5\n\nand\ngood luck"] | 1 second | ["************\n* This is *\n* *\n*Codeforces*\n* Beta *\n* Round *\n* 5 *\n************", "****************\n*welcome to the*\n* Codeforces *\n* Beta *\n* Round 5 *\n* *\n* and *\n* good luck *\n****************"] | null | Java 7 | standard input | [
"implementation",
"strings"
] | a017393743ae70a4d8a9d9dc40410653 | The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000. | 1,200 | Format the given text, aligning it center. Frame the whole text with characters Β«*Β» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better. | standard output | |
PASSED | 05cc78fd4562bd2c12ab66362f9ad001 | train_003.jsonl | 1269100800 | Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor Β«TextpadΒ» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck! | 64 megabytes | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class CenterAlignment
{
public static void main(String[] args) throws Exception
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//OutputStream out = new BufferedOutputStream ( System.out );
//Scanner in = new Scanner(System.in);
String input;
List<String> list = new ArrayList<>();
int max = 0;
while((input = in.readLine()) != null)
//for(String input = in.readLine(); input != null; input = in.readLine())
//while(in.hasNextLine())
{
//input = in.nextLine();
//input = in.readLine();
list.add(input);
max = Math.max(max, input.length());
}
String star = "";
for(int i = 0; i < max+2; i++)
{
star += "*";
}
System.out.println(star);
//out.write((star + "\n").getBytes());
boolean left = true;
int spaces = 0;
for(String line : list)
{
StringBuilder sb = new StringBuilder();
//System.out.print("*");
sb.append("*");
spaces = max - line.length();
if(spaces % 2 == 0)
{
for(int i = 0; i < spaces/2; i++)
{
//System.out.print(" ");
sb.append(" ");
}
//System.out.print(line);
sb.append(line);
for(int i = 0; i < spaces/2; i++)
{
//System.out.print(" ");
sb.append(" ");
}
}
else if(left)
{
for(int i = 0; i < spaces/2; i++)
{
//System.out.print(" ");
sb.append(" ");
}
//System.out.print(line);
sb.append(line);
for(int i = 0; i < (spaces/2)+1; i++)
{
//System.out.print(" ");
sb.append(" ");
}
left = false;
}
else
{
for(int i = 0; i < (spaces/2)+1; i++)
{
//System.out.print(" ");
sb.append(" ");
}
//System.out.print(line);
sb.append(line);
for(int i = 0; i < spaces/2; i++)
{
//System.out.print(" ");
sb.append(" ");
}
left = true;
}
//System.out.println("*");
sb.append("*");
//out.write(sb.toString().getBytes());
System.out.println(sb.toString());
}
//sb.append(star + "\n");
System.out.println(star);
//out.write(sb.toString().getBytes());
//System.out.print(sb.toString());
}
} | Java | ["This is\n\nCodeforces\nBeta\nRound\n5", "welcome to the\nCodeforces\nBeta\nRound 5\n\nand\ngood luck"] | 1 second | ["************\n* This is *\n* *\n*Codeforces*\n* Beta *\n* Round *\n* 5 *\n************", "****************\n*welcome to the*\n* Codeforces *\n* Beta *\n* Round 5 *\n* *\n* and *\n* good luck *\n****************"] | null | Java 7 | standard input | [
"implementation",
"strings"
] | a017393743ae70a4d8a9d9dc40410653 | The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000. | 1,200 | Format the given text, aligning it center. Frame the whole text with characters Β«*Β» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better. | standard output | |
PASSED | 21a7297a090073e1b213ce94e11f2189 | train_003.jsonl | 1269100800 | Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor Β«TextpadΒ» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck! | 64 megabytes | import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void insert(StringBuilder sb, int pos){
if(pos%2==1)
sb.append(" ");
else
sb.insert(0, " ");
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<StringBuilder> list = new ArrayList<StringBuilder>();
int length = 0;
while(in.hasNextLine()){
String s = in.nextLine();
StringBuilder sb = new StringBuilder();
sb.append(s);
list.add(sb);
length = Math.max(length, s.length());
}
int a = length+2,pos = 1;
StringBuilder sb = new StringBuilder();
for(int i=0;i<a;i++)
sb.append("*");
System.out.println(sb.toString());
for(int i=0;i<list.size();i++){
while(list.get(i).length()<length){
insert(list.get(i),pos);
pos ^= 1;
}
list.get(i).insert(0, "*");
list.get(i).append("*");
System.out.println(list.get(i).toString());
}
System.out.println(sb.toString());
}
} | Java | ["This is\n\nCodeforces\nBeta\nRound\n5", "welcome to the\nCodeforces\nBeta\nRound 5\n\nand\ngood luck"] | 1 second | ["************\n* This is *\n* *\n*Codeforces*\n* Beta *\n* Round *\n* 5 *\n************", "****************\n*welcome to the*\n* Codeforces *\n* Beta *\n* Round 5 *\n* *\n* and *\n* good luck *\n****************"] | null | Java 7 | standard input | [
"implementation",
"strings"
] | a017393743ae70a4d8a9d9dc40410653 | The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000. | 1,200 | Format the given text, aligning it center. Frame the whole text with characters Β«*Β» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better. | standard output | |
PASSED | 3a69ff5fc40ef95457d531f42a87d1c5 | train_003.jsonl | 1269100800 | Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor Β«TextpadΒ» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck! | 64 megabytes | import java.util.* ;
public class Main
{
public static void main(String [] args)
{
Scanner s=new Scanner (System.in);
String [] str = new String [1005];
int cnt=0,Max=0 ;
while(s.hasNextLine())
{
str[cnt]=s.nextLine();
if(str[cnt].length()>Max)
Max=str[cnt].length();
cnt++;
}
StringBuilder firstLine =new StringBuilder() ;
for(int i=0;i<=Max+1;i++) firstLine.append("*");
System.out.println(firstLine);
boolean left=false ;
for(int i=0;i<cnt;i++)
{
StringBuilder mid=new StringBuilder("*");
if((Max-str[i].length())%2==0)
{
int lim=(Max-str[i].length())/2;
for(int j=0;j<lim;j++) mid.append(" ");
mid.append(str[i]);
lim=(Max+str[i].length())/2;
for(int j=lim;j<Max;j++) mid.append(" ");
mid.append("*");
System.out.println(mid);
}
else if(left)
{
int lim=(Max+str[i].length())/2;
for(int j=lim;j<Max;j++) mid.append(" ");
mid.append(str[i]);
lim=(Max-str[i].length())/2;
for(int j=0;j<lim;j++) mid.append(" ");
mid.append("*");
System.out.println(mid);
left=false ;
}
else
{
int lim=(Max-str[i].length())/2;
for(int j=0;j<lim;j++) mid.append(" ");
mid.append(str[i]);
lim=(Max+str[i].length())/2;
for(int j=lim;j<Max;j++) mid.append(" ");
mid.append("*");
System.out.println(mid);
left=true ;
}
}
System.out.println(firstLine);
s.close();
}
} | Java | ["This is\n\nCodeforces\nBeta\nRound\n5", "welcome to the\nCodeforces\nBeta\nRound 5\n\nand\ngood luck"] | 1 second | ["************\n* This is *\n* *\n*Codeforces*\n* Beta *\n* Round *\n* 5 *\n************", "****************\n*welcome to the*\n* Codeforces *\n* Beta *\n* Round 5 *\n* *\n* and *\n* good luck *\n****************"] | null | Java 7 | standard input | [
"implementation",
"strings"
] | a017393743ae70a4d8a9d9dc40410653 | The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000. | 1,200 | Format the given text, aligning it center. Frame the whole text with characters Β«*Β» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better. | standard output | |
PASSED | 51efbd9759b46241a2887ca3084cb81c | train_003.jsonl | 1269100800 | Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor Β«TextpadΒ» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck! | 64 megabytes | import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<String> lines = new ArrayList<String>(1000);
int maxLength = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lines.add(line);
maxLength = Math.max(maxLength, line.length());
}
String border = repeat('*', maxLength + 2);
System.out.println(border);
boolean roundRight = false;
for (String line : lines) {
System.out.print('*');
int length = line.length();
int left = (maxLength - length) / 2;
int right = maxLength - left - line.length();
if (left != right) {
if (roundRight) {
left += 1;
right -= 1;
}
roundRight = !roundRight;
}
System.out.print(repeat(' ', left));
System.out.print(line);
System.out.print(repeat(' ', right));
System.out.println('*');
}
System.out.println(border);
}
static String repeat(char c, int count) {
StringBuilder builder = new StringBuilder(count);
for (int i = 0; i < count; ++i) {
builder.append(c);
}
return builder.toString();
}
}
| Java | ["This is\n\nCodeforces\nBeta\nRound\n5", "welcome to the\nCodeforces\nBeta\nRound 5\n\nand\ngood luck"] | 1 second | ["************\n* This is *\n* *\n*Codeforces*\n* Beta *\n* Round *\n* 5 *\n************", "****************\n*welcome to the*\n* Codeforces *\n* Beta *\n* Round 5 *\n* *\n* and *\n* good luck *\n****************"] | null | Java 7 | standard input | [
"implementation",
"strings"
] | a017393743ae70a4d8a9d9dc40410653 | The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000. | 1,200 | Format the given text, aligning it center. Frame the whole text with characters Β«*Β» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better. | standard output | |
PASSED | cb4fe3b326295851730a3fb03937cfa0 | train_003.jsonl | 1269100800 | Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor Β«TextpadΒ» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck! | 64 megabytes | import java.util.*;
public class P005B {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
ArrayList<String> lines = new ArrayList<String>();
int width = 0;
while (in.hasNextLine())
{
String line = in.nextLine();
width = Math.max(width, line.length());
lines.add(line);
}
for (int i = 0; i < width + 2; ++i)
System.out.print("*");
System.out.println();
boolean alternate = true;
for (String line : lines)
{
System.out.print("*");
int val = (width - line.length())/2;
if ((width - line.length())%2 == 1)
{
if (!alternate) ++val;
alternate = !alternate;
}
for (int i = 0; i < val; ++i) System.out.print(" ");
System.out.print(line);
for (int i = val+line.length(); i < width; ++i) System.out.print(" ");
System.out.println("*");
}
for (int i = 0; i < width + 2; ++i)
System.out.print("*");
System.out.println();
}
}
| Java | ["This is\n\nCodeforces\nBeta\nRound\n5", "welcome to the\nCodeforces\nBeta\nRound 5\n\nand\ngood luck"] | 1 second | ["************\n* This is *\n* *\n*Codeforces*\n* Beta *\n* Round *\n* 5 *\n************", "****************\n*welcome to the*\n* Codeforces *\n* Beta *\n* Round 5 *\n* *\n* and *\n* good luck *\n****************"] | null | Java 7 | standard input | [
"implementation",
"strings"
] | a017393743ae70a4d8a9d9dc40410653 | The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000. | 1,200 | Format the given text, aligning it center. Frame the whole text with characters Β«*Β» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better. | standard output | |
PASSED | e3317f8b97937559b81458769b1f6d8b | train_003.jsonl | 1269100800 | Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor Β«TextpadΒ» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck! | 64 megabytes | import java.io.*;
import java.util.*;
public class B {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
void solve() throws IOException {
String s;
ArrayList<String> text = new ArrayList<String>();
int maxLen = 0;
while ((s = br.readLine()) != null) {
text.add(s);
maxLen = Math.max(maxLen, s.length());
}
for (int i = 0; i < maxLen + 2; i++)
out.print('*');
out.println();
boolean alignLeft = false;
for (int i = 0; i < text.size(); i++) {
out.print('*');
s = text.get(i);
int space = maxLen - s.length();
for (int j = 0; j < space / 2; j++)
out.print(' ');
if (space % 2 == 1) {
if (alignLeft)
out.print(' ');
}
out.print(s);
for (int j = 0; j < space / 2; j++)
out.print(' ');
if (space % 2 == 1) {
if (!alignLeft)
out.print(' ');
alignLeft = !alignLeft;
}
out.println('*');
}
for (int i = 0; i < maxLen + 2; i++)
out.print('*');
out.println();
}
void inp() 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 B().inp();
}
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 | ["This is\n\nCodeforces\nBeta\nRound\n5", "welcome to the\nCodeforces\nBeta\nRound 5\n\nand\ngood luck"] | 1 second | ["************\n* This is *\n* *\n*Codeforces*\n* Beta *\n* Round *\n* 5 *\n************", "****************\n*welcome to the*\n* Codeforces *\n* Beta *\n* Round 5 *\n* *\n* and *\n* good luck *\n****************"] | null | Java 7 | standard input | [
"implementation",
"strings"
] | a017393743ae70a4d8a9d9dc40410653 | The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000. | 1,200 | Format the given text, aligning it center. Frame the whole text with characters Β«*Β» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better. | standard output | |
PASSED | 884a06e2faaa497006cf90d316c08717 | train_003.jsonl | 1269100800 | Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor Β«TextpadΒ» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck! | 64 megabytes | import java.io.*;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
public final class CenterAlignment {
private static String print(char c, int n) {
char[] a = new char[n];
Arrays.fill(a, c);
return new String(a);
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
List<String> lines = new ArrayList<String>();
int width = 0;
String line = br.readLine();
while (line != null) {
width = Math.max(width, line.length());
lines.add(line);
line = br.readLine();
}
boolean left = true;
System.out.println(print('*', width + 2));
for (String s : lines) {
System.out.print('*');
int extra = width - s.length();
int mul = extra/2;
int l = mul, r = mul;
if (extra % 2 != 0) {
if (left) r++;
else l++;
left = !left;
}
System.out.print(print(' ', l));
System.out.print(s);
System.out.print(print(' ', r));
System.out.println('*');
}
System.out.println(print('*', width + 2));
}
}
| Java | ["This is\n\nCodeforces\nBeta\nRound\n5", "welcome to the\nCodeforces\nBeta\nRound 5\n\nand\ngood luck"] | 1 second | ["************\n* This is *\n* *\n*Codeforces*\n* Beta *\n* Round *\n* 5 *\n************", "****************\n*welcome to the*\n* Codeforces *\n* Beta *\n* Round 5 *\n* *\n* and *\n* good luck *\n****************"] | null | Java 7 | standard input | [
"implementation",
"strings"
] | a017393743ae70a4d8a9d9dc40410653 | The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000. | 1,200 | Format the given text, aligning it center. Frame the whole text with characters Β«*Β» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better. | standard output | |
PASSED | 16e7effda2675014625a26569dfd816f | train_003.jsonl | 1269100800 | Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor Β«TextpadΒ» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck! | 64 megabytes | //package Round_5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Scanner;
public class B {
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuffer[] a = new StringBuffer[10000];
int size = 0;
int max = 0;
//` String ss = in.readLine();
while (in.ready()) {
String s = in.readLine();
max = Math.max(max, s.length());
a[size++] = new StringBuffer(s);
}
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
for (int i = 0; i < max + 2; i++) {
out.print("*");
}
out.println();
boolean g = true;
for (int i = 0; i < size; i++) {
int len = a[i].length();
if (len < max) {
if ((max - len) % 2 == 0) {
for (int j = 0; j < (max - len) / 2; j++) {
a[i] = new StringBuffer(" ").append(a[i]);
a[i] = a[i].append(new StringBuffer(" "));
}
} else {
if (g) {
for (int j = 0; j < (max - len) / 2; j++) {
a[i] = new StringBuffer(" ").append(a[i]);
a[i] = a[i].append(new StringBuffer(" "));
}
a[i] = a[i].append(new StringBuffer(" "));
} else {
for (int j = 0; j < (max - len) / 2; j++) {
a[i] = new StringBuffer(" ").append(a[i]);
a[i] = a[i].append(new StringBuffer(" "));
}
a[i] = new StringBuffer(" ").append(a[i]);
}
g = !g;
}
}
out.println("*" + a[i] + "*");
out.flush();
}
for (int i = 0; i < max + 2; i++) {
out.print("*");
out.flush();
}
out.println();
out.close();
}
}
/*
c
welcome to the
Codeforces
Beta
Round 5
and
good luck
* ***********
* This is * *Codeforces* Beta * Round * 5 ************
*
*
* *********** This is * *Codeforces* Beta * Round * 5 ************
*/ | Java | ["This is\n\nCodeforces\nBeta\nRound\n5", "welcome to the\nCodeforces\nBeta\nRound 5\n\nand\ngood luck"] | 1 second | ["************\n* This is *\n* *\n*Codeforces*\n* Beta *\n* Round *\n* 5 *\n************", "****************\n*welcome to the*\n* Codeforces *\n* Beta *\n* Round 5 *\n* *\n* and *\n* good luck *\n****************"] | null | Java 7 | standard input | [
"implementation",
"strings"
] | a017393743ae70a4d8a9d9dc40410653 | The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000. | 1,200 | Format the given text, aligning it center. Frame the whole text with characters Β«*Β» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better. | standard output | |
PASSED | 08aa6a833a9ab4d45ac3ed3dd06b0e1b | train_003.jsonl | 1269100800 | Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor Β«TextpadΒ» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck! | 64 megabytes | import java.util.List;
import java.util.Scanner;
import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
}
class TaskB {
public void solve(int testNumber, Scanner in, PrintWriter out) {
List<String> inputText = new ArrayList<String>();
int maxLen = 0;
while (in.hasNextLine()) {
String str = in.nextLine().trim();
inputText.add(str);
if (maxLen < str.length()) {
maxLen = str.length();
}
}
for (int i = 0; i < maxLen + 2; i++) {
out.print("*");
}
out.println();
boolean leftShift = false;
int left;
int right;
for (int i = 0; i < inputText.size(); i++) {
int num = maxLen - inputText.get(i).length();
right = num / 2;
left = num / 2;
if (num % 2 == 1) {
if (leftShift) {
left++;
} else {
right++;
}
leftShift = !leftShift;
}
out.print("*");
for (int j = 0; j < left; j++) {
out.print(" ");
}
out.print(inputText.get(i));
for (int j = 0; j < right; j++) {
out.print(" ");
}
out.print("*");
out.println();
}
for (int i = 0; i < maxLen + 2; i++) {
out.print("*");
}
}
}
| Java | ["This is\n\nCodeforces\nBeta\nRound\n5", "welcome to the\nCodeforces\nBeta\nRound 5\n\nand\ngood luck"] | 1 second | ["************\n* This is *\n* *\n*Codeforces*\n* Beta *\n* Round *\n* 5 *\n************", "****************\n*welcome to the*\n* Codeforces *\n* Beta *\n* Round 5 *\n* *\n* and *\n* good luck *\n****************"] | null | Java 7 | standard input | [
"implementation",
"strings"
] | a017393743ae70a4d8a9d9dc40410653 | The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000. | 1,200 | Format the given text, aligning it center. Frame the whole text with characters Β«*Β» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better. | standard output | |
PASSED | 01d64859b5e539e962eb89a8905dcea4 | train_003.jsonl | 1269100800 | Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor Β«TextpadΒ» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck! | 64 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringBufferInputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static BufferedReader br;
static PrintWriter out;
static StringTokenizer st;
static void isWon() {
}
static void solve() throws Exception {
char[] buf = new char[1000 * 1000];
br.read(buf);
String s = new String(buf);
String[] lines = s.split("\r\n");
int max = 0;
for(int i = 0; i < lines.length - 1; i++) {
max = Math.max(max, lines[i].length());
}
boolean b = true;
StringBuilder sb = new StringBuilder();
print1(max, sb);
sb.append("\n");
for(int i = 0; i < lines.length - 1; i++) {
String str = lines[i];
int half = max - str.length();
int right = half / 2;
int left = half - right;
if(left == right) {
print(left, right, str, sb);
sb.append("\n");
}else {
if(b) {
print(Math.min(left, right), Math.max(left,right), str, sb);
sb.append("\n");
}else{
print(Math.max(left,right), Math.min(left, right), str, sb);
sb.append("\n");
}
b = !b;
}
}
print1(max, sb);
sb.append("\n");
out.print(sb);
}
static void print1(int size, StringBuilder sb){
sb.append("*");
for(int i = 0; i < size; i++) {
sb.append("*");
}
sb.append("*");
}
static void print(int left, int right, String word, StringBuilder sb) {
sb.append("*");
for(int i = 0; i < left; i++) {
sb.append(" ");
}
sb.append(word);
for(int i = 0; i < right; i++) {
sb.append(" ");
}
sb.append("*");
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
static String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = br.readLine();
if (line == null) {
return null;
}
st = new StringTokenizer(line);
}
return st.nextToken();
}
public static void main(String[] args) {
try {
InputStream input = System.in;
OutputStream output = System.out;
br = new BufferedReader(new InputStreamReader(input));
out = new PrintWriter(new PrintStream(output));
solve();
out.close();
br.close();
} catch (Throwable t) {
t.printStackTrace();
}
}
}
| Java | ["This is\n\nCodeforces\nBeta\nRound\n5", "welcome to the\nCodeforces\nBeta\nRound 5\n\nand\ngood luck"] | 1 second | ["************\n* This is *\n* *\n*Codeforces*\n* Beta *\n* Round *\n* 5 *\n************", "****************\n*welcome to the*\n* Codeforces *\n* Beta *\n* Round 5 *\n* *\n* and *\n* good luck *\n****************"] | null | Java 7 | standard input | [
"implementation",
"strings"
] | a017393743ae70a4d8a9d9dc40410653 | The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000. | 1,200 | Format the given text, aligning it center. Frame the whole text with characters Β«*Β» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better. | standard output | |
PASSED | e2565a564a8735316a08286894a9003f | train_003.jsonl | 1269100800 | Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor Β«TextpadΒ» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck! | 64 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CF5B {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] lines = new String[1000];
String line = null;
int idx = 0;
while ((line = br.readLine()) != null) {
lines[idx++] = line;
}
int width = 0;
for (int i=0;i<idx;i++)
if (lines[i].length()>width) width=lines[i].length();
StringBuilder sb = new StringBuilder();
// Do top
sb.append("*");
for (int i=0;i<width;i++) sb.append("*");
sb.append("*");
// Do each line
sb.append("\n");
int lefting = 0;
for (int i=0;i<idx;i++) {
sb.append("*");
int neededspace = width - lines[i].length();
int padspace = neededspace/2;
if (neededspace > 0) {
if (neededspace % 2 == 0) {
for (int j=0;j<padspace;j++) sb.append(" ");
}
else {
for (int j=0;j<padspace + lefting;j++) sb.append(" ");
}
}
int righting = lefting - 1;
sb.append(lines[i]);
if (neededspace > 0) {
if (neededspace % 2 == 0) {
for (int j=0;j<padspace;j++) sb.append(" ");
}
else {
lefting = -righting;
for (int j=0;j<padspace - righting;j++) sb.append(" ");
}
}
sb.append("*\n");
}
// bottom
sb.append("*");
for (int i=0;i<width;i++) sb.append("*");
sb.append("*");
System.out.println(sb.toString());
}
}
| Java | ["This is\n\nCodeforces\nBeta\nRound\n5", "welcome to the\nCodeforces\nBeta\nRound 5\n\nand\ngood luck"] | 1 second | ["************\n* This is *\n* *\n*Codeforces*\n* Beta *\n* Round *\n* 5 *\n************", "****************\n*welcome to the*\n* Codeforces *\n* Beta *\n* Round 5 *\n* *\n* and *\n* good luck *\n****************"] | null | Java 7 | standard input | [
"implementation",
"strings"
] | a017393743ae70a4d8a9d9dc40410653 | The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000. | 1,200 | Format the given text, aligning it center. Frame the whole text with characters Β«*Β» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better. | standard output | |
PASSED | 3dd269e2d6807b98b74014635ad9c095 | train_003.jsonl | 1269100800 | Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor Β«TextpadΒ» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck! | 64 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class CenterAlignment {
public static char[] getStarsLine(int length)
{
char[] starSpacesArray = new char[length];
Arrays.fill(starSpacesArray, '*');
return starSpacesArray;
}
public static char[] getEmptyLine(int length)
{
char[] starSpacesArray = new char[length];
Arrays.fill(starSpacesArray, ' ');
starSpacesArray[0] = '*';
starSpacesArray[length - 1] = '*';
return starSpacesArray;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
List<String> text = new ArrayList<String>();
int maxLine = 0;
while (in.hasNextLine()) {
String line = in.nextLine();
maxLine = Math.max(maxLine, line.length());
text.add(line);
}
in.close();
char[] starArray = getStarsLine(maxLine + 2);
System.out.println(starArray);
boolean lastLeft = false;
for(String line : text) {
int spaces = (maxLine - line.length()) / 2;
if ((maxLine - line.length()) % 2 == 1 ) {
if (lastLeft) {
spaces += 1;
lastLeft = false;
} else {
lastLeft = true;
}
}
char[] lineArray = getEmptyLine(maxLine + 2);
line.getChars(0, line.length(), lineArray, spaces + 1);
System.out.println(lineArray);
}
System.out.println(starArray);
}
} | Java | ["This is\n\nCodeforces\nBeta\nRound\n5", "welcome to the\nCodeforces\nBeta\nRound 5\n\nand\ngood luck"] | 1 second | ["************\n* This is *\n* *\n*Codeforces*\n* Beta *\n* Round *\n* 5 *\n************", "****************\n*welcome to the*\n* Codeforces *\n* Beta *\n* Round 5 *\n* *\n* and *\n* good luck *\n****************"] | null | Java 7 | standard input | [
"implementation",
"strings"
] | a017393743ae70a4d8a9d9dc40410653 | The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000. | 1,200 | Format the given text, aligning it center. Frame the whole text with characters Β«*Β» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better. | standard output | |
PASSED | e2598c37ee0fbf972875d268f186c624 | train_003.jsonl | 1269100800 | Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor Β«TextpadΒ» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck! | 64 megabytes |
import java.io.*;
import java.util.*;
import java.math.*;
public class Main {
static char M[][];
static int m, n;
static boolean left;
static boolean even;
static void set(String s, int line) {
if (even) {
if (s.length() % 2 == 0) { // par - par
int p = (n - s.length()) / 2;
// System.out.println("x = " + line);
for (int i = 0; i < s.length(); i++) {
// System.out.println(i);
M[line][p++] = s.charAt(i);
}
} else { // par - impar
int p = left ? (int) Math.floor((n - s.length()) / 2) : (int) Math.floor((n - s.length()) / 2 + 1);
left = !left;
for (int i = 0; i < s.length(); i++) {
M[line][p++] = s.charAt(i);
}
}
} else {
if (s.length() % 2 == 0) { // impar -par
int p = left ? (int) Math.floor((n - s.length()) / 2) : (int) Math.floor((n - s.length()) / 2 + 1);
left = !left;
for (int i = 0; i < s.length(); i++) {
M[line][p++] = s.charAt(i);
}
} else {
int p = (n - s.length()) / 2;
for (int i = 0; i < s.length(); i++) {
M[line][p++] = s.charAt(i);
}
}
}
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//BufferedReader br = new BufferedReader(new FileReader(new File("in.txt")));
ArrayList<String> al = new ArrayList<String>();
int max = 0;
while (br.ready()) {
String s = br.readLine().trim();
max = Math.max(max, s.length());
al.add(s);
}
n = max + 2;
m = al.size() + 2;
even = n % 2 == 0 ? true : false;
// System.out.println("x = " + max);
M = new char[m][n];
left = true;
for (int i = 0; i < m; i++) {
Arrays.fill(M[i], ' ');
}
for (int i = 0; i < m - 2; i++) {
// System.out.println("pasas");
set(al.get(i), i + 1);
}
for (int i = 0; i < m; i++) {
M[i][0] = M[i][n - 1] = '*';
}
for (int j = 0; j < n; j++) {
M[0][j] = M[m - 1][j] = '*';
}
for (int i = 0; i < m; i++) {
StringBuilder sb = new StringBuilder();
sb.append(M[i]);
System.out.println(sb.toString());
}
}
} | Java | ["This is\n\nCodeforces\nBeta\nRound\n5", "welcome to the\nCodeforces\nBeta\nRound 5\n\nand\ngood luck"] | 1 second | ["************\n* This is *\n* *\n*Codeforces*\n* Beta *\n* Round *\n* 5 *\n************", "****************\n*welcome to the*\n* Codeforces *\n* Beta *\n* Round 5 *\n* *\n* and *\n* good luck *\n****************"] | null | Java 7 | standard input | [
"implementation",
"strings"
] | a017393743ae70a4d8a9d9dc40410653 | The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000. | 1,200 | Format the given text, aligning it center. Frame the whole text with characters Β«*Β» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better. | standard output | |
PASSED | 68b946bbf41e1e9b92302d374b27a3ae | train_003.jsonl | 1269100800 | Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor Β«TextpadΒ» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck! | 64 megabytes | import java.io.*;
import java.util.*;
public class B {
void run() throws IOException {
String line;
String[] lines = new String[1000];
int n = 0, max = 0;
boolean a = true;
while ((line = nl()) != null)
lines[n++] = line;
for (int i = 0; i < n; i++)
max = Math.max(max, lines[i].length());
for (int i = 0; i < max + 2; i++)
pw.print('*');
pw.println();
for (int i = 0; i < n; i++) {
pw.print('*');
int l = lines[i].length(), ls = 0, rs = 0;
if ((max - l) % 2 == 0) {
ls = (max - l) / 2;
rs = (max - l) / 2;
} else {
if (a) {
ls = (max - l) / 2;
rs = ((max - l) / 2) + 1;
} else {
ls = ((max - l) / 2) + 1;
rs = (max - l) / 2;
}
a = !a;
}
for (int j = 0; j < ls; j++)
pw.print(' ');
pw.print(lines[i]);
for (int j = 0; j < rs; j++)
pw.print(' ');
pw.println('*');
}
for (int i = 0; i < max + 2; i++)
pw.print('*');
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int ni() throws IOException {
return Integer.parseInt(next());
}
String nl() throws IOException {
return br.readLine();
}
PrintWriter pw;
BufferedReader br;
StringTokenizer st;
public static void main(String[] args) throws IOException {
long timeout = System.currentTimeMillis();
boolean CF = System.getProperty("ONLINE_JUDGE") != null;
PrintWriter _pw = new PrintWriter(System.out);
BufferedReader _br = new BufferedReader(CF ? new InputStreamReader(System.in) : new FileReader(new File("in.txt")));
new B(_br, _pw).run();
if (!CF) {
_pw.println();
_pw.println(System.currentTimeMillis() - timeout);
}
_br.close();
_pw.close();
}
public B(BufferedReader _br, PrintWriter _pw) {
br = _br;
pw = _pw;
}
}
| Java | ["This is\n\nCodeforces\nBeta\nRound\n5", "welcome to the\nCodeforces\nBeta\nRound 5\n\nand\ngood luck"] | 1 second | ["************\n* This is *\n* *\n*Codeforces*\n* Beta *\n* Round *\n* 5 *\n************", "****************\n*welcome to the*\n* Codeforces *\n* Beta *\n* Round 5 *\n* *\n* and *\n* good luck *\n****************"] | null | Java 7 | standard input | [
"implementation",
"strings"
] | a017393743ae70a4d8a9d9dc40410653 | The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000. | 1,200 | Format the given text, aligning it center. Frame the whole text with characters Β«*Β» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better. | standard output | |
PASSED | 7e4dd808d7a2ed76b5cbee9142cdeb35 | train_003.jsonl | 1269100800 | Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor Β«TextpadΒ» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck! | 64 megabytes | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
*
* @author IR_HAM
*/
public class CenterAlignment
{
public static void main(String [] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String [] s = new String[10000];
int n = 0;
String t = "";
while((t = br.readLine()) != null)
{
s[n] = t;
n++;
}
int max = -1;
for(int i = 0; i < n; i++)
if(max < s[i].length())
max = s[i].length();
String top_bottom = "";
for(int i = 0; i < max + 2; i++)
top_bottom += "*";
System.out.println(top_bottom);
int count = 0;
for(int i = 0; i < n; i++)
{
int left = floor(((double) (max - s[i].length())) / 2);
int right = ceil(((double) (max - s[i].length())) / 2);
String s1 = "";
for(int j = 0; j < left; j++)
s1 += " ";
String s2 = "";
for(int j = 0; j < right; j++)
s2 += " ";
String t1 = "";
if(s1.length() == s2.length())
t1 = s1 + s[i] + s2;
else
{
if(count == 0)
t1 = s1 + s[i] + s2;
else
t1 = s2 + s[i] + s1;
count = (count + 1) % 2;
}
System.out.println("*" + t1 + "*");
}
System.out.println(top_bottom);
}
public static int floor(double x)
{
return (int) x;
}
public static int ceil(double x)
{
int y = (int) x;
if(y < x)
return y + 1;
else
return y;
}
}
| Java | ["This is\n\nCodeforces\nBeta\nRound\n5", "welcome to the\nCodeforces\nBeta\nRound 5\n\nand\ngood luck"] | 1 second | ["************\n* This is *\n* *\n*Codeforces*\n* Beta *\n* Round *\n* 5 *\n************", "****************\n*welcome to the*\n* Codeforces *\n* Beta *\n* Round 5 *\n* *\n* and *\n* good luck *\n****************"] | null | Java 7 | standard input | [
"implementation",
"strings"
] | a017393743ae70a4d8a9d9dc40410653 | The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000. | 1,200 | Format the given text, aligning it center. Frame the whole text with characters Β«*Β» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better. | standard output | |
PASSED | 4d2226fd32674c8eeedfa47f76581116 | train_003.jsonl | 1269100800 | Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor Β«TextpadΒ» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck! | 64 megabytes | import java.util.*;
public class Problem5B
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
ArrayList<String> lines = new ArrayList<String>();
while (s.hasNextLine())
{
lines.add(s.nextLine());
}
//adds lines
int maxLength = 0;
for (int i = 0; i < lines.size(); i++)
{
if (lines.get(i).length() > maxLength)
{
maxLength = lines.get(i).length();
}
}
//determines maxLength
for (int i = 0; i < maxLength+2; i++)
{
System.out.print("*");
}
//firstLine
boolean leftOrRight = false;
//false indicates left, true indicates right
for (int i = 0; i < lines.size(); i++)
{
System.out.println("");
System.out.print("*");
int amountToSpace = (maxLength - lines.get(i).length());
if (amountToSpace % 2 == 0)
{
System.out.print(SpaceGenerator(amountToSpace/2)+lines.get(i)+SpaceGenerator(amountToSpace/2));
}
//actual line
else
{
if (!leftOrRight)
{
System.out.print(SpaceGenerator(amountToSpace/2)+lines.get(i)+SpaceGenerator(amountToSpace/2 + 1));
leftOrRight =true;
}
//above is left
else
{
System.out.print(SpaceGenerator(amountToSpace/2+1)+lines.get(i)+SpaceGenerator(amountToSpace/2));
leftOrRight = false;
}
//above is right
}
System.out.print("*");
}
System.out.println();
//rest of Lines
for (int i = 0; i < maxLength+2; i++)
{
System.out.print("*");
}
//secondLine
}
public static String SpaceGenerator (int n)
{
String a = "";
if (n == 0)
{
return "";
}
for (int i = 0; i < n; i++)
{
a = a+" ";
}
return a;
}
}
| Java | ["This is\n\nCodeforces\nBeta\nRound\n5", "welcome to the\nCodeforces\nBeta\nRound 5\n\nand\ngood luck"] | 1 second | ["************\n* This is *\n* *\n*Codeforces*\n* Beta *\n* Round *\n* 5 *\n************", "****************\n*welcome to the*\n* Codeforces *\n* Beta *\n* Round 5 *\n* *\n* and *\n* good luck *\n****************"] | null | Java 7 | standard input | [
"implementation",
"strings"
] | a017393743ae70a4d8a9d9dc40410653 | The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000. | 1,200 | Format the given text, aligning it center. Frame the whole text with characters Β«*Β» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better. | standard output | |
PASSED | 38b5564a4d8e4e8705e6034495ec18fd | train_003.jsonl | 1269100800 | Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor Β«TextpadΒ» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck! | 64 megabytes | import java.io.*;
import java.util.*;
import java.lang.StringBuilder;
public class Main {
public static boolean f = true;
public static StringBuilder sb = new StringBuilder();
public static void printC(int i, char c) {
while (i-- != 0)
sb.append(c);
}
public static void print(String s, int width) {
if (s == null) {
printC(width + 2, '*');
sb.append('\n');
return;
}
sb.append('*');
int length = s.length();
width -= length;
if (width % 2 != 0) {
width /= 2;
printC(f ? width : width + 1, ' ');
sb.append(s);
printC(f ? width + 1 : width, ' ');
f = !f;
} else {
width /= 2;
printC(width, ' ');
sb.append(s);
printC(width, ' ');
}
sb.append("*\n");
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
LinkedList<String> list = new LinkedList<String>();
String str;
int max = 0;
int tmp;
while (in.hasNextLine()) {
str = in.nextLine();
list.addLast(str);
tmp = str.length();
if (tmp > max)
max = tmp;
}
print(null, max);
for (String s : list) {
print(s, max);
}
print(null, max);
System.out.print(sb.toString());
}
} | Java | ["This is\n\nCodeforces\nBeta\nRound\n5", "welcome to the\nCodeforces\nBeta\nRound 5\n\nand\ngood luck"] | 1 second | ["************\n* This is *\n* *\n*Codeforces*\n* Beta *\n* Round *\n* 5 *\n************", "****************\n*welcome to the*\n* Codeforces *\n* Beta *\n* Round 5 *\n* *\n* and *\n* good luck *\n****************"] | null | Java 7 | standard input | [
"implementation",
"strings"
] | a017393743ae70a4d8a9d9dc40410653 | The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000. | 1,200 | Format the given text, aligning it center. Frame the whole text with characters Β«*Β» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better. | standard output | |
PASSED | 0ccd931c6a5f7a9bce44428fd2c2b3cc | train_003.jsonl | 1269100800 | Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor Β«TextpadΒ» decided to introduce this functionality into the fourth release of the product.You are to implement the alignment in the shortest possible time. Good luck! | 64 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class Example implements Runnable {
private void solve() throws IOException {
List<String> lines = new ArrayList<String>();
while (true) {
try {
String line = reader.readLine();
if (line == null)
break;
lines.add(line);
} catch (Exception e) {
break;
}
}
int maxLen = 0;
for (String x : lines)
maxLen = Math.max(maxLen, x.length());
boolean sw = false;
for (int i = 0; i < maxLen + 2; ++i)
writer.print('*');
writer.println();
for (String x : lines) {
writer.print('*');
int delta = maxLen - x.length();
int rdelta;
if (delta % 2 == 0) {
delta /= 2;
rdelta = delta;
} else {
if (sw) {
rdelta = (delta - 1) / 2;
delta = (delta + 1) / 2;
sw = false;
} else {
rdelta = (delta + 1) / 2;
delta = (delta - 1) / 2;
sw = true;
}
}
for (int i = 0; i < delta; ++i)
writer.print(' ');
writer.print(x);
for (int i = 0; i < rdelta; ++i)
writer.print(' ');
writer.println('*');
}
for (int i = 0; i < maxLen + 2; ++i)
writer.print('*');
writer.println();
}
public static void main(String[] args) {
new Example().run();
}
BufferedReader reader;
StringTokenizer tokenizer;
PrintWriter writer;
public void run() {
try {
reader = new BufferedReader(new InputStreamReader(System.in));
tokenizer = null;
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
}
| Java | ["This is\n\nCodeforces\nBeta\nRound\n5", "welcome to the\nCodeforces\nBeta\nRound 5\n\nand\ngood luck"] | 1 second | ["************\n* This is *\n* *\n*Codeforces*\n* Beta *\n* Round *\n* 5 *\n************", "****************\n*welcome to the*\n* Codeforces *\n* Beta *\n* Round 5 *\n* *\n* and *\n* good luck *\n****************"] | null | Java 7 | standard input | [
"implementation",
"strings"
] | a017393743ae70a4d8a9d9dc40410653 | The input file consists of one or more lines, each of the lines contains Latin letters, digits and/or spaces. The lines cannot start or end with a space. It is guaranteed that at least one of the lines has positive length. The length of each line and the total amount of the lines do not exceed 1000. | 1,200 | Format the given text, aligning it center. Frame the whole text with characters Β«*Β» of the minimum size. If a line cannot be aligned perfectly (for example, the line has even length, while the width of the block is uneven), you should place such lines rounding down the distance to the left or to the right edge and bringing them closer left or right alternatively (you should start with bringing left). Study the sample tests carefully to understand the output format better. | standard output | |
PASSED | 62b5b5e081f7355bb8dfe81502a59914 | train_003.jsonl | 1559745300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ and an integer $$$k$$$.You are asked to divide this array into $$$k$$$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $$$f(i)$$$ be the index of subarray the $$$i$$$-th element belongs to. Subarrays are numbered from left to right and from $$$1$$$ to $$$k$$$.Let the cost of division be equal to $$$\sum\limits_{i=1}^{n} (a_i \cdot f(i))$$$. For example, if $$$a = [1, -2, -3, 4, -5, 6, -7]$$$ and we divide it into $$$3$$$ subbarays in the following way: $$$[1, -2, -3], [4, -5], [6, -7]$$$, then the cost of division is equal to $$$1 \cdot 1 - 2 \cdot 1 - 3 \cdot 1 + 4 \cdot 2 - 5 \cdot 2 + 6 \cdot 3 - 7 \cdot 3 = -9$$$.Calculate the maximum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ non-empty consecutive subarrays. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.Random;
public class Main {
private static FastScanner sc = new FastScanner();
private static boolean DEBUG_FLG = false;
public static void main(String[] args) {
int n = sc.nextInt();
int k = sc.nextInt();
long[] a = new long[n];
long[] s = new long[n];
for(int i=0; i<n; i++) {
a[i] = sc.nextLong();
}
s[n-1] = a[n-1];
for(int i=n-2; i>=0; i--) {
s[i] = s[i+1] + a[i];
}
long ans = s[0];
s[0] = Long.MIN_VALUE;
shuffleArray(s);
Arrays.sort(s);
for(int i=n-1; i>n-k; i--) {
ans += s[i];
}
System.out.println(ans);
}
static void debug(long... args) {
if(!DEBUG_FLG) return;
boolean flg = false;
for(long s : args) {
if(flg) System.out.print(" ");
flg = true;
System.out.print(s);
}
System.out.println();
}
static class FastScanner {
private final InputStream in = System.in;
private final byte[] buffer = new byte[1024];
private int ptr = 0;
private int buflen = 0;
private boolean hasNextByte() {
if(ptr < buflen) {
return true;
} else {
ptr = 0;
try {
buflen = in.read(buffer);
} catch(IOException e) {
e.printStackTrace();
}
if(buflen <= 0) {
return false;
}
}
return true;
}
private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
private void skipUnprintable() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;}
public boolean hasNext() { skipUnprintable(); return hasNextByte();}
public String next() {
if (!hasNext()) throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while(isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt(){
return Integer.parseInt(next());
}
public double nextDouble(){
return Double.parseDouble(next());
}
}
static void shuffleArray(long[] arr){
int n = arr.length;
Random rnd = new Random();
for(int i=0; i<n; ++i){
long tmp = arr[i];
int randomPos = i + rnd.nextInt(n-i);
arr[i] = arr[randomPos];
arr[randomPos] = tmp;
}
}
}
| Java | ["5 2\n-1 -2 5 -4 8", "7 6\n-3 0 -1 -2 -2 -4 -1", "4 1\n3 -1 6 0"] | 2 seconds | ["15", "-45", "8"] | null | Java 8 | standard input | [
"sortings",
"greedy"
] | c7a37e8220d5fc44556dff66c1e129e7 | The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 3 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$ |a_i| \le 10^6$$$). | 1,900 | Print the maximum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ nonempty consecutive subarrays. | standard output | |
PASSED | c5bbcce62e0dae8ad69b0d0ee2e24c46 | train_003.jsonl | 1559745300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ and an integer $$$k$$$.You are asked to divide this array into $$$k$$$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $$$f(i)$$$ be the index of subarray the $$$i$$$-th element belongs to. Subarrays are numbered from left to right and from $$$1$$$ to $$$k$$$.Let the cost of division be equal to $$$\sum\limits_{i=1}^{n} (a_i \cdot f(i))$$$. For example, if $$$a = [1, -2, -3, 4, -5, 6, -7]$$$ and we divide it into $$$3$$$ subbarays in the following way: $$$[1, -2, -3], [4, -5], [6, -7]$$$, then the cost of division is equal to $$$1 \cdot 1 - 2 \cdot 1 - 3 \cdot 1 + 4 \cdot 2 - 5 \cdot 2 + 6 \cdot 3 - 7 \cdot 3 = -9$$$.Calculate the maximum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ non-empty consecutive subarrays. | 256 megabytes |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class D {
class Point implements Comparable<Point>{
long value;
int index;
Point(long v, int i){
value = v;
index = i;
}
@Override
public int compareTo(Point o) {
return -Long.compare(this.value, o.value);
}
}
void solve(){
int n = readInt();
int k = readInt();
long[] a = new long[n];
for(int i = 0;i<n;i++){
a[i] = readInt();
}
long[] pref = new long[n + 1];
for(int i = 0;i<n;i++){
pref[i + 1] =pref[i] + a[i];
}
long[] suff = new long[n + 1];
for(int i = n - 1;i>=0;i--){
suff[i] = suff[i + 1] + a[i];
}
Point[] res = new Point[n];
res[0] = new Point(Long.MIN_VALUE, 0);
for(int i = 1;i<n;i++){
long two = pref[i] + 2 * suff[i];
res[i] = new Point(two, i);
}
Arrays.sort(res);
boolean[] go = new boolean[n];
for(int i = 0;i<k - 1;i++){
go[res[i].index] = true;
}
long now = 1;
long ans = 0;
for(int i = 0;i<n;i++){
if(go[i]) now++;
ans += now * a[i];
}
out.print(ans);
}
public static void main(String[] args) {
new D().run();
}
void run(){
init();
solve();
out.close();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init(){
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
String readLine(){
try{
return in.readLine();
}catch(Exception ex){
throw new RuntimeException(ex);
}
}
String readString(){
while(!tok.hasMoreTokens()){
String nextLine = readLine();
if(nextLine == null) return null;
tok = new StringTokenizer(nextLine);
}
return tok.nextToken();
}
int readInt(){
return Integer.parseInt(readString());
}
long readLong(){
return Long.parseLong(readString());
}
double readDouble(){
return Double.parseDouble(readString());
}
}
| Java | ["5 2\n-1 -2 5 -4 8", "7 6\n-3 0 -1 -2 -2 -4 -1", "4 1\n3 -1 6 0"] | 2 seconds | ["15", "-45", "8"] | null | Java 8 | standard input | [
"sortings",
"greedy"
] | c7a37e8220d5fc44556dff66c1e129e7 | The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 3 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$ |a_i| \le 10^6$$$). | 1,900 | Print the maximum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ nonempty consecutive subarrays. | standard output | |
PASSED | 6325a07a62773f50b02408bdccbb5bf8 | train_003.jsonl | 1559745300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ and an integer $$$k$$$.You are asked to divide this array into $$$k$$$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $$$f(i)$$$ be the index of subarray the $$$i$$$-th element belongs to. Subarrays are numbered from left to right and from $$$1$$$ to $$$k$$$.Let the cost of division be equal to $$$\sum\limits_{i=1}^{n} (a_i \cdot f(i))$$$. For example, if $$$a = [1, -2, -3, 4, -5, 6, -7]$$$ and we divide it into $$$3$$$ subbarays in the following way: $$$[1, -2, -3], [4, -5], [6, -7]$$$, then the cost of division is equal to $$$1 \cdot 1 - 2 \cdot 1 - 3 \cdot 1 + 4 \cdot 2 - 5 \cdot 2 + 6 \cdot 3 - 7 \cdot 3 = -9$$$.Calculate the maximum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ non-empty consecutive subarrays. | 256 megabytes | import java.io.*;
import java.util.*;
public class p22{
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main(String[] args)
{
FastReader sc = new FastReader();
int n = sc.nextInt();
int k = sc.nextInt();
long[] arr = new long[n];
ArrayList<Long> suf = new ArrayList<Long>();
for(int i=0;i<n;i++)
arr[i] = sc.nextLong();
long sum = 0;
for(int i=n-1;i>=0;i--){
sum+=arr[i];
if(i>0)
suf.add(sum);
}
Collections.sort(suf, Collections.reverseOrder());
for(int i=0;i<k-1;i++){
sum += suf.get(i);
}
System.out.println(sum);
}
}
| Java | ["5 2\n-1 -2 5 -4 8", "7 6\n-3 0 -1 -2 -2 -4 -1", "4 1\n3 -1 6 0"] | 2 seconds | ["15", "-45", "8"] | null | Java 8 | standard input | [
"sortings",
"greedy"
] | c7a37e8220d5fc44556dff66c1e129e7 | The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 3 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$ |a_i| \le 10^6$$$). | 1,900 | Print the maximum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ nonempty consecutive subarrays. | standard output | |
PASSED | bb327ac6413cf4dfd4164367a9d05e65 | train_003.jsonl | 1559745300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ and an integer $$$k$$$.You are asked to divide this array into $$$k$$$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $$$f(i)$$$ be the index of subarray the $$$i$$$-th element belongs to. Subarrays are numbered from left to right and from $$$1$$$ to $$$k$$$.Let the cost of division be equal to $$$\sum\limits_{i=1}^{n} (a_i \cdot f(i))$$$. For example, if $$$a = [1, -2, -3, 4, -5, 6, -7]$$$ and we divide it into $$$3$$$ subbarays in the following way: $$$[1, -2, -3], [4, -5], [6, -7]$$$, then the cost of division is equal to $$$1 \cdot 1 - 2 \cdot 1 - 3 \cdot 1 + 4 \cdot 2 - 5 \cdot 2 + 6 \cdot 3 - 7 \cdot 3 = -9$$$.Calculate the maximum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ non-empty consecutive subarrays. | 256 megabytes | import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.List;
public class Main {
InputStream is;
PrintWriter out;
String INPUT = "";
private static final long M = 1000000007;
void solve() {
int n = ni();
int k = ni();
ArrayList<Long> l = new ArrayList<Long>();
for (int i = 0; i < n; i++)
l.add(nl());
for (int i = n - 2; i >= 0; i--)
l.set(i, l.get(i + 1) + l.get(i));
Collections.reverse(l);
long ans = l.remove(n - 1);
Collections.sort(l);
for (int i = 0; i < k - 1; i++)
ans += l.get(n - 2 - i);
out.println(ans);
}
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
if (!INPUT.isEmpty())
tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception {
new Main().run();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != '
// ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n) {
if (!(isSpaceChar(b)))
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private int[][] na(int n, int m) {
int[][] a = new int[n][];
for (int i = 0; i < n; i++)
a[i] = na(m);
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o) {
System.out.println(Arrays.deepToString(o));
}
} | Java | ["5 2\n-1 -2 5 -4 8", "7 6\n-3 0 -1 -2 -2 -4 -1", "4 1\n3 -1 6 0"] | 2 seconds | ["15", "-45", "8"] | null | Java 8 | standard input | [
"sortings",
"greedy"
] | c7a37e8220d5fc44556dff66c1e129e7 | The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 3 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$ |a_i| \le 10^6$$$). | 1,900 | Print the maximum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ nonempty consecutive subarrays. | standard output | |
PASSED | dc4f99ef8eabcfb7dcbfd1056d0e2460 | train_003.jsonl | 1559745300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ and an integer $$$k$$$.You are asked to divide this array into $$$k$$$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $$$f(i)$$$ be the index of subarray the $$$i$$$-th element belongs to. Subarrays are numbered from left to right and from $$$1$$$ to $$$k$$$.Let the cost of division be equal to $$$\sum\limits_{i=1}^{n} (a_i \cdot f(i))$$$. For example, if $$$a = [1, -2, -3, 4, -5, 6, -7]$$$ and we divide it into $$$3$$$ subbarays in the following way: $$$[1, -2, -3], [4, -5], [6, -7]$$$, then the cost of division is equal to $$$1 \cdot 1 - 2 \cdot 1 - 3 \cdot 1 + 4 \cdot 2 - 5 \cdot 2 + 6 \cdot 3 - 7 \cdot 3 = -9$$$.Calculate the maximum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ non-empty consecutive subarrays. | 256 megabytes | import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.InputMismatchException;
public class Main {
InputStream is;
PrintWriter out;
String INPUT = "";
private static final long M = 1000000007;
void solve() {
int n = ni();
int k = ni();
ArrayList<Long> l = new ArrayList<Long>(n+2);
for (int i = 0; i < n; i++)
l.add(nl());
for (int i = n - 2; i >= 0; i--)
l.set(i, l.get(i + 1) + l.get(i));
Collections.reverse(l);
long ans = l.remove(n - 1);
Collections.sort(l);
for (int i = 0; i < k - 1; i++)
ans += l.get(n - 2 - i);
out.println(ans);
}
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
if (!INPUT.isEmpty())
tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception {
new Main().run();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != '
// ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n) {
if (!(isSpaceChar(b)))
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private int[][] na(int n, int m) {
int[][] a = new int[n][];
for (int i = 0; i < n; i++)
a[i] = na(m);
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o) {
System.out.println(Arrays.deepToString(o));
}
} | Java | ["5 2\n-1 -2 5 -4 8", "7 6\n-3 0 -1 -2 -2 -4 -1", "4 1\n3 -1 6 0"] | 2 seconds | ["15", "-45", "8"] | null | Java 8 | standard input | [
"sortings",
"greedy"
] | c7a37e8220d5fc44556dff66c1e129e7 | The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 3 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$ |a_i| \le 10^6$$$). | 1,900 | Print the maximum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ nonempty consecutive subarrays. | standard output | |
PASSED | 1caf3ef8c24310a985b5469420ab1cd7 | train_003.jsonl | 1559745300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ and an integer $$$k$$$.You are asked to divide this array into $$$k$$$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $$$f(i)$$$ be the index of subarray the $$$i$$$-th element belongs to. Subarrays are numbered from left to right and from $$$1$$$ to $$$k$$$.Let the cost of division be equal to $$$\sum\limits_{i=1}^{n} (a_i \cdot f(i))$$$. For example, if $$$a = [1, -2, -3, 4, -5, 6, -7]$$$ and we divide it into $$$3$$$ subbarays in the following way: $$$[1, -2, -3], [4, -5], [6, -7]$$$, then the cost of division is equal to $$$1 \cdot 1 - 2 \cdot 1 - 3 \cdot 1 + 4 \cdot 2 - 5 \cdot 2 + 6 \cdot 3 - 7 \cdot 3 = -9$$$.Calculate the maximum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ non-empty consecutive subarrays. | 256 megabytes | import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.InputMismatchException;
public class Main {
InputStream is;
PrintWriter out;
String INPUT = "";
private static final long M = 1000000007;
void solve() {
int n = ni();
int k = ni();
ArrayList<Long> l = new ArrayList<Long>(n);
for (int i = 0; i < n; i++)
l.add(nl());
for (int i = n - 2; i >= 0; i--)
l.set(i, l.get(i + 1) + l.get(i));
Collections.reverse(l);
long ans = l.remove(n - 1);
Collections.sort(l);
for (int i = 0; i < k - 1; i++)
ans += l.get(n - 2 - i);
out.println(ans);
}
void run() throws Exception {
is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
if (!INPUT.isEmpty())
tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception {
new Main().run();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != '
// ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n) {
if (!(isSpaceChar(b)))
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private int[][] na(int n, int m) {
int[][] a = new int[n][];
for (int i = 0; i < n; i++)
a[i] = na(m);
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private static void tr(Object... o) {
System.out.println(Arrays.deepToString(o));
}
} | Java | ["5 2\n-1 -2 5 -4 8", "7 6\n-3 0 -1 -2 -2 -4 -1", "4 1\n3 -1 6 0"] | 2 seconds | ["15", "-45", "8"] | null | Java 8 | standard input | [
"sortings",
"greedy"
] | c7a37e8220d5fc44556dff66c1e129e7 | The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 3 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$ |a_i| \le 10^6$$$). | 1,900 | Print the maximum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ nonempty consecutive subarrays. | standard output | |
PASSED | 6c787146d3317cb9191a7bbe21b2554c | train_003.jsonl | 1559745300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ and an integer $$$k$$$.You are asked to divide this array into $$$k$$$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $$$f(i)$$$ be the index of subarray the $$$i$$$-th element belongs to. Subarrays are numbered from left to right and from $$$1$$$ to $$$k$$$.Let the cost of division be equal to $$$\sum\limits_{i=1}^{n} (a_i \cdot f(i))$$$. For example, if $$$a = [1, -2, -3, 4, -5, 6, -7]$$$ and we divide it into $$$3$$$ subbarays in the following way: $$$[1, -2, -3], [4, -5], [6, -7]$$$, then the cost of division is equal to $$$1 \cdot 1 - 2 \cdot 1 - 3 \cdot 1 + 4 \cdot 2 - 5 \cdot 2 + 6 \cdot 3 - 7 \cdot 3 = -9$$$.Calculate the maximum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ non-empty consecutive subarrays. | 256 megabytes | import java.io.*;
import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.NoSuchElementException;
public class P1175D_2 {
public static void main(String[] args) {
SimpleScanner scanner = new SimpleScanner(System.in);
PrintWriter writer = new PrintWriter(System.out);
int n = scanner.nextInt();
int k = scanner.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; ++i)
a[i] = scanner.nextInt();
ArrayList<Long> suffixSum = new ArrayList<>(n);
long last = 0;
long sum = 0;
for (int i = n - 1; i > 0; --i) {
last += a[i];
sum += last;
suffixSum.add(last);
}
last += a[0];
sum += last;
if (n > 1) {
Collections.sort(suffixSum);
for (int i = 0; i < n - k; ++i)
sum -= suffixSum.get(i);
}
writer.println(sum);
writer.close();
}
private static class SimpleScanner {
private static final int BUFFER_SIZE = 10240;
private Readable in;
private CharBuffer buffer;
private boolean eof;
SimpleScanner(InputStream in) {
this.in = new BufferedReader(new InputStreamReader(in));
buffer = CharBuffer.allocate(BUFFER_SIZE);
buffer.limit(0);
eof = false;
}
private char read() {
if (!buffer.hasRemaining()) {
buffer.clear();
int n;
try {
n = in.read(buffer);
} catch (IOException e) {
n = -1;
}
if (n <= 0) {
eof = true;
return '\0';
}
buffer.flip();
}
return buffer.get();
}
void checkEof() {
if (eof)
throw new NoSuchElementException();
}
char nextChar() {
checkEof();
char b = read();
checkEof();
return b;
}
String next() {
char b;
do {
b = read();
checkEof();
} while (Character.isWhitespace(b));
StringBuilder sb = new StringBuilder();
do {
sb.append(b);
b = read();
} while (!eof && !Character.isWhitespace(b));
return sb.toString();
}
int nextInt() {
return Integer.valueOf(next());
}
long nextLong() {
return Long.valueOf(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
}
| Java | ["5 2\n-1 -2 5 -4 8", "7 6\n-3 0 -1 -2 -2 -4 -1", "4 1\n3 -1 6 0"] | 2 seconds | ["15", "-45", "8"] | null | Java 8 | standard input | [
"sortings",
"greedy"
] | c7a37e8220d5fc44556dff66c1e129e7 | The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 3 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$ |a_i| \le 10^6$$$). | 1,900 | Print the maximum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ nonempty consecutive subarrays. | standard output | |
PASSED | 9d23e93215672655aa4a57b49145891b | train_003.jsonl | 1559745300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ and an integer $$$k$$$.You are asked to divide this array into $$$k$$$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $$$f(i)$$$ be the index of subarray the $$$i$$$-th element belongs to. Subarrays are numbered from left to right and from $$$1$$$ to $$$k$$$.Let the cost of division be equal to $$$\sum\limits_{i=1}^{n} (a_i \cdot f(i))$$$. For example, if $$$a = [1, -2, -3, 4, -5, 6, -7]$$$ and we divide it into $$$3$$$ subbarays in the following way: $$$[1, -2, -3], [4, -5], [6, -7]$$$, then the cost of division is equal to $$$1 \cdot 1 - 2 \cdot 1 - 3 \cdot 1 + 4 \cdot 2 - 5 \cdot 2 + 6 \cdot 3 - 7 \cdot 3 = -9$$$.Calculate the maximum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ non-empty consecutive subarrays. | 256 megabytes | import java.io.PrintStream;
import java.util.Arrays;
import java.util.Scanner;
public class D1175 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintStream out = System.out;
int n = in.nextInt(), k = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
long[] lp = new long[n + 1];
for (int i = n - 1; i >= 0; i--) {
lp[i] = lp[i + 1] + a[i];
}
long ret = lp[0];
lp[0] = Long.MIN_VALUE;
k--;
lp[n] = Long.MIN_VALUE;
Arrays.sort(lp);
for (int i = n; i > n - k; i--) {
ret += lp[i];
}
out.println(ret);
out.close();
in.close();
}
}
| Java | ["5 2\n-1 -2 5 -4 8", "7 6\n-3 0 -1 -2 -2 -4 -1", "4 1\n3 -1 6 0"] | 2 seconds | ["15", "-45", "8"] | null | Java 8 | standard input | [
"sortings",
"greedy"
] | c7a37e8220d5fc44556dff66c1e129e7 | The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 3 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$ |a_i| \le 10^6$$$). | 1,900 | Print the maximum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ nonempty consecutive subarrays. | standard output | |
PASSED | 66254f31799593105a28d60d1973edfc | train_003.jsonl | 1559745300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ and an integer $$$k$$$.You are asked to divide this array into $$$k$$$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $$$f(i)$$$ be the index of subarray the $$$i$$$-th element belongs to. Subarrays are numbered from left to right and from $$$1$$$ to $$$k$$$.Let the cost of division be equal to $$$\sum\limits_{i=1}^{n} (a_i \cdot f(i))$$$. For example, if $$$a = [1, -2, -3, 4, -5, 6, -7]$$$ and we divide it into $$$3$$$ subbarays in the following way: $$$[1, -2, -3], [4, -5], [6, -7]$$$, then the cost of division is equal to $$$1 \cdot 1 - 2 \cdot 1 - 3 \cdot 1 + 4 \cdot 2 - 5 \cdot 2 + 6 \cdot 3 - 7 \cdot 3 = -9$$$.Calculate the maximum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ non-empty consecutive subarrays. | 256 megabytes | import java.io.*;
import java.lang.instrument.Instrumentation;
import java.util.*;
import java.util.function.Function;
import java.util.stream.*;
public class Main {
static class FastReader {
BufferedReader br;
StringTokenizer st;
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());
}
}
public static class MyObject<T> {
int first;
T second;
MyObject(int i, T j) {
this.first = i;
this.second = j;
}
}
static class Vertex {
int vertextId;
List<Vertex> adjacentVertices;
Vertex(int id) {
this.vertextId = id;
adjacentVertices = new ArrayList<>();
}
void addEdge(Vertex vertex) {
adjacentVertices.add(vertex);
}
}
static class Graph {
int numberOfVertices;
List<Vertex> vertices;
List<Integer> lowestIndex;
List<Integer> indexes;
Set<MyObject> bridges;
Set<Integer> cuttingVertices;
Graph(int n) {
this.numberOfVertices = n;
this.vertices = new ArrayList<>();
this.lowestIndex = new ArrayList<>();
this.indexes = new ArrayList<>();
this.bridges = new HashSet<>();
this.cuttingVertices = new HashSet<>();
IntStream.rangeClosed(0, n).boxed().map(Vertex::new).forEach(vertices::add);
IntStream.range(0, n).boxed().map(integer -> 0).forEach(lowestIndex::add);
IntStream.range(0, n).boxed().map(integer -> 0).forEach(indexes::add);
}
List<Vertex> getVertices(int u) {
return this.vertices.get(u).adjacentVertices;
}
void addEdge(int u, int v) {
Vertex vertexU = vertices.get(u);
Vertex vertexV = vertices.get(v);
vertexU.addEdge(vertexV);
vertexV.addEdge(vertexU);
}
boolean isNotVisited(int u) {
return indexes.get(u).equals(0);
}
int getLowestIndex(int u) {
return lowestIndex.get(u);
}
int getIndex(int u) {
return indexes.get(u);
}
void setIndex(int u, int value) {
indexes.set(u, value);
}
void setLowestIndex(int u, int value) {
lowestIndex.set(u, value);
}
void increaseBridge(int u, int v) {
this.bridges.add(new MyObject<>(u, v));
}
void increaseCuttingVertex(int u) {
this.cuttingVertices.add(u);
}
}
public static void main(String[] args) {
FastReader fr = new FastReader();
PrintWriter out = new PrintWriter(System.out);
int n = fr.nextInt();
int k = fr.nextInt();
List<Integer> input = IntStream.range(0, n).boxed().map(i -> fr.nextInt()).collect(Collectors.toList());
List<Long> sumUp = new ArrayList<>();
sumUp.add((long) input.get(0));
IntStream.range(1, n).boxed().map(i -> (long) input.get(i) + sumUp.get(i - 1)).forEach(sumUp::add);
List<Long> sortedSumUp = sumUp.stream().limit(n - 1).sorted().collect(Collectors.toList());
long pick = sortedSumUp.stream().limit(k - 1).reduce(0L, (a, b) -> a + b);
long result = sumUp.get(n - 1) * k - pick;
System.out.println(result);
out.close();
}
private static List<String> patition(String s) {
List<String> result = new ArrayList<>();
int count = 1;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append('(');
for (int i = 1; i < s.length(); i++) {
stringBuilder.append(s.charAt(i));
count += (s.charAt(i) == '(' ? 1 : -1);
if (count == 0) {
result.add(stringBuilder.toString());
stringBuilder = new StringBuilder();
}
}
return result;
}
private static String getResult(String s, int res) {
int count = 0;
Stack<MyObject<Character>> stack = new Stack<>();
Stack<MyObject<Integer>> stackResult = new Stack<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
MyObject<Character> myObject = new MyObject<>(i, c);
if (c == '(') {
stack.push(myObject);
if (count > 0)
count--;
if (!stackResult.isEmpty())
stackResult.pop();
} else {
count++;
MyObject<Character> inStack = stack.pop();
stackResult.push(new MyObject<>(inStack.first, i));
if (count == res) {
break;
}
}
}
final Set<Integer> set = new HashSet<>();
stackResult.forEach(integerMyObject -> {
set.add(integerMyObject.first);
set.add(integerMyObject.second);
});
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
stringBuilder.append(set.contains(i) ? 1 : 0);
}
return stringBuilder.toString();
}
private static int getDept(String s) {
int count = 0;
int max = 0;
for (int i = 0; i < s.length(); i++) {
count += (s.charAt(i) == '(') ? 1 : -1;
max = Math.max(max, count);
}
return max;
}
} | Java | ["5 2\n-1 -2 5 -4 8", "7 6\n-3 0 -1 -2 -2 -4 -1", "4 1\n3 -1 6 0"] | 2 seconds | ["15", "-45", "8"] | null | Java 8 | standard input | [
"sortings",
"greedy"
] | c7a37e8220d5fc44556dff66c1e129e7 | The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 3 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$ |a_i| \le 10^6$$$). | 1,900 | Print the maximum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ nonempty consecutive subarrays. | standard output | |
PASSED | 2b255f6cee6b2c070659e1a4af918c1c | train_003.jsonl | 1559745300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ and an integer $$$k$$$.You are asked to divide this array into $$$k$$$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $$$f(i)$$$ be the index of subarray the $$$i$$$-th element belongs to. Subarrays are numbered from left to right and from $$$1$$$ to $$$k$$$.Let the cost of division be equal to $$$\sum\limits_{i=1}^{n} (a_i \cdot f(i))$$$. For example, if $$$a = [1, -2, -3, 4, -5, 6, -7]$$$ and we divide it into $$$3$$$ subbarays in the following way: $$$[1, -2, -3], [4, -5], [6, -7]$$$, then the cost of division is equal to $$$1 \cdot 1 - 2 \cdot 1 - 3 \cdot 1 + 4 \cdot 2 - 5 \cdot 2 + 6 \cdot 3 - 7 \cdot 3 = -9$$$.Calculate the maximum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ non-empty consecutive subarrays. | 256 megabytes | import sun.reflect.generics.tree.Tree;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt(), k = in.nextInt();
long[] a = new long[n];
long sum = 0;
long check = 0;
for(int i = 0; i < n; i++) {
a[i] = in.nextInt();
check += a[i];
sum += a[i] * (i + 1);
}
//if(n == 300000) println(sum);
long[] suf = new long[n];
suf[n - 1] = a[n - 1];
for(int i = n - 2; i >= 0; i--) {
suf[i] = suf[i + 1] + a[i];
}
TreeMap<Long, Integer> s = new TreeMap<>();
long sec = 0;
for(int pos = 1; pos < suf.length; pos++) {
long i = suf[pos];
sec += i;
if(s.containsKey(i)) {
s.put(i, s.get(i) + 1);
} else {
s.put(i, 1);
}
}
for(int i = 0; i < n - k; i++) {
long cur = s.firstKey();
if(s.get(cur).equals(1)) s.remove(cur);
else s.put(cur, s.get(cur) - 1);
sum -= cur;
}
println(sum);
}
public static void print(Object o) {
System.out.print(o.toString());
}
public static void println(Object o) {
System.out.println(o.toString());
}
}
| Java | ["5 2\n-1 -2 5 -4 8", "7 6\n-3 0 -1 -2 -2 -4 -1", "4 1\n3 -1 6 0"] | 2 seconds | ["15", "-45", "8"] | null | Java 8 | standard input | [
"sortings",
"greedy"
] | c7a37e8220d5fc44556dff66c1e129e7 | The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 3 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$ |a_i| \le 10^6$$$). | 1,900 | Print the maximum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ nonempty consecutive subarrays. | standard output | |
PASSED | 5ff822de8a2a39a32a742d40cc39b4ba | train_003.jsonl | 1559745300 | You are given an array $$$a_1, a_2, \dots, a_n$$$ and an integer $$$k$$$.You are asked to divide this array into $$$k$$$ non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let $$$f(i)$$$ be the index of subarray the $$$i$$$-th element belongs to. Subarrays are numbered from left to right and from $$$1$$$ to $$$k$$$.Let the cost of division be equal to $$$\sum\limits_{i=1}^{n} (a_i \cdot f(i))$$$. For example, if $$$a = [1, -2, -3, 4, -5, 6, -7]$$$ and we divide it into $$$3$$$ subbarays in the following way: $$$[1, -2, -3], [4, -5], [6, -7]$$$, then the cost of division is equal to $$$1 \cdot 1 - 2 \cdot 1 - 3 \cdot 1 + 4 \cdot 2 - 5 \cdot 2 + 6 \cdot 3 - 7 \cdot 3 = -9$$$.Calculate the maximum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ non-empty consecutive subarrays. | 256 megabytes | import java.util.*;
import java.io.*;
import static java.lang.Math.max;
import static java.lang.Math.min;
import static java.lang.Math.abs;
public class ArraySplitting {
private static InputReader in;
private static PrintWriter out;
public static void main(String[] args) {
new ArraySplitting().run();
}
private static class InputReader {
private final InputStream is;
private final byte[] inbuf = new byte[1024];
private int lenbuf = 0;
private int ptrbuf = 0;
public InputReader(InputStream stream) {
is = stream;
}
private int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
public double nextDouble() {
return Double.parseDouble(nextString());
}
public char nextChar() {
return (char) skip();
}
public String nextString() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public char[] nextString(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
public int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public long nextLong() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
}
private static final boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private static void debug(Object... o) {
if (!oj) {
System.out.println(Arrays.deepToString(o));
}
}
/*==================================================================================================================*/
final long INF = (long) 1e18;
int n, k;
int[] a;
void solve() {
n = in.nextInt();
k = in.nextInt();
a = new int[n];
Arrays.setAll(a, i -> in.nextInt());
long[] suff = new long[n];
suff[n - 1] = a[n - 1];
for (int i = n - 2; i >= 0; i--) {
suff[i] = suff[i + 1] + a[i];
}
long ans = suff[0];
suff[0] = -INF;
sort(suff);
for (int i = n - 1; i >= n - (k - 1); i--) {
ans += suff[i];
}
out.println(ans);
}
void sort(long[] a) {
Long[] sorted = new Long[a.length];
Arrays.setAll(sorted, i -> a[i]);
Arrays.sort(sorted);
Arrays.setAll(a, i -> sorted[i]);
}
public void run() {
in = new InputReader(System.in);
out = new PrintWriter(System.out);
int tt = 1;
// int tt = in.nextInt();
for (int i = 1; i <= tt; i++) {
solve();
}
out.flush();
}
} | Java | ["5 2\n-1 -2 5 -4 8", "7 6\n-3 0 -1 -2 -2 -4 -1", "4 1\n3 -1 6 0"] | 2 seconds | ["15", "-45", "8"] | null | Java 8 | standard input | [
"sortings",
"greedy"
] | c7a37e8220d5fc44556dff66c1e129e7 | The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 3 \cdot 10^5$$$). The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$ |a_i| \le 10^6$$$). | 1,900 | Print the maximum cost you can obtain by dividing the array $$$a$$$ into $$$k$$$ nonempty consecutive subarrays. | standard output | |
PASSED | 17ee904c6597a793f5ce88a3147a0573 | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.util.Scanner;
public class TaskA {
static int c;
static int n;
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
n = scan.nextInt();
c = 0;
scan.nextLine();
char[] t = scan.nextLine().toCharArray();
for(int i = 0; i < n; i++){
if (t[i] == '<') c += 1; else break;
}
for(int i = n-1; i >= 0; i--){
if (t[i] == '>') c += 1; else break;
}
System.out.println(Math.abs(c));
}
}
| Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 8956494c62854f6473e317c6d2e2321d | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
sc.nextInt();
String s = sc.next();
System.out.println(solve(s));
sc.close();
}
static int solve(String s) {
int leftLength = 0;
while (leftLength < s.length() && s.charAt(leftLength) == '<') {
leftLength++;
}
int rightLength = 0;
while (rightLength < s.length() && s.charAt(s.length() - 1 - rightLength) == '>') {
rightLength++;
}
return leftLength + rightLength;
}
}
| Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | bbb88f1c52d46ae54061410e11855b24 | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.util.Scanner;
public class JumpingBall {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt(), c = 0;
char[] in = scan.next().toCharArray();
for(int i = 0; i < n && in[i] == '<'; i++)c++;
for(int i = n-1; i >= 0 && in[i] == '>'; i--)c++;
System.out.println(c);
}
}
| Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 3a4b4b8760a35fc02e4af8166892fdc6 | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class A {
static boolean fall[];
static boolean vis[];
static int n;
static String s;
public static void main(String[] args) throws NumberFormatException, IOException {
Scanner sc = new Scanner();
PrintWriter out = new PrintWriter(System.out);
n = sc.nextInt();
s = sc.next();
fall = new boolean[n];
int start = 0;
int end = n - 1;
while(start < n && s.charAt(start) == '<')
fall[start++] = true;
while(end >= 0 && s.charAt(end) == '>')
fall[end--] = true;
int count = 0;
for(int i = 0; i < n; i++)
if(fall[i])
count++;
out.println(count);
out.flush();
out.close();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() throws IOException {
while(st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
int nextInt() throws NumberFormatException, IOException {
return Integer.parseInt(next());
}
}
}
| Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | cab7b5e12349ea57952bb5a10c8c898f | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner capt = new Scanner(System.in);
int n = capt.nextInt();
String x = capt.next();
System.out.println(solution(x));
}
static int solution(String x){
int count = 0;
if(x.charAt(0) == '<'){
int a = x.indexOf('>');
if(a == -1){
return x.length();
}else count+= x.indexOf('>');
}
if(x.charAt(x.length()-1) == '>'){
for(int i=x.length()-1;i>=0;i--){
if(x.charAt(i) == '<')break;
else count++;
}
}
return count;
}
}
| Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 78b74242231d4ec4118bdb98f8c4b0d5 | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//package javaapplication1;
import java.util.Scanner;
/**
*
* @author TaMeEm
*/
public class JavaApplication1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
int n;
Scanner in=new Scanner(System.in);
n=in.nextInt();
String s;
s=in.next();
int cnt=0;
if(s.charAt(0)=='<')
{
cnt++;
int i=1;
while(i<n&&s.charAt(i)=='<')
{
cnt++;
i++;
}
}
if(s.charAt(n-1)=='>')
{
cnt++;
int i=n-2;
while(i>=0&&s.charAt(i)=='>')
{
cnt++;
i--;
}
}
System.out.println(cnt);
}
}
| Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 8bb6845deae841d2558459b72c02b6a2 | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskCFCC16A solver = new TaskCFCC16A();
solver.solve(1, in, out);
out.close();
}
static class TaskCFCC16A {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
char[] ar = in.next().toCharArray();
int[] stuck = new int[n];
for (int i = 0; i < n; i++) {
// simulate;
int j = i;
int prev = j;
while (true) {
if (ar[j] == '>') {
j += 1;
} else {
j -= 1;
}
if (j < 0 || j > n - 1 || stuck[j] == 2) {
j = (j < 0) ? 0 : j;
j = (j > n - 1) ? n - 1 : j;
// falloff; start at i and falloff.
if (j < i) {
for (int k = j; k <= i; k++) {
stuck[k] = 2;
}
} else {
for (int k = i; k <= j; k++) {
stuck[k] = 2;
}
}
break;
}
if (ar[prev] != ar[j] || stuck[j] == 1) {
// stuck.
if (j < i) {
for (int k = j; k <= i; k++) {
stuck[k] = 1;
}
} else {
for (int k = i; k <= j; k++) {
stuck[k] = 1;
}
}
break;
}
}
}
int count = 0;
for (int i = 0; i < n; i++) {
if (stuck[i] == 2) {
count++;
}
}
out.println(count);
}
}
}
| Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | e0213150f1390c1de838fc9dcaea46bf | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.util.Scanner;
public class jb{
public static void main(String args[]){
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int count = 0;
String seq = s.next();
String[] arr = seq.split("");
if(arr.length != n){
System.exit(0);
}
int len = arr.length-1;
int i = 1;
int k = len-1;
if(arr[0].equals(">") && arr[len].equals("<")){
System.out.println(count);
System.exit(0);
}if(arr[0].equals("<")){
count++;
while(i <= len && arr[i].equals("<")){
count++;
i++;
}
}if(arr[len].equals(">")){
count++;
while( k >= 0 && arr[k].equals(">")){
count++;
k--;
}
}
System.out.println(count);
}
} | Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | ef3aaa56bdef2113f178a96e2c85e95d | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
import java.util.stream.*;
@SuppressWarnings("unchecked")
public class P725A {
public void run() throws Exception {
int n = nextInt();
String s = next();
BitSet tol = new BitSet(n), tor = new BitSet(n);
for (int i = 0; i < n; i++) {
((s.charAt(i) == '<') ? tol : tor).set(i);
}
int p = 0;
for (int i = 0; i < n; i++) {
p += (s.charAt(i) == '<') ? ((tor.previousSetBit(i) == -1) ? 1 : 0)
: ((tol.nextSetBit(i) == -1) ? 1 : 0);
}
println(p);
}
public static void main(String... args) throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedOutputStream(System.out));
new P725A().run();
br.close();
pw.close();
System.err.println("\n[Time : " + (System.currentTimeMillis() - startTime) + " ms]");
}
static long startTime = System.currentTimeMillis();
static BufferedReader br;
static PrintWriter pw;
StringTokenizer stok;
String nextToken() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
String s = br.readLine();
if (s == null) { return null; }
stok = new StringTokenizer(s);
}
return stok.nextToken();
}
void print(byte b) { print("" + b); }
void print(int i) { print("" + i); }
void print(long l) { print("" + l); }
void print(double d) { print("" + d); }
void print(char c) { print("" + c); }
void print(Object o) {
if (o instanceof int[]) { print(Arrays.toString((int [])o));
} else if (o instanceof long[]) { print(Arrays.toString((long [])o));
} else if (o instanceof char[]) { print(Arrays.toString((char [])o));
} else if (o instanceof byte[]) { print(Arrays.toString((byte [])o));
} else if (o instanceof short[]) { print(Arrays.toString((short [])o));
} else if (o instanceof boolean[]) { print(Arrays.toString((boolean [])o));
} else if (o instanceof float[]) { print(Arrays.toString((float [])o));
} else if (o instanceof double[]) { print(Arrays.toString((double [])o));
} else if (o instanceof Object[]) { print(Arrays.toString((Object [])o));
} else { print("" + o); }
}
void print(String s) { pw.print(s); }
void println() { println(""); }
void println(byte b) { println("" + b); }
void println(int i) { println("" + i); }
void println(long l) { println("" + l); }
void println(double d) { println("" + d); }
void println(char c) { println("" + c); }
void println(Object o) { print(o); println(); }
void println(String s) { pw.println(s); }
int nextInt() throws IOException { return Integer.parseInt(nextToken()); }
long nextLong() throws IOException { return Long.parseLong(nextToken()); }
double nextDouble() throws IOException { return Double.parseDouble(nextToken()); }
char nextChar() throws IOException { return (char) (br.read()); }
String next() throws IOException { return nextToken(); }
String nextLine() throws IOException { return br.readLine(); }
int [] readInt(int size) throws IOException {
int [] array = new int [size];
for (int i = 0; i < size; i++) { array[i] = nextInt(); }
return array;
}
long [] readLong(int size) throws IOException {
long [] array = new long [size];
for (int i = 0; i < size; i++) { array[i] = nextLong(); }
return array;
}
double [] readDouble(int size) throws IOException {
double [] array = new double [size];
for (int i = 0; i < size; i++) { array[i] = nextDouble(); }
return array;
}
String [] readLines(int size) throws IOException {
String [] array = new String [size];
for (int i = 0; i < size; i++) { array[i] = nextLine(); }
return array;
}
int gcd(int a, int b) {
return ((b > 0) ? gcd(b, a % b) : a);
}
} | Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 52ed5ee33458738c776c88ee59bd4ce7 | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
import java.util.stream.*;
@SuppressWarnings("unchecked")
public class P725A {
public void run() throws Exception {
int n = nextInt();
String s = next();
TreeSet<Integer> tol = new TreeSet();
TreeSet<Integer> tor = new TreeSet();
for (int i = 0; i < n; i++) {
((s.charAt(i) == '<') ? tol : tor).add(i);
}
int p = 0;
for (int i = 0; i < n; i++) {
p += (s.charAt(i) == '<') ? (( tor.floor(i) == null) ? 1 : 0)
: ((tol.higher(i) == null) ? 1 : 0);
}
println(p);
}
public static void main(String... args) throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new BufferedOutputStream(System.out));
new P725A().run();
br.close();
pw.close();
System.err.println("\n[Time : " + (System.currentTimeMillis() - startTime) + " ms]");
}
static long startTime = System.currentTimeMillis();
static BufferedReader br;
static PrintWriter pw;
StringTokenizer stok;
String nextToken() throws IOException {
while (stok == null || !stok.hasMoreTokens()) {
String s = br.readLine();
if (s == null) { return null; }
stok = new StringTokenizer(s);
}
return stok.nextToken();
}
void print(byte b) { print("" + b); }
void print(int i) { print("" + i); }
void print(long l) { print("" + l); }
void print(double d) { print("" + d); }
void print(char c) { print("" + c); }
void print(Object o) {
if (o instanceof int[]) { print(Arrays.toString((int [])o));
} else if (o instanceof long[]) { print(Arrays.toString((long [])o));
} else if (o instanceof char[]) { print(Arrays.toString((char [])o));
} else if (o instanceof byte[]) { print(Arrays.toString((byte [])o));
} else if (o instanceof short[]) { print(Arrays.toString((short [])o));
} else if (o instanceof boolean[]) { print(Arrays.toString((boolean [])o));
} else if (o instanceof float[]) { print(Arrays.toString((float [])o));
} else if (o instanceof double[]) { print(Arrays.toString((double [])o));
} else if (o instanceof Object[]) { print(Arrays.toString((Object [])o));
} else { print("" + o); }
}
void print(String s) { pw.print(s); }
void println() { println(""); }
void println(byte b) { println("" + b); }
void println(int i) { println("" + i); }
void println(long l) { println("" + l); }
void println(double d) { println("" + d); }
void println(char c) { println("" + c); }
void println(Object o) { print(o); println(); }
void println(String s) { pw.println(s); }
int nextInt() throws IOException { return Integer.parseInt(nextToken()); }
long nextLong() throws IOException { return Long.parseLong(nextToken()); }
double nextDouble() throws IOException { return Double.parseDouble(nextToken()); }
char nextChar() throws IOException { return (char) (br.read()); }
String next() throws IOException { return nextToken(); }
String nextLine() throws IOException { return br.readLine(); }
int [] readInt(int size) throws IOException {
int [] array = new int [size];
for (int i = 0; i < size; i++) { array[i] = nextInt(); }
return array;
}
long [] readLong(int size) throws IOException {
long [] array = new long [size];
for (int i = 0; i < size; i++) { array[i] = nextLong(); }
return array;
}
double [] readDouble(int size) throws IOException {
double [] array = new double [size];
for (int i = 0; i < size; i++) { array[i] = nextDouble(); }
return array;
}
String [] readLines(int size) throws IOException {
String [] array = new String [size];
for (int i = 0; i < size; i++) { array[i] = nextLine(); }
return array;
}
int gcd(int a, int b) {
return ((b > 0) ? gcd(b, a % b) : a);
}
} | Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 058ffb33857f3aaa071a657bee195c0a | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Uber_Pwner
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int N = in.readInt();
char[] bu = in.readLine().toCharArray();
int count = 0;
int posc = 0;
int i = 0;
while (i < bu.length && bu[i] == '<') {
posc++;
count++;
i++;
}
i = bu.length - 1;
while (posc < bu.length && bu[i] == '>') {
posc++;
count++;
i--;
}
out.printLine(count);
}
}
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;
}
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 interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void close() {
writer.close();
}
public void printLine(int i) {
writer.println(i);
}
}
}
| Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 9710de45a33680bcd97549bfaeb9a051 | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.io.*;
import java.util.*;
public class A1008 {
public static void main(String [] args) /*throws Exception*/ {
InputStream inputReader = System.in;
OutputStream outputReader = System.out;
InputReader in = new InputReader(inputReader);//new InputReader(new FileInputStream(new File("input.txt")));new InputReader(inputReader);
PrintWriter out = new PrintWriter(outputReader);//new PrintWriter(new FileOutputStream(new File("output.txt")));
Algorithm solver = new Algorithm();
solver.solve(in, out);
out.close();
}
}
class Algorithm {
void solve(InputReader ir, PrintWriter pw) {
int n = ir.nextInt(), first = 0, second = 0;
String line = ir.next();
char [] directions = line.toCharArray();
for (int i = 0; i < n; i++) {
if (directions[i] == '<') first++;
else break;
}
for (int i = n - 1; i >= 0; i--) {
if (directions[i] == '>') second++;
else break;
}
pw.print(first + second);
}
}
class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
String nextLine(){
String fullLine = null;
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
fullLine = reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return fullLine;
}
return fullLine;
}
String [] toArray() {
return nextLine().split(" ");
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
} | Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 62d5471543ea9ba6efb2de76871f9e25 | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.util.Scanner;
public class Main {
public static Scanner sc=new Scanner(System.in);
public static void main(String[] args) {
while(sc.hasNext()) {
int n=sc.nextInt();
String s=sc.next();
int i=s.indexOf('>');
int j=s.lastIndexOf('<');
if(i==-1||j==-1)
System.out.println(n);
else
System.out.println(n-j+i-1);
}
}
} | Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 28a019fe53746f21a6a60bd72e9014b8 | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.util.HashMap;
import java.util.Scanner;
public class R725A {
static Scanner in = new Scanner(System.in);
public static void solve(){
int n= in.nextInt();
in.nextLine();
char[] arr = in.nextLine().toCharArray();
int ans = 0;
if(arr[0] == '<'){
for(int i = 0;i<n;i++)
{
if(arr[i] =='<')
{
ans++;
}
else{
break;
}
}
}
if(arr[n-1] == '>'){
for(int i = n-1;i>=0;i--)
{
if(arr[i] =='>')
{
ans++;
}
else{
break;
}
}
}
System.out.println(ans);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static HashMap charOrderMap(HashMap inputMap,String orderingString,int startFrom,boolean charAsKey){
char[] chars = orderingString.toCharArray();
if(charAsKey){
for(int i = 0;i< chars.length;i++){
inputMap.put(chars[i], i);
}
}
else{
for(int i = 0;i< chars.length;i++){
inputMap.put(i, chars[i]);
}
}
return inputMap;
}
public static void main(String args[]) {
solve();
}
}
| Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | aa4dc004ddb056069923fc90fcf4e27f | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
public class A {
public static void main(String[] args)throws Exception{
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int size = Integer.parseInt(input.readLine());
String moves = input.readLine();
int counter = 0;
boolean[] directionsR = new boolean[size];
directionsR[0] = moves.charAt(0) == '<';
for(int i = 1; i < size; i++){
if(directionsR[i-1] && moves.charAt(i) == '<'){
directionsR[i] = true;
}
}
boolean[] directionsL = new boolean[size];
directionsL[size-1] = moves.charAt(size-1) == '>';
for(int i = size-2; i >= 0; i--){
if(directionsL[i+1] && moves.charAt(i) == '>'){
directionsL[i] = true;
}
}
for (int i = 0; i < size; i++) {
if(directionsL[i] || directionsR[i])
counter++;
}
System.out.println(counter);
}
} | Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 89f8b8b439d5b0316de9a19cda82c227 | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class JumpingBall {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String s = br.readLine();
br.close();
int cnt = 0;
for (int i = 0; i < n; i++) {
if (s.charAt(i) == '>')
break;
cnt++;
}
for (int i = n - 1; i >= 0; i--) {
if (s.charAt(i) == '<')
break;
cnt++;
}
System.out.println(cnt);
}
}
| Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 115aafa363ff8aa293344ccc39663c00 | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.util.*;
public class Jumping_Ball {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
String s = input.next();
input.close();
int counter1 = 0;
for (int i = 0; i < n; i++) {
if (s.charAt(i) == '>') {
break;
}
counter1++;
}
int counter2 = 0;
for (int i = n - 1; i >= 0; i--) {
if (s.charAt(i) == '<') {
break;
}
counter2++;
}
int ans = counter1 + counter2;
System.out.println(ans);
}
}
| Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 73db7a9ede8fd1d16d9d9d87467d1b6c | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.util.Scanner;
/**
* Created by ΠΠΠ‘ on 22.10.16.
*/
public class ClassA {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int ans = 0, i = 0;
String s = sc.next();
if (s.charAt(0) == '<') do { i++; ans++;} while ( i<n && s.charAt(i) == '<');
i = n-1;
if (s.charAt(n-1) == '>') do { i--; ans++;} while ( i>=0 && s.charAt(i) == '>');
System.out.print(ans);
}
}
| Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 5ad8d49377ffdca0d6beb30642c22e54 | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes |
import static java.lang.System.in;
import static java.lang.System.out;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.stream.IntStream;
public class Main {
static int n;
static String x;
static int t1, t2;
public static void main(String[] args) {
FastReader input = new FastReader();
init(input);
for (int i = 0; i < n; i++) {
if (x.charAt(i) == '>')
break;
t1++;
}
for (int i = n - 1; i >= 0; i--) {
if (x.charAt(i) == '<')
break;
t2++;
}
out.println(t1 + t2);
}
static void init(FastReader reader) {
n = reader.nextInt();
x = reader.nextLine();
}
public static class FastReader {
BufferedReader br;
StringTokenizer st;
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 string = "";
try {
string = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return string;
}
char nextChar() {
return next().charAt(0);
}
}
}
| Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | cc22c687ca948af03e73da5e80605d38 | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | //package CanadaCup;
import java.util.Scanner;
/**
*
* @author vaio pc
*/
public class CanadaCupA {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
String s=sc.next();
char a[]=s.toCharArray();
int fall=0;
int i=0,j=n-1;
if(a[0]=='<'){
// fall++;
// i++;
while(i<=n-1 && a[i]=='<'){
fall++;
i++;
}
}
if(a[n-1]=='>' && j>i-1){
// fall++;
// j--;
while(j>=0 && a[j]=='>'){
fall++;
j--;
}
}
System.out.println(fall);
}
}
| Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 8f8d90878bc888b91e72ecfc9b89c8e1 | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes |
import java.io.*;
import java.util.*;
import java.math.*;
import static java.lang.Math.*;
import static java.lang.Integer.parseInt;
import static java.lang.Long.parseLong;
import static java.lang.Double.parseDouble;
import static java.lang.String.*;
public class Main {
static int n;
static String s;
static int [] dp;
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder out = new StringBuilder();
StringTokenizer tk;
n = parseInt(in.readLine());
s = in.readLine();
int cnt = 0;
for(int i=0; i<n && s.charAt(i)=='<'; i++)
cnt++;
for(int i=n-1; i>=0 && s.charAt(i)=='>'; i--)
cnt++;
System.out.println(cnt);
}
static int calc(int i) {
if(i<0 || i>=n)
return 1;
if(dp[i]!=-1)
return dp[i];
int r;
if(s.charAt(i)=='<') r = calc(i-1);
else r = calc(i+1);
return dp[i] = r;
}
}
| Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 4dab66fc1b841c04f8e72cc4d1f97057 | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.io.*;
import java.util.*;
import static java.lang.Math.abs;
//that moment when your internet goes out when you're about to submit the correct solution
public class CF725A {
public static void main(String[] args) {
MyScanner in = new MyScanner();
int x = in.nextInt();
String string = in.next();
int result = 0;
for(int i=0;i<x;++i){
if(string.charAt(i)=='<'){
result++;
}else{
break;
}
}
for(int i=x-1;i>=0;--i){
if(string.charAt(i)=='>'){
result++;
}else{
break;
}
}
System.out.println(result);
}
public static class MyScanner {
//first buffered reader attempt rip
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | eda4b1d44925909a11108f4df523c32e | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Scanner;
public class A {
private void work() {
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int n = sc.nextInt();
char[] s = sc.next().toCharArray();
sc.close();
int res = 0;
for (int i = 0; i < n; i++) {
if (s[i] != '<')
break;
res++;
}
for (int i = n - 1; i >= 0; i--) {
if (s[i] != '>')
break;
res++;
}
System.out.println(res);
}
public static void main(String[] args) {
new A().work();
}
}
| Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 35f71f85ea3e37ca69276d4af6f65df2 | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes |
import java.io.BufferedReader;
import java.io.FileReader;
import java.text.DecimalFormat;
import java.util.*;
import java.util.regex.Matcher;
public class Main {
private static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
while (sc.hasNextInt()){
int n = sc.nextInt();
sc.nextLine();
String line = sc.nextLine();
int count = 0;
if(line.charAt(0) != '<' && line.charAt(n-1) != '>'){
count = 0;
}else {
Set<Integer> leftSet = new HashSet<>();
Set<Integer> rightSet = new HashSet<>();
if(line.charAt(0) == '<'){
count++;
for(int i = 1; i < n; i++){
if(line.charAt(i) == '<'){
leftSet.add(i);
}else {
break;
}
}
}
if(line.charAt(n-1) == '>'){
count++;
for(int i = n-2; i >= 0; i--){
if(line.charAt(i) == '>'){
rightSet.add(i);
}else {
break;
}
}
}
leftSet.addAll(rightSet);
count += leftSet.size();
}
System.out.println(Math.abs(count));
}
}
} | Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 8b219a94c99fe1e39f15f2f5713f2542 | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.util.*;
public class MainA {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine());
String line = sc.nextLine();
int res = 0;
for (int i = 0; i <= n - 1; i++) {
if (line.charAt(i) == '<') {
res += 1;
} else {
break;
}
}
for (int i = n - 1; i >= 0; i--) {
if (line.charAt(i) == '>') {
res += 1;
} else {
break;
}
}
System.out.println(res);
}
} | Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 2cc8559c3992ed0b00ffbaeb7c9dd29b | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.util.*;
import java.io.*;
import java.lang.*;
public class A725 {
public static void main(String[] args) {
int length;
String given;
boolean first = false;
boolean last = false;
Scanner s = new Scanner(System.in);
length = s.nextInt();
given = s.next();
int firstlocation = length;
for(int i=0; i<length && !first; i++){
if(given.charAt(i) == '>'){
firstlocation = i;
first = true;
}
}
int lastLocation = firstlocation;
for(int i=length-1; i>=firstlocation && !last; i--){
if(given.charAt(i) == '<'){
lastLocation = i+1;
last = true;
}
}
System.out.println(firstlocation + length - lastLocation);
}
}
| Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | a388cd4c5018f5feacba760fddd03784 | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.io.*;
import java.util.*;
public class A {
public static void main(String[]args)throws Throwable{
PrintWriter pw=new PrintWriter(System.out);
MyScanner sc=new MyScanner();
int n=sc.nextInt();
String s=sc.next();
char[] a=s.toCharArray();
int p1=-1,p2=-1;
for(int i=0;i<n;i++){
if(a[i]=='<')
p2=i;
}
for(int i=n-1;i>=0;i--){
if(a[i]=='>')
p1=i;
}
int cnt=0;
for(int i=0;i<n;i++){
if(a[i]=='>'){
if(p2==-1 || p2<i)
cnt++;
}else{
if(p1==-1 || p1>i)
cnt++;
}
}
pw.println(cnt);
pw.flush();
pw.close();
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
| Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 7dfdac0af3364ef3a0ba9aa323481913 | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
public class JumpingBall {
public static void main(String[] args) {
FastScanner I = new FastScanner(); //Input
OutPut O = new OutPut(); //Output
int ans = 0;
int N = I.nextInt();
String S = I.next();
for (int i = 0; i < N; i++) {
if (S.charAt(i)=='>') break;
ans++;
}
for (int i = N-1; i >= 0; i--) {
if (S.charAt(i)=='<') break;
ans++;
}
O.pln(ans);
}
public static long ceil(long num, long den) {long ans = num/den; if (num%den!=0)
ans++; return ans;}
public static long GCD(long a, long b) {
if (a==0||b==0) return Math.max(a,b);
return GCD(Math.min(a, b),Math.max(a, b)%Math.min(a, b));
}
public static long FastExp(long base, long exp, long mod) {
long ans=1;
while (exp>0) {
if (exp%2==1) ans*=base;
exp/=2;
base*=base;
base%=mod;
ans%=mod;
}
return ans;
}
public static long ModInv(long num,long mod) {return FastExp(num,mod-2,mod);}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!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());};
}
static class OutPut{
PrintWriter w = new PrintWriter(System.out);
void pln(int x) {w.println(x);w.flush();}
void pln(long x) {w.println(x);w.flush();}
void pln(String x) {w.println(x);w.flush();}
void pln(char x) {w.println(x);w.flush();}
void pln(StringBuilder x) {w.println(x);w.flush();}
void p(int x) {w.print(x);w.flush();}
void p(long x) {w.print(x);w.flush();}
void p(String x) {w.print(x);w.flush();}
void p(char x) {w.print(x);w.flush();}
void p(StringBuilder x) {w.print(x);w.flush();}
}
} | Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 9929860134c5c2d7d979dd08f6f5ff07 | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
public class JumpingBall {
public static void main(String[] args) {
FastScanner I = new FastScanner(); //Input
OutPut O = new OutPut(); //Output
int ans = 0;
int N = I.nextInt();
int L = 0;
int R = 0;
String S = I.next();
for (int i = 0; i < N; i++) {
if (S.charAt(i)=='>') break;
L++;
}
for (int i = N-1; i >= 0; i--) {
if (S.charAt(i)=='<') break;
R++;
}
O.pln(L+R);
}
public static long ceil(long num, long den) {long ans = num/den; if (num%den!=0)
ans++; return ans;}
public static long GCD(long a, long b) {
if (a==0||b==0) return Math.max(a,b);
return GCD(Math.min(a, b),Math.max(a, b)%Math.min(a, b));
}
public static long FastExp(long base, long exp, long mod) {
long ans=1;
while (exp>0) {
if (exp%2==1) ans*=base;
exp/=2;
base*=base;
base%=mod;
ans%=mod;
}
return ans;
}
public static long ModInv(long num,long mod) {return FastExp(num,mod-2,mod);}
static class FastScanner {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st=new StringTokenizer("");
String next() {
while (!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());};
}
static class OutPut{
PrintWriter w = new PrintWriter(System.out);
void pln(int x) {w.println(x);w.flush();}
void pln(long x) {w.println(x);w.flush();}
void pln(String x) {w.println(x);w.flush();}
void pln(char x) {w.println(x);w.flush();}
void pln(StringBuilder x) {w.println(x);w.flush();}
void p(int x) {w.print(x);w.flush();}
void p(long x) {w.print(x);w.flush();}
void p(String x) {w.print(x);w.flush();}
void p(char x) {w.print(x);w.flush();}
void p(StringBuilder x) {w.print(x);w.flush();}
}
}
| Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 40abf527a7b523079981cb802dfcf00c | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.util.*;
public class A_JumpingBall {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int ans = 0;
String v = in.next();
char[] s = v.toCharArray();
int i = 0, j = n - 1;
while (s[i] == '<' && i < n) {
ans++;
i++;
if (i == n) {
break;
}
}
while (s[j] == '>' && j >= 0) { // it will stop from first case cuz its wrong s[j]== <
ans++;
j--;
if (j == -1) {
break;
}
}
System.out.println(ans);
}
} | Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | ef8f4a1ccb093def75b8d1c81461c061 | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author o_panda_o(emailofpanda@yahoo.com)
*/
public class Code_725A_JumpingBall{
public static void main(String[] args){
InputStream inputStream=System.in;
OutputStream outputStream=System.out;
InputReader in=new InputReader(inputStream);
OutputWriter out=new OutputWriter(outputStream);
_725A_ solver=new _725A_();
solver.solve(1,in,out);
out.close();
}
static class _725A_{
public void solve(int testNumber,InputReader in,OutputWriter out){
int n=in.nextInt();
String s=in.next();
int counter=0;
for(int i=0;i<n;++i){
if(s.charAt(i)=='<') ++counter;
else break;
}
for(int i=n-1;i>=0;--i){
if(s.charAt(i)=='>') ++counter;
else break;
}
out.print(counter);
}
}
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 print(int i){
writer.print(i);
}
}
static class InputReader{
private InputStream stream;
private byte[] buf=new byte[1024];
private int curChar;
private int numChars;
private InputReader.SpaceCharFilter filter;
public InputReader(InputStream stream){
this.stream=stream;
}
public int read(){
if(numChars==-1){
throw new InputMismatchException();
}
if(curChar>=numChars){
curChar=0;
try{
numChars=stream.read(buf);
}catch(IOException e){
throw new InputMismatchException();
}
if(numChars<=0){
return -1;
}
}
return buf[curChar++];
}
public int nextInt(){
int c=read();
while(isSpaceChar(c)){
c=read();
}
int sgn=1;
if(c=='-'){
sgn=-1;
c=read();
}
int res=0;
do{
if(c<'0' || c>'9'){
throw new InputMismatchException();
}
res*=10;
res+=c-'0';
c=read();
}while(!isSpaceChar(c));
return res*sgn;
}
public 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;
}
public String next(){
return nextString();
}
public interface SpaceCharFilter{
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 171296747b830664f28fa5ac50daf513 | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.util.*;
public class canada {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int size = scan.nextInt();
String s = scan.next();
ArrayList<Integer> index = new ArrayList<Integer>();
for (int i = 0; i < size - 1; i++) {
if (s.charAt(i) == '>' && s.charAt(i + 1) == '<') {
index.add(i);
index.add(i+1);
}
}
if(index.size()==0){
System.out.println(size);
return;
}
int max = Collections.max(index);
int min = Collections.min(index);
int count = 0;
for (int i = 0; i < size; i++) {
if(s.charAt(i)=='<' && i<min){
count++;
}
else if(s.charAt(i)=='>' && i>max){
count++;
}
}
System.out.println(count);
}
}
| Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | b92a275e1a2a5ff3dfe9558a95567ab9 | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | // https://codeforces.com/problemset/problem/725/A
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
int n = Integer.parseInt( read.nextLine() );
String bumpers = read.nextLine();
int numberOfValidStartingPositions = 0;
for (int i = 0; i < n && bumpers.charAt(i) == '<'; ++i) {
numberOfValidStartingPositions++;
}
for (int i = n-1; i >= 0 && bumpers.charAt(i) == '>'; --i) {
numberOfValidStartingPositions++;
}
System.out.println(numberOfValidStartingPositions);
// Close scanner
read.close();
}
} | Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 9fd51d89639b5339d5fc406269c74716 | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.util.*;
import java.io.*;
public class Jumping_Ball
{
public static void main(String args[]) throws Exception
{
BufferedReader f=new BufferedReader(new InputStreamReader(System.in));
int length=Integer.parseInt(f.readLine());
String in=f.readLine();
int start=in.indexOf('>');
int end=in.lastIndexOf('<');
if(start==-1||end==-1)
System.out.println(length);
else
System.out.println(length-(end-start+1));
}
} | Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 3a8ccc63f615108cb868afcdbe1c7509 | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Tarek
*/
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);
AJumpingBall solver = new AJumpingBall();
solver.solve(1, in, out);
out.close();
}
static class AJumpingBall {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
char[] k = in.next().toCharArray();
int clef = 0, f = 0, m = 0, cright = 0;
for (int i = 0; i < n; i++) {
if (k[i] == '<' && f == 0) {
clef++;
} else {
f = 1;
}
if (k[n - i - 1] == '>' && m == 0) {
cright++;
} else {
m = 1;
}
}
out.println(clef + cright);
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 7b4a8e5c08a094d3f1650d9ba415c57e | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class CanadaCupA
{
public static void main(String[]args) throws Throwable
{
IR in = new IR(System.in);
int n = in.j();
char c[] = in.next().toCharArray();
int cnt = 0;
boolean dead[] = new boolean[c.length];
int run = 0;
for(int i = 0; i < n ; ++i)
{
run++;
if(c[i] == '<')
{
if(i - 1 < 0)
{
dead[i] = true;
cnt += run;
run = 0;
}
else
{
if(dead[i - 1])
{
cnt += run;
dead[i] = true;
}
run = 0;
}
}
else
{
if(i + 1 >= n)
{
dead[i] = true;
cnt += run;
run = 0;
}
}
}
System.out.println(cnt);
}
static class IR
{
public BufferedReader reader;
public StringTokenizer tokenizer;
public IR(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 j() {
return Integer.parseInt(next());
}
public long ll(){
return Long.parseLong(next());
}
public double d()
{
return Double.parseDouble(next());
}
}
}
| Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 27b2156ddabf42c2e468087fada9acae | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.OutputStream;
public class A {
public static void main(String args[]) {
Sc sc = new Sc(System.in);
int n = sc.nI();
String s = sc.n();
int l = -1;
int r = -1;
for(int i = 0; i<n; i++) {
if(s.charAt(i) == '>'){
l = i;
break;
}
}
for(int i = n-1; i>=0; i--) {
if(s.charAt(i) == '<'){
r = i;
break;
}
}
if(l == -1 || r == -1 || l>r) System.out.println(n);
else System.out.println(n - (r-l+1));
}
}
class Sc {
public Sc(InputStream i) {
r = new BufferedReader(new InputStreamReader(i));
}
public boolean hasM() {
return peekToken() != null;
}
public int nI() {
return Integer.parseInt(nextToken());
}
public double nD() {
return Double.parseDouble(nextToken());
}
public long nL() {
return Long.parseLong(nextToken());
}
public String n() {
return nextToken();
}
private BufferedReader r;
private String line;
private StringTokenizer st;
private String token;
private String peekToken() {
if (token == null)
try {
while (st == null || !st.hasMoreTokens()) {
line = r.readLine();
if (line == null) return null;
st = new StringTokenizer(line);
}
token = st.nextToken();
} catch (IOException e) { }
return token;
}
private String nextToken() {
String ans = peekToken();
token = null;
return ans;
}
} | Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 336d91d58e12f01a8c4c4694203d349d | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes |
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class CF_725A_JumpingBall {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int x = Integer.parseInt(br.readLine());
int result = x;
char[] arr = br.readLine().toCharArray();
boolean firsttime = true ;
int temp = 0;
for(int i=0; i<arr.length;i++){
if(arr[i]=='>'&&firsttime){
temp ++;
firsttime = false ;
continue ;
}
if(!firsttime){
temp++;
if(arr[i]=='<'){
result= result - temp ;
temp = 0 ;
}
}
}
System.out.println(result);
}
}
| Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 9f7f5d605c998a58253b56c7426aaf02 | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes |
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class CF_725A_JumpingBall {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int x = Integer.parseInt(br.readLine());
int result = 0;
char[] arr = br.readLine().toCharArray();
boolean leftcase = false;
boolean rightcase = false;
if (arr[0] == '<')
leftcase = true;
else
rightcase = true;
int temp = 0;
for (int i = 0; i < arr.length; i++) {
if (leftcase) {
if (arr[i] == '<')
result++;
else
{
temp++;
leftcase = false ;
rightcase = true ;
continue;
}
}
if (rightcase) {
if (arr[i] == '>') {
temp++;
}
if(arr[i]=='<')
temp=0;
}
}
result+=temp;
System.out.println(result);
}
}
| Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | f5bedebfa3b3c5210c1ce6c966c03eba | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public final class C2210201601 {
private static long solveNow(String string, long number) {
int count = 0;
for (int i = 0; i < string.length(); i++) {
if (string.charAt(i) == '<') {
count++;
} else {
break;
}
}
for (int i = string.length() - 1; i >= 0; i--) {
if (string.charAt(i) == '>') {
count++;
} else {
break;
}
}
return count;
}
private static void solve(final Input input, final PrintWriter output) throws IOException {
long number = input.nextInt();
String string = input.next();
output.println(solveNow(string, number));
}
public static void main(String[] args) throws IOException {
try (final PrintWriter output = new PrintWriter(System.out); final Input input = new Input(new BufferedReader(new InputStreamReader(System.in)))) {
solve(input, output);
}
}
private static class Input implements Closeable {
private final BufferedReader in;
private final StringBuilder sb = new StringBuilder();
private final static String SEPERATOR = " \n\r\t";
public Input(final BufferedReader in) {
this.in = in;
}
public String next() throws IOException {
sb.setLength(0);
while (true) {
int c = in.read();
if (c == -1) {
return null;
}
if (SEPERATOR.indexOf(c) == -1) {
sb.append((char) c);
break;
}
}
while (true) {
int c = in.read();
if (c == -1 || SEPERATOR.indexOf(c) != -1) {
break;
}
sb.append((char) c);
}
return sb.toString();
}
public int nextInt() throws IOException {
return Integer.parseInt(next(), 10);
}
public void close() throws IOException {
in.close();
}
}
}
| Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | 9fd8312902decbc1d86966e545d540d5 | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | import java.io.*;
import java.util.*;
public class cc2016a {
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e){e.printStackTrace();}
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception e) {e.printStackTrace();}
return st.nextToken();
}
public int nextInt() {return Integer.parseInt(next());}
public long nextLong() {return Long.parseLong(next());}
public double nextDouble() {return Double.parseDouble(next());}
public String nextLine() {
String line = "";
if(st.hasMoreTokens()) line = st.nextToken();
else try {return br.readLine();}catch(IOException e){e.printStackTrace();}
while(st.hasMoreTokens()) line += " "+st.nextToken();
return line;
}
}
public static void main(String[] args) {
FastScanner sc = new FastScanner();
int n = sc.nextInt();
char[] bumpers = sc.nextLine().toCharArray();
int ans = 0;
for(int i=0;i<n;i++) {
if(bumpers[i] == '<') {
ans++;
}
else {
break;
}
}
for(int i=n-1;i>=0;i--) {
if(bumpers[i] == '>') {
ans++;
}
else {
break;
}
}
System.out.println(ans);
}
} | Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | bc65e577fc76174203faed913f186ad7 | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes |
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CF_725A {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int res = 0;
String s = sc.next();
int left = -1;
int right = -1;
for(int i = 0;i<n;i++){
char c = s.charAt(i);
if(c == '>'){
left = i;
break;
}
}
for(int i = n-1;i>=0;i--){
char c = s.charAt(i);
if(c == '<'){
right = i;
break;
}
}
if(!(left<0) && !(right<0))
System.out.println(left + n-1-right);
else
System.out.println(s.length());
}
}
| Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | bdd9e543723ebb73afc9d37d952a364a | train_003.jsonl | 1477148700 | In a new version of the famous Pinball game, one of the most important parts of the game field is a sequence of n bumpers. The bumpers are numbered with integers from 1 to n from left to right. There are two types of bumpers. They are denoted by the characters '<' and '>'. When the ball hits the bumper at position i it goes one position to the right (to the position iβ+β1) if the type of this bumper is '>', or one position to the left (to iβ-β1) if the type of the bumper at position i is '<'. If there is no such position, in other words if iβ-β1β<β1 or iβ+β1β>βn, the ball falls from the game field.Depending on the ball's starting position, the ball may eventually fall from the game field or it may stay there forever. You are given a string representing the bumpers' types. Calculate the number of positions such that the ball will eventually fall from the game field if it starts at that position. | 256 megabytes | // δ½θ
οΌζ¨ζηε
η
import java.io.*;
import java.util.*;
public class cc2016a {
static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e){e.printStackTrace();}
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception e) {e.printStackTrace();}
return st.nextToken();
}
public int nextInt() {return Integer.parseInt(next());}
public long nextLong() {return Long.parseLong(next());}
public double nextDouble() {return Double.parseDouble(next());}
public String nextLine() {
String line = "";
if(st.hasMoreTokens()) line = st.nextToken();
else try {return br.readLine();}catch(IOException e){e.printStackTrace();}
while(st.hasMoreTokens()) line += " "+st.nextToken();
return line;
}
}
public static void main(String[] args) {
FastScanner sc = new FastScanner();
int n = sc.nextInt();
char[] bumpers = sc.nextLine().toCharArray();
int ans = 0;
for(int i=0;i<n;i++) {
if(bumpers[i] == '<') {
ans++;
}
else {
break;
}
}
for(int i=n-1;i>=0;i--) {
if(bumpers[i] == '>') {
ans++;
}
else {
break;
}
}
System.out.println(ans);
}
} | Java | ["4\n<<><", "5\n>>>>>", "4\n>><<"] | 2 seconds | ["2", "5", "0"] | NoteIn the first sample, the ball will fall from the field if starts at position 1 or position 2.In the second sample, any starting position will result in the ball falling from the field. | Java 8 | standard input | [
"implementation"
] | 6b4242ae9a52d36548dda79d93fe0aef | The first line of the input contains a single integer n (1ββ€βnββ€β200β000)Β β the length of the sequence of bumpers. The second line contains the string, which consists of the characters '<' and '>'. The character at the i-th position of this string corresponds to the type of the i-th bumper. | 1,000 | Print one integerΒ β the number of positions in the sequence such that the ball will eventually fall from the game field if it starts at that position. | standard output | |
PASSED | d244689c6d5e4301ff13960df7e0e848 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.util.Scanner;
public class CircleLine {
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
int[] a = new int[n + 1];
for (int i = 1; i <= n; i++) {
a[i] = a[i - 1] + cin.nextInt();
}
int b = cin.nextInt();
int c = cin.nextInt();
cin.close();
int min = Math.min(b, c);
int max = Math.max(b, c);
int ans1 = a[max - 1] - a[min - 1];
int ans2 = a[n] - ans1;
System.out.println(Math.min(ans1, ans2));
}
} | Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 0f87e7540f4dc34dbd35f72afdcf21ff | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.util.Scanner;
import java.io.OutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
}
class TaskA {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int[] d = new int[n];
for (int i = 0; i < n; i++) {
d[i] = in.nextInt();
}
int s = in.nextInt();
int t = in.nextInt();
int direct = 0;
int indirect = 0;
int directsteps = Math.abs(s-t);
int indirectsteps = n - directsteps;
//out.println(directsteps + " " + indirectsteps);
for (int i = Math.min(s,t)-1; i < Math.min(s,t)-1+directsteps; i++) {
direct += d[i];
}
for (int i = Math.max(s,t)-1; i < Math.max(s,t)-1+indirectsteps; i++) {
//out.println("Indirect " + d[i % n]);
indirect += d[i % n];
}
//out.println(direct + " " + indirect);
int res = Math.min(direct, indirect);
out.println(res);
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | ed45fb8323a189d7b34249408214fd76 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.util.Scanner;
public class _170_A {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] ar = new int[n];
int sum = 0;
for (int i = 0; i < n; i++) {
ar[i] = in.nextInt();
sum += ar[i];
}
int l = in.nextInt();
int r = in.nextInt();
l--;
r--;
if (l > r) {
int temp = l;
l = r;
r = temp;
}
int ans = 0;
for (int i = l; i < r; i++) {
ans += ar[i];
}
System.out.println(Math.min(ans, sum - ans));
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 3565375a4efa9063c5d2fcda33936457 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.util.Scanner;
public class Circle_Line{
public static void main(String args[]){
Scanner in = new Scanner(System.in);
int n =in.nextInt();
int[] mas = new int[n];
for(int i=0;i<n;i++)
mas[i] = in.nextInt();
int start = in.nextInt();
int finish = in.nextInt();
long ans=0;
long k=0;
if(start == finish)
System.out.println(0);
else{
if(start<finish){
for(int i=start-1;i<finish-1;i++){
ans+=mas[i];
mas[i]=0;
}
for(int i=0;i<n;i++)
k+=mas[i];
}else{
for(int i=finish-1;i<start-1;i++){
ans+=mas[i];
mas[i]=0;
}
for(int i=0;i<n;i++){
k+=mas[i];
}
}
System.out.println(ans<=k ? ans : k);
}
}
} | Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 7c7a9b999d5671250da2774955492ab7 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.util.Scanner;
public class CircleLine
{
public static void main(String[] args)
{
Scanner inp=new Scanner(System.in);
int a=inp.nextInt();
int A[]=new int[a];
int sum=0,sum1=0,sum2=0;
for(int i=0;i<a;i++)
{
A[i]=inp.nextInt();
sum=sum+A[i];
}
int s=inp.nextInt();
int t=inp.nextInt();
if(s<t)
{
for(int i=s-1;i<t-1;i++)
{
sum1=sum1+A[i];
}
sum2=sum-sum1;
}
else
{
for(int i=t-1;i<s-1;i++)
{
sum1=sum1+A[i];
}
sum2=sum-sum1;
}
if(sum1<sum2)
{
System.out.println(sum1);
}
else
{
System.out.println(sum2);
}
}
} | Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | b8df3f0b75443da50436a181b209b991 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.util.Scanner;
public class A170 {
/**
* @param args
*/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] d = new int[n],
a = new int[2*n+1];
for (int i = 0; i < n; i++){
d[i] = in.nextInt();
a[i+1] = a[i] + d[i];
}
for (int i = 0; i < n; i++){
a[i+1+n] = a[i+n] + d[i];
}
int s = in.nextInt(), t = in.nextInt();
int s2 = Math.min(s, t), t2 = Math.max(s, t);
System.out.print(Math.min(a[t2-1]-a[s2-1], a[s2-1+n]-a[t2-1]));
in.close();
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | f5f2f0e74a94f5ab239d978db23306c6 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | //package TestOnly.Div2A_170.Code1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
public class Main
{
FastScanner in;
PrintWriter out;
public void solve() throws IOException
{
int sum = 0;
int n = in.nextInt();
int a[] = new int[n];
for (int i = 0; i < a.length; i++)
{
a[i] = in.nextInt();
sum += a[i];
}
int t1 = in.nextInt();
int t2 = in.nextInt();
int start = Math.min(t1, t2) - 1;
int end = Math.max(t1, t2) - 2;
int dist1 = 0;
for (int i = start; i <= end; i++)
{
dist1 += a[i];
}
System.out.println(Math.min(sum - dist1, dist1));
}
public void run()
{
try
{
in = new FastScanner();
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
class FastScanner
{
BufferedReader br;
StringTokenizer st;
FastScanner()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreTokens())
{
try
{
st = new StringTokenizer(br.readLine());
} catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
}
public static void main(String[] arg)
{
new Main().run();
}
}
class Item implements Comparable<Item>
{
int apples;
int dist;
public Item(int dist, int apples)
{
this.dist = dist;
this.apples = apples;
}
public int compareTo(Item that)
{
if (this.dist < 0)
{
return that.dist - this.dist;
}
return this.dist - that.dist;
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 958011c18d7747bdfd613be3bab5a136 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | //In the name of God
import java.util.*;
public class Main
{
int n, st, en, d1, d2;
int[] a;
private void run ()
{
Scanner in = new Scanner(System.in);
n = in.nextInt();
a = new int[n];
for(int i = 0 ; i < n ; i++)
a[i] = in.nextInt();
st = in.nextInt(); en = in.nextInt();
st --; en --;
for(int i = st ;; i++)
{
if(i >= n)
i -= n;
if(i == en)
break;
d1 += a[i];
}
for(int i = st - 1 ;; i--)
{
if(i < 0)
i += n;
d2 += a[i];
if(i == en)
break;
}
System.out.println(Math.min(d1, d2));
}
public static void main (String args[])
{
new Main().run();
}
} | Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 33a3939b652ad6f96170c5e9a5c14ac3 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes |
import java.util.Scanner;
public class problemA {
static public void main(String[] arg){
Scanner in = new Scanner(System.in);
int n=in.nextInt();
int[] d = new int [n];
for(int i=0; i<n;i++)
d[i]=in.nextInt();
int s=in.nextInt()-1;
int v=in.nextInt()-1;
int r=10000000,p=s, a=0;
while (p!=v){
a=a+d[p];
p++;
if (p==n) p=0;
} r=a;a=0;p=s;
while (p!=v){
p--;
if (p<0) p=n-1;
a=a+d[p];
}
if (r>a) r=a;
System.out.print(r);
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 226ad0a6e28d9da9e732925f0ea693b2 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
int n = myScanner.nextInt();
int dist[] = new int[n];
for (int i = 0; i < dist.length; i++)
dist[i] = myScanner.nextInt();
int d1 = myScanner.nextInt() - 1, d2 = myScanner.nextInt() - 1;
if(d1>d2){
int tmp = d1;
d1 = d2;
d2 = tmp;
}
int r1 = 0, r2 = 0;
for (int i = d1; i < d2; i++) {
r1 += dist[i];
}
for (int i = d2; i < 10000; i++) {
if(i%dist.length==d1)
break;
r2 += dist[i%n];
}
System.out.println(Math.min(r1, r2));
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 71a4797e9a55de45453589715a1373b2 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.util.*;
public class Main
{
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] dis = new int[n];
for(int i = 0; i < n; i++)
dis[i] = scan.nextInt();
int from = scan.nextInt()-1;
int to = scan.nextInt()-1;
if(from > to)
{
int t = from;
from = to;
to = t;
}
int dis1 = 0, dis2 = 0;
for(int i = from%n; i != to; i = (++i)%n)
dis1 += dis[i];
for(int i = to%n; i != from; i = (++i)%n)
dis2 += dis[i];
System.out.println(Math.min(dis1, dis2));
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 02a471714e55aac0cac77e19e32943d7 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.util.ArrayList;
import java.util.Scanner;
public class Main{
public static void main(String args[]){
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();
ArrayList<ArrayList<Integer>> al = new ArrayList<ArrayList<Integer>>();
for(int i = 0;i < n;i++) al.add(new ArrayList<Integer>());
int from1,from2,to;
from1 = from2 = in.nextInt();
to = in.nextInt();
al.get(0).add(a[a.length-1]);
al.get(0).add(a[0]);
al.get(al.size()-1).add(a[a.length-2]);
al.get(al.size()-1).add(a[a.length-1]);
for(int i = 1;i < n-1;i++){
al.get(i).add(a[i-1]);
al.get(i).add(a[i]);
}
//traverse right and left and calc path
int right = 0,left = 0;
//right
while(from1 != to){
if(from1 < to){
for(int i = from1-1;i < to-1;i++){
right += al.get(i).get(1);
from1++;
}
}else{ //from > to
for(int i = from1-1;i < n;i++){ //traverse to end right and collect pts
right += al.get(i).get(1);
from1++;
}
from1 = 1;
}
}
//left
while(from2 != to){
if(from2 > to){
for(int i = from2-1;i > to-1;i--){
left += al.get(i).get(0);
from2--;
}
}else{ //from < to
for(int i = from2-1;i >= 0;i--){ //traverse to end left and collect pts
left += al.get(i).get(0);
from2--;
}
from2 = n;
}
}
System.out.println(Math.min(left, right));
}
} | Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 7e6de7bb7cec6538b99aefd2e9caddf3 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes |
import java.io.*;
import java.util.*;
public class Main {
public static void main(String args[]) throws IOException {
Reader.init(System.in);
int n = Reader.nextInt();
int d [] = new int [n];
int total = 0;
for (int i = 0; i < n; i++) {
d[i] = Reader.nextInt();
total+=d[i];
}
int s = Reader.nextInt()-1;
int e = Reader.nextInt()-1;
if(s>e){
int temp =s;
s= e ;
e= temp;
}
int forw = 0 ;
for (int i = s; i < e; i++) {
forw+=d[i];
}
System.out.println(Math.min(forw, total-forw));
}
class suger implements Comparable<suger> {
double d;
double c;
public suger(double d, double c) {
this.d= d ;
this.c= c;
}
@Override
public int compareTo(suger o) {
return Double.compare(this.c,o.c);
}
}}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
/**
* call this method to initialize reader for InputStream
*/
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
/**
* get next word
*/
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
// TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
static public void nextIntArrays(int[]... arrays) throws IOException {
for (int i = 1; i < arrays.length; ++i) {
if (arrays[i].length != arrays[0].length) {
throw new InputMismatchException("Lengths are different");
}
}
for (int i = 0; i < arrays[0].length; ++i) {
for (int[] array : arrays) {
array[i] = nextInt();
}
}
}
static public void nextLineArrays(String[]... arrays) throws IOException {
for (int i = 1; i < arrays.length; ++i) {
if (arrays[i].length != arrays[0].length) {
throw new InputMismatchException("Lengths are different");
}
}
for (int i = 0; i < arrays[0].length; ++i) {
for (String[] array : arrays) {
array[i] = reader.readLine();
}
}
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | dd8ad902441a23574052b07975701dec | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.util.Scanner;
/**
*
* @author kai
*/
public class JavaApplication5 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] a = new int[n];
int counter = 0, counter2 = 0;
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
int s = in.nextInt(), t = in.nextInt();
if (s - 1 == 0 || t - 1 == 0) {
if (s < t) {
for (int i = 0; i < t - 1; i++) {
counter += a[i];
}
for (int i = t - 1; i < n; i++) {
counter2 += a[i];
}
} else if (s > t) {
for (int i = t - 1; i < s - 1; i++) {
counter += a[i];
}
for (int i = s - 1; i < n; i++) {
counter2 += a[i];
}
}
} else if (s - 1 > 0) {
if (s < t) {
for (int i = s - 1; i < t - 1; i++) {
counter += a[i];
}
for (int i = 0; i < s - 1; i++) {
counter2 += a[i];
}
for (int j = t - 1; j < n; j++) {
counter2 += a[j];
}
} else if (s > t) {
for (int i = t - 1; i < s - 1; i++) {
counter += a[i];
}
for (int i = 0; i < t - 1; i++) {
counter2 += a[i];
}
for (int j = s - 1; j < n; j++) {
counter2 += a[j];
}
}
}
if (counter <= counter2) {
System.out.println(counter);
} else {
System.out.println(counter2);
}
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 023cabe9c44ab96713b837f21505690f | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/**
*
* @author takhi
*/
public class circleline_278A {
public static void main(String args[])throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
String str=br.readLine();
StringTokenizer st=new StringTokenizer(str);
int arr[]=new int[n];
int min=101;
for(int i=0;i<n;i++){
arr[i]=Integer.parseInt(st.nextToken());
}
String c=br.readLine();
StringTokenizer st1=new StringTokenizer(c);
int a=Integer.parseInt(st1.nextToken());
int b=Integer.parseInt(st1.nextToken());
int sum=0;
if(a==n){
int m=arr[a-1];
for(int i=b;i<a;i++){
sum+=arr[i-1];
}
if(m<sum){
min=m;
}
else{
min=sum;
}
System.out.println(min);
}
else{
if(a>b){
int z=a;
a=b;
b=z;
}
for(int i=a;i<b;i++){
sum+=arr[i-1];
}
int sum1=0;
while(b<=n){
sum1+=arr[b-1];
b++;
}
b=1;
while(b<a){
sum1+=arr[b-1];
b++;
}
if(sum<sum1)
System.out.println(sum);
else System.out.println(sum1);
}
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | a5cc6d47d5796b67a21ceff94635e7ad | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
Scanner read = new Scanner(System.in);
int n = read.nextInt();
int[] a = new int[n];
long sum = 0;
for (int i = 0; i < n; i++) {
a[i] = read.nextInt();
sum += a[i];
}
int s = read.nextInt(), t = read.nextInt(), temp;
temp = Math.max(s, t);
s = Math.min(s, t);
t = temp;
s--;
t--;
int sum2 = 0;
for (int i = s; i < t; i++)
sum2 += a[i];
System.out.println(Math.min(sum2, sum - sum2));
}
} | Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output | |
PASSED | 8410398a0c961adfa4afb1fef052d857 | train_003.jsonl | 1362065400 | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: d1 is the distance between the 1-st and the 2-nd station; d2 is the distance between the 2-nd and the 3-rd station;... dnβ-β1 is the distance between the nβ-β1-th and the n-th station; dn is the distance between the n-th and the 1-st station.The trains go along the circle line in both directions. Find the shortest distance between stations with numbers s and t. | 256 megabytes | import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Comparator;
import java.util.Iterator;
import java.util.StringTokenizer;
public class A implements CodeforcesSolver {
// κ·Έλ₯νλ€.
private static final JavaIntegerNumberSystem NS = JavaIntegerNumberSystem.getInstance();
public void solve(InputStream is) {
FastScanner in = new FastScanner(is);
DynamicArray<Integer> a = DynamicArray.create();
for(int i : ZeroTo.get(in.nextInt()))
a.addToLast(in.nextInt());
int p1 = in.nextInt()-1;
int p2 = in.nextInt()-1;
int sum = Sum.calc(NS, a);
int one = Sum.calc(NS, SubArray.create(a, Math.min(p1, p2), Math.max(p1, p2)));
System.out.println(Math.min(one, sum-one));
}
public static void main(String[] args) throws Exception {
CodeforcesSolverLauncher.launch(new CodeforcesSolverFactory() {
public CodeforcesSolver create() {
return new A();
}
}, "A1.txt", "A2.txt");
}
}
interface CodeforcesSolver {
void solve(InputStream is);
}
interface CodeforcesSolverFactory {
CodeforcesSolver create();
}
class CodeforcesSolverLauncher {
public static void launch(CodeforcesSolverFactory factory, String... inputFilePath) throws FileNotFoundException, IOException {
if(System.getProperty("ONLINE_JUDGE", "false").equals("true")) {
factory.create().solve(System.in);
} else {
for(String path : inputFilePath) {
FileInputStream is = new FileInputStream(new File(path));
factory.create().solve(is);
is.close();
System.out.println();
}
}
}
}
class FastScanner {
private StringTokenizer tokenizer;
public FastScanner(InputStream is) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024*1024);
byte[] buf = new byte[1024*1024];
while(true) {
int read = is.read(buf);
if(read == -1)
break;
bos.write(buf, 0, read);
}
tokenizer = new StringTokenizer(new String(bos.toByteArray()));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public int nextInt() {
return Integer.parseInt(tokenizer.nextToken());
}
public long nextLong() {
return Long.parseLong(tokenizer.nextToken());
}
public double nextDouble() {
return Double.parseDouble(tokenizer.nextToken());
}
public String next() {
return tokenizer.nextToken();
}
}
class ZeroTo {
public static Iterable<Integer> get(int end) {
return IntSequenceIterable.create(0, 1, end);
}
}
class IntSequenceIterable {
public static Iterable<Integer> create(final int from, final int step, final int size) {
return new Iterable<Integer>() {
public Iterator<Integer> iterator() {
return new ReadOnlyIterator<Integer>() {
int nextIndex = 0;
public boolean hasNext() {
return nextIndex < size;
}
public Integer next() {
return from + step * (nextIndex++);
}
};
}
};
}
private IntSequenceIterable() {
}
}
abstract class ReadOnlyIterator<T> implements Iterator<T> {
public final void remove() {
throw new UnsupportedOperationException();
}
}
class Sum {
public static <T> T calc(final AddableNumberSystem<T> ns, Iterable<T> iterable) {
return Accumulate.calc(iterable, ns.getZero(), new BinaryOperator<T>() {
public T calc(T a, T b) {
return ns.add(a, b);
}
});
}
}
interface AddableNumberSystem<T> extends NumberSystem<T> {
T add(T v1, T v2);
T subtract(T minuend, T subtrahend);
T getZero();
boolean isPositive(T v);
boolean isZero(T v);
boolean isNegative(T v);
int getSign(T v);
}
interface NumberSystem<T> extends EqualityTester<T>, Comparator<T> {
}
interface EqualityTester<T> {
boolean areEqual(T o1, T o2);
}
class Accumulate {
public static <T> T calc(Iterable<T> values, T init, BinaryOperator<T> op) {
T r = init;
for(T v : values)
r = op.calc(r, v);
return r;
}
}
interface BinaryOperator<T> {
T calc(T a, T b);
}
class DynamicArray<T> implements MutableArray<T>, EqualityTester<DynamicArray<T>> {
public static <T> DynamicArray<T> create() {
return new DynamicArray<T>();
}
private T[] a;
private int asize;
@SuppressWarnings("unchecked")
public DynamicArray() {
asize = 0;
a = (T[])new Object[1];
}
public T get(int index) {
return a[index];
}
public void set(int index, T value) {
a[index] = value;
}
public int size() {
return asize;
}
public void clear() {
asize = 0;
}
@SuppressWarnings("unchecked")
public void reserve(int size) {
if(a.length < size) {
T[] na = (T[])new Object[size];
for(int i=0;i<a.length;i++)
na[i] = a[i];
a = na;
}
}
@SuppressWarnings("unchecked")
public void addToLast(T value) {
if(a.length == asize) {
T[] ta = (T[])new Object[asize*2];
for(int i=0;i<asize;i++)
ta[i] = a[i];
a =ta;
}
a[asize++] = value;
}
public T removeLast() {
T r = LastInArray.getLast(this);
a[--asize] = null;
return r;
}
public boolean equals(Object obj) {
return StrictEqualityTester.areEqual(this, obj, this);
}
public boolean areEqual(DynamicArray<T> o1, DynamicArray<T> o2) {
if(o1.size() != o2.size())
return false;
for(int i=0;i<o1.size();i++)
if(!o1.get(i).equals(o2.get(i)))
return false;
return true;
}
public int hashCode() {
int r = 0;
for(int i=0;i<size();i++)
r ^= ThomasWangHash.hash32bit(get(i).hashCode());
return r;
}
public final boolean isEmpty() {
return size() == 0;
}
public final Iterator<T> iterator() {
return ArrayIterator.create(this);
}
public final String toString() {
return IterableToString.toString(this);
}
}
class IterableToString {
public static <T> String toString(Iterable<T> iterable) {
StringBuilder sb = new StringBuilder();
sb.append('(');
boolean first = true;
for(T v : iterable) {
if(first)
first = false;
else
sb.append(',');
sb.append(v);
}
sb.append(')');
return sb.toString();
}
}
class StrictEqualityTester {
@SuppressWarnings("unchecked")
public static <T> boolean areEqual(T me, Object you, EqualityTester<T> tester) {
if(me == you)
return true;
if(you == null)
return false;
if(you.getClass() != me.getClass())
return false;
return tester.areEqual(me, (T)you);
}
}
class ThomasWangHash {
// from http://www.concentric.net/~ttwang/tech/inthash.htm
public static int hash32bit(int key) {
key = ~key + (key << 15); // key = (key << 15) - key - 1;
key = key ^ (key >>> 12);
key = key + (key << 2);
key = key ^ (key >>> 4);
key = key * 2057; // key = (key + (key << 3)) + (key << 11);
key = key ^ (key >>> 16);
return key;
}
public static int hash64bit(long key) {
key = (~key) + (key << 18); // key = (key << 18) - key - 1;
key = key ^ (key >>> 31);
key = key * 21; // key = (key + (key << 2)) + (key << 4);
key = key ^ (key >>> 11);
key = key + (key << 6);
key = key ^ (key >>> 22);
return (int) key;
}
}
class ArrayIterator {
public static <T> Iterator<T> create(final Array<T> a) {
return new ReadOnlyIterator<T>() {
int p = 0;
public boolean hasNext() {
return p < a.size();
}
public T next() {
return a.get(p++);
}
};
}
private ArrayIterator() {
}
}
interface Array<T> extends Collection<T> {
T get(int index);
}
interface Collection<T> extends Iterable<T> {
int size();
boolean isEmpty();
}
class LastInArray {
public static <T> T getLast(Array<T> a) {
return a.get(a.size()-1);
}
}
interface MutableArray<T> extends Array<T> {
void set(int index, T value);
}
class SubArray {
public static <T> Array<T> create(final Array<T> original, final int start, final int end) {
return new Array<T>() {
public T get(int index) {
return original.get(start + index);
}
public int size() {
return end - start;
}
public final boolean isEmpty() {
return size() == 0;
}
public final Iterator<T> iterator() {
return ArrayIterator.create(this);
}
public final String toString() {
return IterableToString.toString(this);
}
};
}
}
class JavaIntegerNumberSystem implements IntegerDivisableNumberSystem<Integer> {
public static final JavaIntegerNumberSystem INSTANCE = new JavaIntegerNumberSystem();
public static JavaIntegerNumberSystem getInstance() {
return INSTANCE;
}
private JavaIntegerNumberSystem() {
}
public Integer getZero() {
return 0;
}
public boolean isPositive(Integer v) {
return v > 0;
}
public boolean isZero(Integer v) {
return v == 0;
}
public boolean isNegative(Integer v) {
return v < 0;
}
public int getSign(Integer v) {
if (v > 0)
return 1;
else if (v < 0)
return -1;
else
return 0;
}
public boolean areEqual(Integer o1, Integer o2) {
return o1 == o2;
}
public Integer getOne() {
return Integer.valueOf(1);
}
public boolean isOne(Integer v) {
return v == 1;
}
public Integer add(Integer v1, Integer v2) {
long res = (long) v1 + (long) v2;
return safeCastFromLong(res);
}
public Integer subtract(Integer minuend, Integer subtrahend) {
long res = (long) minuend - (long) subtrahend;
return safeCastFromLong(res);
}
public Integer multiply(Integer v1, Integer v2) {
long r = (long) v1 * (long) v2;
return safeCastFromLong(r);
}
public Integer integerDivide(Integer dividend, Integer divisor) {
return Integer.valueOf(dividend / divisor);
}
public Integer integerRemainder(Integer dividend, Integer divisor) {
return Integer.valueOf(dividend % divisor);
}
private Integer safeCastFromLong(long v) {
if(v != (int)v)
throw OverflowException.create();
return Integer.valueOf((int) v);
}
public int compare(Integer o1, Integer o2) {
if (o1 > o2)
return 1;
else if (o1 < o2)
return -1;
else
return 0;
}
}
interface IntegerDivisableNumberSystem<T> extends MultipliableNumberSystem<T>, Comparator<T> {
T integerDivide(T dividend, T divisor);
T integerRemainder(T dividend, T divisor);
}
interface MultipliableNumberSystem<T> extends AddableNumberSystem<T> {
T multiply(T v1, T v2);
T getOne();
boolean isOne(T v);
}
class OverflowException {
public static ArithmeticException create() {
return new ArithmeticException("Overflow");
}
}
| Java | ["4\n2 3 4 9\n1 3", "4\n5 8 2 100\n4 1", "3\n1 1 1\n3 1", "3\n31 41 59\n1 1"] | 2 seconds | ["5", "15", "1", "0"] | NoteIn the first sample the length of path 1βββ2βββ3 equals 5, the length of path 1βββ4βββ3 equals 13.In the second sample the length of path 4βββ1 is 100, the length of path 4βββ3βββ2βββ1 is 15.In the third sample the length of path 3βββ1 is 1, the length of path 3βββ2βββ1 is 2.In the fourth sample the numbers of stations are the same, so the shortest distance equals 0. | Java 7 | standard input | [
"implementation"
] | 22ef37041ebbd8266f62ab932f188b31 | The first line contains integer n (3ββ€βnββ€β100) β the number of stations on the circle line. The second line contains n integers d1,βd2,β...,βdn (1ββ€βdiββ€β100) β the distances between pairs of neighboring stations. The third line contains two integers s and t (1ββ€βs,βtββ€βn) β the numbers of stations, between which you need to find the shortest distance. These numbers can be the same. The numbers in the lines are separated by single spaces. | 800 | Print a single number β the length of the shortest path between stations number s and t. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.