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
sequencelengths 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 | 5fb76e449544602e21cf9fd123e249e5 | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.io.UncheckedIOException;
import java.util.List;
import java.io.Closeable;
import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) throws Exception {
Thread thread = new Thread(null, new TaskAdapter(), "", 1 << 27);
thread.start();
thread.join();
}
static class TaskAdapter implements Runnable {
@Override
public void run() {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastInput in = new FastInput(inputStream);
FastOutput out = new FastOutput(outputStream);
DKuroniAndTheCelebration solver = new DKuroniAndTheCelebration();
solver.solve(1, in, out);
out.close();
}
}
static class DKuroniAndTheCelebration {
public void solve(int testNumber, FastInput in, FastOutput out) {
int n = in.readInt();
Node[] nodes = new Node[n + 1];
for (int i = 1; i <= n; i++) {
nodes[i] = new Node();
nodes[i].id = i;
}
for (int i = 1; i < n; i++) {
Node a = nodes[in.readInt()];
Node b = nodes[in.readInt()];
a.next.add(b);
b.next.add(a);
}
Node root = nodes[1];
while (true) {
for (int i = 1; i <= n; i++) {
nodes[i].depth = -1;
}
int cnt = dfs(root, null, 0);
if (cnt == 1) {
out.append("! ").append(root.id).println();
out.flush();
return;
}
dfs(root, null, 0);
for (int i = 1; i <= n; i++) {
if (!nodes[i].deleted && nodes[i].depth > root.depth) {
root = nodes[i];
}
}
dfs(root, null, 0);
Node end = root;
for (int i = 1; i <= n; i++) {
if (!nodes[i].deleted && nodes[i].depth > end.depth) {
end = nodes[i];
}
}
out.append("? ").append(root.id).append(' ').append(end.id).println();
out.flush();
botToUp(end);
root = nodes[in.readInt()];
root.deleted = false;
}
}
public void botToUp(Node root) {
if (root == null) {
return;
}
root.deleted = true;
botToUp(root.parent);
}
public int dfs(Node root, Node p, int depth) {
if (root.deleted) {
return 0;
}
root.parent = p;
root.depth = depth;
int ans = 1;
for (Node node : root.next) {
if (node == p) {
continue;
}
ans += dfs(node, root, depth + 1);
}
return ans;
}
}
static class FastOutput implements AutoCloseable, Closeable, Appendable {
private StringBuilder cache = new StringBuilder(10 << 20);
private final Writer os;
public FastOutput append(CharSequence csq) {
cache.append(csq);
return this;
}
public FastOutput append(CharSequence csq, int start, int end) {
cache.append(csq, start, end);
return this;
}
public FastOutput(Writer os) {
this.os = os;
}
public FastOutput(OutputStream os) {
this(new OutputStreamWriter(os));
}
public FastOutput append(char c) {
cache.append(c);
return this;
}
public FastOutput append(int c) {
cache.append(c);
return this;
}
public FastOutput append(String c) {
cache.append(c);
return this;
}
public FastOutput println() {
cache.append(System.lineSeparator());
return this;
}
public FastOutput flush() {
try {
os.append(cache);
os.flush();
cache.setLength(0);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return this;
}
public void close() {
flush();
try {
os.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public String toString() {
return cache.toString();
}
}
static class FastInput {
private final InputStream is;
private byte[] buf = new byte[1 << 20];
private int bufLen;
private int bufOffset;
private int next;
public FastInput(InputStream is) {
this.is = is;
}
private int read() {
while (bufLen == bufOffset) {
bufOffset = 0;
try {
bufLen = is.read(buf);
} catch (IOException e) {
bufLen = -1;
}
if (bufLen == -1) {
return -1;
}
}
return buf[bufOffset++];
}
public void skipBlank() {
while (next >= 0 && next <= 32) {
next = read();
}
}
public int readInt() {
int sign = 1;
skipBlank();
if (next == '+' || next == '-') {
sign = next == '+' ? 1 : -1;
next = read();
}
int val = 0;
if (sign == 1) {
while (next >= '0' && next <= '9') {
val = val * 10 + next - '0';
next = read();
}
} else {
while (next >= '0' && next <= '9') {
val = val * 10 - next + '0';
next = read();
}
}
return val;
}
}
static class Node {
Node parent;
int depth;
int id;
boolean deleted;
List<Node> next = new ArrayList<>();
}
}
| Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output | |
PASSED | e11862e3ddf32f6b00844ad9f3082710 | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 256 megabytes | import java.util.*;
import java.io.*;
import java.text.*;
public class D1305 {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
int[] lvl = new int[n];
ArrayList<Integer>[] adjList = new ArrayList[n];
for (int i = 0; i < adjList.length; i++) {
adjList[i] = new ArrayList<Integer>();
}
for (int i = 0; i < n - 1; i++) {
int u = sc.nextInt() - 1;
int v = sc.nextInt() - 1;
adjList[u].add(v);
adjList[v].add(u);
lvl[u]++;
lvl[v]++;
}
Queue<Integer> leaves = new LinkedList<Integer>();
for (int i = 0; i < lvl.length; i++) {
if (lvl[i] == 1)
leaves.add(i);
}
while (leaves.size() > 1) {
int u = leaves.poll();
int v = leaves.poll();
pw.printf("? %d %d%n", u + 1, v + 1);
pw.flush();
int lca = sc.nextInt() - 1;
if (lca == -2) {
return;
}
if (lca == u) {
pw.println("! " + (u + 1));
pw.flush();
return;
}
if (lca == v) {
pw.println("! " + (v + 1));
pw.flush();
return;
}
for (int x : adjList[u]) {
lvl[x]--;
if (lvl[x] == 1)
leaves.add(x);
}
for (int x : adjList[v]) {
lvl[x]--;
if (lvl[x] == 1)
leaves.add(x);
}
}
pw.println("! " + (leaves.poll() + 1));
pw.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public int[] nextIntArr(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++)
arr[i] = nextInt();
return arr;
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
| Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output | |
PASSED | 476abb64ea2996f3e08f7e20c8e860aa | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
public class D {
private void work() {
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in), 1 << 16));
n = Integer.parseInt(sc.nextLine().trim());
adj = new int[n][n];
deg = new int[n];
for (int i = 0; i < n - 1; i++) {
String[] spl = sc.nextLine().trim().split("\\s+");
int u = Integer.parseInt(spl[0]) - 1;
int v = Integer.parseInt(spl[1]) - 1;
adj[u][deg[u]++] = v;
adj[v][deg[v]++] = u;
}
int[] idx = new int[n];
for (int i = 0; i < n; i++) idx[i] = i;
for (int i = 0; i < n; i++) {
for (int j = n - 1; j > i; j--) {
if (deg[idx[i]] > deg[idx[j]]) {
int t = idx[i];
idx[i] = idx[j];
idx[j] = t;
}
}
}
int[] p = new int[n];
Arrays.fill(p, -1);
int cnt = n - 1;
for (int i = 0; i < n; i += 2) {
int u = idx[i];
int v = idx[i + 1];
System.out.printf("? %d %d\n", u + 1, v + 1);
System.out.flush();
int w = Integer.parseInt(sc.nextLine().trim()) - 1;
if (w < 0) {
System.exit(0);
}
if (w == u || w == v) {
if (deg[w] == 1) {
System.out.printf("! %d\n", w + 1);
System.out.flush();
System.out.close();
sc.close();
System.exit(0);
}
int s;
if (w == u) s = v;
else s = u;
while (p[s] >= 0 && s != w) s = p[s];
if (s != w) {
List<Integer> path = search(s, w);
for (int j = 0; j < path.size() - 1; j++) {
int uu = path.get(j);
int vv = path.get(j + 1);
if (p[uu] < 0) {
cnt--;
p[uu] = vv;
}
}
}
} else {
int s = u;
while (p[s] >= 0 && s != w) s = p[s];
if (s != w) {
List<Integer> path = search(s, w);
for (int j = 0; j < path.size() - 1; j++) {
int uu = path.get(j);
int vv = path.get(j + 1);
if (p[uu] < 0) {
cnt--;
p[uu] = vv;
}
}
}
s = v;
while (p[s] >= 0 && s != w) s = p[s];
if (s != w) {
List<Integer> path = search(s, w);
for (int j = 0; j < path.size() - 1; j++) {
int uu = path.get(j);
int vv = path.get(j + 1);
if (p[uu] < 0) {
cnt--;
p[uu] = vv;
}
}
}
}
if (cnt == 0) {
for (int j = 0; j < n; j++) {
if (p[idx[j]] < 0) {
System.out.printf("! %d\n", idx[j] + 1);
System.out.flush();
System.out.close();
sc.close();
System.exit(0);
}
}
}
}
for (int j = 0; j < n; j++) {
if (p[idx[j]] < 0) {
System.out.printf("! %d\n", idx[j] + 1);
System.out.flush();
System.out.close();
sc.close();
System.exit(0);
}
}
}
private int n;
private int[] deg;
private int[][] adj;
private List<Integer> search(int u, int w) {
Queue<State> q = new LinkedList<>();
boolean[] seen = new boolean[n];
q.add(new State(u, null));
seen[u] = true;
List<Integer> path = new ArrayList<>();
while (!q.isEmpty()) {
State cur = q.poll();
if (cur.u == w) {
while (cur != null) {
path.add(0, cur.u);
cur = cur.prev;
}
break;
}
for (int i = 0; i < deg[cur.u]; i++) {
int v = adj[cur.u][i];
if (!seen[v]) {
q.add(new State(v, cur));
seen[v] = true;
}
}
}
return path;
}
public static void main(String[] args) {
new D().work();
}
static class State {
int u;
State prev;
State(int u, State prev) {
this.u = u;
this.prev = prev;
}
}
}
| Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output | |
PASSED | 8c10112ddf8cd377f6cc023b671c17f2 | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 256 megabytes | import java.io.*;
import java.util.Arrays;
import java.util.StringJoiner;
import java.util.StringTokenizer;
public class MainD {
static int N;
static Edge[] E;
public static void main(String[] args) {
FastScanner sc = new FastScanner(System.in);
N = sc.nextInt();
E = new Edge[N-1];
for (int i = 0; i < N - 1; i++) {
E[i] = new Edge(sc.nextInt()-1, sc.nextInt()-1);
}
Query q = new Query() {
@Override
public int excuse(int u, int v) {
System.out.println("? " + (u+1) + " " + (v+1));
System.out.flush();
int w = sc.nextInt();
if( w == -1 ) throw new RuntimeException("wtf");
return w-1;
}
@Override
public void say(int r) {
System.out.println("! " + (r+1));
System.out.flush();
}
};
solve(q);
}
interface Query {
int excuse(int u, int v);
void say(int r);
}
static void solve(Query q) {
Edge[][] G = adjB(N, E);
int curr = 0;
while(true) {
int a = findNotLeaf(-1, curr, G);
if( a == -1 ) {
int pair = last2Node(curr, G);
if( pair == -1 ) {
q.say(curr);
} else {
q.say(q.excuse(curr, pair));
}
return;
}
int u = -1, v = -1;
for (Edge e : G[a]) {
if( e.del ) continue;
int b = e.a == a ? e.b : e.a;
if( u == -1 ) {
u = b;
} else {
v = b;
break;
}
}
if( v == -1 ) v = a;
int w = q.excuse(u, v);
for (Edge e : G[w]) {
int b = e.a == w ? e.b : e.a;
if( b == u || b == v || b == a ) {
e.del = true;
}
}
curr = w;
}
}
// ついになるものを返す or -1
static int last2Node(int a, Edge[][] G) {
int candidate = -1;
for (Edge e : G[a]) {
if( e.del ) continue;
int b = e.a == a ? e.b : e.a;
if( candidate == -1 ) {
candidate = b;
} else {
return -1;
}
}
if( candidate == -1 ) return -1;
for (Edge e : G[candidate]){
if( e.del ) continue;
int b = e.a == candidate ? e.b : e.a;
if( b != a ) return -1;
}
return candidate;
}
static int findNotLeaf(int parent, int a, Edge[][] G) {
int cnt = 0;
for (Edge e : G[a]) {
if( !e.del ) {
cnt++;
}
}
if( cnt >= 2 ) return a;
for (Edge e : G[a]) {
if( e.del ) continue;
int b = e.a == a ? e.b : e.a;
if( b == parent ) continue;
int ret = findNotLeaf(a, b, G);
if( ret != -1 ) return ret;
}
return -1;
}
static class Edge {
int a, b;
boolean del;
public Edge(int a, int b) {
this.a = a;
this.b = b;
}
}
static Edge[][] adjB(int n, Edge[] E) {
Edge[][] adj = new Edge[n][];
int[] cnt = new int[n];
for (Edge e : E) {
cnt[e.a]++;
cnt[e.b]++;
}
for (int i = 0; i < n; i++) {
adj[i] = new Edge[cnt[i]];
}
for (Edge e : E) {
adj[e.a][--cnt[e.a]] = e;
adj[e.b][--cnt[e.b]] = e;
}
return adj;
}
@SuppressWarnings("unused")
static class FastScanner {
private BufferedReader reader;
private StringTokenizer tokenizer;
FastScanner(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
tokenizer = null;
}
String next() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
String nextLine() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken("\n");
}
long nextLong() {
return Long.parseLong(next());
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
int[] nextIntArray(int n, int delta) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt() + delta;
return a;
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) a[i] = nextLong();
return a;
}
}
static void writeLines(int[] as) {
PrintWriter pw = new PrintWriter(System.out);
for (int a : as) pw.println(a);
pw.flush();
}
static void writeLines(long[] as) {
PrintWriter pw = new PrintWriter(System.out);
for (long a : as) pw.println(a);
pw.flush();
}
static void writeSingleLine(int[] as) {
PrintWriter pw = new PrintWriter(System.out);
for (int i = 0; i < as.length; i++) {
if (i != 0) pw.print(" ");
pw.print(as[i]);
}
pw.println();
pw.flush();
}
static int max(int... as) {
int max = Integer.MIN_VALUE;
for (int a : as) max = Math.max(a, max);
return max;
}
static int min(int... as) {
int min = Integer.MAX_VALUE;
for (int a : as) min = Math.min(a, min);
return min;
}
static void debug(Object... args) {
StringJoiner j = new StringJoiner(" ");
for (Object arg : args) {
if (arg == null) j.add("null");
else if (arg instanceof int[]) j.add(Arrays.toString((int[]) arg));
else if (arg instanceof long[]) j.add(Arrays.toString((long[]) arg));
else if (arg instanceof double[]) j.add(Arrays.toString((double[]) arg));
else if (arg instanceof Object[]) j.add(Arrays.toString((Object[]) arg));
else j.add(arg.toString());
}
System.err.println(j.toString());
}
static void printSingleLine(int[] array) {
PrintWriter pw = new PrintWriter(System.out);
for (int i = 0; i < array.length; i++) {
if (i != 0) pw.print(" ");
pw.print(array[i]);
}
pw.println();
pw.flush();
}
static int lowerBound(int[] array, int value) {
int lo = 0, hi = array.length, mid;
while (lo < hi) {
mid = (hi + lo) / 2;
if (array[mid] < value) lo = mid + 1;
else hi = mid;
}
return lo;
}
static int upperBound(int[] array, int value) {
int lo = 0, hi = array.length, mid;
while (lo < hi) {
mid = (hi + lo) / 2;
if (array[mid] <= value) lo = mid + 1;
else hi = mid;
}
return lo;
}
}
| Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output | |
PASSED | 262bc976ea3274f261b7f162279570c2 | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 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;
import java.util.*;
public class A2 {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solve(in, out);
out.close();
}
static String reverse(String s){
return (new StringBuilder(s)).reverse().toString();
}
static void sort(int ar[]){
int n=ar.length;
ArrayList<Integer> a=new ArrayList<>();
for(int i=0;i<n;i++)
a.add(ar[i]);
Collections.sort(a);
for(int i=0;i<n;i++)
ar[i]=a.get(i);
}
public static void solve(InputReader sc, PrintWriter pw) {
int i,j=0;
int t=1;
// int t=sc.nextInt();
u:while(t-->0){
int n=sc.nextInt();
ArrayList<Integer> ar[]=new ArrayList[n+1];
for(i=1;i<=n;i++)
ar[i]=new ArrayList<Integer>();
int v[]=new int[n+1];
for(i=0;i<n-1;i++){
int b=sc.nextInt();
int c=sc.nextInt();
ar[b].add(c);
ar[c].add(b);
v[b]++;
v[c]++;
}
int u[]=new int[n+1];
int count=n/2,f=0;
while(count>0){
int a=0,b=0;
for(i=1;i<=n;i++){
if(v[i]==1){
a=i;
break;
}
}
for(i=1;i<=n;i++){
if(i!=a&&v[i]==1){
b=i;
break;
}
}
System.out.println("? "+a+" "+b);
System.out.flush();
int r=sc.nextInt();
if(r==a||r==b){
f=r;
break;
}
for(int y:ar[a]){
if(v[y]!=0)
v[y]--;
}
for(int y:ar[b]){
if(v[y]!=0)
v[y]--;
}
v[a]=0;
v[b]=0;
u[a]=1;
u[b]=1;
count--;
}
if(f>0){
System.out.println("! "+f);
}
else{
for(i=1;i<=n;i++){
if(u[i]==0){
System.out.println("! "+i);
break;
}
// System.out.println(v[i]);
}
}
}
}
static class Pair implements Comparable<Pair>{
int a;
int b;
// int i;
Pair(int a,int b){
this.a=a;
this.b=b;
// this.i=i;
}
public int compareTo(Pair p){
if(a!=p.a)
return (a-p.a);
return (b-p.b);
}
}
static boolean isPrime(int n) {
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static long fast_pow(long base,long n,long M){
if(n==0)
return 1;
if(n==1)
return base%M;
long halfn=fast_pow(base,n/2,M);
if(n%2==0)
return ( halfn * halfn ) % M;
else
return ( ( ( halfn * halfn ) % M ) * base ) % M;
}
static long modInverse(long n,long M){
return fast_pow(n,M-2,M);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output | |
PASSED | b483e6415c671330e217b374e6a02ded | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 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;
import java.util.*;
public class A3 {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solve(in, out);
out.close();
}
static String reverse(String s){
return (new StringBuilder(s)).reverse().toString();
}
static void sort(int ar[]){
int n=ar.length;
ArrayList<Integer> a=new ArrayList<>();
for(int i=0;i<n;i++)
a.add(ar[i]);
Collections.sort(a);
for(int i=0;i<n;i++)
ar[i]=a.get(i);
}
public static void solve(InputReader sc, PrintWriter pw) {
int i,j=0;
int t=1;
// int t=sc.nextInt();
u:while(t-->0){
int n=sc.nextInt();
ArrayList<Integer> ar[]=new ArrayList[n+1];
for(i=1;i<=n;i++)
ar[i]=new ArrayList<Integer>();
int v[]=new int[n+1];
for(i=0;i<n-1;i++){
int b=sc.nextInt();
int c=sc.nextInt();
ar[b].add(c);
ar[c].add(b);
v[b]++;
v[c]++;
}
int u[]=new int[n+1];
int count=n/2,f=0;
while(count>0){
int a=0,b=0;
for(i=1;i<=n;i++){
if(v[i]==1){
a=i;
break;
}
}
for(i=1;i<=n;i++){
if(i!=a&&v[i]==1){
b=i;
break;
}
}
System.out.println("? "+a+" "+b);
System.out.flush();
int r=sc.nextInt();
if(r==a||r==b){
f=r;
break;
}
for(int y:ar[a]){
if(v[y]!=0)
v[y]--;
}
for(int y:ar[b]){
if(v[y]!=0)
v[y]--;
}
v[a]=0;
v[b]=0;
u[a]=1;
u[b]=1;
count--;
}
if(f>0){
System.out.println("! "+f);
}
else{
for(i=1;i<=n;i++){
if(u[i]==0){
System.out.println("! "+i);
break;
}
// System.out.println(v[i]);
}
}
}
}
static class Pair implements Comparable<Pair>{
int a;
int b;
// int i;
Pair(int a,int b){
this.a=a;
this.b=b;
// this.i=i;
}
public int compareTo(Pair p){
if(a!=p.a)
return (a-p.a);
return (b-p.b);
}
}
static boolean isPrime(int n) {
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
static long fast_pow(long base,long n,long M){
if(n==0)
return 1;
if(n==1)
return base%M;
long halfn=fast_pow(base,n/2,M);
if(n%2==0)
return ( halfn * halfn ) % M;
else
return ( ( ( halfn * halfn ) % M ) * base ) % M;
}
static long modInverse(long n,long M){
return fast_pow(n,M-2,M);
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
} | Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output | |
PASSED | 38ba1b10879499d7cff4d1d5db99340e | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 256 megabytes | import java.util.*;
import java.io.*;
public class Main implements Runnable{
Scanner sc;
final 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 long nlo() {
return Long.parseLong(next());
}
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 ni() {
return Integer.parseInt(next());
}
public String nli() {
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 double nd() {
return Double.parseDouble(next());
}
}
public static void main(String[] args)
{
new Thread(null,new Main(),"codeforces",1<<28).start();
}
public void run()
{
sc=new Scanner(System.in);
int t=1;
while(t-->0)
solve();
}
/////// LOGIC //////
HashSet<Integer>[] adj;
public void solve()
{
int count=0;
int n=sc.nextInt();
adj=new HashSet[n];
for(int i=0;i<n;i++)
adj[i]=new HashSet();
for(int i=0;i<n-1;i++)
{
int x=sc.nextInt()-1;
int y=sc.nextInt()-1;
adj[x].add(y);
adj[y].add(x);
}
int rot=-1;
int i=0;
while(true)
{
int[] visit=new int[n];
int[] arr=dfs(i,visit);
i=arr[1];
//System.out.println(i);
ArrayList<Integer> list=new ArrayList(adj[i]);
int l=list.size();
int tmp=0;
if(l==0)
break;
for(int j=0;j+1<l;j+=2)
{
int x=list.get(j)+1;
int y=list.get(j+1)+1;count++;
System.out.println("? " +x+" "+y);
System.out.flush();
int k=sc.nextInt();
if(k==y)
{
adj[y-1].remove(i);
i=y-1;
tmp=-1;
rot=k;
break;
}
else if(k==x)
{
adj[x-1].remove(i);
i=x-1;
tmp=-1;
rot=k;
break;
}
else
rot=k;
}
if(tmp==-1)
continue;
if((l%2==0))
break;
else
{
if(l==1)
{
int x=i+1;
int y=list.get(0)+1;
System.out.println("? "+x+" "+y);count++;
System.out.flush();
rot=sc.nextInt();
break;
}
adj[i]=new HashSet();
adj[i].add(list.get(l-1));
//System.out.println(i+" "+list.get(l-1)+" "+adj[i].size());
}
}
System.out.println("! "+rot);
System.out.flush();
}
public int[] dfs(int x,int[] visit)
{
int l=adj[x].size();
int[] arr=new int[2];
arr[0]=l;
arr[1]=x;
visit[x]=1;
for(int y:adj[x])
{
if(visit[y]==0)
{
int[] brr=dfs(y,visit);
if(brr[0]>arr[0])
arr=brr;
}
}
return arr;
}
}
| Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output | |
PASSED | a100bf4c9f3405daec0e8c24bf3daeef | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 256 megabytes | import java.util.*;
import java.io.*;
public class Main implements Runnable{
Scanner sc;
final 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 long nlo() {
return Long.parseLong(next());
}
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 ni() {
return Integer.parseInt(next());
}
public String nli() {
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 double nd() {
return Double.parseDouble(next());
}
}
public static void main(String[] args)
{
new Thread(null,new Main(),"codeforces",1<<28).start();
}
public void run()
{
sc=new Scanner(System.in);
int t=1;
while(t-->0)
solve();
}
/////// LOGIC //////
HashSet<Integer>[] adj;
public void solve()
{
int count=0;
int n=sc.nextInt();
adj=new HashSet[n];
for(int i=0;i<n;i++)
adj[i]=new HashSet();
for(int i=0;i<n-1;i++)
{
int x=sc.nextInt()-1;
int y=sc.nextInt()-1;
adj[x].add(y);
adj[y].add(x);
}
int rot=-1;
int i=0;
while(true)
{
int[] visit=new int[n];
int[] arr=dfs(i,visit);
i=arr[1];
ArrayList<Integer> list=new ArrayList(adj[i]);
int l=list.size();
int tmp=0;
if(l==0)
break;
for(int j=0;j+1<l;j+=2)
{
int x=list.get(j)+1;
int y=list.get(j+1)+1;count++;
System.out.println("? " +x+" "+y);
System.out.flush();
int k=sc.nextInt();
if(k==y)
{
adj[y-1].remove(i);
i=y-1;
tmp=-1;
rot=k;
break;
}
else if(k==x)
{
adj[x-1].remove(i);
i=x-1;
tmp=-1;
rot=k;
break;
}
else
rot=k;
}
if(tmp==-1)
continue;
if((l%2==0))
break;
else
{
if(l==1)
{
int x=i+1;
int y=list.get(0)+1;
System.out.println("? "+x+" "+y);count++;
System.out.flush();
rot=sc.nextInt();
break;
}
adj[i]=new HashSet();
adj[i].add(list.get(l-1));
}
}
System.out.println("! "+rot);
System.out.flush();
}
public int[] dfs(int x,int[] visit)
{
int l=adj[x].size();
int[] arr=new int[2];
arr[0]=l;
arr[1]=x;
visit[x]=1;
for(int y:adj[x])
{
if(visit[y]==0)
{
int[] brr=dfs(y,visit);
if(brr[0]>arr[0])
arr=brr;
}
}
return arr;
}
}
| Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output | |
PASSED | ad9035946b8ad6c98c6c753185771d8a | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 256 megabytes | import java.io.*;
import java.util.*;
public class Main implements Runnable {
boolean judge = false;
FastReader scn;
PrintWriter out;
String INPUT = "";
void solve() {
int n = scn.nextInt();
HashMap<Integer, HashSet<Integer>> gr = new HashMap<Integer, HashSet<Integer>>();
for(int i = 0; i < n - 1; i++) {
int u = scn.nextInt(), v = scn.nextInt();
if(!gr.containsKey(u)) {
gr.put(u, new HashSet<>());
}
gr.get(u).add(v);
if(!gr.containsKey(v)) {
gr.put(v, new HashSet<>());
}
gr.get(v).add(u);
}
for(int i = 0; i < n / 2; i++) {
int l1 = 0, l2 = 0;
for(int u = 1; u <= n; u++) {
if(gr.containsKey(u) && gr.get(u).size() == 1) {
if(l1 == 0) {
l1 = u;
} else {
l2 = u;
}
}
}
out.println("? " + l1 + " " + l2);
out.flush();
int lca = scn.nextInt();
if(lca == l1 || lca == l2) {
out.println("! " + lca);
out.flush();
return;
}
for(int u = 1; u <= n; u++) {
if(gr.containsKey(u)) {
gr.get(u).remove(l1);
gr.get(u).remove(l2);
}
}
gr.remove(l1);
gr.remove(l2);
}
out.println("! " + gr.keySet().iterator().next());
out.flush();
}
public void run() {
long time = System.currentTimeMillis();
boolean oj = System.getProperty("ONLINE_JUDGE") != null || judge;
out = new PrintWriter(System.out);
scn = new FastReader(oj);
solve();
out.flush();
if (!oj) {
System.out.println(Arrays.deepToString(new Object[] { System.currentTimeMillis() - time + " ms" }));
}
}
public static void main(String[] args) {
new Thread(null, new Main(), "Main", 1 << 28).start();
}
class FastReader {
InputStream is;
public FastReader(boolean onlineJudge) {
is = onlineJudge ? System.in : new ByteArrayInputStream(INPUT.getBytes());
}
byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
double nextDouble() {
return Double.parseDouble(next());
}
char nextChar() {
return (char) skip();
}
String next() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
String nextLine() {
int b = skip();
StringBuilder sb = new StringBuilder();
while ((!isSpaceChar(b) || b == ' ')) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
char[] next(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
long nextLong() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
char[][] nextMatrix(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = next(m);
return map;
}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
int[][] next2DInt(int n, int m) {
int[][] arr = new int[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextIntArray(m);
}
return arr;
}
long[][] next2DLong(int n, int m) {
long[][] arr = new long[n][];
for (int i = 0; i < n; i++) {
arr[i] = nextLongArray(m);
}
return arr;
}
int[] shuffle(int[] arr) {
Random r = new Random();
for (int i = 1, j; i < arr.length; i++) {
j = r.nextInt(i);
int c = arr[i];
arr[i] = arr[j];
arr[j] = c;
}
return arr;
}
long[] shuffle(long[] arr) {
Random r = new Random();
for (int i = 1, j; i < arr.length; i++) {
j = r.nextInt(i);
long c = arr[i];
arr[i] = arr[j];
arr[j] = c;
}
return arr;
}
int[] uniq(int[] arr) {
arr = scn.shuffle(arr);
Arrays.sort(arr);
int[] rv = new int[arr.length];
int pos = 0;
rv[pos++] = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1]) {
rv[pos++] = arr[i];
}
}
return Arrays.copyOf(rv, pos);
}
long[] uniq(long[] arr) {
arr = scn.shuffle(arr);
Arrays.sort(arr);
long[] rv = new long[arr.length];
int pos = 0;
rv[pos++] = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] != arr[i - 1]) {
rv[pos++] = arr[i];
}
}
return Arrays.copyOf(rv, pos);
}
int[] reverse(int[] arr) {
int l = 0, r = arr.length - 1;
while (l < r) {
arr[l] = arr[l] ^ arr[r];
arr[r] = arr[l] ^ arr[r];
arr[l] = arr[l] ^ arr[r];
l++;
r--;
}
return arr;
}
long[] reverse(long[] arr) {
int l = 0, r = arr.length - 1;
while (l < r) {
arr[l] = arr[l] ^ arr[r];
arr[r] = arr[l] ^ arr[r];
arr[l] = arr[l] ^ arr[r];
l++;
r--;
}
return arr;
}
int[] compress(int[] arr) {
int n = arr.length;
int[] rv = Arrays.copyOf(arr, n);
rv = uniq(rv);
for (int i = 0; i < n; i++) {
arr[i] = Arrays.binarySearch(rv, arr[i]);
}
return arr;
}
long[] compress(long[] arr) {
int n = arr.length;
long[] rv = Arrays.copyOf(arr, n);
rv = uniq(rv);
for (int i = 0; i < n; i++) {
arr[i] = Arrays.binarySearch(rv, arr[i]);
}
return arr;
}
}
} | Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output | |
PASSED | ae7191f6c7663650c257e9084a4b8ae2 | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 256 megabytes | // package OzonTechChallenge;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
public class ProblemD {
public static void main(String[] args)throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
HashSet<Integer> tree[]=new HashSet[n+1];
for(int i=1;i<=n;i++){
tree[i]=new HashSet<>();
}
for(int i=1;i<n;i++){
String line[]=br.readLine().split(" ");
int x=Integer.parseInt(line[0]);
int y=Integer.parseInt(line[1]);
tree[x].add(y);
tree[y].add(x);
}
// int size=n;
boolean removed[]=new boolean[n+1];
for(int i=1;i<=n/2;i++){
ArrayList<Integer> leaves=new ArrayList<>();
int start=0;
for(int j=1;j<=n;j++){
if(!removed[j]){
start=j;
break;
}
}
dfs(new boolean[n+1],tree,start,leaves);
int u=start;
int v=leaves.get(0);
if(leaves.size()>=2){
u=leaves.get(1);
}
System.out.println("? "+u+" "+v);
System.out.flush();
int l=Integer.parseInt(br.readLine());
if(l==u){
System.out.println("! "+l);
return;
}
if(l==v){
System.out.println("! "+l);
return;
}
rem(tree,u);
rem(tree,v);
removed[u]=true;
removed[v]=true;
}
for(int i=1;i<=n;i++){
if(!removed[i]){
System.out.println("! "+i);
return;
}
}
}
public static void dfs(boolean visited[],HashSet<Integer> tree[],int curr,
ArrayList<Integer> leaves){
visited[curr]=true;
boolean isLeaf=true;
HashSet<Integer> child=tree[curr];
for(int k:child){
if(!visited[k]){
isLeaf=false;
dfs(visited,tree,k,leaves);
}
}
if(isLeaf){
leaves.add(curr);
}
}
public static void rem(HashSet<Integer> tree[],int v){
HashSet<Integer> child=tree[v];
for(int k:child){
tree[k].remove(v);
}
}
}
| Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output | |
PASSED | c01ee77810fbf553455fb9326fc9b506 | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.ArrayList;
public class kuroni_celebration {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
kc.init(System.in);
int n=kc.nextInt();
kc_tree g=new kc_tree(n);
int[] deg_arr=new int[n];
for(int e=0;e<n-1;e++) {
int x=kc.nextInt();
int y=kc.nextInt();
x--;
y--;
deg_arr[x]++;
deg_arr[y]++;
g.add_edge(x, y);
}
int ans=-2;
for(int e=0;e<n/2;e++) {
int u=-2;
int v=-2;
for(int x=0;x<n;x++) {
if(deg_arr[x]==1) {
if(u==-2) {
u=x;
}
else {
v=x;
break;
}
}
}
System.out.println("? "+(u+1)+" "+(v+1));
ans=kc.nextInt();
ans-=1;
if(ans==u || ans==v) {
break;
}
for(int p=0;p<g.adj.get(u).size();p++) {
deg_arr[g.adj.get(u).get(p)]-=1;
}
for(int q=0;q<g.adj.get(v).size();q++) {
deg_arr[g.adj.get(v).get(q)]-=1;
}
deg_arr[u]=-1;
deg_arr[v]=-1;
}
ans++;
System.out.println("! "+ans);
}
}
class kc_tree{
int n;
ArrayList<ArrayList<Integer>> adj;
kc_tree(int V){
n=V;
adj=new ArrayList<ArrayList<Integer>>();
for(int g=0;g<n;g++) {
adj.add(new ArrayList<Integer>());
}
}
void add_edge(int a,int b) {
adj.get(a).add(b);
adj.get(b).add(a);
}
}
/** Class for buffered reading int and double values */
class kc {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input));
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
// TODO add check for eof if necessary
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
}
| Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output | |
PASSED | 1c4afc8fa1fb8aba2dde10e6f565df54 | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 256 megabytes |
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.Map.Entry;
import java.util.Stack;
public class ROUGH{
public static class FastReader {
BufferedReader br;
StringTokenizer root;
public FastReader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (root == null || !root.hasMoreTokens()) {
try {
root = new StringTokenizer(br.readLine());
} catch (Exception addd) {
addd.printStackTrace();
}
}
return root.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (Exception addd) {
addd.printStackTrace();
}
return str;
}
}
public static PrintWriter out = new PrintWriter (new BufferedOutputStream(System.out));
public static FastReader sc = new FastReader();
public static void main(String[] args) {
int n = sc.nextInt();
boolean[][] adj = new boolean[n+1][n+1];
int[] deg = new int[n+1];
for(int i=1;i<n;++i) {
int u = sc.nextInt();
int v = sc.nextInt();
adj[u][v] = true;
adj[v][u] = true;
deg[u]++; deg[v]++;
}
Queue<Integer> leaf = new LinkedList<>();
boolean[] deleted = new boolean[n+1];
int root = -1;
for(int i=0;i<deg.length;++i)
if(deg[i] == 1) leaf.add(i);
while(leaf.size() > 1) {
int a = leaf.poll();
int b = leaf.poll();
int lca = ask(a,b);
if(lca == a || lca == b) { root = lca; break; }
else {
deleted[a] = deleted[b] = true;
for(int i=1;i<=n;++i) {
if(adj[i][a]) {
adj[i][a] = false;
adj[a][i] = false;
deg[i]--;
if(deg[i] == 1) leaf.add(i);
break;
}
}
for(int i=1;i<=n;++i) {
if(adj[i][b]) {
adj[i][b] = false;
adj[b][i] = false;
deg[i]--;
if(deg[i] == 1) leaf.add(i);
break;
}
}
}
}
if(root == -1) {
if(leaf.size() != 0) root = leaf.poll();
else for(int i=1;i<=n;++i) if(!deleted[i]) root = i;
}
System.out.println("! "+root);
System.out.flush();
}
private static int ask(int a, int b) {
System.out.println("? "+a+" "+b);
System.out.flush();
int lca = sc.nextInt();
return lca;
}
static class Pair{
int val;
int idx;
Pair(int val,int idx){
this.val = val;
this.idx = idx;
}
}
}
| Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output | |
PASSED | 3a8a30eb77e0e1820de1faf8d413764f | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 256 megabytes | import javafx.beans.property.IntegerProperty;
import java.util.*;
import java.io.*;
public class D {
public static void main(String[] args) throws IOException{
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(f.readLine());
LinkedList<Integer>[] edges = new LinkedList[n+1];
for(int i = 0; i <= n; i++){
edges[i] = new LinkedList<Integer>();
}
for(int i = 0; i < n-1; i++){
StringTokenizer st = new StringTokenizer(f.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
edges[b].add(a);
edges[a].add(b);
}
HashSet<Integer> removed = new HashSet<Integer>();
int lca = 1;
while(true){
ArrayList<Integer> query = new ArrayList<Integer>();
HashSet<Integer> seen = new HashSet<Integer>();
Stack<Integer> stk = new Stack<Integer>();
stk.add(lca);
while(!stk.isEmpty()){
int temp = stk.pop();
if(seen.contains(temp)) continue;
seen.add(temp);
int count = 0;
for(int e: edges[temp]){
if(!seen.contains(e) && !removed.contains(e)){
stk.add(e);
count++;
}
}
if(count == 0){
query.add(temp);
if(query.size() == 2) break;
}
}
if(removed.size() == n-1){
out.println("! " + lca);
break;
}
if(query.size() == 1){ query.add(lca);}
out.println("? " + query.get(0) + " " + query.get(1));
out.flush();
lca = Integer.parseInt(f.readLine());
int temp1 = query.get(0);
int temp2 = query.get(1);
if(temp1 == lca || temp2 == lca){
out.println("! " + lca);
break;
}
removed.add(temp1);
removed.add(temp2);
}
out.close();
}
}
| Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output | |
PASSED | b68e35d8ab3b3a35be7c38041760730f | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 256 megabytes | import java.io.*;
import java.util.*;
public class D {
public static void main(String[] args) {
FastScanner sc = new FastScanner();
int n = sc.nextInt();
ArrayList<Integer>[] g = new ArrayList[n];
for(int i = 0; i < n; i++) {
g[i] = new ArrayList<>();
}
for(int i = 0; i < n-1; i++) {
int u = sc.nextInt()-1;
int v = sc.nextInt()-1;
g[u].add(v);
g[v].add(u);
}
// boolean[] done = new boolean[n];
int u = -1;
for(int i = 0; i < n; i++) {
if(g[i].size() == 1) {
u = i; break;
}
}
int lca;
boolean[] done = new boolean[n];
while(true) {
int v = -1;
for(int x: g[u]) {
if(!done[x]) {
v = x; break;
}
}
if(v < 0) break;
int w = -1;
for(int x: g[u]) {
if(!done[x] && x != v) {
w = x;
}
}
if(w >= 0) {
System.out.printf("? %d %d\n", v+1, w+1);
}
else {
for(int x: g[v]) {
if(!done[x] && x != u) {
w = x; break;
}
}
if(w >= 0) {
System.out.printf("? %d %d\n", u+1, w+1);
}
else {
System.out.printf("? %d %d\n", u+1, v+1);
w = u;
}
}
lca = sc.nextInt()-1;
if(u != lca) done[u] = true;
if(v != lca) done[v] = true;
if(w != lca) done[w] = true;
u = lca;
}
System.out.printf("! %d\n", u+1);
}
static class FastScanner {
public BufferedReader reader;
public StringTokenizer tokenizer;
public FastScanner() {
reader = new BufferedReader(new InputStreamReader(System.in), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
try {
return reader.readLine();
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
}
| Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output | |
PASSED | d160197a9f4e0daec0fafa715af87ad4 | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static int inf = (int) (1e9 + 7);
static int n;
static TreeSet<Integer> gr[];
static boolean good[];
static int cnt_good;
static void find(int v, int fin) {
if (v == fin || !good[v]) return;
good[v] = false;
cnt_good--;
for (int i : gr[v]) {
find(i, fin);
}
}
static void solve() throws IOException {
scan();
cnt_good = n;
good = new boolean[n];
for (int i = 0; i < n; i++) good[i] = true;
int it = 0;
while (cnt_good != 1) {
ArrayList<Integer> temp1 = new ArrayList<>();
for (int i = 0; i < n; i++) if (good[i]) temp1.add(i);
for (int v1 = 0; v1 < n; v1++) {
if (!good[v1]) continue;
boolean temp = false;
for(int v2 : temp1) {
if (v2 == v1 || (cnt_good != 2 && gr[v1].contains(v2))) continue;
pw.println("? " + (v1 + 1) + " " + (v2 + 1));
pw.flush();
int w = sc.nextInt() - 1;
find(v1, w);
find(v2, w);
temp = true;
break;
}
if (temp) break;
}
it++;
if (it > n / 2) n /= 0;
}
int res = 0;
for (int i = 0; i < n; i++) if (good[i]) res = i + 1;
pw.println("! " + res);
}
static void scan() throws IOException {
n = sc.nextInt();
gr = new TreeSet[n];
for (int i = 0; i < n; i++) gr[i] = new TreeSet<>();
for (int i = 0; i < n - 1; i++) {
int v1 = sc.nextInt() - 1;
int v2 = sc.nextInt() - 1;
gr[v1].add(v2);
gr[v2].add(v1);
}
}
public static void main(String[] args) throws IOException {
sc = new Scanner(System.in);
pw = new PrintWriter(System.out);
solve();
pw.close();
}
static Scanner sc;
static PrintWriter pw;
static class Scanner {
BufferedReader br;
StringTokenizer st = new StringTokenizer("");
Scanner(InputStream in) throws FileNotFoundException {
br = new BufferedReader(new InputStreamReader(in));
}
Scanner(String in) throws FileNotFoundException {
br = new BufferedReader(new FileReader(in));
}
String next() throws IOException {
while (!st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
}
class pair {
int a, t;
pair(int a, int t) {
this.a = a;
this.t = t;
}
pair() {
}
} | Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output | |
PASSED | 52750c1eb640891fbfd11e1f330d30d1 | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 256 megabytes | import java.io.*;
import java.util.*;
public class JavAki {
public static Scanner sc = new Scanner(System.in);
public static int n;
public static ArrayList<HashSet<Integer>> adj;
public static HashSet<Integer> leafList;
public static int ask(int u, int v) {
System.out.println("? " + (u+1) + " " + (v+1)); System.out.flush();
return (sc.nextInt() - 1);
}
public static void answer(int r) {
System.out.println("! " + (r+1)); System.out.flush();
System.exit(0);
}
public static void purge(int z, int last, int blockpoint) {
if (leafList.contains(z)) leafList.remove(z);
for (int t: adj.get(z)) {
if (t == last) continue;
if (t == blockpoint) adj.get(t).remove(z);
else if (adj.get(t).size() > 0) purge(t, z, blockpoint);
}
adj.get(z).clear();
}
public static void Input() {
n = sc.nextInt();
adj = new ArrayList<>();
for (int i=0; i<n; i++) adj.add(new HashSet<>());
for (int i=1; i<n; i++) {
int x = sc.nextInt() - 1, y = sc.nextInt() - 1;
adj.get(x).add(y); adj.get(y).add(x);
}
}
public static void Solve() {
leafList = new HashSet<>();
for (int i=0; i<n; i++) {
if (adj.get(i).size() == 1) leafList.add(i);
}
while (leafList.size() > 1) {
int u = leafList.iterator().next(); leafList.remove(u);
int v = leafList.iterator().next(); leafList.remove(v);
int w = ask(u, v);
if (w == u || w == v) answer(w);
purge(u, -1, w); purge(v, -1, w);
if (adj.get(w).size() <= 1) leafList.add(w);
}
answer(leafList.iterator().next());
}
public static void main(String[] args) {
Input(); Solve();
}
} | Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output | |
PASSED | 1c5798ce565386203b70a57b6b5012b5 | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 256 megabytes | // package OzonTechChallenge;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
public class ProblemD {
public static void main(String[] args)throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=Integer.parseInt(br.readLine());
HashSet<Integer> tree[]=new HashSet[n+1];
for(int i=1;i<=n;i++){
tree[i]=new HashSet<>();
}
for(int i=1;i<n;i++){
String line[]=br.readLine().split(" ");
int x=Integer.parseInt(line[0]);
int y=Integer.parseInt(line[1]);
tree[x].add(y);
tree[y].add(x);
}
// int size=n;
boolean removed[]=new boolean[n+1];
for(int i=1;i<=n/2;i++){
ArrayList<Integer> leaves=new ArrayList<>();
int start=0;
for(int j=1;j<=n;j++){
if(!removed[j]){
start=j;
break;
}
}
dfs(new boolean[n+1],tree,start,leaves);
int u=start;
int v=leaves.get(0);
if(leaves.size()>=2){
u=leaves.get(1);
}
System.out.println("? "+u+" "+v);
System.out.flush();
int l=Integer.parseInt(br.readLine());
if(l==u){
System.out.println("! "+l);
return;
}
if(l==v){
System.out.println("! "+l);
return;
}
rem(tree,u);
rem(tree,v);
removed[u]=true;
removed[v]=true;
}
for(int i=1;i<=n;i++){
if(!removed[i]){
System.out.println("! "+i);
return;
}
}
}
public static void dfs(boolean visited[],HashSet<Integer> tree[],int curr,
ArrayList<Integer> leaves){
visited[curr]=true;
boolean isLeaf=true;
HashSet<Integer> child=tree[curr];
for(int k:child){
if(!visited[k]){
isLeaf=false;
dfs(visited,tree,k,leaves);
}
}
if(isLeaf){
leaves.add(curr);
}
}
public static void rem(HashSet<Integer> tree[],int v){
HashSet<Integer> child=tree[v];
for(int k:child){
tree[k].remove(v);
}
}
}
| Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output | |
PASSED | 7bea763bb9c2cc6e68e57f2a27f4ef58 | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.util.*;
public class Main {
static int n;
static ArrayList<ArrayList<Integer>> edge;
static boolean[] flag;
static int[] dfs(int root) {
int[] dist = new int[n];
Arrays.fill(dist, -1);
int[] first = {root, 0};
ArrayDeque<int[]> q = new ArrayDeque<int[]>();
q.add(first);
while (!q.isEmpty()) {
int[] rem = q.poll();
if (dist[rem[0]]!=-1) continue;
dist[rem[0]] = rem[1];
for (Integer i : edge.get(rem[0])) {
int[] add = {i, rem[1]+1};
if (flag[i]) q.add(add);
}
}
return dist;
}
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
n = in.nextInt();
edge = new ArrayList<ArrayList<Integer>>();
for (int i=0;i<n;i++) {
ArrayList<Integer> add = new ArrayList<Integer>();
edge.add(add);
}
for (int i=0;i<n-1;i++) {
int x = in.nextInt()-1;
int y = in.nextInt()-1;
edge.get(x).add(y);
edge.get(y).add(x);
}
flag = new boolean[n];
for (int i=0;i<n;i++) flag[i] = true;
int w = 0;
loop:while (true) {
int[] dist_1 = dfs(w);
int max_index_1 = -1;
int max_1 = 0;
for (int i=0;i<n;i++) {
if (max_1<dist_1[i]) {
max_index_1 = i;
max_1 = dist_1[i];
}
}
if (max_index_1==-1) {
StringBuilder sb = new StringBuilder();
sb.append("! ");
sb.append(w+1);
out.println(sb);
out.flush();
break loop;
}
int[] dist_2 = dfs(max_index_1);
int max_index_2 = -1;
int max_2 = 0;
for (int i=0;i<n;i++) {
if (max_2<dist_2[i]) {
max_index_2 = i;
max_2 = dist_2[i];
}
}
if (max_index_2==-1) {
StringBuilder sb = new StringBuilder();
sb.append("! ");
sb.append(w+1);
out.println(sb);
out.flush();
break loop;
}
int[] dist_3 = dfs(max_index_2);
int max_index_3 = -1;
int max_3 = 0;
for (int i=0;i<n;i++) {
if (max_3<dist_3[i]) {
max_index_3 = i;
max_3 = dist_3[i];
}
}
if (max_index_3==-1) {
StringBuilder sb = new StringBuilder();
sb.append("! ");
sb.append(w+1);
out.println(sb);
out.flush();
break loop;
}
StringBuilder sb = new StringBuilder();
sb.append("? ");
sb.append(max_index_2+1);
sb.append(" ");
sb.append(max_index_3+1);
out.println(sb);
out.flush();
w = in.nextInt()-1;
for (int i=0;i<n;i++) {
if (dist_2[i]<dist_2[w] || dist_3[i]<dist_3[w]) {
flag[i] = false;
}
}
// out.println(Arrays.toString(flag));
}
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output | |
PASSED | 47368d47f1e9f8552bed1bc93fd042fa | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 256 megabytes | //make sure to make new file!
import java.io.*;
import java.util.*;
//semi-t
public class DOzonb{
public static int n;
public static boolean[][] edges;
public static void main(String[] args)throws IOException{
BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
n = Integer.parseInt(f.readLine());
ArrayList<HashSet<Integer>> adj = new ArrayList<HashSet<Integer>>(n+1);
for(int k = 0; k <= n; k++) adj.add(new HashSet<Integer>());
for(int k = 0; k < n-1; k++){
StringTokenizer st = new StringTokenizer(f.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
adj.get(a).add(b);
adj.get(b).add(a);
}
int vertex = 1;
HashSet<Integer> nodes = new HashSet<Integer>();
for(int k = 1; k <= n; k++){
nodes.add(k);
}
while(true){
if(nodes.size() == 1){
int i = -1;
for(int node : nodes){
i = node;
}
out.println("! " + i);
break;
}
//find two leaves
int v2 = 0;
int v3 = 0;
Stack<Integer> q = new Stack<Integer>();
q.add(vertex);
boolean[] seen = new boolean[n+1];
seen[vertex] = true;
while(!q.isEmpty()){
int s = q.pop();
if(adj.get(s).size() == 1){
if(v2 == 0){
v2 = s;
} else {
v3 = s;
break;
}
}
for(int nei : adj.get(s)){
if(!seen[nei]){
q.add(nei);
seen[nei] = true;
}
}
}
out.println("? " + v2 + " " + v3);
out.flush();
int ans = Integer.parseInt(f.readLine());
if(ans == v2 || ans == v3){
out.println("! " + ans);
break;
}
nodes.remove(v2);
nodes.remove(v3);
for(int v = 1; v <= n; v++){
adj.get(v).remove(v2);
adj.get(v).remove(v3);
}
for(int node : nodes){
vertex = node;
break;
}
}
out.close();
}
public static int farthestpoint(int vertex){
Stack<State> q = new Stack<State>();
q.add(new State(vertex,0));
int maxdis = -1;
int maxvertex = -1;
boolean[] seen = new boolean[n+1];
seen[vertex] = true;
while(!q.isEmpty()){
State s = q.pop();
if(s.d > maxdis){
maxdis = s.d;
maxvertex = s.v;
}
for(int k = 1; k <= n; k++){
if(k != s.v && !seen[k] && edges[s.v][k]){
q.add(new State(k,s.d+1));
seen[k] = true;
}
}
}
return maxvertex;
}
public static class State{
int v;
int d;
public State(int a, int b){
v = a;
d = b;
}
}
} | Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output | |
PASSED | 46ca309873838fdb661d04c430f1cfcd | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class Ozon2020D {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
//PrintWriter writer = new PrintWriter(System.out);
int n = Integer.parseInt(reader.readLine());
TreeMap<Integer, Set<Integer>> edges = new TreeMap<Integer, Set<Integer>>();
for (int i = 0; i < n; i++) {
edges.put(i, new HashSet<Integer>());
}
for (int i = 0; i < n - 1; i++) {
StringTokenizer tokenizer = new StringTokenizer(reader.readLine());
int x = Integer.parseInt(tokenizer.nextToken()) - 1;
int y = Integer.parseInt(tokenizer.nextToken()) - 1;
edges.get(x).add(y);
edges.get(y).add(x);
}
int numQueries = n / 2; // floor(n / 2)
int someVertex = edges.firstKey();
Deque<Integer> deque = new ArrayDeque<Integer>();
Set<Integer> visited = new HashSet<Integer>();
for (int xx = 0; xx < numQueries; xx++) {
// bfs at some vertex
deque.clear();
visited.clear();
// a vertex not removed
deque.add(someVertex);
visited.add(someVertex);
int last = -1;
while (!deque.isEmpty()) {
int polled = deque.poll();
last = polled;
for (int neighbor : edges.get(polled)) {
if (!visited.contains(neighbor)) {
deque.add(neighbor);
visited.add(neighbor);
}
}
}
deque.clear();
visited.clear();
deque.add(last);
visited.add(last);
int last2 = -1;
int[] parent = new int[n];
while (!deque.isEmpty()) {
int polled = deque.poll();
last2 = polled;
for (int neighbor : edges.get(polled)) {
if (!visited.contains(neighbor)) {
parent[neighbor] = polled;
deque.add(neighbor);
visited.add(neighbor);
}
}
}
System.out.println("? " + (last + 1) + " " + (last2 + 1));
System.out.flush();
int w = Integer.parseInt(reader.readLine()) - 1;
if (w == last || w == last2) {
System.out.println("! " + (w + 1));
System.out.flush();
break;
} else {
int x = last2;
while (parent[x] != w) {
x = parent[x];
}
// remove parent[w] and x
edges.get(w).remove(parent[w]);
edges.get(w).remove(x);
someVertex = w;
if (edges.get(w).isEmpty()) {
System.out.println("! " + (w + 1));
System.out.flush();
break;
}
}
}
//writer.close();
reader.close();
}
}
| Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output | |
PASSED | 61a3dfd2d8bad7150fa66e005e63f779 | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 256 megabytes | //package codeforces.ozontech2020;
import java.io.*;
import java.util.*;
public class KuroniAndCelebration {
public static void main(String[] args) {
// try {
// FastScanner in = new FastScanner(new FileInputStream("src/input.in"));
// PrintWriter out = new PrintWriter(new FileOutputStream("src/output.out"));
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
solve(1, in, out);
// } catch (IOException e) {
// e.printStackTrace();
// }
}
private static void solve(int q, FastScanner in, PrintWriter out) {
for (int qq = 0; qq < q; qq++) {
int n = in.nextInt();
Set<Integer>[] neighbors = new Set[n];
for(int i = 0; i < n; i++) {
neighbors[i] = new HashSet<>();
}
for(int i = 0; i < n - 1; i++) {
int u = in.nextInt() - 1;
int v = in.nextInt() - 1;
neighbors[u].add(v);
neighbors[v].add(u);
}
Queue<Integer> leafQ = new LinkedList<>();
for(int i = 0; i < n; i++) {
if(neighbors[i].size() == 1) {
leafQ.add(i);
}
}
int root = -1;
while(leafQ.size() >= 2) {
int u = leafQ.poll();
int v = leafQ.poll();
out.println("? " + (u + 1) + " " + (v + 1));
out.flush();
int lca = in.nextInt() - 1;
if(lca == u || lca == v) {
root = lca;
break;
}
for(int neighbor : neighbors[u]) {
neighbors[neighbor].remove(u);
if(neighbors[neighbor].size() == 1) {
leafQ.add(neighbor);
}
}
for(int neighbor : neighbors[v]) {
neighbors[neighbor].remove(v);
if(neighbors[neighbor].size() == 1) {
leafQ.add(neighbor);
}
}
}
if(root < 0) {
out.println("! " + (leafQ.poll() + 1));
}
else {
out.println("! " + (root + 1));
}
out.flush();
}
out.close();
}
private static class NumberTheory {
private static long modularAdd(long a, long b, int mod) {
long sum = a + b;
if (sum >= mod) {
sum -= mod;
}
return sum;
}
private static long modularSubtract(long a, long b, int mod) {
long diff = a - b;
if (diff < 0) {
diff += mod;
}
return diff;
}
private static long fastModPow2(long x, int n, int mod) {
if (n == 0) {
return 1;
}
long coeff = 1, base = x;
while (n > 1) {
if (n % 2 != 0) {
coeff = (coeff * base % mod);
}
base = (base * base % mod);
n = n / 2;
}
long res = coeff * base % mod;
return res;
}
}
private static class Graph {
private static int UNVISITED = 0;
private static int VISITING = -1;
private static int VISITED = 1;
private static Stack<Integer> topologicalSort(Set<Integer>[] g) {
Stack<Integer> stack = new Stack<>();
int[] state = new int[g.length];
for (int node = 0; node < g.length; node++) {
if (!topoSortHelper(g, stack, state, node)) {
return null;
}
}
return stack;
}
private static boolean topoSortHelper(Set<Integer>[] g, Stack<Integer> stack, int[] state, int currNode) {
if (state[currNode] == VISITED) {
return true;
} else if (state[currNode] == VISITING) {
return false;
}
state[currNode] = VISITING;
for (int neighbor : g[currNode]) {
if (!topoSortHelper(g, stack, state, neighbor)) {
return false;
}
}
state[currNode] = VISITED;
stack.push(currNode);
return true;
}
}
private static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream stream) {
try {
br = new BufferedReader(new InputStreamReader(stream));
} catch (Exception e) {
e.printStackTrace();
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
Integer[] nextIntArray(int n) {
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
Long[] nextLongArray(int n) {
Long[] a = new Long[n];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
return a;
}
}
}
| Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output | |
PASSED | 4ad6655f65f0b48a29237ed800d12beb | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 256 megabytes | import java.util.*;
import java.io.*;
public class tr0 {
static PrintWriter out;
static StringBuilder sb;
static long mod = 1000000007;
static long inf = (long) 1e15;
static ArrayList<Integer>[] ad;
static int n, p, k;
static boolean[] in;
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
out = new PrintWriter(System.out);
n = sc.nextInt();
ad = new ArrayList[n];
for (int i = 0; i < n; i++)
ad[i] = new ArrayList<>();
for (int i = 0; i < n - 1; i++) {
int a = sc.nextInt() - 1;
int b = sc.nextInt() - 1;
ad[a].add(b);
ad[b].add(a);
}
in = new boolean[n];
Arrays.fill(in, true);
int q = n / 2;
while (q-- > 0) {
diameter();
System.out.println("? " + (s + 1) + " " + (t + 1));
lca = sc.nextInt();
if (s == t) {
System.out.println("! " + lca);
}
dfs(s);
// System.out.println(Arrays.toString(in));
dfs(t);
// System.out.println(Arrays.toString(in));
int c = 0;
for (int i = 0; i < n; i++)
if (in[i])
c++;
if (c == 1) {
System.out.println("! " + lca);
return;
}
}
System.out.println("! " + lca);
out.flush();
}
static int s, t, lca;
static void dfs(int u) {
if (u == lca-1)
return;
// System.out.println(u);
in[u] = false;
for (int v : ad[u])
if (in[v])
dfs(v);
}
static void diameter() {
int[] dist = new int[n];
Arrays.fill(dist, -1);
int u = 0;
for (int i = 0; i < n; i++)
if (in[i]) {
u = i;
break;
}
dist[u] = 0;
Queue<Integer> q = new LinkedList<Integer>();
q.add(u);
while (!q.isEmpty()) {
int cur = q.poll();
for (int v : ad[cur])
if (dist[v] == -1 && in[v]) {
dist[v] = 1 + dist[cur];
q.add(v);
}
}
// System.out.println(u+" "+Arrays.toString(dist));
int k = -1;
for (int i = 0; i < n; i++)
if (dist[i] > k) {
k = dist[i];
s = i;
}
// System.out.println(u+" "+Arrays.toString(dist));
Arrays.fill(dist, -1);
dist[s] = 0;
q = new LinkedList<Integer>();
q.add(s);
while (!q.isEmpty()) {
int cur = q.poll();
for (int v : ad[cur])
if (dist[v] == -1 && in[v]) {
dist[v] = 1 + dist[cur];
q.add(v);
}
}
k = -1;
for (int i = 0; i < n; i++)
if (dist[i] > k) {
k = dist[i];
t = i;
}
// System.out.println(t+" "+s+" "+Arrays.toString(dist));
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
} | Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output | |
PASSED | d7db404ed789618409337616eba77d0b | train_000.jsonl | 1583246100 | This is an interactive problem.After getting AC after 13 Time Limit Exceeded verdicts on a geometry problem, Kuroni went to an Italian restaurant to celebrate this holy achievement. Unfortunately, the excess sauce disoriented him, and he's now lost!The United States of America can be modeled as a tree (why though) with $$$n$$$ vertices. The tree is rooted at vertex $$$r$$$, wherein lies Kuroni's hotel.Kuroni has a phone app designed to help him in such emergency cases. To use the app, he has to input two vertices $$$u$$$ and $$$v$$$, and it'll return a vertex $$$w$$$, which is the lowest common ancestor of those two vertices.However, since the phone's battery has been almost drained out from live-streaming Kuroni's celebration party, he could only use the app at most $$$\lfloor \frac{n}{2} \rfloor$$$ times. After that, the phone would die and there will be nothing left to help our dear friend! :(As the night is cold and dark, Kuroni needs to get back, so that he can reunite with his comfy bed and pillow(s). Can you help him figure out his hotel's location? | 256 megabytes | import java.util.*;
import java.io.*;
public class tr0 {
static PrintWriter out;
static StringBuilder sb;
static long mod = 1000000007;
static long inf = (long) 1e15;
static ArrayList<Integer>[] ad;
static int n, p, k;
static boolean[] in;
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
out = new PrintWriter(System.out);
n = sc.nextInt();
ad = new ArrayList[n];
for (int i = 0; i < n; i++)
ad[i] = new ArrayList<>();
for (int i = 0; i < n - 1; i++) {
int a = sc.nextInt() - 1;
int b = sc.nextInt() - 1;
ad[a].add(b);
ad[b].add(a);
}
in = new boolean[n];
Arrays.fill(in, true);
int q = n / 2;
while (q-- > 0) {
diameter();
System.out.println("? " + (s + 1) + " " + (t + 1));
lca = sc.nextInt();
if (s == t) {
System.out.println("! " + lca);
}
dfs(s);
// System.out.println(Arrays.toString(in));
dfs(t);
// System.out.println(Arrays.toString(in));
int c = 0;
for (int i = 0; i < n; i++)
if (in[i])
c++;
if (c == 1) {
System.out.println("! " + lca);
return;
}
}
//System.out.println("! " + lca);
out.flush();
}
static int s, t, lca;
static void dfs(int u) {
if (u == lca-1)
return;
// System.out.println(u);
in[u] = false;
for (int v : ad[u])
if (in[v])
dfs(v);
}
static void diameter() {
int[] dist = new int[n];
Arrays.fill(dist, -1);
int u = 0;
for (int i = 0; i < n; i++)
if (in[i]) {
u = i;
break;
}
dist[u] = 0;
Queue<Integer> q = new LinkedList<Integer>();
q.add(u);
while (!q.isEmpty()) {
int cur = q.poll();
for (int v : ad[cur])
if (dist[v] == -1 && in[v]) {
dist[v] = 1 + dist[cur];
q.add(v);
}
}
// System.out.println(u+" "+Arrays.toString(dist));
int k = -1;
for (int i = 0; i < n; i++)
if (dist[i] > k) {
k = dist[i];
s = i;
}
// System.out.println(u+" "+Arrays.toString(dist));
Arrays.fill(dist, -1);
dist[s] = 0;
q = new LinkedList<Integer>();
q.add(s);
while (!q.isEmpty()) {
int cur = q.poll();
for (int v : ad[cur])
if (dist[v] == -1 && in[v]) {
dist[v] = 1 + dist[cur];
q.add(v);
}
}
k = -1;
for (int i = 0; i < n; i++)
if (dist[i] > k) {
k = dist[i];
t = i;
}
// System.out.println(t+" "+s+" "+Arrays.toString(dist));
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
} | Java | ["6\n1 4\n4 2\n5 3\n6 3\n2 3\n\n3\n\n4\n\n4"] | 1 second | ["? 5 6\n\n? 3 1\n\n? 1 2\n\n! 4"] | NoteNote that the example interaction contains extra empty lines so that it's easier to read. The real interaction doesn't contain any empty lines and you shouldn't print any extra empty lines as well.The image below demonstrates the tree in the sample test: | Java 8 | standard input | [
"constructive algorithms",
"dfs and similar",
"trees",
"interactive"
] | a291ee66980d8b5856b24d1541e66fd0 | null | 1,900 | null | standard output | |
PASSED | fecbe88e31421431cd30ef91d0f99be7 | train_000.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes |
import java.io.*;
import java.util.Arrays;
import java.util.Collections;
public class Boredom {
static long[] dp;
static int size = 100001;
public static void main(String[] args)throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
/* int t = Integer.parseInt(br.readLine());
while(t-- > 0){*/
int n = Integer.parseInt(br.readLine());
String[] s = br.readLine().split(" ");
int[] a = new int[n];
for(int i=0; i<n ;i++)a[i] = Integer.parseInt(s[i]);
dp = new long[size];
Arrays.fill(dp,0);
for(int i=0; i<n; i++){
dp[a[i]]++;
}
long ans = interesting(n);
System.out.println(ans);
/*}*/
}
private static long interesting(int n){
for(int i=2; i<size; i++){
dp[i] = Math.max(dp[i-1] , dp[i-2]+dp[i]*i);
}
return dp[size-1];
}
}
| Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105). | 1,500 | Print a single integer — the maximum number of points that Alex can earn. | standard output | |
PASSED | dca06d3f0ecd3f764284bdabec5d0604 | train_000.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.lang.reflect.Array;
import java.security.KeyPair;
import java.util.*;
import java.lang.*;
import java.io.*;
public final class ProblemA
{
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
public static Reader sc = new Reader();
public static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
public static OutputStream out2 = new BufferedOutputStream ( System.out );
public static final int maxN = 100001;
public static long[] dp = new long[maxN];
public static long[] count = new long[maxN];
public static void main(String[] args) throws IOException
{
int n = sc.nextInt();
for(int i = 0; i < n; i++)
count[sc.nextInt()]++;
dp[0] = 0;
dp[1] = count[1];
for(int i = 2; i < maxN; i++)
{
dp[i] = Math.max(dp[i-1], dp[i-2]+count[i]*i);
}
out.write(dp[maxN-1]+"");
out.flush();
}
}
| Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105). | 1,500 | Print a single integer — the maximum number of points that Alex can earn. | standard output | |
PASSED | b8defef9f2980cc0f39dfce17589f39c | train_000.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.util.*;
import java.util.Scanner;
public class Solution {
static Scanner sc = new Scanner(System.in);
static PrintWriter pw = new PrintWriter(System.out);
public static void solve(int c, int n){
long[] count = new long[100001];
int max = 0;
for (int i = 0; i < n; i ++){
int a = sc.nextInt();
count[a] += 1;
max = Math.max(max, a);
}
long[] dp = new long[max + 1];
dp[0] = 0;
dp[1] = count[1];
for (int i = 2; i <= max; i ++){
dp[i] = Math.max(dp[i - 1], dp[i - 2] + i * count[i]);
}
pw.println(dp[max]);
}
public static void main(String[] args) {
int t = 1;
for (int i = 0; i < t; i ++){
int n = sc.nextInt();
solve(i + 1, n);
}
pw.close();
}
}
| Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105). | 1,500 | Print a single integer — the maximum number of points that Alex can earn. | standard output | |
PASSED | 790d88b02cb89419483b7fef65c7f536 | train_000.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main{
static int mod=1000000007;
public static void main(String[] args) throws IOException {
Writer out=new Writer(System.out);
Reader in=new Reader(System.in);
int t=1;
while(t-->0) {
int n=in.nextInt();
int a[]=in.readArray(n);
long cnt[]=new long[100001];
for(int i=0; i<n; i++) {
cnt[a[i]]++;
}
long f[]=new long[100001];
f[0]=0; f[1]=cnt[1];
for(int i=2; i<100001; i++){
//f[i] gives us the number of points we have after deleting i;
f[i]=Math.max(f[i-1],f[i-2]+cnt[i]*i);
}
out.println(f[100000]);
}
out.close();
}
static long pow(int b, int e) {
if(e==0) return 1;
long temp=pow(b,e/2);
temp=(temp*temp)%mod;
if(e%2==0) return temp;
return (temp*b)%mod;
}
/*********************************** UTILITY CODE BELOW **************************************/
static void sort(int[] a) {
ArrayList<Integer> list=new ArrayList<>();
for (int i:a) list.add(i);
Collections.sort(list);
for (int i=0; i<a.length; i++) a[i]=list.get(i);
}
static class Reader{
BufferedReader br;
StringTokenizer to;
Reader(InputStream stream){
br=new BufferedReader(new InputStreamReader(stream));
to=new StringTokenizer("");
}
String next() {
while(!to.hasMoreTokens()) {
try {
to=new StringTokenizer(br.readLine());
}catch(IOException e) {}
}
return to.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
int [] readArray(int n) {
int a[]=new int[n];
for(int i=0; i<n ;i++) a[i]=nextInt();
return a;
}
long [] readLongArray(int n) {
long a[]=new long[n];
for(int i=0; i<n ;i++) a[i]=nextLong();
return a;
}
}
static class Writer extends PrintWriter{
Writer(OutputStream stream){
super(stream);
}
void println(int [] array) {
for(int i=0; i<array.length; i++) {
print(array[i]+" ");
}
println();
}
void println(long [] array) {
for(int i=0; i<array.length; i++) {
print(array[i]+" ");
}
println();
}
}
} | Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105). | 1,500 | Print a single integer — the maximum number of points that Alex can earn. | standard output | |
PASSED | 5f3274cb08c4ab360fe2581611181648 | train_000.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main
{
public static void main(String []args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)), false);
solve(in, out);
in.close();
out.close();
}
static class FastScanner{
BufferedReader reader;
StringTokenizer st;
FastScanner(InputStream stream){reader=new BufferedReader(new InputStreamReader(stream));st=null;}
String next(){while(st == null || !st.hasMoreTokens()){try{String line = reader.readLine();if(line == null){return null;}
st = new StringTokenizer(line);}catch (Exception e){throw new RuntimeException();}}return st.nextToken();}
String nextLine() {String s=null;try{s=reader.readLine();}catch(IOException e){e.printStackTrace();}return s;}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble(){return Double.parseDouble(next());}
char nextChar() {return next().charAt(0);}
int[] nextIntArray(int n) {int[] arr= new int[n]; int i=0;while(i<n){arr[i++]=nextInt();} return arr;}
long[] nextLongArray(int n) {long[]arr= new long[n]; int i=0;while(i<n){arr[i++]=nextLong();} return arr;}
int[] nextIntArrayOneBased(int n) {int[] arr= new int[n+1]; int i=1;while(i<=n){arr[i++]=nextInt();} return arr;}
long[] nextLongArrayOneBased(int n){long[]arr= new long[n+1];int i=1;while(i<=n){arr[i++]=nextLong();}return arr;}
void close(){try{reader.close();}catch(IOException e){e.printStackTrace();}}
}
/********* SOLUTION STARTS HERE ************/
private static void solve(FastScanner in, PrintWriter out){
int n = in.nextInt(),cnt=0,x;
int MX = (int)1e5+5;
long a[] = new long[MX];
for(int i=0;i<n;i++) a[in.nextInt()]++;
for(int i=2;i<MX;i++) a[i] = Math.max(a[i]*1L*i + a[i-2], a[i-1]);
out.println(a[MX-1]);
}
/************* SOLUTION ENDS HERE **********/
} | Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105). | 1,500 | Print a single integer — the maximum number of points that Alex can earn. | standard output | |
PASSED | 4e0fd1e94768b5512c0ba37b76a66870 | train_000.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes |
import java.util.*;
import java.io.*;
public class vc_hahaha {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str=br.readLine();
StringTokenizer st=new StringTokenizer(str);
int n=Integer.parseInt(st.nextToken());
long[]arr=new long[100001];
str=br.readLine();
st=new StringTokenizer(str);
for(int i=0;i<n;i++) {
arr[Integer.parseInt(st.nextToken())]++;
}
long[]dp=new long[100001];
dp[0]=(long)0;
dp[1]=1L*arr[1];
for(int i=2;i<=100000;i++) {
dp[i]=Math.max(dp[i-1],dp[i-2]+i*arr[i]);
}
System.out.println(dp[100000]);
}
}
| Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105). | 1,500 | Print a single integer — the maximum number of points that Alex can earn. | standard output | |
PASSED | 00625345ca0ceaa84874f37931857dc5 | train_000.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | /*
ID: davidzh8
PROG: subset
LANG: JAVA
*/
import java.io.*;
import java.util.*;
import java.lang.*;
public class boredom {
//Start Stub
static long startTime = System.nanoTime();
//Globals Go Here
//Globals End
public static void main(String[] args) throws IOException {
FastScanner sc = new FastScanner("boredom.in", true);
FastWriter pw = new FastWriter("boredom.out", true);
int N= sc.ni();
long[] dp= new long[100001];
int[] arr= new int[100001];
for (int i = 0; i <N ; i++) {
arr[sc.ni()-1]++;
}
dp[0]= arr[0];
dp[1]=Math.max(dp[0],arr[1]*2);
for (int i = 2; i < 100001; i++) {
dp[i]= Math.max(dp[i-1],Math.max((long)arr[i]*(i+1)+dp[i-2], (long)arr[i-1]*(i)));
// System.out.println(dp[i]);
}
System.out.println(dp[100000]);
/* End Stub */
long endTime = System.nanoTime();
//System.out.println("Execution Time: " + (endTime - startTime) / 1e9 + " s");
pw.close();
}
static class Edge implements Comparable<Edge> {
int w;
int a;
int b;
public Edge(int w, int a, int b) {
this.w = w;
this.a = a;
this.b = b;
}
public int compareTo(Edge obj) {
if (obj.w == w) {
if (obj.a == a) {
return b - obj.b;
}
return a - obj.a;
} else return w - obj.w;
}
}
static class Pair implements Comparable<Pair> {
int a;
int b;
public Pair(int a, int b) {
this.a = a;
this.b = b;
}
public int compareTo(Pair obj) {
if (obj.a == a) {
return b - obj.b;
} else return a - obj.a;
}
}
static class SegmentTree {
public long[] arr;
public long[] tree;
public int N;
//Zero initialization
public SegmentTree(int n) {
N = n;
arr = new long[N];
tree = new long[4 * N + 1];
}
public long query(int treeIndex, int lo, int hi, int i, int j) {
// query for arr[i..j]
if (lo > j || hi < i)
return 0;
if (i <= lo && j >= hi)
return tree[treeIndex];
int mid = lo + (hi - lo) / 2;
if (i > mid)
return query(2 * treeIndex + 2, mid + 1, hi, i, j);
else if (j <= mid)
return query(2 * treeIndex + 1, lo, mid, i, j);
long leftQuery = query(2 * treeIndex + 1, lo, mid, i, mid);
long rightQuery = query(2 * treeIndex + 2, mid + 1, hi, mid + 1, j);
// merge query results
return merge(leftQuery, rightQuery);
}
public void update(int treeIndex, int lo, int hi, int arrIndex, long val) {
if (lo == hi) {
tree[treeIndex] = val;
arr[arrIndex] = val;
return;
}
int mid = lo + (hi - lo) / 2;
if (arrIndex > mid)
update(2 * treeIndex + 2, mid + 1, hi, arrIndex, val);
else if (arrIndex <= mid)
update(2 * treeIndex + 1, lo, mid, arrIndex, val);
// merge updates
tree[treeIndex] = merge(tree[2 * treeIndex + 1], tree[2 * treeIndex + 2]);
}
public long merge(long a, long b) {
return (a + b);
}
}
static class djset {
int N;
int[] parent;
// Creates a disjoint set of size n (0, 1, ..., n-1)
public djset(int n) {
parent = new int[n];
N = n;
for (int i = 0; i < n; i++)
parent[i] = i;
}
public int find(int v) {
// I am the club president!!! (root of the tree)
if (parent[v] == v) return v;
// Find my parent's root.
int res = find(parent[v]);
// Attach me directly to the root of my tree.
parent[v] = res;
return res;
}
public boolean union(int v1, int v2) {
// Find respective roots.
int rootv1 = find(v1);
int rootv2 = find(v2);
// No union done, v1, v2 already together.
if (rootv1 == rootv2) return false;
// Attach tree of v2 to tree of v1.
parent[rootv2] = rootv1;
return true;
}
}
static class FastScanner {
public BufferedReader br;
public StringTokenizer st;
public InputStream is;
public FastScanner(String name, boolean debug) throws IOException {
if (debug) {
is = System.in;
} else {
is = new FileInputStream(name);
}
br = new BufferedReader(new InputStreamReader(is), 32768);
st = null;
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int ni() {
return Integer.parseInt(next());
}
public long nl() {
return Long.parseLong(next());
}
public double nd() {
return Double.parseDouble(next());
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
return str;
}
}
static class FastWriter {
public PrintWriter pw;
public FastWriter(String name, boolean debug) throws IOException {
if (debug) {
pw = new PrintWriter(System.out);
} else {
pw = new PrintWriter(new BufferedWriter(new FileWriter(new File(name))));
}
}
public void println(Object text) {
pw.println(text);
}
public void print(Object text) {
pw.print(text);
}
public void close() {
pw.close();
}
public void flush() {
pw.flush();
}
}
}
| Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105). | 1,500 | Print a single integer — the maximum number of points that Alex can earn. | standard output | |
PASSED | ef205fd70b4671fba53a98d8903fc812 | train_000.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class P_455A {
static final FS sc = new FS();
static final PrintWriter pw = new PrintWriter(System.out);
public static void main(String[] args) {
int n = sc.nextInt();
int[] a = sc.nextArray(n);
long[] f = new long[100_001];
long[] ans = new long[100_001];
for(int i=0; i<n; i++){
f[a[i]]++;
}
ans[0] = 0;
ans[1] = f[1];
for(int i=2; i<100_001; i++){
ans[i] = Math.max(ans[i-1], ans[i-2]+f[i]*i);
}
System.out.println(ans[100_000]);
/*
Arrays.sort(a);
int ans = Integer.MIN_VALUE;
//int[] temp = new int[n];
ArrayList<Integer> temp = new ArrayList<>();
TreeMap<Integer, Integer> map = new TreeMap<>();
int count = 1;
for(int i=1; i<n; i++){
if(a[i]!=a[i-1]){
map.put(a[i-1],count);
count = 1;
}
else{
count++;
}
}
map.put(a[n-1],count);
int last = -1, prevLast = -1;
int ind = 0;
for(Map.Entry<Integer,Integer> entry : map.entrySet()){
if(ind<2){
int val = entry.getKey()*entry.getValue();
temp.add(val);
prevLast = last;
last = val;
ind++;
}
else{
int val = Math.max(last,prevLast+entry.getKey()*entry.getValue());
temp.add(val);
prevLast = last;
last = val;
}
}
for(int i : temp){
ans = Math.max(ans, i);
}
System.out.println(ans);
*/
}
static class FS {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
String next() {
while (!st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception ignored) {
}
}
return st.nextToken();
}
int[] nextArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
return a;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105). | 1,500 | Print a single integer — the maximum number of points that Alex can earn. | standard output | |
PASSED | 16bb9dc7ffb1ef76f8bd911ae0f050e2 | train_000.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Boredom {
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(bf.readLine());
long [] count = new long[100001];
StringTokenizer st = new StringTokenizer(bf.readLine());
for (int i = 0; i < n; i++) {
int x = Integer.parseInt(st.nextToken());
count[x]++;
}
long []dp = new long[100001];
dp[1]=count[1];
for (int i = 2; i < 100001; i++) {
dp [i]= Math.max(dp[i-1],dp[i-2]+count[i]*i);
}
System.out.print(dp[100000]);
}
}
| Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105). | 1,500 | Print a single integer — the maximum number of points that Alex can earn. | standard output | |
PASSED | 07f9a9d520d2300f1c6114b0d65820c1 | train_000.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
public static void process(int test_number)throws IOException
{
int n = ni(), cnt[] = new int[1000*100 + 1];
long dp[] = new long[1000 * 100 +1];
for(int i = 1; i <= n; i++){
int num = ni();
cnt[num]++;
}
dp[1] = cnt[1];
for(int i = 2; i <= 100*1000; i++){
dp[i] = Math.max(dp[i-1], (cnt[i] * 1l) * (i * 1l) + dp[i-2]);
}
pn(dp[100*1000]);
}
static final long mod = (long)1e9+7l;
static FastReader sc;
static PrintWriter out;
public static void main(String[]args)throws IOException
{
out = new PrintWriter(System.out);
sc = new FastReader();
long s = System.currentTimeMillis();
int t = 1;
//t = ni();
for(int i = 1; i <= t; i++)
process(i);
out.flush();
System.err.println(System.currentTimeMillis()-s+"ms");
}
static void trace(Object... o){ System.err.println(Arrays.deepToString(o)); };
static void pn(Object o){ out.println(o); }
static void p(Object o){ out.print(o); }
static int ni()throws IOException{ return Integer.parseInt(sc.next()); }
static long nl()throws IOException{ return Long.parseLong(sc.next()); }
static double nd()throws IOException{ return Double.parseDouble(sc.next()); }
static String nln()throws IOException{ return sc.nextLine(); }
static long gcd(long a, long b)throws IOException{ return (b==0)?a:gcd(b,a%b);}
static int gcd(int a, int b)throws IOException{ return (b==0)?a:gcd(b,a%b); }
static int bit(long n)throws IOException{ return (n==0)?0:(1+bit(n&(n-1))); }
static class FastReader{
BufferedReader br;
StringTokenizer st;
public FastReader(){
br = new BufferedReader(new InputStreamReader(System.in));
}
String next(){
while (st == null || !st.hasMoreElements()){
try{ st = new StringTokenizer(br.readLine()); } catch (IOException e){ e.printStackTrace(); }
}
return st.nextToken();
}
String nextLine(){
String str = "";
try{ str = br.readLine(); } catch (IOException e) { e.printStackTrace(); }
return str;
}
}
}
| Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105). | 1,500 | Print a single integer — the maximum number of points that Alex can earn. | standard output | |
PASSED | edf71f2b64d771f6ae728eb0271da9e5 | train_000.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes |
import java.util.Scanner;
public class Boredom {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
long n = sc.nextLong();
long arr[] = new long[100001];
for(int i = 0;i<n;i++)
{
arr[(int)sc.nextLong()]++;
}
long ans = 0;
long max2 = 0;
long max1 = 0;
for(int i = 1;i<100001;i++)
{
ans = Math.max(max1, max2 + (arr[i] * i));
max2 = max1;
max1 = ans;
}
System.out.println(ans);
sc.close();
}
}
| Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105). | 1,500 | Print a single integer — the maximum number of points that Alex can earn. | standard output | |
PASSED | 70766a8c8d3baf7a2fc7b433eee8f382 | train_000.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int n = Integer.parseInt(st.nextToken());
st = new StringTokenizer(infile.readLine());
List<Integer> special=new ArrayList<Integer>();
int MaxEl=0;
for (int index=0;index<n;index++)
{
special.add(Integer.parseInt(st.nextToken()));
MaxEl= Math.max(MaxEl,special.get(index));
}
long[] specialMas=new long[MaxEl+1];
for (int index=0;index<n;index++)
{
specialMas[special.get(index)]++;
}
Collections.sort(special);
long[] fRes=new long[MaxEl+1];
// int indexspecial=0;
for (int index=special.get(0);index<=MaxEl;index++)
{
// while (special.get(indexspecial)<index)
// indexspecial++;
specialMas[index]*=index;
if(index>1)
fRes[index] = Math.max(fRes[index-1],fRes[index-2]+specialMas[index]);
else
fRes[index] = specialMas[index];
}
System.out.println(fRes[MaxEl]);
}
}
| Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105). | 1,500 | Print a single integer — the maximum number of points that Alex can earn. | standard output | |
PASSED | f416cbe231dcd7821f71be5bd2c903f3 | train_000.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.io.*;
import java.util.*;
public class Solution{
public static long[] vals;
public static void main(final String[] args) throws IOException {
final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
StringTokenizer st = new StringTokenizer(input, " ");
int total = Integer.parseInt(st.nextToken());
input = br.readLine();
st = new StringTokenizer(input, " ");
int[] in = new int[total];
for (int i = 0; i < in.length; i++) {
in[i] = Integer.parseInt(st.nextToken());
}
Arrays.sort(in);
vals = new long[in[in.length-1]+1];
for(int i = 0; i<in.length; i++){
vals[in[i]]++;
}
//System.out.println(value(vals.length-1));
long[] dp = new long[vals.length];
dp[0] = 0;
dp[1] = 1*vals[1];
for(int i = 2; i<vals.length; i++){
dp[i] = Math.max(dp[i-1], vals[i]*i+dp[i-2]);
}
System.out.println(dp[dp.length-1]);
}
public static long value(int ind){
if(ind==0) return 0;
if(ind==1) return ind*vals[ind];
return Math.max(vals[ind]*ind+value(ind-2), value(ind-1));
}
} | Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105). | 1,500 | Print a single integer — the maximum number of points that Alex can earn. | standard output | |
PASSED | b2cde10f805ea65784ebe03ece4416eb | train_000.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.util.*;
import java.util.Scanner;
import java.io.*;
import javax.lang.model.util.ElementScanner6;
import static java.lang.System.out;
public class A455
{
public static void main(String args[])
{
FastReader in=new FastReader();
PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int tc=1;
//tc=in.nextInt();
while(tc-->0)
{
int n=in.nextInt();
long[] freq=new long[(int)(1e5)+1];
for(int i=0;i<n;i++)freq[in.nextInt()]++;
long ans[]=new long[(int)(1e5)+1];
ans[0]=0;
ans[1]=freq[1];
for(int i=2;i<=(int)(1e5);i++)
{
ans[i]=Math.max(ans[i-1],ans[i-2]+(long)i*freq[i]);
}
pr.println(ans[(int)(1e5)]);
}
pr.flush();
}
static void sort(long[] a) {
ArrayList<Long> l = new ArrayList<>();
for (long i : a)
l.add(i);
Collections.sort(l);
for (int i = 0; i < a.length; i++)
a[i] = l.get(i);
}
static void sort(int[] a) {
ArrayList<Integer> l = new ArrayList<>();
for (int i : a)
l.add(i);
Collections.sort(l);
for (int i = 0; i < a.length; i++)
a[i] = l.get(i);
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
| Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105). | 1,500 | Print a single integer — the maximum number of points that Alex can earn. | standard output | |
PASSED | 1f048d8c711b89dd174cd08e8c105eb9 | train_000.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java .util.*;
public class Soln
{
static long count[];
static long dp[];
static int max=100007;
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
int n=s.nextInt();
count=new long[max];
dp=new long[max];
for(int i=0;i<n;i++)
{
count[s.nextInt()]++;
}
dp[0]=0;
dp[1]=count[1];
for(int i=2;i<max;i++)
{
dp[i]=Math.max(dp[i-1],dp[i-2]+count[i]*i);
}
System.out.print(dp[max-1]);
}
} | Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105). | 1,500 | Print a single integer — the maximum number of points that Alex can earn. | standard output | |
PASSED | e280c3cc56ff6077bc11cd0a7dae494c | train_000.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes |
import java.util.*;
import java.io.*;
public class Boredom {
// https://codeforces.com/problemset/problem/455/A
public static void main(String[] args) throws IOException, FileNotFoundException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
//BufferedReader in = new BufferedReader(new FileReader("Boredom.in"));
// INPUT //
long n = Long.parseLong(in.readLine());
StringTokenizer st = new StringTokenizer(in.readLine());
long[] count = new long[100001];
long max = 0;
for (int i = 0; i < n; i++) {
long m = Long.parseLong(st.nextToken());
count[(int) m]++;
max = Math.max(max, m);
}
in.close();
// CALCULATION //
long[] dp = new long[(int )max+1];
dp[0] = 0;
dp[1] = count[1];
for (int i = 2; i < dp.length; i++) {
dp[i] = Math.max(dp[i-1], dp[i-2] + i * count[i]);
}
// OUTPUT //
System.out.println(dp[(int) max]);
}
}
| Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105). | 1,500 | Print a single integer — the maximum number of points that Alex can earn. | standard output | |
PASSED | 20943b08edfe799aebf06f932f2cae50 | train_000.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.util.*;
public class Boredom {
private static int temp;
private static int range = 0;
private static long[] dp = new long[100001];
private static long[] cnt = new long[100001];
private static int n;
public static void main(String[] args) {
final Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
for (int i = 0; i < n; i++) {
temp = scanner.nextInt();
if (temp > range) {
range = temp;
}
cnt[temp]++;
}
scanner.close();
dp[1] = cnt[1];
dp[2] = max(cnt[2]*2, dp[1]);
for (int i = 3; i <= range; i++) {
dp[i] = max(dp[i-1], dp[i-2] + cnt[i]*i);
}
System.out.println(dp[range]);
}
private static long max(long a, long b) {
return (a > b) ? a : b;
}
} | Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105). | 1,500 | Print a single integer — the maximum number of points that Alex can earn. | standard output | |
PASSED | 62abb35318a052ff91570f0e7e68c199 | train_000.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | /*package whatever //do not write package name here */
import java.util.*;
import java.lang.*;
import java.io.*;
public class Main {
public static long calc(long[] arr,long[] dp,int n){
dp[0]=0;
dp[1]=arr[1];
for(int i=2;i<100001;i++){
dp[i]=Math.max(dp[i-1],dp[i-2]+arr[i]*i);
}
return dp[100000];
}
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
long arr[]=new long[100001];
long dp[]=new long[100001];
for(int i=0;i<n;i++){
long x=sc.nextLong();
arr[(int)x]++;
}
long ans=calc(arr,dp,100001);
System.out.println(ans);
// System.out.println(Arrays.toString(dp));
}
} | Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105). | 1,500 | Print a single integer — the maximum number of points that Alex can earn. | standard output | |
PASSED | 62e4362500c12c7039be5268e0911ae2 | train_000.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.util.*;
import java.io.*;
public class Boredom {
public static void main(String[] args) {
Scanner sc = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int N = sc.nextInt();
int max = 0;
long[] A = new long[100001];
for (int i = 0; i < N; i++) {
int x = sc.nextInt();
A[x] += x;
max = Math.max(max, x);
}
long[] dp = new long[max+1];
dp[0] = 0;
dp[1] = A[1];
for (int i = 1; i < max; i++) {
dp[i+1] = Math.max(dp[i], A[i+1] + dp[i-1]);
}
System.out.println(dp[max]);
}
} | Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105). | 1,500 | Print a single integer — the maximum number of points that Alex can earn. | standard output | |
PASSED | 9bcf3d37ba11396c50cf3ae55a7da242 | train_000.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
import java.util.regex.*;
import java.util.concurrent.*;
import java.text.*;
public class Solution {
public static final Scanner scanner = new Scanner(System.in);
public static Long getMaxPoints(int[] arr, int n) {
Long[] freq = new Long[100005];
for(int i = 0;i <n;i++) {
freq[arr[i]] = (freq[arr[i]] == null ? 0L : freq[arr[i]]) + 1 ;
}
Long[] maxPoints = new Long[100001];
Long maxPointsGlobal = 0L;
for(int i=0; i < 100001; i++) {
if( i-2 >= 0 ) {
maxPoints[i] = (freq[i] == null ? 0L : freq[i]) * i + maxPoints[i-2];
} else {
maxPoints[i] = (freq[i] == null ? 0L : freq[i]) * i;
}
maxPointsGlobal = Math.max(maxPointsGlobal, maxPoints[i]);
maxPoints[i] = maxPointsGlobal;
}
return maxPointsGlobal;
}
public static void main(String[] args) {
int n = scanner.nextInt();
int[] q = new int[n];
int i=0;
while(scanner.hasNext()) {
q[i++] = scanner.nextInt();
}
System.out.println(getMaxPoints(q, n));
}
} | Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105). | 1,500 | Print a single integer — the maximum number of points that Alex can earn. | standard output | |
PASSED | 04a5a2575547ce30cb2e9d7559af2871 | train_000.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static long freq[];
static long memo[];
private static long f(int i){
if(i==0) return 0;
if(i==1) return freq[1];
if(memo[i]!=-1) return memo[i];
memo[i] = Math.max(f(i-1), f(i-2) + freq[i] * i);
return memo[i];
}
private static void solve(InputReader sc, PrintWriter out) throws Exception {
int n = sc.nextInt();
int arr[] = new int[n];
freq = new long[100001];
memo = new long[100001];
Arrays.fill(memo, -1);
int max = 0;
for(int i=0; i<n; i++) {
arr[i] = sc.nextInt();
if(arr[i] > max) max = arr[i];
freq[arr[i]]++;
}
out.println(f(max));
}
public static Set<Integer> seive(int n) {
boolean[] arr = new boolean[n + 1];
Set<Integer> hs = new HashSet<>();
Arrays.fill(arr, true);
for (int i = 2; i <= n; i++) {
if (arr[i]) {
for (int j = i + i; j <= n; j += i) {
arr[j] = false;
}
}
}
for (int i = 2; i <= n; i++) {
if (arr[i]) hs.add(i);
}
return hs;
}
private static int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
public static void main(String[] args) throws Exception {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
solve(in, out);
out.close();
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
class Pair {
int x, y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
return x == pair.x &&
y == pair.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
} | Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105). | 1,500 | Print a single integer — the maximum number of points that Alex can earn. | standard output | |
PASSED | 7eac2c3d196d97368c4adc38febd9f4c | train_000.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main {
static final int M = 1000000007;
static FastReader in = new FastReader();
static PrintWriter out = new PrintWriter(System.out);
// static Scanner in = new Scanner(System.in);
// File file = new File("input.txt");
// Scanner in = new Scanner(file);
// PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
public static void main(String[] args) {
// int t = in.nextInt();
// while(t-- > 0){
long n = in.nextLong();
long[] a= new long[100001];
for(int i=0;i<n;i++) {
int x= in.nextInt();
a[x]+=x;
}
for(int i=2;i<100001;i++){
a[i]=Math.max(a[i-2]+a[i], a[i-1]);
}
out.println(a[100000]);
// }
out.close();
}
static int gcd(int a, int b) {
if(b==0) return a;
return gcd(b, a%b);
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
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 | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105). | 1,500 | Print a single integer — the maximum number of points that Alex can earn. | standard output | |
PASSED | 9a467ba7cc3e1076048785fedf48e119 | train_000.jsonl | 1407511800 | Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and delete it, at that all elements equal to ak + 1 and ak - 1 also must be deleted from the sequence. That step brings ak points to the player. Alex is a perfectionist, so he decided to get as many points as possible. Help him. | 256 megabytes | //Coded By Visnunathan
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.lang.*;
public class codeforces {
// static int[] arr;
// static int n,k;
public static void main(String[] args) {
FastScanner sc=new FastScanner();
// int T=sc.nextInt();
// for (int tt=0; tt<T; tt++) {
int n = sc.nextInt();
//arr = sc.readArray(n);
int x;
long[] freq = new long[100005];
for(int i=0; i<n; i++) {
x = sc.nextInt();
freq[x]++;
}
long[] dp = new long[100005];
dp[1] = freq[1];
dp[2] = Math.max(2*freq[2],dp[1]);
for(int i=3; i<100001; i++) {
dp[i] = Math.max(dp[i-1],dp[i-2]+i*freq[i]);
}
System.out.println(dp[100000]);
}
static final Random random=new Random();
static void ruffleSort(int[] a) {
int n=a.length;//shuffle, then sort
for (int i=0; i<n; i++) {
int oi=random.nextInt(n), temp=a[oi];
a[oi]=a[i]; a[i]=temp;
}
Arrays.sort(a);
}
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());
}
int[] readArray(int n) {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["2\n1 2", "3\n1 2 3", "9\n1 2 1 3 2 2 2 2 3"] | 1 second | ["2", "4", "10"] | NoteConsider the third test example. At first step we need to choose any element equal to 2. After that step our sequence looks like this [2, 2, 2, 2]. Then we do 4 steps, on each step we choose any element equals to 2. In total we earn 10 points. | Java 11 | standard input | [
"dp"
] | 41b3e726b8146dc733244ee8415383c0 | The first line contains integer n (1 ≤ n ≤ 105) that shows how many numbers are in Alex's sequence. The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105). | 1,500 | Print a single integer — the maximum number of points that Alex can earn. | standard output | |
PASSED | bdb9ad3f62902e27ac07d8730e93e075 | train_000.jsonl | 1488096300 | Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int k = in.nextInt();
int[] a = new int[n];
int[] b = new int[n];
for (int i = 0; i < n; ++i)
a[i] = in.nextInt();
for (int i = 0; i < n; ++i)
b[i] = in.nextInt();
long ans = 0;
int[] diff = new int[n];
int index = 0;
for (int i = 0; i < n; ++i) {
if (a[i] <= b[i]) {
ans += a[i];
--k;
} else {
ans += b[i];
diff[index++] = a[i] - b[i];
}
}
Arrays.sort(diff, 0, index);
for (int i = 0; i < k; ++i)
ans += diff[i];
out.println(ans);
}
}
}
| Java | ["3 1\n5 4 6\n3 1 5", "5 3\n3 4 7 10 3\n4 5 5 12 5"] | 2 seconds | ["10", "25"] | NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy"
] | b5355e1f4439b198d2cc7dea01bc4bc3 | In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week). | 1,200 | Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now. | standard output | |
PASSED | 663c50395c000bebb14634c364330c0c | train_000.jsonl | 1488096300 | Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items. | 256 megabytes |
import java.util.*;
import java.lang.*;
import java.io.*;
public class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc=new Scanner(System.in);
StringBuilder sb=new StringBuilder();
int n=sc.nextInt();
int k=sc.nextInt();
int a[]=new int[n];
int b[]=new int[n];
for( int i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
for( int i=0;i<n;i++)
{
b[i]=sc.nextInt();
}
ArrayList<Pair> adj=new ArrayList<>();
for( int i=0;i<n;i++)
{
adj.add(new Pair(a[i]-b[i],i));
}
Collections.sort(adj, new myComparator());
int i=0;
long ans=0;
while((i<n&&adj.get(i).x<0)||i<k)
{
ans+=1l*a[adj.get(i).y];
i++;
}
while(i<n)
{
ans+=b[adj.get(i).y];
i++;
}
System.out.println(ans);
}
public static int bin( long val, long a[])
{
int l=0;
int h=a.length;
int ans=0;
while(l<h)
{
int m=(l+h)/2;
if(a[m]>=val)
{
ans=m+1;
h=m;
}
else
{
l=m+1;
}
}
return ans;
}
}
class Pair{
int x; int y;
Pair( int x, int y)
{
this.x=x;
this.y=y;
}
}
class myComparator implements Comparator<Pair>
{
public int compare(Pair a, Pair b)
{
return Integer.compare(a.x, b.x);
}
} | Java | ["3 1\n5 4 6\n3 1 5", "5 3\n3 4 7 10 3\n4 5 5 12 5"] | 2 seconds | ["10", "25"] | NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy"
] | b5355e1f4439b198d2cc7dea01bc4bc3 | In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week). | 1,200 | Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now. | standard output | |
PASSED | cebb815eb653ec7e6798aac1269ae0e1 | train_000.jsonl | 1488096300 | Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items. | 256 megabytes | import java.util.*;
import java.io.*;
public class Solution1 {
private void solve() throws IOException {
int n = in.nextInt();
int k = in.nextInt();
Tovar[] t = new Tovar[n];
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
for (int i = 0; i < n; i++) {
int p = in.nextInt();
t[i] = new Tovar(a[i], p, a[i] - p);
}
Arrays.sort(t);
int ans = 0;
for (int i = 0; i < n; i++) {
if (t[i].r <= 0) {
ans += t[i].a;
t[i].stock = false;
k -= 1;
}
}
int i = 0;
for (; k > 0 && i < n; i++) {
if (t[i].stock) {
k -= 1;
ans += t[i].a;
t[i].stock = false;
}
}
for (; i < n; i++) {
if (t[i].stock) {
ans += t[i].b;
t[i].stock = false;
}
}
System.out.println(ans);
}
private class Tovar implements Comparable<Tovar> {
int a;
int b;
int r;
boolean stock;
public Tovar(int a, int b, int r) {
this.a = a;
this.b = b;
this.r = r;
stock = true;
}
@Override
public String toString() {
return "Tovar{" +
"a=" + a +
", b=" + b +
", r=" + r +
'}';
}
@Override
public int compareTo(Tovar t) {
return this.r > t.r ? 1 : this.r < t.r ? - 1 : 0;
}
}
private static String filename = "";
private PrintWriter out;
MyScanner in;
private void run() throws IOException {
in = new MyScanner();
out = new PrintWriter(System.out);
solve();
in.close();
out.close();
}
private class MyScanner {
private BufferedReader br;
private StringTokenizer st;
public MyScanner() throws IOException {
this.br = new BufferedReader(new InputStreamReader(System.in));
}
public MyScanner(String fileTitle) throws IOException {
this.br = new BufferedReader(new FileReader(fileTitle));
}
public String nextLine() throws IOException {
String s = br.readLine();
return s == null ? "-1" : s;
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String s = br.readLine();
if (s == null) {
return "-1";
}
st = new StringTokenizer(s);
}
return st.nextToken();
}
public Integer nextInt() throws IOException {
return Integer.parseInt(this.next());
}
public Long nextLong() throws IOException {
return Long.parseLong(this.next());
}
public Double nextDouble() throws IOException {
return Double.parseDouble(this.next());
}
public void close() throws IOException {
this.br.close();
}
}
public static void main(String[] args) throws IOException{
Locale.setDefault(Locale.US);
new Solution1().run();
}
}
| Java | ["3 1\n5 4 6\n3 1 5", "5 3\n3 4 7 10 3\n4 5 5 12 5"] | 2 seconds | ["10", "25"] | NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy"
] | b5355e1f4439b198d2cc7dea01bc4bc3 | In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week). | 1,200 | Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now. | standard output | |
PASSED | c54a5cfb46a7fbed9f6ee9e6ab0d40b1 | train_000.jsonl | 1488096300 | Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items. | 256 megabytes | //package yahia;
import java.util.*;
import java.io.*;
public class yahia {
public static void main (String [] Yahia_Mostafa) {
Scanner sc =new Scanner(System.in);
int n=sc.nextInt(),k=sc.nextInt(),t=n-k;
int [ ] x=new int [n];
int [] y=new int[n];
Integer r [] =new Integer [n];
long sum=0; for (int i=0;i<n;++i) {
x[i]=sc.nextInt();
sum+=x[i];
}
for (int i=0;i<n;++i) {
y[i]=sc.nextInt();
r[i]=y[i]-x[i];
}
Arrays.sort(r);
//System.out.println(Arrays.toString(r));
for (int i =0;i<n-k;++i) {
if (r[i]>=0)
break;
sum+=r[i];
//System.out.println(sum+" "+i);
}
System.out.println(sum);
}
}
| Java | ["3 1\n5 4 6\n3 1 5", "5 3\n3 4 7 10 3\n4 5 5 12 5"] | 2 seconds | ["10", "25"] | NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy"
] | b5355e1f4439b198d2cc7dea01bc4bc3 | In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week). | 1,200 | Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now. | standard output | |
PASSED | 109a188e75bc6bbc63caa9b7d10aa13c | train_000.jsonl | 1488096300 | Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items. | 256 megabytes |
import java.io.*;
import java.util.*;
import static java.lang.Integer.parseInt;
import java.lang.Math;
;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tk;
//Scanner in = new Scanner(System.in);
PrintWriter p = new PrintWriter(System.out);
StringBuilder out = new StringBuilder();
tk=new StringTokenizer(in.readLine());
int n=parseInt(tk.nextToken()),k=parseInt(tk.nextToken());
pair[]a=new pair[n];
tk=new StringTokenizer(in.readLine());
for (int i = 0; i < n; i++) {
a[i]=new pair(i, i);
a[i].x=parseInt(tk.nextToken());
}
tk=new StringTokenizer(in.readLine());
for (int i = 0; i < n; i++) {
a[i].y=parseInt(tk.nextToken());
a[i].d=a[i].x-a[i].y;
}
Arrays.sort(a);
long ans=0;
for (int i = 0; i < n; i++) {
if(i<k){
ans+=a[i].x;
}
else if(a[i].d<0)
ans+=a[i].x;
else
ans+=a[i].y;
}
p.println(ans);
p.flush();
p.close();
}
}
class pair implements Comparable<pair>{
int x,y,d;
public pair(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(pair t) {
return d-t.d;
}
} | Java | ["3 1\n5 4 6\n3 1 5", "5 3\n3 4 7 10 3\n4 5 5 12 5"] | 2 seconds | ["10", "25"] | NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy"
] | b5355e1f4439b198d2cc7dea01bc4bc3 | In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week). | 1,200 | Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now. | standard output | |
PASSED | d1bf45bb87a70d72f751b904013fe17b | train_000.jsonl | 1488096300 | Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items. | 256 megabytes | import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
static class Obj {
public int pr1;
public int pr2;
public int profit;
public Obj() {
pr1 = 0;
pr2 = 0;
profit = 0;
}
int getProfit() {
return -profit;
}
};
static class Task {
int n, k;
Obj[] objs;
private void readInput() {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
k = sc.nextInt();
objs = new Obj[n];
for (int i = 0; i < n; i++) {
objs[i] = new Obj();
objs[i].pr1 = sc.nextInt();
}
for (int i = 0; i < n; i++) {
objs[i].pr2 = sc.nextInt();
objs[i].profit = objs[i].pr2 - objs[i].pr1;
}
sc.close();
}
public void sortare(Obj[] objs, int n) {
for (int i = 0; i < n-1; i++)
for (int j = i+1; j < n; j++) {
if (objs[i].profit < objs[j].profit) {
Obj aux = objs[i];
objs[i] = objs[j];
objs[j] = aux;
}
}
}
private void getResult() {
int rez = 0;
Arrays.sort(objs, Comparator.comparing(Obj::getProfit));
int i;
for (i = 0; i < k; i++) {
rez+=objs[i].pr1;
}
while(i < n && objs[i].profit > 0) {
rez += objs[i].pr1;
i++;
}
while(i < n) {
rez += objs[i].pr2;
i++;
}
System.out.println(rez);
}
public void solve() {
readInput();
getResult();
}
}
public static void main(String[] args) {
new Task().solve();
}
}
| Java | ["3 1\n5 4 6\n3 1 5", "5 3\n3 4 7 10 3\n4 5 5 12 5"] | 2 seconds | ["10", "25"] | NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy"
] | b5355e1f4439b198d2cc7dea01bc4bc3 | In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week). | 1,200 | Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now. | standard output | |
PASSED | 0ae8bb16deaa48828b0bc160ddb78d79 | train_000.jsonl | 1488096300 | Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items. | 256 megabytes | import java.awt.List;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.*;
public class Watermelon {
public static void main(String[] args) throws IOException{
Main m=new Main();
m.solve();
}
}
class Main{
static int[] temp=new int[100];
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
private int[] array;
private int[] tempMergArr;
private int length;
StringTokenizer stringTokenizer;
String next() throws IOException {
while (stringTokenizer == null || !stringTokenizer.hasMoreTokens()) {
stringTokenizer = new StringTokenizer(reader.readLine());
}
return stringTokenizer.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
void solve() throws IOException {
int n=this.nextInt();
int k=this.nextInt();
int[] arr=new int[n];
int[] carr=new int[n];
ArrayList<Integer> list=new ArrayList<>();
ArrayList<Integer> list1=new ArrayList<>();
for(int i=0;i<n;i++)
{ arr[i]=this.nextInt();list.add(arr[i]);}
for(int i=0;i<n;i++)
{ carr[i]=this.nextInt();list1.add(carr[i]);}
Count[] parr=new Count[n];
for(int i=0;i<n;i++)
parr[i]=new Count(i,arr[i]-carr[i],arr[i],carr[i]);
Arrays.sort(parr);
int sum=0;
for(int i=0;i<k;i++){
sum+=arr[parr[i].i];
list.set(parr[i].i, -1);
list1.set(parr[i].i, -1);
}
for(int i=0;i<list.size();i++){
if(list.get(i)==-1)
continue;
if(list.get(i)>list1.get(i))
sum+=list1.get(i);
else
sum+=list.get(i);
}
System.out.println(sum);
}
private static int add(int x,int y){
if(x==0&&y==1)
return 1;
if(x==1&&y==0)
return 1;
if(x==0&&y==0)
return 0;
if(x==1&&y==1)
return 0;
return 0;
}
private static int[] column(int[] arr){
for(int i=0;i<arr.length;i++)
arr[i]=(1-arr[i]);
return arr;
}
private static int[] row(int[] arr){
for(int i=0;i<arr.length;i++)
arr[i]=(1-arr[i]);
return arr;
}
private static int gcd(int a, int b)
{
while (b > 0)
{
int temp = b;
b = a % b; // % is remainder
a = temp;
}
return a;
}
private static int lcm(int a, int b)
{
return a * (b / gcd(a, b));
}
static int[] toFractionPos(int x,int y){
int a=gcd(x,y);
int[] arr={x/a,y/a};
//display(arr);
return arr;
}
static void display(int[][] arr){
for(int i=0;i<arr.length;i++){
for(int j=0;j<arr[i].length;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
System.out.println();
}
static void display(String[] arr){
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+" ");
}
System.out.println();
}
static void display(int[] arr){
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
System.out.println();
}
static void display(double[] arr){
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+" ");
}
System.out.println();
}
static void display(char[] arr){
// System.out.println();
int t=0;
for(int i=0;i<arr.length;i++){
if(arr[i]!='0'){t=i;break;}
}
while(t!=arr.length){
System.out.print(arr[t]);
t++;
}
System.out.println();
}
static String str(char[] carr){
String str="";
for(int i=0;i<carr.length;i++){
str=str+carr[i];
}
return str;
}
public void sort(int inputArr[]) {
this.array = inputArr;
this.length = inputArr.length;
this.tempMergArr = new int[length];
doMergeSort(0, length - 1);
}
private void doMergeSort(int lowerIndex, int higherIndex) {
if (lowerIndex < higherIndex) {
int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
// Below step sorts the left side of the array
doMergeSort(lowerIndex, middle);
// Below step sorts the right side of the array
doMergeSort(middle + 1, higherIndex);
// Now merge both sides
mergeParts(lowerIndex, middle, higherIndex);
}
}
private void mergeParts(int lowerIndex, int middle, int higherIndex) {
for (int i = lowerIndex; i <= higherIndex; i++) {
tempMergArr[i] = array[i];
}
int i = lowerIndex;
int j = middle + 1;
int k = lowerIndex;
while (i <= middle && j <= higherIndex) {
if (tempMergArr[i] <= tempMergArr[j]) {
array[k] = tempMergArr[i];
i++;
} else {
array[k] = tempMergArr[j];
j++;
}
k++;
}
while (i <= middle) {
array[k] = tempMergArr[i];
k++;
i++;
}
}
}
class Count implements Comparable {
int i;
int j;
int k;
int l;
Count(int i,int j,int k,int l){
this.j=j;
this.i=i;
this.k=k;
this.l=l;
}
void display(){
System.out.println(i+" "+j);
}
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
Count c=(Count)o;
if(j>c.j)
return 1;
else if(j<c.j)
return -1;
else{
return 0;
}
}
}
class Extra{
ArrayList<Integer> list=new ArrayList<>();
Extra(int l,int r){
for(int i=l;i<=r;i++){
list.add(i);
}
}
void display(){
System.out.println(list.size());
for(int i=0;i<list.size();i++){
System.out.print(list.get(i)+" ");
}
System.out.println();
}
}
| Java | ["3 1\n5 4 6\n3 1 5", "5 3\n3 4 7 10 3\n4 5 5 12 5"] | 2 seconds | ["10", "25"] | NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy"
] | b5355e1f4439b198d2cc7dea01bc4bc3 | In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week). | 1,200 | Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now. | standard output | |
PASSED | b3d02175120fddf9e8779c4a59dc7d72 | train_000.jsonl | 1488096300 | Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Watermelon{
static int[] a;
static boolean[] visited;
public static void main (String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n=sc.nextInt(),k=sc.nextInt();
Node[] node=new Node[n];
for(int i=0;i<n;i++) node[i]=new Node(-1,-1);
for(int i=0;i<n;i++) node[i].a=sc.nextInt();
for(int i=0;i<n;i++) node[i].b=sc.nextInt();
Arrays.sort(node);
long sum=0;
for(int i=0;i<k;i++)sum+=node[i].a;
for(int i=k;i<n;i++)sum+=(((node[i].a-node[i].b)<0)?(long)node[i].a:(long)node[i].b);
System.out.print(sum);
}
static class Node implements Comparable<Node>{
int a,b;
Node(int a,int b){this.a=a;this.b=b;}
@Override
public int compareTo(Node node) {
if((this.a-this.b)>(node.a-node.b))return 1;
else if((this.a-this.b)<(node.a-node.b))return -1;
else return 0;
}
}
}
| Java | ["3 1\n5 4 6\n3 1 5", "5 3\n3 4 7 10 3\n4 5 5 12 5"] | 2 seconds | ["10", "25"] | NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy"
] | b5355e1f4439b198d2cc7dea01bc4bc3 | In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week). | 1,200 | Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now. | standard output | |
PASSED | dce8f095c4ffa28b767a25ce7fac8172 | train_000.jsonl | 1488096300 | Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items. | 256 megabytes | import java.io.*;
import java.util.*;
public class C {
public static void main(String[] args) throws Exception {
FastScannerC fs = new FastScannerC();
PrintWriter out = new PrintWriter(System.out);
int n = fs.nextInt(), k = fs.nextInt();
Buy[] a = new Buy[n];
int[] x = fs.nextIntArray(n), y = fs.nextIntArray(n);
for(int i = 0; i < n; i++) {
a[i] = new Buy();
a[i].dis = x[i]; a[i].now = y[i];
a[i].diff = (y[i] - x[i]);
}
Arrays.sort(a);
long res = 0;
int start = 0;
for(int i = 0; i < n; i++) {
if(i < k) {
res += a[i].dis;
} else {
if(a[i].diff >= 0) {
res += a[i].dis;
} else {
start = i;
break;
}
}
start = i+1;
}
if(k == n) start = n;
for(int i = start; i < n; i++) {
res += a[i].now;
}
out.println(res);
out.close();
}
static class Buy implements Comparable<Buy> {
int now, dis, diff;
@Override
public int compareTo(Buy o) {
if(o.diff == diff) {
return now - o.now;
}
return o.diff - diff;
}
}
}
class FastScannerC {
BufferedReader br;
StringTokenizer st;
public FastScannerC() {
try {
// br = new BufferedReader(new FileReader("testdata.out"));
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer("");
} catch (Exception e){e.printStackTrace();}
}
public String next() {
if (st.hasMoreTokens()) return st.nextToken();
try {st = new StringTokenizer(br.readLine());}
catch (Exception e) {e.printStackTrace();}
return st.nextToken();
}
public int nextInt() {return Integer.parseInt(next());}
public long nextLong() {return Long.parseLong(next());}
public double nextDouble() {return Double.parseDouble(next());}
public String nextLine() {
String line = "";
try {line = br.readLine();}
catch (Exception e) {e.printStackTrace();}
return line;
}
public Integer[] nextIntegerArray(int n) {
Integer[] a = new Integer[n];
for(int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for(int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
public char[] nextCharArray() {
return nextLine().toCharArray();
}
} | Java | ["3 1\n5 4 6\n3 1 5", "5 3\n3 4 7 10 3\n4 5 5 12 5"] | 2 seconds | ["10", "25"] | NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy"
] | b5355e1f4439b198d2cc7dea01bc4bc3 | In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week). | 1,200 | Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now. | standard output | |
PASSED | b2bb2f031d4423815eb03fcddd3da381 | train_000.jsonl | 1488096300 | Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items. | 256 megabytes | import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
public class FirstApp {
class Tov implements Comparable<Tov>{
int index;
float sailToAfter;
public Tov(int ind,float val){
index = ind;
sailToAfter = val;
}
@Override
public int compareTo(Tov tov){
if(this.sailToAfter < tov.sailToAfter){
return -1;
}
else if(this.sailToAfter > tov.sailToAfter){
return 1;
}
return 0;
}
}
public int function(){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
int [] sail = new int[n];
int [] after = new int[n];
for(int i = 0; i < n; i++){
sail[i] = in.nextInt();
}
for(int i = 0; i < n; i++){
after[i] = in.nextInt();
}
boolean [] wasBought = new boolean[n];
Tov [] array = new Tov[n];
for(int i = 0; i < n; i++){
Tov t = new Tov(i,(float)(sail[i] - after[i]));
array[i] = t;
}
Arrays.sort(array);
int i = 0;
int cost = 0;
while(i < k){
cost += sail[array[i].index];
i++;
}
while(i!=n && sail[array[i].index] < after[array[i].index]){
cost += sail[array[i].index];
i++;
}
while(i < n){
cost += after[array[i].index];
i++;
}
return cost;
}
public static void main(String[] args) {
FirstApp app = new FirstApp();
System.out.print(app.function());
}
} | Java | ["3 1\n5 4 6\n3 1 5", "5 3\n3 4 7 10 3\n4 5 5 12 5"] | 2 seconds | ["10", "25"] | NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy"
] | b5355e1f4439b198d2cc7dea01bc4bc3 | In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week). | 1,200 | Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now. | standard output | |
PASSED | 1c4ecba4953ba5490e229d16c5860bc4 | train_000.jsonl | 1488096300 | Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items. | 256 megabytes |
import java.util.*;
public class SOLVE {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
int k = reader.nextInt();
int[] before = new int[n];
int[] diff = new int[n];
int sum = 0;
for (int i = 0; i < n; i++) {
before[i] = reader.nextInt();
}
for (int i = 0; i < n; i++) {
int b = reader.nextInt();
diff[i] = before[i] - b;
sum += b;
}
int totalDiff = 0;
Arrays.sort(diff);
for (int i = 0; i < n && (i < k || diff[i] <= 0); i++) {
totalDiff += diff[i];
}
System.out.println(sum + totalDiff);
}
}
| Java | ["3 1\n5 4 6\n3 1 5", "5 3\n3 4 7 10 3\n4 5 5 12 5"] | 2 seconds | ["10", "25"] | NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy"
] | b5355e1f4439b198d2cc7dea01bc4bc3 | In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week). | 1,200 | Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now. | standard output | |
PASSED | 0d4a4340a9d0e0bc2560f3b280fa9eec | train_000.jsonl | 1488096300 | Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items. | 256 megabytes | import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class TestFindBuyItem {
public static void main(String[] args) throws IOException {
// System.out.println("200000 0");
// for (int i=0; i<400000; i++) {
// System.out.print("1 ");
// }
// BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Integer totalMoney = 0;
Scanner sc = new Scanner(System.in);
int totalItem = sc.nextInt();
int leastItem = sc.nextInt();
List<Integer> disPrice = new ArrayList<>(totalItem);
for (int i=0; i<totalItem; i++) {
disPrice.add(sc.nextInt());
}
final List<Integer> norPrice = new ArrayList<>(totalItem);
for (int i=0; i<totalItem; i++) {
norPrice.add(sc.nextInt());
}
sc.close();
List<Integer> sortList = new ArrayList<>(totalItem);
Map<Integer, ArrayList<Integer>> indexMap = new HashMap<>();
for (int i = 0; i < disPrice.size(); i++) {
int a = disPrice.get(i) - norPrice.get(i);
sortList.add(a);
if (null == indexMap.get(a)) {
indexMap.put(a, new ArrayList<Integer>());
}
indexMap.get(a).add(i);
}
//List<Integer> sortList = sort(price, false);
Collections.sort(sortList);
Integer hasChooseDis = 0;
for (int i = 0; i < sortList.size();) {
ArrayList<Integer> list = indexMap.get(sortList.get(i));
for (Integer index : list) {
if (hasChooseDis < leastItem || sortList.get(i) <= 0) {
totalMoney += disPrice.get(index);
hasChooseDis++;
} else {
totalMoney += norPrice.get(index);
}
i++;
}
}
System.out.println(totalMoney);
}
}
| Java | ["3 1\n5 4 6\n3 1 5", "5 3\n3 4 7 10 3\n4 5 5 12 5"] | 2 seconds | ["10", "25"] | NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy"
] | b5355e1f4439b198d2cc7dea01bc4bc3 | In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week). | 1,200 | Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now. | standard output | |
PASSED | 4604f0f1dbc75bfab3d30e4cf408018a | train_000.jsonl | 1488096300 | Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.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);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, Scanner in, PrintWriter out) {
int n = in.nextInt();
int k = in.nextInt();
TaskC.Item[] arr = new TaskC.Item[n];
for (int i = 0; i < n; i++) {
arr[i] = new TaskC.Item();
arr[i].dis = in.nextInt();
}
for (int i = 0; i < n; i++)
arr[i].not = in.nextInt();
Arrays.sort(arr);
int answer = 0;
int i;
// for(i=0;i<n;i++)
// out.println(arr[i].dis+" "+arr[i].not);
for (i = 0; i < k; i++) {
answer += arr[i].dis;
//out.println(arr[i].dis+" "+arr[i].not);
}
while (i < n) {
if (arr[i].not < arr[i].dis)
answer += arr[i].not;
else
answer += arr[i].dis;
i++;
}
out.println(answer);
}
static class Item implements Comparable<TaskC.Item> {
int dis;
int not;
public int compareTo(TaskC.Item item) {
int temp = (this.dis - this.not) - (item.dis - item.not);
return temp;
// else if(item.dis>this.dis)
// return -1;
// else
// return temp;
}
}
}
}
| Java | ["3 1\n5 4 6\n3 1 5", "5 3\n3 4 7 10 3\n4 5 5 12 5"] | 2 seconds | ["10", "25"] | NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy"
] | b5355e1f4439b198d2cc7dea01bc4bc3 | In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week). | 1,200 | Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now. | standard output | |
PASSED | 77a3c0d03bc9ef768c8d75b58ccf9ec0 | train_000.jsonl | 1488096300 | Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items. | 256 megabytes | import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static class Item implements Comparable {
public int price;
public int discountedPrice;
public int dif;
public Item() {
price = 0;
discountedPrice = 0;
}
@Override
public int compareTo(Object arg0) {
if (dif > ((Item) arg0).dif) {
return 1;
}
if (dif == ((Item) arg0).dif)
return 0;
return -1;
}
}
static class Task {
public final static String INPUT_FILE = "in";
public final static String OUTPUT_FILE = "out";
int n, k;
Item[] items;
private void readInput() {
{
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
k = sc.nextInt();
items = new Item[n];
for (int i = 0; i < n; i++) {
items[i] = new Item();
items[i].price = sc.nextInt();
}
for (int i = 0; i < n; i++) {
items[i].discountedPrice = sc.nextInt();
items[i].dif = items[i].price - items[i].discountedPrice;
}
sc.close();
}
}
private void writeOutput(int result) {
{
PrintWriter pw = new PrintWriter(System.out);
pw.printf("%d\n", result);
pw.close();
}
}
private int getResult() {
// TODO: sort dupa diferenta then take all with positive pri-discPrice
Arrays.sort(items);
int price = 0, i=0;
for (i = 0; i < k; i++) {
Item sitem = items[i];
//System.out.println("dif " + items[i].dif + " this week " + items[i].price + " next week "
// + items[i].discountedPrice);
price+= sitem.price;
}
while(i<n && items[i].dif<0) {
price+= items[i].price;
i++;
}
while (i<n) {
price+= items[i].discountedPrice;
i++;
}
return price;
}
public void solve() {
readInput();
writeOutput(getResult());
}
}
public static void main(String[] args) {
new Task().solve();
}
} | Java | ["3 1\n5 4 6\n3 1 5", "5 3\n3 4 7 10 3\n4 5 5 12 5"] | 2 seconds | ["10", "25"] | NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy"
] | b5355e1f4439b198d2cc7dea01bc4bc3 | In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week). | 1,200 | Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now. | standard output | |
PASSED | 7a6c40a298fa26605ceb60e6261cb8bf | train_000.jsonl | 1488096300 | Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items. | 256 megabytes | import java.util.*;
import java.io.*;
public class hello
{
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 z=new FastReader();
int n=z.nextInt();
int k=z.nextInt();
int ar[][]=new int[n][3];
int i;int j;
for(i=0;i<n;i++)ar[i][0]=z.nextInt();
for(i=0;i<n;i++)ar[i][1]=z.nextInt();
for(i=0;i<n;i++)ar[i][2]=ar[i][0]-ar[i][1];
Arrays.sort(ar, Comparator.comparingInt(arr -> arr[2]));
long sum=0;
for(i=0;i<k;i++)sum+=ar[i][0];
for(i=k;i<n;i++)
{
if(ar[i][2]>0)sum+=ar[i][1];
else sum+=ar[i][0];
}
System.out.println(sum);
}
}
| Java | ["3 1\n5 4 6\n3 1 5", "5 3\n3 4 7 10 3\n4 5 5 12 5"] | 2 seconds | ["10", "25"] | NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy"
] | b5355e1f4439b198d2cc7dea01bc4bc3 | In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week). | 1,200 | Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now. | standard output | |
PASSED | 302c868fdd5bb23356b9d2eacd344208 | train_000.jsonl | 1488096300 | Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items. | 256 megabytes |
import java.util.*;
public class Dishonest_Sellers {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int n,k;
n=scanner.nextInt();
k=scanner.nextInt();
int a[]=new int[n];
int b[]=new int[n];
for(int i=0;i<n;i++) {
a[i]=scanner.nextInt();
}
for(int i=0;i<n;i++) {
b[i]=scanner.nextInt();
}
ArrayList<Pair> arrayList=new ArrayList<Pair>();
for(int i=0;i<n;i++)
{
arrayList.add(new Pair(a[i], b[i]));
}
// System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");
Collections.sort(arrayList, new MyComparator());
// for(int i=0;i<n;i++)
// {
// System.out.println(arrayList.get(i).a+" "+arrayList.get(i).b);
// }
long sum=0;
for(int i=1;i<=k;i++)
{
sum+=arrayList.get(i-1).a;
}
//System.out.println(sum);
for(int i=k;i<n;i++)
{
if(arrayList.get(i).a>arrayList.get(i).b)
{
sum+=arrayList.get(i).b;//System.out.println(arrayList.get(i).a+">>>>>>>>"+arrayList.get(i).b);
}
else {
sum+=arrayList.get(i).a;//System.out.println(arrayList.get(i).a+">>>>>>>>"+arrayList.get(i).b);
}
}
System.out.println(sum);
}
}
class Pair
{
int a,b;
Pair(int a,int b)
{
this.a=a;
this.b=b;
}
}
class MyComparator implements Comparator<Pair>
{
@Override
public int compare(Pair p1, Pair p2) {
if(p1.a-p1.b <p2.a-p2.b)
return -1;
else if(p1.a-p1.b >p2.a-p2.b)return 1;
else
{
if(p1.a>p2.a)
return 1;
else if(p1.a==p2.a)
return 0;
else {
return -1;
}
}
}
}
| Java | ["3 1\n5 4 6\n3 1 5", "5 3\n3 4 7 10 3\n4 5 5 12 5"] | 2 seconds | ["10", "25"] | NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy"
] | b5355e1f4439b198d2cc7dea01bc4bc3 | In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week). | 1,200 | Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now. | standard output | |
PASSED | a33b4d95e90005c27a6e1b9231f7924b | train_000.jsonl | 1488096300 | Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items. | 256 megabytes | //author : Brijesh Patel
import java.io.*;
import java.math.*;
import java.util.*;
import javax.print.attribute.SetOfIntegerSyntax;
public class Main {
private static InputStream stream;
private static byte[] buf = new byte[1024];
private static int curChar;
private static int numChars;
private static SpaceCharFilter filter;
private static PrintWriter pw;
private static long count = 0,mod=1000000007;
private static TreeSet<Integer>ts[]=new TreeSet[200000];
ArrayList<Integer> gph[]=new ArrayList[200000];
public static void main(String args[]) throws Exception {
InputReader(System.in);
pw = new PrintWriter(System.out);
soln();
pw.close();
}
private static void soln() {
int n=nextInt();
int k = nextInt();
int a[]=new int[n];
int b[]=new int[n];
int c[]=new int[n];
for(int i=0;i<n;i++){
a[i]=nextInt();
}
for(int i=0;i<n;i++){
b[i]=nextInt();
}
for(int i=0;i<n;i++){
c[i]=a[i]-b[i];
}
//nextLine();
Pair[] arr=new Pair[n];
for(int i=0;i<n;i++){
//int temp = nextInt();
arr[i] = new Pair(c[i],i);
}
Arrays.sort(arr);
int ans=0;
for(int i=0;i<n;i++){
//System.out.println(arr[i].d+" "+ arr[i].index);
if(i<k || arr[i].d<=0){
ans=ans+a[arr[i].index];
}
else {
ans=ans+b[arr[i].index];
}
}
System.out.println(ans);
//.sort(arr);
/*Iterator it=al.iterator();
while(it.hasNext()){
pw.println(it.next());
}
for(int i=0;i<n;i++){
//pw.println(arr[i].str);
}*/
}
public static class SegTree{
ArrayList<Integer> tree = new ArrayList<Integer>();
int[] A;
SegTree(int[] arr){
A=arr;
build(0,0,arr.length-1);
}
int leftchld(int n){ return 2*n+1;}
int rightchld(int n){ return 2*n+2;}
void build(int node, int start, int end)
{
if(start == end)
{
// Leaf node will have a single element
tree.remove(node);
tree.add(node, A[start]);
}
else
{
int mid = (start + end) / 2;
// Recurse on the left child
build(2*node, start, mid);
// Recurse on the right child
build(2*node+1, mid+1, end);
// Internal node will have the sum of both of its children
tree.remove(node);
tree.add(node, (tree.get(2*node+1) + tree.get(2*node+2)));
}
}
}
public static void dfs(ArrayList<Integer>[] al,int a){
ArrayList<Boolean> mark=new ArrayList<Boolean>(al.length+1);
mark.add(a, true);
for(int i=0;i<al[a].size();i++){
int current=al[a].get(i);
if(!mark.get(i)){
dfs(al,current);
mark.set(current, true);
}
}
}
public static class Graph<T>{
ArrayList<T> vertex=new ArrayList<T>();
Vector<T> edge=new Vector<T>();
Graph(){
}
}
public static ArrayList<Integer> allprime(int n){
ArrayList<Integer> arr=new ArrayList<Integer>();
arr.add(2);
for(int i=3;i<n;i++){
int flag=0;
for(int j=0;j<arr.size();j++){
if(i%arr.get(j)==0) {flag=1;break;}
}
if(flag==0) arr.add(i);
}
return arr;
}
public static int fact(int n){
int ans=1;
for(int i=1;i<=n;i++) ans=(ans*i)%1000000007;
return ans;
}
static class Pair implements Comparable<Pair>{
int d;
int index;
Pair(int d,int in){
this.d=d;
this.index=in;
}
@Override
public int compareTo(Pair o){
return Integer.compare(this.d, o.d);
}
/*String str;
int l;
Pair(String s){
this.str=s;
this.l=str.length();
}
public int compareTo(Pair o) {
// TODO Auto-generated method stub
// Sort in increasing order
if(o.l<l){
return 1;
}
if(o.l==l ){
return str.compareTo(o.str);
}else{
return -1;
}
}*/
}
public static long gcd(long x, long y) {
if (x % y == 0)
return y;
else
return gcd(y, x % y);
}
private static int BinarySearch(int a[], int low, int high, int target) {
if (low > high)
return -1;
int mid = low + (high - low) / 2;
if (a[mid] == target)
return mid;
if (a[mid] > target)
high = mid - 1;
if (a[mid] < target)
low = mid + 1;
return BinarySearch(a, low, high, target);
}
public static String reverseString(String s) {
StringBuilder sb = new StringBuilder(s);
sb.reverse();
return (sb.toString());
}
public static long pow(long n, long p, long m) {
long result = 1;
if (p == 0)
return 1;
if (p == 1)
return n;
while (p != 0) {
if (p % 2 == 1)
result *= n;
if (result >= m)
result %= m;
p >>= 1;
n *= n;
if (n >= m)
n %= m;
}
return result;
}
public static long pow(long n, long p) {
long result = 1;
if (p == 0)
return 1;
if (p == 1)
return n;
while (p != 0) {
if (p % 2 == 1)
result *= n;
p >>= 1;
n *= n;
}
return result;
}
public static int[] radixSort(int[] f) {
int[] to = new int[f.length];
{
int[] b = new int[65537];
for (int i = 0; i < f.length; i++)
b[1 + (f[i] & 0xffff)]++;
for (int i = 1; i <= 65536; i++)
b[i] += b[i - 1];
for (int i = 0; i < f.length; i++)
to[b[f[i] & 0xffff]++] = f[i];
int[] d = f;
f = to;
to = d;
}
{
int[] b = new int[65537];
for (int i = 0; i < f.length; i++)
b[1 + (f[i] >>> 16)]++;
for (int i = 1; i <= 65536; i++)
b[i] += b[i - 1];
for (int i = 0; i < f.length; i++)
to[b[f[i] >>> 16]++] = f[i];
int[] d = f;
f = to;
to = d;
}
return f;
}
public static int nextPowerOf2(final int a) {
int b = 1;
while (b < a) {
b = b << 1;
}
return b;
}
public static boolean PointInTriangle(int p1, int p2, int p3, int p4, int p5, int p6, int p7, int p8) {
int s = p2 * p5 - p1 * p6 + (p6 - p2) * p7 + (p1 - p5) * p8;
int t = p1 * p4 - p2 * p3 + (p2 - p4) * p7 + (p3 - p1) * p8;
if ((s < 0) != (t < 0))
return false;
int A = -p4 * p5 + p2 * (p5 - p3) + p1 * (p4 - p6) + p3 * p6;
if (A < 0.0) {
s = -s;
t = -t;
A = -A;
}
return s > 0 && t > 0 && (s + t) <= A;
}
public static float area(int x1, int y1, int x2, int y2, int x3, int y3) {
return (float) Math.abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0);
}
public static boolean isPrime(int n) {
// Corner cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
//merge Sort
static long sort(int a[])
{ int n=a.length;
int b[]=new int[n];
return mergeSort(a,b,0,n-1);}
static long mergeSort(int a[],int b[],long left,long right)
{ long c=0;if(left<right)
{ long mid=left+(right-left)/2;
c= mergeSort(a,b,left,mid);
c+=mergeSort(a,b,mid+1,right);
c+=merge(a,b,left,mid+1,right); }
return c; }
static long merge(int a[],int b[],long left,long mid,long right)
{long c=0;int i=(int)left;int j=(int)mid; int k=(int)left;
while(i<=(int)mid-1&&j<=(int)right)
{ if(a[i]>a[j]) {b[k++]=a[i++]; }
else { b[k++]=a[j++];c+=mid-i;}}
while (i <= (int)mid - 1) b[k++] = a[i++];
while (j <= (int)right) b[k++] = a[j++];
for (i=(int)left; i <= (int)right; i++)
a[i] = b[i]; return c; }
// To Get Input
// Some Buffer Methods
public static void InputReader(InputStream stream1) {
stream = stream1;
}
private static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private static boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
private static int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
private static int 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;
}
private static long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
private static String nextToken() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private static String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
private static int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
private static int[][] next2dArray(int n, int m) {
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = nextInt();
}
}
return arr;
}
private static long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
private static void pArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
pw.print(arr[i] + " ");
}
pw.println();
return;
}
private static void pArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
pw.print(arr[i] + " ");
}
pw.println();
return;
}
private static void pArray(boolean[] arr) {
for (int i = 0; i < arr.length; i++) {
pw.print(arr[i] + " ");
}
pw.println();
return;
}
private static boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
private interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
} | Java | ["3 1\n5 4 6\n3 1 5", "5 3\n3 4 7 10 3\n4 5 5 12 5"] | 2 seconds | ["10", "25"] | NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy"
] | b5355e1f4439b198d2cc7dea01bc4bc3 | In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week). | 1,200 | Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now. | standard output | |
PASSED | e3ed4af0b0136985b5a02b7df33fbd3b | train_000.jsonl | 1488096300 | Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items. | 256 megabytes | //author : Brijesh Patel
import java.io.*;
import java.math.*;
import java.util.*;
import javax.print.attribute.SetOfIntegerSyntax;
public class Main {
private static InputStream stream;
private static byte[] buf = new byte[1024];
private static int curChar;
private static int numChars;
private static SpaceCharFilter filter;
private static PrintWriter pw;
private static long count = 0,mod=1000000007;
private static TreeSet<Integer>ts[]=new TreeSet[200000];
ArrayList<Integer> gph[]=new ArrayList[200000];
public static void main(String args[]) throws Exception {
InputReader(System.in);
pw = new PrintWriter(System.out);
soln();
pw.close();
}
private static void soln() {
int n=nextInt();
int k = nextInt();
int a[]=new int[n];
int b[]=new int[n];
int c[]=new int[n];
for(int i=0;i<n;i++){
a[i]=nextInt();
}
for(int i=0;i<n;i++){
b[i]=nextInt();
}
for(int i=0;i<n;i++){
c[i]=a[i]-b[i];
}
//nextLine();
Pair[] arr=new Pair[n];
for(int i=0;i<n;i++){
//int temp = nextInt();
arr[i] = new Pair(c[i],i);
}
Arrays.sort(arr);
int ans=0;
for(int i=0;i<n;i++){
//System.out.println(arr[i].d+" "+ arr[i].index);
if(i<k || arr[i].d<=0){
ans=ans+a[arr[i].index];
}
else {
ans=ans+b[arr[i].index];
}
}
System.out.println(ans);
//.sort(arr);
/*Iterator it=al.iterator();
while(it.hasNext()){
pw.println(it.next());
}
for(int i=0;i<n;i++){
//pw.println(arr[i].str);
}*/
}
public static class SegTree{
ArrayList<Integer> tree = new ArrayList<Integer>();
int[] A;
SegTree(int[] arr){
A=arr;
build(0,0,arr.length-1);
}
int leftchld(int n){ return 2*n+1;}
int rightchld(int n){ return 2*n+2;}
void build(int node, int start, int end)
{
if(start == end)
{
// Leaf node will have a single element
tree.remove(node);
tree.add(node, A[start]);
}
else
{
int mid = (start + end) / 2;
// Recurse on the left child
build(2*node, start, mid);
// Recurse on the right child
build(2*node+1, mid+1, end);
// Internal node will have the sum of both of its children
tree.remove(node);
tree.add(node, (tree.get(2*node+1) + tree.get(2*node+2)));
}
}
}
public static void dfs(ArrayList<Integer>[] al,int a){
ArrayList<Boolean> mark=new ArrayList<Boolean>(al.length+1);
mark.add(a, true);
for(int i=0;i<al[a].size();i++){
int current=al[a].get(i);
if(!mark.get(i)){
dfs(al,current);
mark.set(current, true);
}
}
}
public static class Graph<T>{
ArrayList<T> vertex=new ArrayList<T>();
Vector<T> edge=new Vector<T>();
Graph(){
}
}
public static ArrayList<Integer> allprime(int n){
ArrayList<Integer> arr=new ArrayList<Integer>();
arr.add(2);
for(int i=3;i<n;i++){
int flag=0;
for(int j=0;j<arr.size();j++){
if(i%arr.get(j)==0) {flag=1;break;}
}
if(flag==0) arr.add(i);
}
return arr;
}
public static int fact(int n){
int ans=1;
for(int i=1;i<=n;i++) ans=(ans*i)%1000000007;
return ans;
}
static class Pair implements Comparable<Pair>{
int d;
int index;
Pair(int d,int in){
this.d=d;
this.index=in;
}
@Override
public int compareTo(Pair o){
if(o.d<d){
return 1;
}
else if(o.d==d){
return 0;
}
else return -1;
}
/*String str;
int l;
Pair(String s){
this.str=s;
this.l=str.length();
}
public int compareTo(Pair o) {
// TODO Auto-generated method stub
// Sort in increasing order
if(o.l<l){
return 1;
}
if(o.l==l ){
return str.compareTo(o.str);
}else{
return -1;
}
}*/
}
public static long gcd(long x, long y) {
if (x % y == 0)
return y;
else
return gcd(y, x % y);
}
private static int BinarySearch(int a[], int low, int high, int target) {
if (low > high)
return -1;
int mid = low + (high - low) / 2;
if (a[mid] == target)
return mid;
if (a[mid] > target)
high = mid - 1;
if (a[mid] < target)
low = mid + 1;
return BinarySearch(a, low, high, target);
}
public static String reverseString(String s) {
StringBuilder sb = new StringBuilder(s);
sb.reverse();
return (sb.toString());
}
public static long pow(long n, long p, long m) {
long result = 1;
if (p == 0)
return 1;
if (p == 1)
return n;
while (p != 0) {
if (p % 2 == 1)
result *= n;
if (result >= m)
result %= m;
p >>= 1;
n *= n;
if (n >= m)
n %= m;
}
return result;
}
public static long pow(long n, long p) {
long result = 1;
if (p == 0)
return 1;
if (p == 1)
return n;
while (p != 0) {
if (p % 2 == 1)
result *= n;
p >>= 1;
n *= n;
}
return result;
}
public static int[] radixSort(int[] f) {
int[] to = new int[f.length];
{
int[] b = new int[65537];
for (int i = 0; i < f.length; i++)
b[1 + (f[i] & 0xffff)]++;
for (int i = 1; i <= 65536; i++)
b[i] += b[i - 1];
for (int i = 0; i < f.length; i++)
to[b[f[i] & 0xffff]++] = f[i];
int[] d = f;
f = to;
to = d;
}
{
int[] b = new int[65537];
for (int i = 0; i < f.length; i++)
b[1 + (f[i] >>> 16)]++;
for (int i = 1; i <= 65536; i++)
b[i] += b[i - 1];
for (int i = 0; i < f.length; i++)
to[b[f[i] >>> 16]++] = f[i];
int[] d = f;
f = to;
to = d;
}
return f;
}
public static int nextPowerOf2(final int a) {
int b = 1;
while (b < a) {
b = b << 1;
}
return b;
}
public static boolean PointInTriangle(int p1, int p2, int p3, int p4, int p5, int p6, int p7, int p8) {
int s = p2 * p5 - p1 * p6 + (p6 - p2) * p7 + (p1 - p5) * p8;
int t = p1 * p4 - p2 * p3 + (p2 - p4) * p7 + (p3 - p1) * p8;
if ((s < 0) != (t < 0))
return false;
int A = -p4 * p5 + p2 * (p5 - p3) + p1 * (p4 - p6) + p3 * p6;
if (A < 0.0) {
s = -s;
t = -t;
A = -A;
}
return s > 0 && t > 0 && (s + t) <= A;
}
public static float area(int x1, int y1, int x2, int y2, int x3, int y3) {
return (float) Math.abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2.0);
}
public static boolean isPrime(int n) {
// Corner cases
if (n <= 1)
return false;
if (n <= 3)
return true;
// This is checked so that we can skip
// middle five numbers in below loop
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
//merge Sort
static long sort(int a[])
{ int n=a.length;
int b[]=new int[n];
return mergeSort(a,b,0,n-1);}
static long mergeSort(int a[],int b[],long left,long right)
{ long c=0;if(left<right)
{ long mid=left+(right-left)/2;
c= mergeSort(a,b,left,mid);
c+=mergeSort(a,b,mid+1,right);
c+=merge(a,b,left,mid+1,right); }
return c; }
static long merge(int a[],int b[],long left,long mid,long right)
{long c=0;int i=(int)left;int j=(int)mid; int k=(int)left;
while(i<=(int)mid-1&&j<=(int)right)
{ if(a[i]>a[j]) {b[k++]=a[i++]; }
else { b[k++]=a[j++];c+=mid-i;}}
while (i <= (int)mid - 1) b[k++] = a[i++];
while (j <= (int)right) b[k++] = a[j++];
for (i=(int)left; i <= (int)right; i++)
a[i] = b[i]; return c; }
// To Get Input
// Some Buffer Methods
public static void InputReader(InputStream stream1) {
stream = stream1;
}
private static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private static boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
private static int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
private static int 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;
}
private static long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
private static String nextToken() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private static String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
private static int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
private static int[][] next2dArray(int n, int m) {
int[][] arr = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
arr[i][j] = nextInt();
}
}
return arr;
}
private static long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
private static void pArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
pw.print(arr[i] + " ");
}
pw.println();
return;
}
private static void pArray(long[] arr) {
for (int i = 0; i < arr.length; i++) {
pw.print(arr[i] + " ");
}
pw.println();
return;
}
private static void pArray(boolean[] arr) {
for (int i = 0; i < arr.length; i++) {
pw.print(arr[i] + " ");
}
pw.println();
return;
}
private static boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
private interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
} | Java | ["3 1\n5 4 6\n3 1 5", "5 3\n3 4 7 10 3\n4 5 5 12 5"] | 2 seconds | ["10", "25"] | NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy"
] | b5355e1f4439b198d2cc7dea01bc4bc3 | In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week). | 1,200 | Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now. | standard output | |
PASSED | 7021671edce8f0599152bf96bcf8e980 | train_000.jsonl | 1488096300 | Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class Main {
class Num implements Comparable<Num> {
int x;
int index;
@Override
public int compareTo(Num num) {
return this.x - num.x;
}
}
int n, k;
Num[] a;
Num[] b;
public void solve() {
Scanner scan = new Scanner(System.in);
n = scan.nextInt();
k = scan.nextInt();
a = new Num[n];
b = new Num[n];
int payment = 0;
for (int i = 0; i < n; i++) {
a[i] = new Num();
a[i].x = scan.nextInt();
a[i].index = i;
}
for (int i = 0; i < n; i++) {
b[i] = new Num();
b[i].x = scan.nextInt();
b[i].index = i;
}
Num[] differenceVector = new Num[n];
for (int i = 0; i < n; i++) {
differenceVector[i] = new Num();
differenceVector[i].x = a[i].x - b[i].x;
differenceVector[i].index = i;
}
Arrays.sort(differenceVector);
int i = 0;
while(i < n && (i < k || differenceVector[i].x <= 0)) {
payment += a[differenceVector[i].index].x;
i++;
}
while(i < n) {
payment += b[differenceVector[i].index].x;
i++;
}
System.out.println(payment);
}
public static void main(String[] args)
{
Main m = new Main();
m.solve();
}
}
| Java | ["3 1\n5 4 6\n3 1 5", "5 3\n3 4 7 10 3\n4 5 5 12 5"] | 2 seconds | ["10", "25"] | NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy"
] | b5355e1f4439b198d2cc7dea01bc4bc3 | In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week). | 1,200 | Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now. | standard output | |
PASSED | 3fb8f3936a0abb955b507fd7b664022a | train_000.jsonl | 1488096300 | Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items. | 256 megabytes | import java.util.Arrays;
import java.util.Scanner;
public class C {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();int k=sc.nextInt();
int a[]=new int[n];
int c[]=new int[n];
int b;
for(int i=0;i<n;i++)
{b=sc.nextInt();a[i]+=b;}
for(int i=0;i<n;i++)
{b=sc.nextInt();c[i]=Math.min(a[i], b);a[i]-=b;}
Arrays.sort(a);
int ans=0;
for(int i=0;i<k;i++)
if(a[i]>0)ans+=a[i];
for(int i=0;i<n;i++)
ans+=c[i];
System.out.println(ans);
}
}
| Java | ["3 1\n5 4 6\n3 1 5", "5 3\n3 4 7 10 3\n4 5 5 12 5"] | 2 seconds | ["10", "25"] | NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy"
] | b5355e1f4439b198d2cc7dea01bc4bc3 | In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week). | 1,200 | Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now. | standard output | |
PASSED | a263a27a0926e992762d37f1f68cb945 | train_000.jsonl | 1488096300 | Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items. | 256 megabytes |
import java.util.Arrays;
import java.util.Scanner;
public class C {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();int k=sc.nextInt();
int a[]=new int[n];
int c[]=new int[n];
int b;
for(int i=0;i<n;i++)
{b=sc.nextInt();a[i]+=b;}
for(int i=0;i<n;i++)
{b=sc.nextInt();c[i]=Math.min(a[i], b);a[i]-=c[i];}
Arrays.sort(a);
int ans=0;
for(int i=0;i<k;i++)
ans+=a[i];
for(int i=0;i<n;i++)
ans+=c[i];
System.out.println(ans);
}
}
| Java | ["3 1\n5 4 6\n3 1 5", "5 3\n3 4 7 10 3\n4 5 5 12 5"] | 2 seconds | ["10", "25"] | NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy"
] | b5355e1f4439b198d2cc7dea01bc4bc3 | In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week). | 1,200 | Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now. | standard output | |
PASSED | cab9b23550d0671dadc732eae6daea28 | train_000.jsonl | 1488096300 | Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items. | 256 megabytes | import java.io.*;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int k = in.nextInt();
int a[] = new int[n];
PriorityQueue<Price> pq = new PriorityQueue<>();
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
for (int i = 0; i < n; i++) {
int b = in.nextInt();
pq.add(new Price(a[i],b, a[i]-b));
}
int min = 0;
for (int i = 0; i < k; i++) {
min += pq.poll().price;
}
while(!pq.isEmpty()) {
Price p = pq.peek();
if(p.price < p.price2) {
min += pq.poll().price;
} else {
min += pq.poll().price2;
}
}
out.println(min);
out.close();
}
static class Price implements Comparable<Price> {
int price;
int price2;
double cheapest;
public Price(int price, int price2, double cheapest) {
this.price = price;
this.price2 = price2;
this.cheapest = cheapest;
}
@Override
public int compareTo(Price o) {
return Double.compare(cheapest, o.cheapest);
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
} | Java | ["3 1\n5 4 6\n3 1 5", "5 3\n3 4 7 10 3\n4 5 5 12 5"] | 2 seconds | ["10", "25"] | NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy"
] | b5355e1f4439b198d2cc7dea01bc4bc3 | In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week). | 1,200 | Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now. | standard output | |
PASSED | af73c4f423a27d9c2c9f284f9e79899e | train_000.jsonl | 1488096300 | Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items. | 256 megabytes | /*
Logic is the strongest weapon.
*/
import java.io.*;
import java.math.*;
import java.util.*;
import java.util.Map.Entry;
public class Coding {
private static InputStream stream;
private static byte[] buf = new byte[1024];
private static int curChar;
private static int numChars;
private static SpaceCharFilter filter;
private static PrintWriter pw;
private static int N = 1234567;
public static int soln() {
int n = nI();
int k = nI();
int[] a = new int[n];
int[] b = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nI();
}
for (int i = 0; i < n; ++i) {
b[i] = nI();
}
int[] c = new int[n];
int p = 0;
int r = 0;
for (int i = 0; i < n; i++) {
if (a[i] <= b[i]) {
r += a[i];
--k;
} else {
r += b[i];
c[p++] = a[i] - b[i];
}
}
Arrays.sort(c, 0, p); //start & end index................
for (int i = 0; i < k; i++) {
r += c[i];
}
pw.println(r);
return 0;
}
public static void main(String[] args) {
InputReader(System.in);
pw = new PrintWriter(System.out);
soln();
pw.close();
}
/*
*********************************************************************************************
*/
public static void InputReader(InputStream stream1) {
stream = stream1;
}
private static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private static boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
private static int read() {
if (numChars == -1) {
throw new InputMismatchException();
}
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0) {
return -1;
}
}
return buf[curChar++];
}
private static int nI() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
private static long nL() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
private static String nS() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private static String nLi() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
private static boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
private interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
| Java | ["3 1\n5 4 6\n3 1 5", "5 3\n3 4 7 10 3\n4 5 5 12 5"] | 2 seconds | ["10", "25"] | NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy"
] | b5355e1f4439b198d2cc7dea01bc4bc3 | In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week). | 1,200 | Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now. | standard output | |
PASSED | 1e90e5c8703700e8a6277c7b5dc0074a | train_000.jsonl | 1488096300 | Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), k = sc.nextInt(),ans=0;
int[] b = new int[n], a = new int[n], d = new int[n];
for(int i=0 ; i<n ;i++){
b[i] = sc.nextInt();
ans+=b[i];
}
for(int i=0 ; i<n ;i++){
a[i] = sc.nextInt();
}
for(int i=0 ; i<n ;i++){
d[i] = a[i] - b[i];
}
Arrays.sort(d);
for(int i=n-k-1 ; i>=0 ; i--){
if(d[i]>0)
continue;
ans+=d[i];
}
System.out.print(ans);
}
} | Java | ["3 1\n5 4 6\n3 1 5", "5 3\n3 4 7 10 3\n4 5 5 12 5"] | 2 seconds | ["10", "25"] | NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy"
] | b5355e1f4439b198d2cc7dea01bc4bc3 | In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week). | 1,200 | Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now. | standard output | |
PASSED | cbe614a814fe324774d56424f1f31591 | train_000.jsonl | 1488096300 | Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items. | 256 megabytes | import java.util.List;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.StringTokenizer;
import java.util.TreeMap;
public class Tester{
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int k = Integer.parseInt(st.nextToken());
int[]ar1 = new int[n];
int[] b = new int[n];
st = new StringTokenizer(br.readLine());
for(int i=0 ;i<n ; i++) ar1[i] = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
for(int i=0 ; i<n ; i++) b[i] = Integer.parseInt(st.nextToken());
TreeMap<Integer,Integer> map = new TreeMap<Integer,Integer>();
List<Integer> list = new ArrayList<Integer>();
for(int i=0 ; i<n ; i++){
map.put(i, ar1[i]-b[i]);
list.add(i);
}
Collections.sort(list, new Comparator<Integer>(){
public int compare(Integer o1, Integer o2){
int a = map.get(o1);
int b = map.get(o2);
if(a<b) return -1;
if(a>b) return 1;
Integer a1 = ar1[o1];
Integer a2 = ar1[o2];
return a1.compareTo(a2);
}
});
int[] sa = new int[n];
int[] sb = new int[n];
for(int i=0 ; i<n ; i++){
sa[i] = ar1[list.get(i)];
sb[i] = b[list.get(i)];
}
int sum = 0;
for(int i=0 ; i<n ; i++){
if(i<k) sum+=sa[i];
else{
sum+= Math.min(sa[i], sb[i]);
}
}
System.out.println(sum);
}
} | Java | ["3 1\n5 4 6\n3 1 5", "5 3\n3 4 7 10 3\n4 5 5 12 5"] | 2 seconds | ["10", "25"] | NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy"
] | b5355e1f4439b198d2cc7dea01bc4bc3 | In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week). | 1,200 | Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now. | standard output | |
PASSED | 155b500c95c37cebc870d8d79c4527be | train_000.jsonl | 1488096300 | Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items. | 256 megabytes | //package cf;
import java.util.*;
import java.io.*;
public class Cf{
static class Node{
int diff,left,right;
Node(int left,int right,int diff){
this.diff=diff;
this.left=left;
this.right=right;
}
}
public static void main(String[]args){
Scanner in=new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
long t=1;//in.nextLong();
while(t-->0){
int n=in.nextInt();
int k=in.nextInt();
//int a[]=new int[n];
//TreeSet<Integer>ts=new TreeSet<Integer>();
//for(int i=0;i<n;i++){}
//for(int i=0;i<n;a[i++]=in.nextInt()){}
int count=0;
long sum=0;
int aa[]=new int[n];
int bb[]=new int[n];
for(int i=0;i<n;aa[i++]=in.nextInt()){}
for(int i=0;i<n;bb[i++]=in.nextInt()){}
Node cc[]=new Node[n];
for(int i=0;i<n;i++){
// int a=aa[i];
// int b=bb[i];
// if(a<=b){count++;
// sum=sum+a;
// }
// else {
cc[i]=new Node(aa[i],bb[i],aa[i]-bb[i]);
// }
}
Arrays.sort(cc,(Node n1,Node n2) ->n1.diff-n2.diff);
// if(count>=k)
// for(Node i:v){
// sum=sum+i.right;
// }
// }
// else{
for(int i=0;i<n;i++){
if(i<k){
sum=sum+cc[i].left;
}
else{
sum=sum+Math.min(cc[i].left,cc[i].right);
}
}
out.println(sum);
}
in.close();
out.close();
}
} | Java | ["3 1\n5 4 6\n3 1 5", "5 3\n3 4 7 10 3\n4 5 5 12 5"] | 2 seconds | ["10", "25"] | NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy"
] | b5355e1f4439b198d2cc7dea01bc4bc3 | In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week). | 1,200 | Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now. | standard output | |
PASSED | f9a0b3e7e3796ab331274dafdd157938 | train_000.jsonl | 1488096300 | Igor found out discounts in a shop and decided to buy n items. Discounts at the store will last for a week and Igor knows about each item that its price now is ai, and after a week of discounts its price will be bi.Not all of sellers are honest, so now some products could be more expensive than after a week of discounts.Igor decided that buy at least k of items now, but wait with the rest of the week in order to save money as much as possible. Your task is to determine the minimum money that Igor can spend to buy all n items. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map.Entry;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
import java.util.*;
public class Solution {
/*public static int ispr(int n)
{
//boolean[] isPrime = new boolean[n+1];
for (int i = 2; i <= n; i++) {
Prime[i] = true;
}
// mark non-primes <= n using Sieve of Eratosthenes
for (int factor = 2; factor*factor <= n; factor++) {
// if factor is prime, then mark multiples of factor as nonprime
// suffices to consider mutiples factor, factor+1, ..., n/factor
if (Prime[factor]) {
for (int j = factor; factor*j <= n; j++) {
Prime[factor*j] = false;
}
}
}
// count primes
/*int primes = 0;
for (int i = 2; i <= n; i++) {
if (isPrime [i])System.out.println(i);
}*/
// System.out.println("The number of primes <= " + n + " is " + primes);
//return 0;
// if(isPrime[n]==true)return 1; else return 0;
//}
public static long fact(long x)
{
if(x==0)return 1;
else return x*fact(x-1);
}
public static long exp(long x, long n, long M)
{
if(n==0) return 1;
else if(n%2==0) return exp((x*x)%M,n/2,M);
else return (x*exp((x*x)%M,(n-1)/2,M))%M;
}
//fi
static long fib(long n)
{
long F[][] = new long[][]{{1,1},{1,0}};
if (n == 0)
return 0;
power(F, n-1);
return F[0][0];
}
static void multiply(long F[][], long M[][])
{
long x = F[0][0]*M[0][0] + F[0][1]*M[1][0];
long y = F[0][0]*M[0][1] + F[0][1]*M[1][1];
long z = F[1][0]*M[0][0] + F[1][1]*M[1][0];
long w = F[1][0]*M[0][1] + F[1][1]*M[1][1];
F[0][0] = x;
F[0][1] = y;
F[1][0] = z;
F[1][1] = w;
}
/* Optimized version of power() in method 4 */
static void power(long F[][], long n)
{
if( n == 0 || n == 1)
return;
long M[][] = new long[][]{{1,1},{1,0}};
power(F, n/2);
multiply(F, F);
if (n%2 != 0)
multiply(F, M);
}
static class Point
{
long x,y;
public Point(long a, long b)
{
x=a;
y=b;
}
}
static class compy implements Comparator<Point>
{
public int compare(Point a, Point b)
{
if(a.y>b.y)return 1;
if(a.y<b.y) return -1;
if(a.x>b.x) return 1;
if(a.x<b.x) return -1;
return 0;
}
}
static class compx implements Comparator<Point>
{
public int compare(Point a, Point b)
{
if(a.x>b.x)return 1;
if(a.x<b.x) return -1;
if(a.y>b.y) return 1;
if(a.y<b.y) return -1;
return 0;
}
}
public static int gcd(int a, int b)
{
if(b==0)
return a;
else return gcd(b,a%b);
}
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;
}
}
static MyScanner sc = new MyScanner();
static PrintWriter pw = new PrintWriter(System.out, true);
static class Node
{
int id,wt;
public Node(int x, int y)
{
id=x; wt=y;
}
}
static class Distance
{
int id;
long dist;
public Distance(long x, int y)
{
dist=x; id=y;
}
}
static int factor(int x)
{
if(x%2==1)return x;
else
return factor(x/2);
}
static void printPath(int parent[], int j)
{
// Base Case : If j is source
if (parent[j]==-1)
{pw.print(j+" ");return;}
printPath(parent, parent[j]);
pw.print(j+" ");
}
static void spiralPrint(int m, int n, int[][] a)
{
int i, k = 0, l = 0;
/* k - starting row index
m - ending row index
l - starting column index
n - ending column index
i - iterator
*/
while (k < m && l < n)
{
/* Print the first row from the remaining rows */
for (i = l; i < n; ++i)
{
pw.print(a[k][i]+" ");
}
k++;
/* Print the last column from the remaining columns */
for (i = k; i < m; ++i)
{
pw.print(a[i][n-1]+" ");
}
n--;
/* Print the last row from the remaining rows */
if ( k < m)
{
for (i = n-1; i >= l; --i)
{
pw.print(a[m-1][i]+" ");
}
m--;
}
/* Print the first column from the remaining columns */
if (l < n)
{
for (i = m-1; i >= k; --i)
{
pw.print(a[i][l]+" ");
}
l++;
}
}
}
//Main begins here :)
public static int exp(Price p)
{
if(p.bf<p.af)
{
return 1;
}
else return 0;
}
static class Price
{
int bf;
int af;
int diff;
public Price(int x, int y, int d)
{
bf=x; af=y; diff=d;
}
}
static class expcomp implements Comparator<Price>
{
@Override
public int compare(Price o1, Price o2) {
if(o1.af>o2.af)return -1;
else if(o1.af==o2.af)
{
if(o1.bf<o2.bf)return 1;
else return -1;
}
else
return 1;
}
}
static class chcomp implements Comparator<Price>
{
@Override
public int compare(Price o1, Price o2) {
if(o1.diff>o2.diff)
return 1;
if(o1.diff<o2.diff)
return -1;
return 0;
}
}
public static void main(String[] args) {
int n = sc.nextInt();
int k = sc.nextInt();
int ai[] = new int[n];
int bi[] = new int[n];
int diff[] = new int[n];
Price[] items = new Price[n];
for(int i=0;i<n;i++)ai[i]=sc.nextInt();
for(int i=0;i<n;i++)bi[i]=sc.nextInt();
for(int i=0;i<n;i++)
{
diff[i]=ai[i]-bi[i];
Price p = new Price(ai[i],bi[i],diff[i]);
items[i]=p;
}
Arrays.sort(items, new chcomp());
/*for(int i=0;i<n;i++)
{
pw.println(items[i].bf+" "+items[i].af);
}
*/
int early=0;
int total=0;
for(int i=0;i<n;i++)
{
Price p = items[i];
if(early<k)
{
total+=p.bf;
early++;
}
else
{
total+=Math.min(p.af, p.bf);
}
}
pw.println(total);
pw.close();
}
} | Java | ["3 1\n5 4 6\n3 1 5", "5 3\n3 4 7 10 3\n4 5 5 12 5"] | 2 seconds | ["10", "25"] | NoteIn the first example Igor should buy item 3 paying 6. But items 1 and 2 he should buy after a week. He will pay 3 and 1 for them. So in total he will pay 6 + 3 + 1 = 10.In the second example Igor should buy right now items 1, 2, 4 and 5, paying for them 3, 4, 10 and 3, respectively. Item 3 he should buy after a week of discounts, he will pay 5 for it. In total he will spend 3 + 4 + 10 + 3 + 5 = 25. | Java 8 | standard input | [
"constructive algorithms",
"sortings",
"greedy"
] | b5355e1f4439b198d2cc7dea01bc4bc3 | In the first line there are two positive integer numbers n and k (1 ≤ n ≤ 2·105, 0 ≤ k ≤ n) — total number of items to buy and minimal number of items Igor wants to by right now. The second line contains sequence of integers a1, a2, ..., an (1 ≤ ai ≤ 104) — prices of items during discounts (i.e. right now). The third line contains sequence of integers b1, b2, ..., bn (1 ≤ bi ≤ 104) — prices of items after discounts (i.e. after a week). | 1,200 | Print the minimal amount of money Igor will spend to buy all n items. Remember, he should buy at least k items right now. | standard output | |
PASSED | 6dd6d5afa422be982d66b1e780347172 | train_000.jsonl | 1537171500 | Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$. | 256 megabytes | import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import java.util.Scanner;
// 1042D - Fail (use fenwick trees)
public class PetyaAndArray {
static long T;
static long[] A;
static long[] SUM;
public static void main(String[] args) {
Locale.setDefault(Locale.US);
final Scanner scanner = new Scanner(System.in);
final int n = scanner.nextInt();
T = scanner.nextLong();
A = new long[n + 1];
SUM = new long[n + 1];
for (int i = 1; i <= n; i++) {
A[i] = scanner.nextLong();
SUM[i] = SUM[i - 1] + A[i];
}
System.out.println(solve(1, n + 1));
}
static long solve(int i, int j) {
if (j - i < 1) return 0;
if (j - i == 1) return count(i, i, j);
final int p = (i + j) >> 1;
return count(i, p, j) + solve(i, p) + solve(p, j);
}
static long count(int i, int p, int j) {
if (i == p) return A[i] < T ? 1 : 0;
final List<Long> list = new ArrayList<>(j - i);
for (int k = p; k < j; k++) list.add(SUM[k] - SUM[p - 1]);
list.sort(Comparator.naturalOrder());
long res = 0;
for (int k = i; k < p; k++) {
long t = T - (SUM[p - 1] - SUM[k - 1]);
res += ceilIndex(list, t);
}
return res;
}
static int ceilIndex(List<Long> list, long key) {
int i = 0;
int j = list.size();
while (i < j) {
int p = (i + j) >> 1;
if (list.get(p) < key) i = p + 1;
else j = p;
}
return i;
}
} | Java | ["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"] | 2 seconds | ["5", "4", "3"] | NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$ | Java 8 | standard input | [
"data structures",
"two pointers",
"divide and conquer"
] | 42c4adc1c4a10cc619c05a842e186e60 | The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements. | 1,800 | Print the number of segments in Petya's array with the sum of elements less than $$$t$$$. | standard output | |
PASSED | bca16ca4881d90029ad5d1375fe1eef7 | train_000.jsonl | 1537171500 | Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$. | 256 megabytes | import java.util.*;
import java.io.*;
public class _1042_D {
public static void main(String[] args) throws IOException {
int N = readInt();
long T = readLong();
long arr[] = new long[N+1];
long BIT[] = new long[N+2];
long tot = 0;
PriorityQueue<Long > pq = new PriorityQueue<>(Collections.reverseOrder());
for(int i = 1; i<=N; i++) {
arr[i] = arr[i-1] + readLong();
pq.add(arr[i]);
}
pq.add(0L);
TreeMap<Long, Integer> comp = new TreeMap<>();
for(int i = 1; i<=N+1; i++) comp.put(pq.poll(), i);
for(int i = comp.get(0L); i<=N+1; i+=i&-i) BIT[i]++;
for(int i = 1; i<=N; i++) {
Long idx = comp.higherKey(-(T-arr[i]));
if(idx == null) {
for(int j = comp.get(arr[i]); j<=N+1; j+=j&-j) BIT[j]++;
continue;
}
for(int j = comp.get(idx); j>0; j-=j&-j) tot += BIT[j];
for(int j = comp.get(arr[i]); j<=N+1; j+=j&-j) BIT[j]++;
}
println(tot);
exit();
}
final private static int BUFFER_SIZE = 1 << 16;
private static DataInputStream din = new DataInputStream(System.in);
private static byte[] buffer = new byte[BUFFER_SIZE];
private static int bufferPointer = 0, bytesRead = 0;
static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
public static String readLine() throws IOException {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = Read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public static String read() throws IOException {
byte[] ret = new byte[1024];
int idx = 0;
byte c = Read();
while (c <= ' ') {
c = Read();
}
do {
ret[idx++] = c;
c = Read();
} while (c != -1 && c != ' ' && c != '\n' && c != '\r');
return new String(ret, 0, idx);
}
public static int readInt() throws IOException {
int ret = 0;
byte c = Read();
while (c <= ' ')
c = Read();
boolean neg = (c == '-');
if (neg)
c = Read();
do {
ret = ret * 10 + c - '0';
} while ((c = Read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public static long readLong() throws IOException {
long ret = 0;
byte c = Read();
while (c <= ' ')
c = Read();
boolean neg = (c == '-');
if (neg)
c = Read();
do {
ret = ret * 10 + c - '0';
} while ((c = Read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public static double readDouble() throws IOException {
double ret = 0, div = 1;
byte c = Read();
while (c <= ' ')
c = Read();
boolean neg = (c == '-');
if (neg)
c = Read();
do {
ret = ret * 10 + c - '0';
} while ((c = Read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = Read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private static void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private static byte Read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
static void print(Object o) {
pr.print(o);
}
static void println(Object o) {
pr.println(o);
}
static void flush() {
pr.flush();
}
static void println() {
pr.println();
}
static void exit() throws IOException {
din.close();
pr.close();
System.exit(0);
}
}
| Java | ["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"] | 2 seconds | ["5", "4", "3"] | NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$ | Java 8 | standard input | [
"data structures",
"two pointers",
"divide and conquer"
] | 42c4adc1c4a10cc619c05a842e186e60 | The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements. | 1,800 | Print the number of segments in Petya's array with the sum of elements less than $$$t$$$. | standard output | |
PASSED | f925b02fca012fbfc742de82c6758645 | train_000.jsonl | 1537171500 | Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
import static java.util.Arrays.fill;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;
public class D {
static int mod = 1000000007;
static InputReader in = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
static int n;
static long t;
static long[] sum;
static long[] a;
static int[] tree;
static void updatetree(int node,int start,int end,int idx,int val)
{
if(start>end)
{
return;
}
if(start==end)
{
tree[node]+=val;
return;
}
int mid=(start+end)/2;
if(start<=idx && mid>=idx)
updatetree(2*node, start, mid, idx, val);
else
updatetree(2*node+1, mid+1, end, idx, val);
tree[node]=tree[2*node]+tree[2*node+1];
}
static int query(int node,int start,int end,int l,int r)
{
if(start>r||end<l||start>end)
{
return 0;
}
if(start>=l&&end<=r)
{
return tree[node];
}
int mid=(start+end)/2;
int p1=query(2*node, start, mid, l, r);
int p2=query(2*node+1, mid+1, end, l, r);
return (p1+p2);
}
public static void main(String[] args) {
n=in.nextInt();
t=in.nextLong();
sum=new long[n+1];
a=new long[n+1];
tree=new int[5*n];
for(int i=1;i<=n;i++)
{
a[i]=in.nextLong();
sum[i]=sum[i-1]+a[i];
}
long[] sum2=Arrays.copyOfRange(sum, 1, n+1);
Arrays.sort(sum2);
HashMap<Long, Integer> map=new HashMap<>();
int j=1;
TreeSet<Long> set=new TreeSet<>();
for(int i=0;i<n;i++)
{
set.add(sum2[i]);
if(!map.containsKey(sum2[i]))
{
map.put(sum2[i], j++);
}
}
long ans=0;
for(int i=n;i>=1;i--)
{
long maxi=t+sum[i];
if(sum[i]<t)
ans++;
if(set.lower(maxi)==null)
{
updatetree(1, 1, n, map.get(sum[i]), 1);
continue;
}
maxi=set.lower(maxi);
int key=map.get(maxi);
ans+=query(1, 1, n, 1, key);
updatetree(1, 1, n, map.get(sum[i]), 1);
}
out.println(ans);
out.close();
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
private static void tr(Object... o) {
if (!(System.getProperty("ONLINE_JUDGE") != null))
System.out.println(Arrays.deepToString(o));
}
}
| Java | ["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"] | 2 seconds | ["5", "4", "3"] | NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$ | Java 8 | standard input | [
"data structures",
"two pointers",
"divide and conquer"
] | 42c4adc1c4a10cc619c05a842e186e60 | The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements. | 1,800 | Print the number of segments in Petya's array with the sum of elements less than $$$t$$$. | standard output | |
PASSED | f57a2d24ac55f2febe16b66e24c1785e | train_000.jsonl | 1537171500 | Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
import static java.util.Arrays.fill;
import static java.lang.Math.*;
import static java.util.Arrays.sort;
import static java.util.Collections.sort;
public class D {
static int mod = 1000000007;
static InputReader in = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
static int n;
static long t;
static long[] sum;
static long[] a;
static int[] tree;
static void updatetree(int node,int start,int end,int idx,int val)
{
if(start>end)
{
return;
}
if(start==end)
{
tree[node]+=val;
return;
}
int mid=(start+end)/2;
if(start<=idx && mid>=idx)
updatetree(2*node, start, mid, idx, val);
else
updatetree(2*node+1, mid+1, end, idx, val);
tree[node]=tree[2*node]+tree[2*node+1];
}
static int query(int node,int start,int end,int l,int r)
{
if(start>r||end<l||start>end)
{
return 0;
}
if(start>=l&&end<=r)
{
return tree[node];
}
int mid=(start+end)/2;
int p1=query(2*node, start, mid, l, r);
int p2=query(2*node+1, mid+1, end, l, r);
return (p1+p2);
}
public static void main(String[] args) {
n=in.nextInt();
t=in.nextLong();
sum=new long[n+1];
a=new long[n+1];
tree=new int[5*n];
for(int i=1;i<=n;i++)
{
a[i]=in.nextLong();
sum[i]=sum[i-1]+a[i];
}
long[] sum2=Arrays.copyOfRange(sum, 1, n+1);
Arrays.sort(sum2);
HashMap<Long, Integer> map=new HashMap<>();
int j=1;
TreeSet<Long> set=new TreeSet<>();
for(int i=0;i<n;i++)
{
set.add(sum2[i]);
if(!map.containsKey(sum2[i]))
{
map.put(sum2[i], j++);
}
}
long ans=0;
for(int i=n;i>=1;i--)
{
long maxi=t+sum[i];
if(sum[i]<t)
ans++;
if(set.lower(maxi)==null)
{
updatetree(1, 1, n, map.get(sum[i]), 1);
continue;
}
maxi=set.lower(maxi);
int key=map.get(maxi);
ans+=query(1, 1, n, 0, key);
updatetree(1, 1, n, map.get(sum[i]), 1);
}
out.println(ans);
out.close();
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
private static void tr(Object... o) {
if (!(System.getProperty("ONLINE_JUDGE") != null))
System.out.println(Arrays.deepToString(o));
}
}
| Java | ["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"] | 2 seconds | ["5", "4", "3"] | NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$ | Java 8 | standard input | [
"data structures",
"two pointers",
"divide and conquer"
] | 42c4adc1c4a10cc619c05a842e186e60 | The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements. | 1,800 | Print the number of segments in Petya's array with the sum of elements less than $$$t$$$. | standard output | |
PASSED | c6cd4ddace614e837289954aff072993 | train_000.jsonl | 1537171500 | Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map.Entry;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.stream.Stream;
public class Solution implements Runnable {
static final double time = 1e9;
static final int MOD = (int) 1e9 + 7;
static final long mh = Long.MAX_VALUE;
static final Reader in = new Reader();
static final PrintWriter out = new PrintWriter(System.out);
StringBuilder answer = new StringBuilder();
public static void main(String[] args) {
new Thread(null, new Solution(), "persefone", 1 << 28).start();
}
@Override
public void run() {
long start = System.nanoTime();
solve();
printf();
long elapsed = System.nanoTime() - start;
// out.println("stamp : " + elapsed / time);
// out.println("stamp : " + TimeUnit.SECONDS.convert(elapsed,
// TimeUnit.NANOSECONDS));
close();
}
// s[i] - s[j] < t -> si - t < sj
void solve() {
int n = in.nextInt();
long t = in.nextLong();
long[] a = new long[n];
a[0] = in.nextLong();
for (int i = 1; i < n; i++) a[i] = a[i - 1] + in.nextLong();
long[] b = a.clone();
ArrayUtils.compressed(b, n);
TreeMap<Long, Integer> map = new TreeMap<>();
map.put(a[0], 0);
Fenwick fw = new Fenwick(n);
fw.update((int) b[0], 1);
long ans = a[0] < t ? 1 : 0;
for (int i = 1; i < n; i++) {
if (a[i] < t) ans++;
Entry<Long, Integer> max = map.floorEntry(a[i] - t);
ans += i - (max == null ? 0 : fw.get((int) b[max.getValue()]));
fw.update((int) b[i], 1);
map.put(a[i], i);
}
printf(ans);
}
static class Fenwick {
private int n;
private int[] count;
public Fenwick(int n) {
this.n = n;
this.count = new int[n + 10];
}
void update(int i, int val) {
for (; i < count.length; i += i & -i) {
count[i] += val;
}
}
int get(int i) {
int sum = 0;
for (; i > 0; i -= i & -i) {
sum += count[i];
}
return sum;
}
}
static class ArrayUtils {
static void compressed(int[] a, int n) {
int[] b = a.clone();
Arrays.sort(b);
for (int i = 0; i < n; i++)
a[i] = lw(b, 0, n, a[i]) + 1;
}
static void compressed(long[] a, int n) {
long[] b = a.clone();
Arrays.sort(b);
for (int i = 0; i < n; i++)
a[i] = lw(b, 0, n, a[i]) + 1;
}
static int lw(int[] b, int l, int r, int k) {
int R = r, m = 0;
while (l <= r) {
m = l + r >> 1;
if (m == R) return m;
if (b[m] >= k)
r = m - 1;
else
l = m + 1;
}
return l;
}
static int lw(long[] b, int l, int r, long k) {
int R = r, m = 0;
while (l <= r) {
m = l + r >> 1;
if (m == R) return m;
if (b[m] >= k)
r = m - 1;
else
l = m + 1;
}
return l;
}
}
public static int[] shuffle(int[] a, Random gen) {
for (int i = 0, n = a.length; i < n; i++) {
int ind = gen.nextInt(n - i) + i;
int d = a[i];
a[i] = a[ind];
a[ind] = d;
}
return a;
}
public static int[] shrinkX(int[] a) {
int n = a.length;
long[] b = new long[n];
for (int i = 0; i < n; i++)
b[i] = (long) a[i] << 32 | i;
Arrays.sort(b);
int[] ret = new int[n];
int p = 0;
ret[0] = (int) (b[0] >> 32);
for (int i = 0; i < n; i++) {
if (i > 0 && (b[i] ^ b[i - 1]) >> 32 != 0) {
p++;
ret[p] = (int) (b[i] >> 32);
}
a[(int) b[i]] = p;
}
return Arrays.copyOf(ret, p + 1);
}
int pow(int a, int b, int p) {
long ans = 1, base = a;
while (b > 0) {
if ((b & 1) > 0) {
ans *= base %= p;
}
base *= base %= p;
b >>= 1;
}
return (int) ans;
}
public static int[] enumLowestPrimeFactors(int n) {
int tot = 0;
int[] lpf = new int[n + 1];
int u = n + 32;
double lu = Math.log(u);
int[] primes = new int[(int) (u / lu + u / lu / lu * 1.5)];
for (int i = 2; i <= n; i++)
lpf[i] = i;
for (int p = 2; p <= n; p++) {
if (lpf[p] == p)
primes[tot++] = p;
int tmp;
for (int i = 0; i < tot && primes[i] <= lpf[p] && (tmp = primes[i] * p) <= n; i++) {
lpf[tmp] = primes[i];
}
}
return lpf;
}
public static int[] enumNumDivisorsFast(int n, int[] lpf) {
int[] nd = new int[n + 1];
nd[1] = 1;
for (int i = 2; i <= n; i++) {
int j = i, e = 0;
while (j % lpf[i] == 0) {
j /= lpf[i];
e++;
}
nd[i] = nd[j] * (e + 1);
}
return nd;
}
boolean isPrime(long n) {
for (int i = 2; 1l * i * i <= n; i++)
if (n % i == 0)
return false;
return true;
}
void printf() {
out.print(answer);
}
void close() {
out.close();
}
void printf(Stream<?> str) {
str.forEach(o -> add(o, " "));
add("\n");
}
void printf(Object... obj) {
printf(false, obj);
}
void printfWithDescription(Object... obj) {
printf(true, obj);
}
private void printf(boolean b, Object... obj) {
if (obj.length > 1) {
for (int i = 0; i < obj.length; i++) {
if (b)
add(obj[i].getClass().getSimpleName(), " - ");
if (obj[i] instanceof Collection<?>) {
printf((Collection<?>) obj[i]);
} else if (obj[i] instanceof int[][]) {
printf((int[][]) obj[i]);
} else if (obj[i] instanceof long[][]) {
printf((long[][]) obj[i]);
} else if (obj[i] instanceof double[][]) {
printf((double[][]) obj[i]);
} else
printf(obj[i]);
}
return;
}
if (b)
add(obj[0].getClass().getSimpleName(), " - ");
printf(obj[0]);
}
void printf(Object o) {
if (o instanceof int[])
printf(Arrays.stream((int[]) o).boxed());
else if (o instanceof char[])
printf(new String((char[]) o));
else if (o instanceof long[])
printf(Arrays.stream((long[]) o).boxed());
else if (o instanceof double[])
printf(Arrays.stream((double[]) o).boxed());
else if (o instanceof boolean[]) {
for (boolean b : (boolean[]) o)
add(b, " ");
add("\n");
} else
add(o, "\n");
}
void printf(int[]... obj) {
for (int i = 0; i < obj.length; i++)
printf(obj[i]);
}
void printf(long[]... obj) {
for (int i = 0; i < obj.length; i++)
printf(obj[i]);
}
void printf(double[]... obj) {
for (int i = 0; i < obj.length; i++)
printf(obj[i]);
}
void printf(boolean[]... obj) {
for (int i = 0; i < obj.length; i++)
printf(obj[i]);
}
void printf(Collection<?> col) {
printf(col.stream());
}
<T, K> void add(T t, K k) {
if (t instanceof Collection<?>) {
((Collection<?>) t).forEach(i -> add(i, " "));
} else if (t instanceof Object[]) {
Arrays.stream((Object[]) t).forEach(i -> add(i, " "));
} else
add(t);
add(k);
}
<T> void add(T t) {
answer.append(t);
}
@SuppressWarnings("unchecked")
<T extends Comparable<? super T>> T min(T... t) {
if (t.length == 0)
return null;
T m = t[0];
for (int i = 1; i < t.length; i++)
if (t[i].compareTo(m) < 0)
m = t[i];
return m;
}
@SuppressWarnings("unchecked")
<T extends Comparable<? super T>> T max(T... t) {
if (t.length == 0)
return null;
T m = t[0];
for (int i = 1; i < t.length; i++)
if (t[i].compareTo(m) > 0)
m = t[i];
return m;
}
int gcd(int a, int b) {
return (b == 0) ? a : gcd(b, a % b);
}
long gcd(long a, long b) {
return (b == 0) ? a : gcd(b, a % b);
}
long lcm(int a, int b) {
return (1l * a * b / gcd(a, b));
}
long lcm(long a, long b) {
if (a > Long.MAX_VALUE / b)
throw new RuntimeException();
return a * b / gcd(a, b);
}
// c = gcd(a, b) -> extends gcd method: ax + by = c <----> (b % a)p + q = c;
int[] ext_gcd(int a, int b) {
if (b == 0)
return new int[] { a, 1, 0 };
int[] vals = ext_gcd(b, a % b);
int d = vals[0]; // gcd
int p = vals[2]; //
int q = vals[1] - (a / b) * vals[2];
return new int[] { d, p, q };
}
// find any solution of the equation: ax + by = c using extends gcd
boolean find_any_solution(int a, int b, int c, int[] root) {
int[] vals = ext_gcd(Math.abs(a), Math.abs(b));
if (c % vals[0] != 0)
return false;
printf(vals);
root[0] = c * vals[1] / vals[0];
root[1] = c * vals[2] / vals[0];
if (a < 0)
root[0] *= -1;
if (b < 0)
root[1] *= -1;
return true;
}
int mod(int x) {
return x % MOD;
}
int mod(int x, int y) {
return mod(mod(x) + mod(y));
}
long mod(long x) {
return x % MOD;
}
long mod(long x, long y) {
return mod(mod(x) + mod(y));
}
int lw(long[] f, int l, int r, long k) {
int R = r, m = 0;
while (l <= r) {
m = l + r >> 1;
if (m == R)
return m;
if (f[m] >= k)
r = m - 1;
else
l = m + 1;
}
return l;
}
int up(long[] f, int l, int r, long k) {
int R = r, m = 0;
while (l <= r) {
m = l + r >> 1;
if (m == R)
return m;
if (f[m] > k)
r = m - 1;
else
l = m + 1;
}
return l;
}
int lw(int[] f, int l, int r, int k) {
int R = r, m = 0;
while (l <= r) {
m = l + r >> 1;
if (m == R)
return m;
if (f[m] >= k)
r = m - 1;
else
l = m + 1;
}
return l;
}
int up(int[] f, int l, int r, int k) {
int R = r, m = 0;
while (l <= r) {
m = l + r >> 1;
if (m == R)
return m;
if (f[m] > k)
r = m - 1;
else
l = m + 1;
}
return l;
}
<K extends Comparable<K>> int lw(List<K> li, int l, int r, K k) {
int R = r, m = 0;
while (l <= r) {
m = l + r >> 1;
if (m == R)
return m;
if (li.get(m).compareTo(k) >= 0)
r = m - 1;
else
l = m + 1;
}
return l;
}
<K extends Comparable<K>> int up(List<K> li, int l, int r, K k) {
int R = r, m = 0;
while (l <= r) {
m = l + r >> 1;
if (m == R)
return m;
if (li.get(m).compareTo(k) > 0)
r = m - 1;
else
l = m + 1;
}
return l;
}
<K extends Comparable<K>> int bs(List<K> li, int l, int r, K k) {
while (l <= r) {
int m = l + r >> 1;
if (li.get(m) == k)
return m;
else if (li.get(m).compareTo(k) < 0)
l = m + 1;
else
r = m - 1;
}
return -1;
}
long calc(int base, int exponent, int p) {
if (exponent == 0)
return 1;
if (exponent == 1)
return base % p;
long m = calc(base, exponent >> 1, p);
if (exponent % 2 == 0)
return (m * m) % p;
return 1l * base * m % p * m % p;
}
long calc(int base, long exponent, int p) {
if (exponent == 0)
return 1;
if (exponent == 1)
return base % p;
long m = calc(base, exponent >> 1, p);
if (exponent % 2 == 0)
return (m * m) % p;
return 1l * base * m % p * m % p;
}
long calc(long base, long exponent, int p) {
if (exponent == 0)
return 1;
if (exponent == 1)
return base % p;
long m = calc(base, exponent >> 1, p);
if (exponent % 2 == 0)
return (m * m) % p;
return base * m % p * m % p;
}
long power(int base, int exponent) {
if (exponent == 0)
return 1;
long m = power(base, exponent / 2);
if (exponent % 2 == 0)
return m * m;
return base * m * m;
}
void swap(int[] a, int i, int j) {
a[i] ^= a[j];
a[j] ^= a[i];
a[i] ^= a[j];
}
void swap(long[] a, int i, int j) {
long tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
static class Pair<K extends Comparable<? super K>, V extends Comparable<? super V>>
implements Comparable<Pair<K, V>> {
private K k;
private V v;
Pair() {
}
Pair(K k, V v) {
this.k = k;
this.v = v;
}
K getK() {
return k;
}
V getV() {
return v;
}
void setK(K k) {
this.k = k;
}
void setV(V v) {
this.v = v;
}
void setKV(K k, V v) {
this.k = k;
this.v = v;
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || !(o instanceof Pair))
return false;
Pair<K, V> p = (Pair<K, V>) o;
return k.compareTo(p.k) == 0 && v.compareTo(p.v) == 0;
}
@Override
public int hashCode() {
int hash = 31;
hash = hash * 89 + k.hashCode();
hash = hash * 89 + v.hashCode();
return hash;
}
@Override
public int compareTo(Pair<K, V> pair) {
return k.compareTo(pair.k) == 0 ? v.compareTo(pair.v) : k.compareTo(pair.k);
}
@Override
public Pair<K, V> clone() {
return new Pair<K, V>(this.k, this.v);
}
@Override
public String toString() {
return String.valueOf(k).concat(" ").concat(String.valueOf(v)).concat("\n");
}
}
static class Reader {
private BufferedReader br;
private StringTokenizer st;
Reader() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
try {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
long nextLong() {
return Long.parseLong(next());
}
String nextLine() {
String s = "";
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
}
} | Java | ["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"] | 2 seconds | ["5", "4", "3"] | NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$ | Java 8 | standard input | [
"data structures",
"two pointers",
"divide and conquer"
] | 42c4adc1c4a10cc619c05a842e186e60 | The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements. | 1,800 | Print the number of segments in Petya's array with the sum of elements less than $$$t$$$. | standard output | |
PASSED | 8d8507c4b8bbfbc07051ac90e3c449fa | train_000.jsonl | 1537171500 | Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class CF1042D {
public static void main(String[] args) {
FastReader reader = new FastReader();
int n = reader.nextInt();
long t = reader.nextLong();
// S[C] - S[x] < t => -S[x] < t - S[C]
AVLTree<Long, Long> tree = new AVLTree<>();
tree.insert(0L, 0L);
long result = 0;
long current = 0;
for (int i = 0; i < n; i++) {
int v = reader.nextInt();
current += v;
result += tree.order(t - current - 1);
tree.insert(-1 * current, current);
}
System.out.println(result);
}
public 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 class AVLTree<K extends Comparable<K>, V> {
static class Node<K extends Comparable<K>, V> implements Comparable<Node<K, V>> {
K key;
long index;
V value;
int size = 1;
int depth;
Node(K key, V value, long index) {
this.key = key;
this.value = value;
this.index = index;
}
Node<K, V> left;
Node<K, V> right;
Node<K, V> parent;
public int compareTo(Node<K, V> o) {
int keyCompare = key.compareTo(o.key);
if (keyCompare != 0) return keyCompare;
return Long.compare(index, o.index);
}
void print(StringBuilder sb, String line) {
sb.append(line).append(" ")
.append(key)
.append(" (")
.append(parent != null ? parent.key : "root")
.append(":")
.append(depth)
.append(":")
.append(size)
.append(")").append('\n');
int indent = line.length() + 1;
StringBuilder newLine = new StringBuilder(indent);
for (int i = 0; i < indent; i++) {
newLine.append(' ');
}
if (left != null) {
left.print(sb, newLine.toString() + "l: ->");
}
if (right != null) {
right.print(sb, newLine.toString() + "r: ->");
}
}
@Override
public String toString() {
return "Node{" +
"key=" + key +
'}';
}
}
Node<K, V> root;
private long logIndex = 0;
public void insert(K key, V value) {
Node<K, V> current = root;
Node<K, V> newNode = new Node<>(key, value, logIndex++);
if (current == null) {
this.root = newNode;
this.root.depth = 1;
return;
}
while (true) {
Node<K, V> next;
if (current.compareTo(newNode) <= 0) {
next = current.right;
if (next == null) {
current.right = new Node<>(key, value, logIndex++);
current.right.depth = 1;
current.right.parent = current;
break;
}
} else {
next = current.left;
if (next == null) {
current.left = new Node<>(key, value, logIndex++);
current.left.depth = 1;
current.left.parent = current;
break;
}
}
current = next;
}
fixBalanceToRoot(current);
}
public Node<K, V> delete(K key) {
Node<K, V> expected = findLower(new Node<K, V>(key, null, Long.MAX_VALUE));
if (expected == null || expected.key.compareTo(key) != 0) return null;
return deleteNode(expected);
}
public V find(K key) {
Node<K, V> expected = findLower(new Node<K, V>(key, null, Long.MAX_VALUE));
if (expected == null || expected.key.compareTo(key) != 0) return null;
return expected.value;
}
public int order(K key) {
return order(new Node<K, V>(key, null, Long.MAX_VALUE));
}
private void fixBalanceToRoot(Node<K, V> current) {
while (current != null) {
Node<K, V> parent = current.parent;
Node<K, V> newRoot = fixBalance(current);
if (parent != null) {
if (parent.right == current) {
parent.right = newRoot;
} else {
parent.left = newRoot;
}
} else {
root = newRoot;
}
current = parent;
}
}
private Node<K, V> deleteNode(Node<K, V> current) {
if (current.left == null && current.right == null) {
if (current.parent == null) {
root = null;
} else {
if (current.parent.left == current) {
current.parent.left = null;
} else {
current.parent.right = null;
}
rebalance(current.parent);
}
fixBalanceToRoot(current.parent);
} else {
if (current.left != null) {
Node<K, V> nextLower = findLower(current);
nextLower = deleteNode(nextLower);
nextLower.left = current.left;
if (nextLower.left != null) nextLower.left.parent = nextLower;
nextLower.right = current.right;
if (nextLower.right != null) nextLower.right.parent = nextLower;
rebalance(nextLower);
if (current.parent == null) {
root = nextLower;
nextLower.parent = null;
} else {
if (current.parent.left == current) {
current.parent.left = nextLower;
} else {
current.parent.right = nextLower;
}
nextLower.parent = current.parent;
}
} else {
if (current.parent == null) {
root = current.right;
current.right.parent = null;
} else {
if (current.parent.left == current) {
current.parent.left = current.right;
} else {
current.parent.right = current.right;
}
current.right.parent = current.parent;
}
fixBalanceToRoot(current.right.parent);
}
}
return current;
}
private Node<K, V> findLower(Node<K, V> findNode) {
Node<K, V> prev = null;
Node<K, V> current = root;
while (current != null) {
int compare = current.compareTo(findNode);
if (compare < 0) {
prev = current;
current = current.right;
} else {
current = current.left;
}
}
return prev;
}
private int order(Node<K, V> findNode) {
Node<K, V> current = root;
int count = 0;
while (current != null) {
int compare = current.compareTo(findNode);
if (compare < 0) {
if (current.left != null) {
count += current.left.size;
}
count++;
current = current.right;
} else {
current = current.left;
}
}
return count;
}
private void rebalance(Node<K, V> current) {
current.depth = Math.max((current.right == null ? 0 : current.right.depth),
(current.left == null ? 0 : current.left.depth)) + 1;
current.size = (current.right == null ? 0 : current.right.size) +
(current.left == null ? 0 : current.left.size) + 1;
}
private Node<K, V> rotateLeft(Node<K, V> current) {
Node<K, V> parent = current.parent;
Node<K, V> right = current.right;
Node<K, V> rightLeft = right.left;
current.right = rightLeft;
if (rightLeft != null) rightLeft.parent = current;
right.left = current;
current.parent = right;
right.parent = parent;
rebalance(current);
rebalance(right);
return right;
}
private Node<K, V> rotateRight(Node<K, V> current) {
Node<K, V> parent = current.parent;
Node<K, V> left = current.left;
Node<K, V> leftRight = left.right;
current.left = leftRight;
if (leftRight != null) leftRight.parent = current;
left.right = current;
current.parent = left;
left.parent = parent;
rebalance(current);
rebalance(left);
return left;
}
private Node<K, V> rotateLeftLarge(Node<K, V> current) {
Node<K, V> parent = current.parent;
Node<K, V> right = current.right;
Node<K, V> rightLeft = right.left;
Node<K, V> rightLeftRight = right.left.right;
Node<K, V> rightLeftLeft = right.left.left;
current.right = rightLeftLeft;
if (rightLeftLeft != null) rightLeftLeft.parent = current;
right.left = rightLeftRight;
if (rightLeftRight != null) rightLeftRight.parent = right;
rightLeft.left = current;
rightLeft.right = right;
current.parent = rightLeft;
right.parent = rightLeft;
rightLeft.parent = parent;
rebalance(current);
rebalance(right);
rebalance(rightLeft);
return rightLeft;
}
private Node<K, V> rotateRightLarge(Node<K, V> current) {
Node<K, V> parent = current.parent;
Node<K, V> left = current.left;
Node<K, V> leftRight = left.right;
Node<K, V> leftRightLeft = left.right.left;
Node<K, V> leftRightRight = left.right.right;
current.left = leftRightRight;
if (leftRightRight != null) leftRightRight.parent = current;
left.right = leftRightLeft;
if (leftRightLeft != null) leftRightLeft.parent = left;
leftRight.right = current;
leftRight.left = left;
current.parent = leftRight;
left.parent = leftRight;
leftRight.parent = parent;
rebalance(current);
rebalance(left);
rebalance(leftRight);
return leftRight;
}
private int getDepth(Node<K, V> current) {
return current == null ? 0 : current.depth;
}
private Node<K, V> fixBalance(Node<K, V> current) {
if (current.left == null && current.right == null) {
return current;
}
int rightDepth = getDepth(current.right);
int leftDepth = getDepth(current.left);
int diff = rightDepth - leftDepth;
if (Math.abs(diff) <= 1) {
rebalance(current);
return current;
}
if (diff == -2) { // left deeper
int leftLeftDepth = getDepth(current.left.left);
int leftRightDepth = getDepth(current.left.right);
if (leftLeftDepth >= leftRightDepth) {
return rotateRight(current);
} else {
return rotateRightLarge(current);
}
} else if (diff == 2) { // right deeper
int rightRightDepth = getDepth(current.right.right);
int rightLeftDepth = getDepth(current.right.left);
if (rightRightDepth >= rightLeftDepth) {
return rotateLeft(current);
} else {
return rotateLeftLarge(current);
}
} else {
throw new RuntimeException("Unexpected state");
}
}
public int size() {
return root == null ? 0 : root.size;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (root != null) {
root.print(sb, "");
}
return sb.toString();
}
}
} | Java | ["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"] | 2 seconds | ["5", "4", "3"] | NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$ | Java 8 | standard input | [
"data structures",
"two pointers",
"divide and conquer"
] | 42c4adc1c4a10cc619c05a842e186e60 | The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements. | 1,800 | Print the number of segments in Petya's array with the sum of elements less than $$$t$$$. | standard output | |
PASSED | 857e7cd8e3e1bf00f653954af2e70d50 | train_000.jsonl | 1537171500 | Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
/**
* Created by himanshubhardwaj on 17/09/18.
* Statement: https://codeforces.com/contest/1042/problem/D
* Algo:
* 1. Sqrt Decomposition
* 2.
*/
public class PetyaAndArray {
public static void main(String[] args) throws IOException {
PersistandSegmentTreeSolution.solve();
// ArrayList<Long> list = new ArrayList<>();
// list.add(7l);
// list.add(10l);
// System.out.println(SqrtDecompositionSolution.countElement(0,list.size()-1,8,list));
}
}
//Sqrt root decomposition solution
//Time complexity: n^(1.5)logn
//Extra Space: O(n)
//AC
class SqrtDecompositionSolution {
static ArrayList<Long>[] sqrt;
static long pref[];
static int sqrtN;
static void solve() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str[] = br.readLine().split(" ");
int n = Integer.parseInt(str[0]);
long t = Long.parseLong(str[1]);
int arr[] = new int[n];
str = br.readLine().split(" ");
pref = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(str[i]);
pref[i] = (i == 0) ? arr[i] : (arr[i] + pref[i - 1]);//prefix sum
}
sqrtN = (int) Math.sqrt(n);
sqrt = new ArrayList[(int) Math.ceil(n / (double) sqrtN)];
for (int i = 0; i < sqrt.length; i++) {
sqrt[i] = new ArrayList<>(sqrtN);
}
for (int i = 0; i < n; i++) {
sqrt[i / sqrtN].add(pref[i]);
}
for (int i = 0; i < sqrt.length; i++) {
Collections.sort(sqrt[i]);
}
long count = 0;
for (int i = 0; i < n; i++) {
count += getNumElementsSqrtDecomposition(i, (i == 0) ? t : (t + pref[i - 1]));
}
System.out.print(count);
}
private static long getNumElementsBruteForce(int pos, long k) {
long count = 0;
for (int i = pos; i < pref.length; i++) {
if (pref[i] < k) {
count++;
}
System.out.print(pref[i] + ",");
}
System.out.println("\tBruteForce:\t" + pos + "\t" + k + "\t" + count);
return count;
}
private static long getNumElementsSqrtDecomposition(int pos, long k) {
int currentBucket = pos / sqrtN;
long count = 0;
for (int i = pos; i < Math.min(pref.length, sqrtN * (currentBucket + 1)); i++) {
if (pref[i] < k) {
count++;
}
}
for (int i = currentBucket + 1; i < sqrt.length; i++) {
count += countElement(0, sqrt[i].size() - 1, k, sqrt[i]);
}
return count;
}
//this will return number of elements from start to end are less than k
static public int countElement(int start, int end, long k, ArrayList<Long> list) {
if (start > end || start < 0 || end >= list.size() || list.get(start) >= k) {
return 0;
}
if (list.get(end) < k) {
return end - start + 1;
}
int mid = (end + start) / 2;
if (list.get(mid) < k) {
return mid - start + 1 + countElement(mid + 1, end, k, list);
} else {
return countElement(start, mid - 1, k, list);
}
}
}
//Time Complexity: nlog^2 n
//Extra Space: O(n logn)
class PersistandSegmentTreeSolution {
static long pref[];
static void solve() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str[] = br.readLine().split(" ");
int n = Integer.parseInt(str[0]);
long t = Long.parseLong(str[1]);
int arr[] = new int[n];
str = br.readLine().split(" ");
pref = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(str[i]);
pref[i] = (i == 0) ? arr[i] : (arr[i] + pref[i - 1]);//prefix sum
}
PersistentSegmentTree.constructPersistantSegmentTree(pref);
long count = 0;
for (int i = 0; i < n; i++) {
count += PersistentSegmentTree.getNumElementsSegTree(i, (i == 0) ? t : (t + pref[i - 1]), n - 1);
}
System.out.print(count);
}
}
//we can implement a simpler version only for suffix, but we won't
class PersistentSegmentTree {
static ArrayList<Long>[] persistentSegmentTree;
static long[] segmentTree;
static int size;
static int end;
public static void constructPersistantSegmentTree(long pref[]) {
size = (int) Math.pow(2, Math.ceil(Math.log(pref.length) / Math.log(2)));
size = size + size - 1;
segmentTree = new long[size];
persistentSegmentTree = new ArrayList[size];
for (int i = 0; i <= (size / 2); i++) {
persistentSegmentTree[(size / 2) + i] = new ArrayList<>();
segmentTree[(size / 2) + i] = Long.MIN_VALUE;
if (i < pref.length) {
segmentTree[(size / 2) + i] = pref[i];
persistentSegmentTree[(size / 2) + i].add(segmentTree[(size / 2) + i]);
end = (size / 2) + i;
}
}
for (int i = ((size / 2) - 1); i >= 0; i--) {
segmentTree[i] = Math.max(segmentTree[2 * i + 1], segmentTree[2 * i + 2]);
// System.out.println(i + "\t" + (2 * i + 1) + ", " + persistentSegmentTree[2 * i + 1] + "\t" + (2 * i + 2) + ", " + persistentSegmentTree[2 * i + 2]);
persistentSegmentTree[i] = new ArrayList<Long>(persistentSegmentTree[2 * i + 1]);
persistentSegmentTree[i].addAll(persistentSegmentTree[2 * i + 2]);
Collections.sort(persistentSegmentTree[i]);
}
}
public static long getNumElementsSegTree(int pos, long k, int end) {
return getNumElementsLessThanK(0, size / 2, pos, end, k, 0);
}
public static long getNumElementsLessThanK(int segTStart, int segTEnd, int rangeStart, int rangeEnd, long k, int segTIndex) {
if (segTEnd < segTStart || segTStart < 0 || segTStart > rangeEnd || segTEnd < rangeStart || segTIndex > end) {
return 0;
}
if (segTStart >= rangeStart && segTEnd <= rangeEnd) {
if (segmentTree[segTIndex] < k) {
return segTEnd - segTStart + 1;
} else {
return countElement(0, persistentSegmentTree[segTIndex].size() - 1, k, persistentSegmentTree[segTIndex]);
}
}
int mid = (segTEnd + segTStart) / 2;
return getNumElementsLessThanK(segTStart, mid, rangeStart, rangeEnd, k, 2 * segTIndex + 1) +
getNumElementsLessThanK(mid + 1, segTEnd, rangeStart, rangeEnd, k, 2 * segTIndex + 2);
}
//this will return number of elements from start to end are less than k
static public int countElement(int start, int end, long k, ArrayList<Long> list) {
if (start > end || start < 0 || end >= list.size() || list.get(start) >= k) {
return 0;
}
if (list.get(end) < k) {
return end - start + 1;
}
int mid = (end + start) / 2;
if (list.get(mid) < k) {
return mid - start + 1 + countElement(mid + 1, end, k, list);
} else {
return countElement(start, mid - 1, k, list);
}
}
} | Java | ["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"] | 2 seconds | ["5", "4", "3"] | NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$ | Java 8 | standard input | [
"data structures",
"two pointers",
"divide and conquer"
] | 42c4adc1c4a10cc619c05a842e186e60 | The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements. | 1,800 | Print the number of segments in Petya's array with the sum of elements less than $$$t$$$. | standard output | |
PASSED | 36dc659651871f46c7bbb28f6b808193 | train_000.jsonl | 1537171500 | Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
/**
* Created by himanshubhardwaj on 17/09/18.
* Statement: https://codeforces.com/contest/1042/problem/D
* Algo:
* 1. Sqrt Decomposition: Submission: https://codeforces.com/contest/1042/submission/43010464
* 2.Persistant segment tree decomposition, Submission: https://codeforces.com/contest/1042/submission/43024941
*
*/
public class PetyaAndArray {
public static void main(String[] args) throws IOException {
PersistandSegmentTreeSolution.solve();
}
}
//Sqrt root decomposition solution
//Time complexity: n^(1.5)logn
//Extra Space: O(n)
//AC: 1747ms
class SqrtDecompositionSolution {
static ArrayList<Long>[] sqrt;
static long pref[];
static int sqrtN;
static void solve() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str[] = br.readLine().split(" ");
int n = Integer.parseInt(str[0]);
long t = Long.parseLong(str[1]);
int arr[] = new int[n];
str = br.readLine().split(" ");
pref = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(str[i]);
pref[i] = (i == 0) ? arr[i] : (arr[i] + pref[i - 1]);//prefix sum
}
sqrtN = (int) Math.sqrt(n);
sqrt = new ArrayList[(int) Math.ceil(n / (double) sqrtN)];
for (int i = 0; i < sqrt.length; i++) {
sqrt[i] = new ArrayList<>(sqrtN);
}
for (int i = 0; i < n; i++) {
sqrt[i / sqrtN].add(pref[i]);
}
for (int i = 0; i < sqrt.length; i++) {
Collections.sort(sqrt[i]);
}
long count = 0;
for (int i = 0; i < n; i++) {
count += getNumElementsSqrtDecomposition(i, (i == 0) ? t : (t + pref[i - 1]));
}
System.out.print(count);
}
private static long getNumElementsBruteForce(int pos, long k) {
long count = 0;
for (int i = pos; i < pref.length; i++) {
if (pref[i] < k) {
count++;
}
System.out.print(pref[i] + ",");
}
System.out.println("\tBruteForce:\t" + pos + "\t" + k + "\t" + count);
return count;
}
private static long getNumElementsSqrtDecomposition(int pos, long k) {
int currentBucket = pos / sqrtN;
long count = 0;
for (int i = pos; i < Math.min(pref.length, sqrtN * (currentBucket + 1)); i++) {
if (pref[i] < k) {
count++;
}
}
for (int i = currentBucket + 1; i < sqrt.length; i++) {
count += countElement(0, sqrt[i].size() - 1, k, sqrt[i]);
}
return count;
}
//this will return number of elements from start to end are less than k
static public int countElement(int start, int end, long k, ArrayList<Long> list) {
if (start > end || start < 0 || end >= list.size() || list.get(start) >= k) {
return 0;
}
if (list.get(end) < k) {
return end - start + 1;
}
int mid = (end + start) / 2;
if (list.get(mid) < k) {
return mid - start + 1 + countElement(mid + 1, end, k, list);
} else {
return countElement(start, mid - 1, k, list);
}
}
}
//Time Complexity: nlog^2 n
//Extra Space: O(n logn)
//AC
//Time: 858
class PersistandSegmentTreeSolution {
static long pref[];
static void solve() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str[] = br.readLine().split(" ");
int n = Integer.parseInt(str[0]);
long t = Long.parseLong(str[1]);
int arr[] = new int[n];
str = br.readLine().split(" ");
pref = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(str[i]);
pref[i] = (i == 0) ? arr[i] : (arr[i] + pref[i - 1]);//prefix sum
}
PersistentSegmentTree.constructPersistantSegmentTree(pref);
long count = 0;
for (int i = 0; i < n; i++) {
count += PersistentSegmentTree.getNumElementsSegTree(i, (i == 0) ? t : (t + pref[i - 1]), n - 1);
}
System.out.print(count);
}
}
//we can implement a simpler version only for suffix, but I want to get AC on generic so that it could be used further
class PersistentSegmentTree {
static ArrayList<Long>[] persistentSegmentTree;
static long[] segmentTree;
static int size;
static int end;
public static void constructPersistantSegmentTree(long pref[]) {
size = (int) Math.pow(2, Math.ceil(Math.log(pref.length) / Math.log(2)));
size = size + size - 1;
segmentTree = new long[size];
persistentSegmentTree = new ArrayList[size];
for (int i = 0; i <= (size / 2); i++) {
persistentSegmentTree[(size / 2) + i] = new ArrayList<>();
segmentTree[(size / 2) + i] = Long.MIN_VALUE;
if (i < pref.length) {
segmentTree[(size / 2) + i] = pref[i];
persistentSegmentTree[(size / 2) + i].add(segmentTree[(size / 2) + i]);
end = (size / 2) + i;
}
}
for (int i = ((size / 2) - 1); i >= 0; i--) {
segmentTree[i] = Math.max(segmentTree[2 * i + 1], segmentTree[2 * i + 2]);
persistentSegmentTree[i] = new ArrayList<Long>(persistentSegmentTree[2 * i + 1]);
persistentSegmentTree[i].addAll(persistentSegmentTree[2 * i + 2]);
Collections.sort(persistentSegmentTree[i]);
}
}
public static long getNumElementsSegTree(int pos, long k, int end) {
return getNumElementsLessThanK(0, size / 2, pos, end, k, 0);
}
public static long getNumElementsLessThanK(int segTStart, int segTEnd, int rangeStart, int rangeEnd, long k, int segTIndex) {
if (segTEnd < segTStart || segTStart < 0 || segTStart > rangeEnd || segTEnd < rangeStart || segTIndex > end) {
return 0;
}
if (segTStart >= rangeStart && segTEnd <= rangeEnd) {
if (segmentTree[segTIndex] < k) {
return segTEnd - segTStart + 1;
} else {
return countElement(0, persistentSegmentTree[segTIndex].size() - 1, k, persistentSegmentTree[segTIndex]);
}
}
int mid = (segTEnd + segTStart) / 2;
return getNumElementsLessThanK(segTStart, mid, rangeStart, rangeEnd, k, 2 * segTIndex + 1) +
getNumElementsLessThanK(mid + 1, segTEnd, rangeStart, rangeEnd, k, 2 * segTIndex + 2);
}
//this will return number of elements from start to end are less than k
static public int countElement(int start, int end, long k, ArrayList<Long> list) {
if (start > end || start < 0 || end >= list.size() || list.get(start) >= k) {
return 0;
}
if (list.get(end) < k) {
return end - start + 1;
}
int mid = (end + start) / 2;
if (list.get(mid) < k) {
return mid - start + 1 + countElement(mid + 1, end, k, list);
} else {
return countElement(start, mid - 1, k, list);
}
}
} | Java | ["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"] | 2 seconds | ["5", "4", "3"] | NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$ | Java 8 | standard input | [
"data structures",
"two pointers",
"divide and conquer"
] | 42c4adc1c4a10cc619c05a842e186e60 | The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements. | 1,800 | Print the number of segments in Petya's array with the sum of elements less than $$$t$$$. | standard output | |
PASSED | 39e0053308b0119267a128f88fa9b2a6 | train_000.jsonl | 1537171500 | Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
/**
* Created by himanshubhardwaj on 17/09/18.
* Statement: https://codeforces.com/contest/1042/problem/D
* Algo:
*/
public class PetyaAndArray {
public static void main(String[] args) throws IOException {
SqrtDecompositionSolution.solve();
// ArrayList<Long> list = new ArrayList<>();
// list.add(7l);
// list.add(10l);
// System.out.println(SqrtDecompositionSolution.countElement(0,list.size()-1,8,list));
}
}
//Sqrt root decomposition solution
//Time complexity: n^(1.5)logn
//Extra Space: O(n)
class SqrtDecompositionSolution {
static ArrayList<Long>[] sqrt;
static long pref[];
static int sqrtN;
static void solve() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str[] = br.readLine().split(" ");
int n = Integer.parseInt(str[0]);
long t = Long.parseLong(str[1]);
int arr[] = new int[n];
str = br.readLine().split(" ");
pref = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(str[i]);
pref[i] = (i == 0) ? arr[i] : (arr[i] + pref[i - 1]);//prefix sum
}
sqrtN = (int) Math.sqrt(n);
sqrt = new ArrayList[(int) Math.ceil(n / (double) sqrtN)];
for (int i = 0; i < sqrt.length; i++) {
sqrt[i] = new ArrayList<>(sqrtN);
}
for (int i = 0; i < n; i++) {
sqrt[i / sqrtN].add(pref[i]);
}
for (int i = 0; i < sqrt.length; i++) {
Collections.sort(sqrt[i]);
}
long count = 0;
for (int i = 0; i < n; i++) {
count += getNumElementsSqrtDecomposition(i, (i == 0) ? t : (t + pref[i - 1]));
}
System.out.print(count);
}
private static long getNumElementsBruteForce(int pos, long k) {
long count = 0;
for (int i = pos; i < pref.length; i++) {
if (pref[i] < k) {
count++;
}
System.out.print(pref[i] + ",");
}
System.out.println("\tBruteForce:\t" + pos + "\t" + k + "\t" + count);
return count;
}
private static long getNumElementsSqrtDecomposition(int pos, long k) {
int currentBucket = pos / sqrtN;
long count = 0;
for (int i = pos; i < Math.min(pref.length, sqrtN * (currentBucket + 1)); i++) {
if (pref[i] < k) {
count++;
}
}
for (int i = currentBucket + 1; i < sqrt.length; i++) {
count += countElement(0, sqrt[i].size() - 1, k, sqrt[i]);
}
return count;
}
//this will return number of elements from start to end are less than k
static public int countElement(int start, int end, long k, ArrayList<Long> list) {
if (start > end || start < 0 || end >= list.size() || list.get(start) >= k) {
return 0;
}
if (list.get(end) < k) {
return end - start + 1;
}
int mid = (end + start) / 2;
if (list.get(mid) < k) {
return mid - start + 1 + countElement(mid + 1, end, k, list);
} else {
return countElement(start, mid - 1, k, list);
}
}
}
//Time Complexity: nlogn
//Extra Space: O(n log n)
class PersistandSegmentTreeSolution {
} | Java | ["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"] | 2 seconds | ["5", "4", "3"] | NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$ | Java 8 | standard input | [
"data structures",
"two pointers",
"divide and conquer"
] | 42c4adc1c4a10cc619c05a842e186e60 | The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements. | 1,800 | Print the number of segments in Petya's array with the sum of elements less than $$$t$$$. | standard output | |
PASSED | 350a7c09f795e81988c1564d8b2039ff | train_000.jsonl | 1537171500 | Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
/**
* Created by himanshubhardwaj on 17/09/18.
* Statement: https://codeforces.com/contest/1042/problem/D
* Algo:
* 1. Sqrt Decomposition: Submission, https://codeforces.com/contest/1042/submission/43010464 time: 1747 ms
* 2.Persistant segment tree decomposition, Submission: https://codeforces.com/contest/1042/submission/43025040 time: 795ms
* 3. Normal Segment Tre gave TLE, Submission: https://codeforces.com/contest/1042/submission/43025346
*
*/
public class PetyaAndArray {
public static void main(String[] args) throws IOException {
PersistandSegmentTreeSolution.solve();
}
}
//Sqrt root decomposition solution
//Time complexity: n^(1.5)logn
//Extra Space: O(n)
//AC: 1747ms
class SqrtDecompositionSolution {
static ArrayList<Long>[] sqrt;
static long pref[];
static int sqrtN;
static void solve() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str[] = br.readLine().split(" ");
int n = Integer.parseInt(str[0]);
long t = Long.parseLong(str[1]);
int arr[] = new int[n];
str = br.readLine().split(" ");
pref = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(str[i]);
pref[i] = (i == 0) ? arr[i] : (arr[i] + pref[i - 1]);//prefix sum
}
sqrtN = (int) Math.sqrt(n);
sqrt = new ArrayList[(int) Math.ceil(n / (double) sqrtN)];
for (int i = 0; i < sqrt.length; i++) {
sqrt[i] = new ArrayList<>(sqrtN);
}
for (int i = 0; i < n; i++) {
sqrt[i / sqrtN].add(pref[i]);
}
for (int i = 0; i < sqrt.length; i++) {
Collections.sort(sqrt[i]);
}
long count = 0;
for (int i = 0; i < n; i++) {
count += getNumElementsSqrtDecomposition(i, (i == 0) ? t : (t + pref[i - 1]));
}
System.out.print(count);
}
private static long getNumElementsBruteForce(int pos, long k) {
long count = 0;
for (int i = pos; i < pref.length; i++) {
if (pref[i] < k) {
count++;
}
System.out.print(pref[i] + ",");
}
System.out.println("\tBruteForce:\t" + pos + "\t" + k + "\t" + count);
return count;
}
private static long getNumElementsSqrtDecomposition(int pos, long k) {
int currentBucket = pos / sqrtN;
long count = 0;
for (int i = pos; i < Math.min(pref.length, sqrtN * (currentBucket + 1)); i++) {
if (pref[i] < k) {
count++;
}
}
for (int i = currentBucket + 1; i < sqrt.length; i++) {
count += countElement(0, sqrt[i].size() - 1, k, sqrt[i]);
}
return count;
}
//this will return number of elements from start to end are less than k
static public int countElement(int start, int end, long k, ArrayList<Long> list) {
if (start > end || start < 0 || end >= list.size() || list.get(start) >= k) {
return 0;
}
if (list.get(end) < k) {
return end - start + 1;
}
int mid = (end + start) / 2;
if (list.get(mid) < k) {
return mid - start + 1 + countElement(mid + 1, end, k, list);
} else {
return countElement(start, mid - 1, k, list);
}
}
}
//Time Complexity: nlog^2 n
//Extra Space: O(n logn)
//AC
//Time: 858
class PersistandSegmentTreeSolution {
static long pref[];
static void solve() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str[] = br.readLine().split(" ");
int n = Integer.parseInt(str[0]);
long t = Long.parseLong(str[1]);
int arr[] = new int[n];
str = br.readLine().split(" ");
pref = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(str[i]);
pref[i] = (i == 0) ? arr[i] : (arr[i] + pref[i - 1]);//prefix sum
}
PersistentSegmentTree.constructPersistantSegmentTree(pref);
long count = 0;
for (int i = 0; i < n; i++) {
count += PersistentSegmentTree.getNumElementsSegTree(i, (i == 0) ? t : (t + pref[i - 1]), n - 1);
}
System.out.print(count);
}
}
//we can implement a simpler version only for suffix, but I want to get AC on generic so that it could be used further
class PersistentSegmentTree {
static ArrayList<Long>[] persistentSegmentTree;
static long[] segmentTree;
static int size;
static int end;
public static void constructPersistantSegmentTree(long pref[]) {
size = (int) Math.pow(2, Math.ceil(Math.log(pref.length) / Math.log(2)));
size = size + size - 1;
segmentTree = new long[size];
persistentSegmentTree = new ArrayList[size];
for (int i = 0; i <= (size / 2); i++) {
persistentSegmentTree[(size / 2) + i] = new ArrayList<>();
segmentTree[(size / 2) + i] = Long.MIN_VALUE;
if (i < pref.length) {
segmentTree[(size / 2) + i] = pref[i];
persistentSegmentTree[(size / 2) + i].add(segmentTree[(size / 2) + i]);
end = (size / 2) + i;
}
}
for (int i = ((size / 2) - 1); i >= 0; i--) {
segmentTree[i] = Math.max(segmentTree[2 * i + 1], segmentTree[2 * i + 2]);
persistentSegmentTree[i] = new ArrayList<Long>(persistentSegmentTree[2 * i + 1]);
persistentSegmentTree[i].addAll(persistentSegmentTree[2 * i + 2]);
Collections.sort(persistentSegmentTree[i]);
}
}
public static long getNumElementsSegTree(int pos, long k, int end) {
return getNumElementsLessThanK(0, size / 2, pos, end, k, 0);
}
public static long getNumElementsLessThanK(int segTStart, int segTEnd, int rangeStart, int rangeEnd, long k, int segTIndex) {
if (segTEnd < segTStart || segTStart < 0 || segTStart > rangeEnd || segTEnd < rangeStart || segTIndex > end) {
return 0;
}
if (segTStart >= rangeStart && segTEnd <= rangeEnd) {
if (segmentTree[segTIndex] < k) {
return segTEnd - segTStart + 1;
} else {
return countElement(0, persistentSegmentTree[segTIndex].size() - 1, k, persistentSegmentTree[segTIndex]);
}
}
int mid = (segTEnd + segTStart) / 2;
return getNumElementsLessThanK(segTStart, mid, rangeStart, rangeEnd, k, 2 * segTIndex + 1) +
getNumElementsLessThanK(mid + 1, segTEnd, rangeStart, rangeEnd, k, 2 * segTIndex + 2);
}
//this will return number of elements from start to end are less than k
static public int countElement(int start, int end, long k, ArrayList<Long> list) {
if (start > end || start < 0 || end >= list.size() || list.get(start) >= k) {
return 0;
}
if (list.get(end) < k) {
return end - start + 1;
}
int mid = (end + start) / 2;
if (list.get(mid) < k) {
return mid - start + 1 + countElement(mid + 1, end, k, list);
} else {
return countElement(start, mid - 1, k, list);
}
}
}
//This gave TLE
class SegmentTreeSolution {
static long pref[];
static void solve() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str[] = br.readLine().split(" ");
int n = Integer.parseInt(str[0]);
long t = Long.parseLong(str[1]);
int arr[] = new int[n];
str = br.readLine().split(" ");
pref = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = Integer.parseInt(str[i]);
pref[i] = (i == 0) ? arr[i] : (arr[i] + pref[i - 1]);//prefix sum
}
SegmentTree.constructPersistantSegmentTree(pref);
long count = 0;
for (int i = 0; i < n; i++) {
count += SegmentTree.getNumElementsSegTree(i, (i == 0) ? t : (t + pref[i - 1]), n - 1);
}
System.out.print(count);
}
}
//Simpiler segment tree just to test speed
class SegmentTree {
static long[] segmentTree;
static int size;
static int end;
public static void constructPersistantSegmentTree(long pref[]) {
size = (int) Math.pow(2, Math.ceil(Math.log(pref.length) / Math.log(2)));
size = size + size - 1;
segmentTree = new long[size];
for (int i = 0; i <= (size / 2); i++) {
segmentTree[(size / 2) + i] = Long.MIN_VALUE;
if (i < pref.length) {
segmentTree[(size / 2) + i] = pref[i];
end = (size / 2) + i;
}
}
for (int i = ((size / 2) - 1); i >= 0; i--) {
segmentTree[i] = Math.max(segmentTree[2 * i + 1], segmentTree[2 * i + 2]);
}
}
public static long getNumElementsSegTree(int pos, long k, int end) {
return getNumElementsLessThanK(0, size / 2, pos, end, k, 0);
}
public static long getNumElementsLessThanK(int segTStart, int segTEnd, int rangeStart, int rangeEnd, long k, int segTIndex) {
if (segTEnd < segTStart || segTStart < 0 || segTStart > rangeEnd || segTEnd < rangeStart || segTIndex > end) {
return 0;
}
if (segTStart >= rangeStart && segTEnd <= rangeEnd) {
if (segmentTree[segTIndex] < k) {
return segTEnd - segTStart + 1;
} else {
if (segTStart == segTEnd) {
return 0;
}
}
}
int mid = (segTEnd + segTStart) / 2;
return getNumElementsLessThanK(segTStart, mid, rangeStart, rangeEnd, k, 2 * segTIndex + 1) +
getNumElementsLessThanK(mid + 1, segTEnd, rangeStart, rangeEnd, k, 2 * segTIndex + 2);
}
//this will return number of elements from start to end are less than k
static public int countElement(int start, int end, long k, ArrayList<Long> list) {
if (start > end || start < 0 || end >= list.size() || list.get(start) >= k) {
return 0;
}
if (list.get(end) < k) {
return end - start + 1;
}
int mid = (end + start) / 2;
if (list.get(mid) < k) {
return mid - start + 1 + countElement(mid + 1, end, k, list);
} else {
return countElement(start, mid - 1, k, list);
}
}
} | Java | ["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"] | 2 seconds | ["5", "4", "3"] | NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$ | Java 8 | standard input | [
"data structures",
"two pointers",
"divide and conquer"
] | 42c4adc1c4a10cc619c05a842e186e60 | The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements. | 1,800 | Print the number of segments in Petya's array with the sum of elements less than $$$t$$$. | standard output | |
PASSED | 079c0c1d919987df0ee187e88f18820e | train_000.jsonl | 1537171500 | Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$. | 256 megabytes |
import java.io.*;
import java.util.*;
public class D {
static StringBuilder st = new StringBuilder() ;
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner();
int n = sc.nextInt();
long t = sc.nextLong()-1;
long [] a = new long [n];
for(int i = 0 ; i < n ;i++)
a[i] = sc.nextLong();
long [] acc = new long [n+1];
Long [] temp = new Long [n+1];
TreeMap<Long , Integer> compress = new TreeMap<>();
temp[0] = 0l;
for(int i = 1; i <= n ; i++)
temp[i] = acc[i] = acc[i-1] + a[i-1];
Arrays.sort(temp);
int _id = 0 ;
for(int i = 0 ; i <= n ;i++)
compress.put(temp[i], ++ _id);
FenwickTree ft = new FenwickTree(n+1);
long ans = 0 ;
ft.adjust(compress.get(0l));
for(int R = 1 ; R <= n ; R++)
{
if(compress.ceilingEntry(acc[R] - t) != null)
ans += ft.rsq(compress.ceilingEntry(acc[R] - t).getValue() , n+1);
ft.adjust(compress.get(acc[R]));
}
System.out.println(ans);
}
static class FenwickTree {
int n ;
int [] ft ;
FenwickTree(int size)
{
n = size ;
ft = new int [n+1];
}
void adjust(int i )
{
for(int k = i; k<= n ; k += (k & -k) )
ft[k] ++;
}
long rsq(int i)
{
long sum = 0;
for(int b = i ; b > 0 ; b ^= (b& -b))
sum += ft[b];
return sum ;
}
long rsq(int i , int j)
{
return rsq(j) - rsq(i-1);
}
}
static class Compress implements Comparable<Compress>{
static int _ID = 0;
long val ;
int id ;
public Compress(long a ) {
val = a ;
id = _ID ++;
}
@Override
public int compareTo(Compress o) {
return Long.compare(val, o.val);
}
@Override
public String toString() {
return val+" "+id;
}
}
static class Scanner{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st ;
String next () throws Exception{
while(st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
int nextInt() throws Exception{
return Integer.parseInt(next());
}
long nextLong() throws Exception{
return Long.parseLong(next());
}
double nextDouble() throws Exception{
return Double.parseDouble(next());
}
}
}
| Java | ["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"] | 2 seconds | ["5", "4", "3"] | NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$ | Java 8 | standard input | [
"data structures",
"two pointers",
"divide and conquer"
] | 42c4adc1c4a10cc619c05a842e186e60 | The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements. | 1,800 | Print the number of segments in Petya's array with the sum of elements less than $$$t$$$. | standard output | |
PASSED | fd432f6c8635f09bb3e8b9b384bb66be | train_000.jsonl | 1537171500 | Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class PetyaAndArray {
public static void main(String[] args) throws IOException {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskA solver = new TaskA();
solver.solve(1, in, out);
out.close();
}
static class TaskA {
long mod = (long)(1000000007);
public void solve(int testNumber, InputReader in, PrintWriter out) throws IOException {
while(testNumber-->0){
int n = in.nextInt();
long t = in.nextLong();
long a[] = new long[n+1];
for(int i=1;i<=n;i++)
a[i] = a[i-1] + in.nextLong();
long count = 0;
AVLTree tree = new AVLTree();
for(int i=n;i>=0;i--){
count += tree.getElementLessThanK(t + a[i]);
tree.insertElement(a[i]);
// tree.inorder(tree.root , out);
// out.println();
}
out.println(count);
}
}
static class AVLTree{
Node root;
public AVLTree(){
this.root = null;
}
public int height(Node n){
return (n == null ? 0 : n.height);
}
public int getBalance(Node n){
return (n == null ? 0 : height(n.left) - height(n.right));
}
public Node rotateRight(Node a){
Node b = a.left;
Node br = b.right;
a.lSum -= b.lSum;
a.lCount -= b.lCount;
b.rSum += a.rSum;
b.rCount += a.rCount;
b.right = a;
a.left = br;
a.height = 1 + Math.max(height(a.left) , height(a.right));
b.height = 1 + Math.max(height(b.left) , height(b.right));
return b;
}
public Node rotateLeft(Node a){
Node b = a.right;
Node bl = b.left;
a.rSum -= b.rSum;
a.rCount -= b.rCount;
b.lSum += a.lSum;
b.lCount += a.lCount;
b.left = a;
a.right = bl;
a.height = 1 + Math.max(height(a.left) , height(a.right));
b.height = 1 + Math.max(height(b.left) , height(b.right));
return b;
}
public Node insert(Node root , long value){
if(root == null){
return new Node(value);
}
if(value<=root.value){
root.lCount++;
root.lSum += value;
root.left = insert(root.left , value);
}
if(value>root.value){
root.rCount++;
root.rSum += value;
root.right = insert(root.right , value);
}
// updating the height of the root
root.height = 1 + Math.max(height(root.left) , height(root.right));
int balance = getBalance(root);
//ll
if(balance>1 && value<=root.left.value)
return rotateRight(root);
//rr
if(balance<-1 && value>root.right.value)
return rotateLeft(root);
//lr
if(balance>1 && value>root.left.value){
root.left = rotateLeft(root.left);
return rotateRight(root);
}
//rl
if(balance<-1 && value<=root.right.value){
root.right = rotateRight(root.right);
return rotateLeft(root);
}
return root;
}
public void insertElement(long value){
this.root = insert(root , value);
}
public int getElementLessThanK(long k){
int count = 0;
Node temp = root;
while(temp!=null){
if(temp.value == k){
if(temp.left == null || temp.left.value<k){
count += temp.lCount;
return count-1;
}
else
temp = temp.left;
}
else if(temp.value>k){
temp = temp.left;
}
else{
count += temp.lCount;
temp = temp.right;
}
}
return count;
}
public void inorder(Node root , PrintWriter out){
Node temp = root;
if(temp!=null){
inorder(temp.left , out);
out.println(temp.value + " " + temp.lCount + " " + temp.rCount);
inorder(temp.right , out);
}
}
}
static class Node{
long value;
long lCount , rCount;
long lSum , rSum;
Node left , right;
int height;
public Node(long value){
this.value = value;
left = null;
right = null;
lCount = 1;
rCount = 1;
lSum = value;
rSum = value;
height = 1;
}
}
public void sieve(int a[]){
a[0] = a[1] = 1;
int i;
for(i=2;i*i<=a.length;i++){
if(a[i] != 0)
continue;
a[i] = i;
for(int k = (i)*(i);k<a.length;k+=i){
if(a[k] != 0)
continue;
a[k] = i;
}
}
}
public int [][] matrixExpo(int c[][] , int n){
int a[][] = new int[c.length][c[0].length];
int b[][] = new int[a.length][a[0].length];
for(int i=0;i<c.length;i++)
for(int j=0;j<c[0].length;j++)
a[i][j] = c[i][j];
for(int i=0;i<a.length;i++)
b[i][i] = 1;
while(n!=1){
if(n%2 == 1){
b = matrixMultiply(a , a);
n--;
}
a = matrixMultiply(a , a);
n/=2;
}
return matrixMultiply(a , b);
}
public int [][] matrixMultiply(int a[][] , int b[][]){
int r1 = a.length;
int c1 = a[0].length;
int c2 = b[0].length;
int c[][] = new int[r1][c2];
for(int i=0;i<r1;i++){
for(int j=0;j<c2;j++){
for(int k=0;k<c1;k++)
c[i][j] += a[i][k]*b[k][j];
}
}
return c;
}
public long nCrPFermet(int n , int r , long p){
if(r==0)
return 1l;
long fact[] = new long[n+1];
fact[0] = 1;
for(int i=1;i<=n;i++)
fact[i] = (i*fact[i-1])%p;
long modInverseR = pow(fact[r] , p-2 , 1l , p);
long modInverseNR = pow(fact[n-r] , p-2 , 1l , p);
long w = (((fact[n]*modInverseR)%p)*modInverseNR)%p;
return w;
}
public long pow(long a , long b , long res , long mod){
if(b==0)
return res;
if(b==1)
return (res*a)%mod;
if(b%2==1){
res *= a;
res %= mod;
b--;
}
// System.out.println(a + " " + b + " " + res);
return pow((a*a)%mod , b/2 , res , mod);
}
public long pow(long a , long b , long res){
if(b == 0)
return res;
if(b==1)
return res*a;
if(b%2==1){
res *= a;
b--;
}
return pow(a*a , b/2 , res);
}
public void swap(int a[] , int p1 , int p2){
int x = a[p1];
a[p1] = a[p2];
a[p2] = x;
}
public void sortedArrayToBST(TreeSet<Integer> a , int start, int end) {
if (start > end) {
return;
}
int mid = (start + end) / 2;
a.add(mid);
sortedArrayToBST(a, start, mid - 1);
sortedArrayToBST(a, mid + 1, end);
}
class Combine{
int value;
int delete;
Combine(int val , int delete){
this.value = val;
this.delete = delete;
}
}
class Sort2 implements Comparator<Combine>{
public int compare(Combine a , Combine b){
if(a.value > b.value)
return 1;
else if(a.value == b.value && a.delete>b.delete)
return 1;
else if(a.value == b.value && a.delete == b.delete)
return 0;
return -1;
}
}
public int lowerLastBound(ArrayList<Integer> a , int x){
int l = 0;
int r = a.size()-1;
if(a.get(l)>=x)
return -1;
if(a.get(r)<x)
return r;
int mid = -1;
while(l<=r){
mid = (l+r)/2;
if(a.get(mid) == x && a.get(mid-1)<x)
return mid-1;
else if(a.get(mid)>=x)
r = mid-1;
else if(a.get(mid)<x && a.get(mid+1)>=x)
return mid;
else if(a.get(mid)<x && a.get(mid+1)<x)
l = mid+1;
}
return mid;
}
public int upperFirstBound(ArrayList<Integer> a , Integer x){
int l = 0;
int r = a.size()-1;
if(a.get(l)>x)
return l;
if(a.get(r)<=x)
return r+1;
int mid = -1;
while(l<=r){
mid = (l+r)/2;
if(a.get(mid) == x && a.get(mid+1)>x)
return mid+1;
else if(a.get(mid)<=x)
l = mid+1;
else if(a.get(mid)>x && a.get(mid-1)<=x)
return mid;
else if(a.get(mid)>x && a.get(mid-1)>x)
r = mid-1;
}
return mid;
}
public int lowerLastBound(int a[] , int x){
int l = 0;
int r = a.length-1;
if(a[l]>=x)
return -1;
if(a[r]<x)
return r;
int mid = -1;
while(l<=r){
mid = (l+r)/2;
if(a[mid] == x && a[mid-1]<x)
return mid-1;
else if(a[mid]>=x)
r = mid-1;
else if(a[mid]<x && a[mid+1]>=x)
return mid;
else if(a[mid]<x && a[mid+1]<x)
l = mid+1;
}
return mid;
}
public int upperFirstBound(long a[] , long x){
int l = 0;
int r = a.length-1;
if(a[l]>x)
return l;
if(a[r]<=x)
return r+1;
int mid = -1;
while(l<=r){
mid = (l+r)/2;
if(a[mid] == x && a[mid+1]>x)
return mid+1;
else if(a[mid]<=x)
l = mid+1;
else if(a[mid]>x && a[mid-1]<=x)
return mid;
else if(a[mid]>x && a[mid-1]>x)
r = mid-1;
}
return mid;
}
public long log(float number , int base){
return (long) Math.floor((Math.log(number) / Math.log(base)));
}
public long gcd(long a , long b){
if(a<b){
long c = b;
b = a;
a = c;
}
if(b == 0)
return a;
return gcd(b , a%b);
}
public void print2d(long a[][] , PrintWriter out){
for(int i=0;i<a.length;i++){
for(int j=0;j<a[i].length;j++)
out.print(a[i][j] + " ");
out.println();
}
out.println();
}
public void print1d(int a[] , PrintWriter out){
for(int i=0;i<a.length;i++)
out.print(a[i] + " ");
out.println();
out.println();
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
}
| Java | ["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"] | 2 seconds | ["5", "4", "3"] | NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$ | Java 8 | standard input | [
"data structures",
"two pointers",
"divide and conquer"
] | 42c4adc1c4a10cc619c05a842e186e60 | The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements. | 1,800 | Print the number of segments in Petya's array with the sum of elements less than $$$t$$$. | standard output | |
PASSED | aa0e164556216b26751dcc4c07589926 | train_000.jsonl | 1537171500 | Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
static InputReader in = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
static int oo = (int)1e9;
// static long oo = (long)1e15;
static int mod = 1_000_000_007;
// static int mod = 998244353;
static int[] dx = {1, 0, -1, 0};
static int[] dy = {0, -1, 0, 1};
static int M = 1000005;
static double EPS = 1e-13;
public static void main(String[] args) throws IOException {
int n = in.nextInt();
long t = in.nextLong();
int[] a = in.nextIntArray(n);
TreeSet<Long> set = new TreeSet<>();
long tot = 0;
long ps = 0;
for(int i = n-1; i >= 0; --i) {
ps += a[i];
set.add(ps);
tot += a[i];
}
long[] sum = new long[set.size() + 1];
int ii = 1;
for(long x : set)
sum[ii++] = x;
sum[0] = Long.MIN_VALUE;
int[] f = new int[sum.length];
long left = tot;
long right = 0;
long ans = 0;
for(int i = n-1; i >= 0; --i) {
left -= a[i];
if(tot - left < t)
ans++;
long b = tot - left - t + 1;
int k = lower_bound(sum, sum.length, b);
int cnt = query(f, f.length - 1) - query(f, k-1);
ans += cnt;
right += a[i];
int kk = lower_bound(sum, sum.length, right);
update(f, kk);
}
System.out.println(ans);
out.close();
}
static void update(int[] f, int i) {
while(i < f.length) {
f[i]++;
i += (i & -i);
}
}
static int query(int[] f, int i) {
int ret = 0;
while(i > 0) {
ret += f[i];
i -= (i & -i);
}
return ret;
}
static int search(long[] a, boolean[] visit, long k) {
int l = 0, r = a.length - 1;
int ret = -1;
while(l <= r) {
int mid = (l + r) / 2;
if(a[mid] == k) {
if(!visit[mid]) {
ret = mid;
r = mid - 1;
}
else {
l = mid + 1;
}
}
else if(a[mid] < k) {
l = mid + 1;
}
else {
r = mid - 1;
}
}
return ret;
}
static long invmod(long a, long mod) {
BigInteger b = BigInteger.valueOf(a);
BigInteger m = BigInteger.valueOf(mod);
return b.modInverse(m).longValue();
}
static int find(int[] g, int x) {
return g[x] = g[x] == x ? x : find(g, g[x]);
}
static void union(int[] g, int[] size, int x, int y) {
x = find(g, x); y = find(g, y);
if(x == y)
return;
if(size[x] < size[y]) {
g[x] = y;
size[y] += size[x];
}
else {
g[y] = x;
size[x] += size[y];
}
}
static class Segment {
Segment left, right;
int size;
// int time, lazy;
public Segment(long[] a, int l, int r) {
super();
if(l == r) {
return;
}
int mid = (l + r) / 2;
left = new Segment(a, l, mid);
right = new Segment(a, mid+1, r);
}
boolean covered(int ll, int rr, int l, int r) {
return ll <= l && rr >= r;
}
boolean noIntersection(int ll, int rr, int l, int r) {
return ll > r || rr < l;
}
// void lazyPropagation() {
// if(lazy != 0) {
// if(left != null) {
// left.setLazy(this.time, this.lazy);
// right.setLazy(this.time, this.lazy);
// }
// else {
// val = lazy;
// }
// }
// }
// void setLazy(int time, int lazy) {
// if(this.time != 0 && this.time <= time)
// return;
// this.time = time;
// this.lazy = lazy;
// }
int querySize(int ll, int rr, int l, int r) {
// lazyPropagation();
if(noIntersection(ll, rr, l, r))
return 0;
if(covered(ll, rr, l, r))
return size;
int mid = (l + r) / 2;
int leftSize = left.querySize(ll, rr, l, mid);
int rightSize = right.querySize(ll, rr, mid+1, r);
return leftSize + rightSize;
}
int query(int k, int l, int r) {
Segment trace = this;
while(l < r) {
int mid = (l + r) / 2;
if(trace.left.size > k) {
trace = trace.left;
r = mid;
}
else {
k -= trace.left.size;
trace = trace.right;
l = mid + 1;
}
}
return l;
}
void update(int ll, int rr, int l, int r) {
// lazyPropagation();
if(noIntersection(ll, rr, l, r))
return;
if(covered(ll, rr, l, r)) {
// setLazy(time, knight);
this.size = 1;
return;
}
int mid = (l + r) / 2;
left.update(ll, rr, l, mid);
right.update(ll, rr, mid+1, r);
this.size = left.size + right.size;
}
}
static long pow(long a, long n, long mod) {
if(n == 0)
return 1;
if(n % 2 == 1)
return a * pow(a, n-1, mod) % mod;
long x = pow(a, n / 2, mod);
return x * x % mod;
}
static int[] getPi(char[] a) {
int m = a.length;
int j = 0;
int[] pi = new int[m];
for(int i = 1; i < m; ++i) {
while(j > 0 && a[i] != a[j])
j = pi[j-1];
if(a[i] == a[j]) {
pi[i] = j + 1;
j++;
}
}
return pi;
}
static long lcm(long a, long b) {
return a * b / gcd(a, b);
}
static BigInteger lcm2(long a, long b) {
long g = gcd(a, b);
BigInteger gg = BigInteger.valueOf(g);
BigInteger aa = BigInteger.valueOf(a);
BigInteger bb = BigInteger.valueOf(b);
return aa.multiply(bb).divide(gg);
}
static boolean nextPermutation(int[] a) {
for(int i = a.length - 2; i >= 0; --i) {
if(a[i] < a[i+1]) {
for(int j = a.length - 1; ; --j) {
if(a[i] < a[j]) {
int t = a[i];
a[i] = a[j];
a[j] = t;
for(i++, j = a.length - 1; i < j; ++i, --j) {
t = a[i];
a[i] = a[j];
a[j] = t;
}
return true;
}
}
}
}
return false;
}
static void shuffle(Object[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
Object t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static void shuffle(int[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
int t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static void shuffle(long[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
long t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static int lower_bound(int[] a, int n, int k) {
int s = 0;
int e = n;
int m;
while (e - s > 0) {
m = (s + e) / 2;
if (a[m] < k)
s = m + 1;
else
e = m;
}
return e;
}
static int lower_bound(long[] a, int n, long k) {
int s = 0;
int e = n;
int m;
while (e - s > 0) {
m = (s + e) / 2;
if (a[m] < k)
s = m + 1;
else
e = m;
}
return e;
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static BigInteger gcd(BigInteger a, BigInteger b) {
return b.compareTo(BigInteger.ZERO) == 0 ? a : gcd(b, a.mod(b));
}
static class Pair implements Comparable<Pair> {
int first, second;
public Pair(int first, int second) {
super();
this.first = first;
this.second = second;
}
@Override
public int compareTo(Pair o) {
return this.first != o.first ? this.first - o.first : this.second - o.second;
}
// @Override
// public int compareTo(Pair o) {
// return this.first != o.first ? o.first - this.first : o.second - this.second;
// }
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + first;
result = prime * result + second;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
if (first != other.first)
return false;
if (second != other.second)
return false;
return true;
}
}
}
class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
} | Java | ["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"] | 2 seconds | ["5", "4", "3"] | NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$ | Java 8 | standard input | [
"data structures",
"two pointers",
"divide and conquer"
] | 42c4adc1c4a10cc619c05a842e186e60 | The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements. | 1,800 | Print the number of segments in Petya's array with the sum of elements less than $$$t$$$. | standard output | |
PASSED | d77335364bff4aa2ec0c4a57eb95b202 | train_000.jsonl | 1537171500 | Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
static InputReader in = new InputReader(System.in);
static PrintWriter out = new PrintWriter(System.out);
static int oo = (int)1e9;
// static long oo = (long)1e15;
static int mod = 1_000_000_007;
// static int mod = 998244353;
static int[] dx = {1, 0, -1, 0};
static int[] dy = {0, -1, 0, 1};
static int M = 1000005;
static double EPS = 1e-13;
static long[][] C;
public static void main(String[] args) throws IOException {
int n = in.nextInt();
long t = in.nextLong();
int[] a = in.nextIntArray(n);
long[] rps = new long[n];
long tot = 0;
for(int i = n-1; i >= 0; --i) {
rps[i] = i == n-1 ? a[i] : (rps[i+1] + a[i]);
tot += a[i];
}
shuffle(rps);
Arrays.sort(rps);
Segment seg = new Segment(rps, 0, n);
long left = tot;
long right = 0;
long ans = 0;
boolean[] visit = new boolean[n];
for(int i = n-1; i >= 0; --i) {
left -= a[i];
if(tot - left < t)
ans++;
long b = tot - left - t + 1;
int k = lower_bound(rps, n, b);
ans += seg.querySize(k, n-1, 0, n-1);
right += a[i];
int kk = search(rps, visit, right);
seg.update(kk, kk, 0, n-1);
visit[kk] = true;
}
System.out.println(ans);
out.close();
}
static int search(long[] a, boolean[] visit, long k) {
int l = 0, r = a.length - 1;
int ret = -1;
while(l <= r) {
int mid = (l + r) / 2;
if(a[mid] == k) {
if(!visit[mid]) {
ret = mid;
r = mid - 1;
}
else {
l = mid + 1;
}
}
else if(a[mid] < k) {
l = mid + 1;
}
else {
r = mid - 1;
}
}
return ret;
}
static long invmod(long a, long mod) {
BigInteger b = BigInteger.valueOf(a);
BigInteger m = BigInteger.valueOf(mod);
return b.modInverse(m).longValue();
}
static int find(int[] g, int x) {
return g[x] = g[x] == x ? x : find(g, g[x]);
}
static void union(int[] g, int[] size, int x, int y) {
x = find(g, x); y = find(g, y);
if(x == y)
return;
if(size[x] < size[y]) {
g[x] = y;
size[y] += size[x];
}
else {
g[y] = x;
size[x] += size[y];
}
}
static class Segment {
Segment left, right;
int size;
// int time, lazy;
public Segment(long[] a, int l, int r) {
super();
if(l == r) {
return;
}
int mid = (l + r) / 2;
left = new Segment(a, l, mid);
right = new Segment(a, mid+1, r);
}
boolean covered(int ll, int rr, int l, int r) {
return ll <= l && rr >= r;
}
boolean noIntersection(int ll, int rr, int l, int r) {
return ll > r || rr < l;
}
// void lazyPropagation() {
// if(lazy != 0) {
// if(left != null) {
// left.setLazy(this.time, this.lazy);
// right.setLazy(this.time, this.lazy);
// }
// else {
// val = lazy;
// }
// }
// }
// void setLazy(int time, int lazy) {
// if(this.time != 0 && this.time <= time)
// return;
// this.time = time;
// this.lazy = lazy;
// }
int querySize(int ll, int rr, int l, int r) {
// lazyPropagation();
if(noIntersection(ll, rr, l, r))
return 0;
if(covered(ll, rr, l, r))
return size;
int mid = (l + r) / 2;
int leftSize = left.querySize(ll, rr, l, mid);
int rightSize = right.querySize(ll, rr, mid+1, r);
return leftSize + rightSize;
}
int query(int k, int l, int r) {
Segment trace = this;
while(l < r) {
int mid = (l + r) / 2;
if(trace.left.size > k) {
trace = trace.left;
r = mid;
}
else {
k -= trace.left.size;
trace = trace.right;
l = mid + 1;
}
}
return l;
}
void update(int ll, int rr, int l, int r) {
// lazyPropagation();
if(noIntersection(ll, rr, l, r))
return;
if(covered(ll, rr, l, r)) {
// setLazy(time, knight);
this.size = 1;
return;
}
int mid = (l + r) / 2;
left.update(ll, rr, l, mid);
right.update(ll, rr, mid+1, r);
this.size = left.size + right.size;
}
}
static long pow(long a, long n, long mod) {
if(n == 0)
return 1;
if(n % 2 == 1)
return a * pow(a, n-1, mod) % mod;
long x = pow(a, n / 2, mod);
return x * x % mod;
}
static int[] getPi(char[] a) {
int m = a.length;
int j = 0;
int[] pi = new int[m];
for(int i = 1; i < m; ++i) {
while(j > 0 && a[i] != a[j])
j = pi[j-1];
if(a[i] == a[j]) {
pi[i] = j + 1;
j++;
}
}
return pi;
}
static long lcm(long a, long b) {
return a * b / gcd(a, b);
}
static BigInteger lcm2(long a, long b) {
long g = gcd(a, b);
BigInteger gg = BigInteger.valueOf(g);
BigInteger aa = BigInteger.valueOf(a);
BigInteger bb = BigInteger.valueOf(b);
return aa.multiply(bb).divide(gg);
}
static boolean nextPermutation(int[] a) {
for(int i = a.length - 2; i >= 0; --i) {
if(a[i] < a[i+1]) {
for(int j = a.length - 1; ; --j) {
if(a[i] < a[j]) {
int t = a[i];
a[i] = a[j];
a[j] = t;
for(i++, j = a.length - 1; i < j; ++i, --j) {
t = a[i];
a[i] = a[j];
a[j] = t;
}
return true;
}
}
}
}
return false;
}
static void shuffle(Object[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
Object t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static void shuffle(int[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
int t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static void shuffle(long[] a) {
Random r = new Random();
for(int i = a.length - 1; i > 0; --i) {
int si = r.nextInt(i);
long t = a[si];
a[si] = a[i];
a[i] = t;
}
}
static int lower_bound(int[] a, int n, int k) {
int s = 0;
int e = n;
int m;
while (e - s > 0) {
m = (s + e) / 2;
if (a[m] < k)
s = m + 1;
else
e = m;
}
return e;
}
static int lower_bound(long[] a, int n, long k) {
int s = 0;
int e = n;
int m;
while (e - s > 0) {
m = (s + e) / 2;
if (a[m] < k)
s = m + 1;
else
e = m;
}
return e;
}
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
static long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
static BigInteger gcd(BigInteger a, BigInteger b) {
return b.compareTo(BigInteger.ZERO) == 0 ? a : gcd(b, a.mod(b));
}
static class Pair implements Comparable<Pair> {
int first, second;
public Pair(int first, int second) {
super();
this.first = first;
this.second = second;
}
@Override
public int compareTo(Pair o) {
return this.first != o.first ? this.first - o.first : this.second - o.second;
}
// @Override
// public int compareTo(Pair o) {
// return this.first != o.first ? o.first - this.first : o.second - this.second;
// }
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + first;
result = prime * result + second;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
if (first != other.first)
return false;
if (second != other.second)
return false;
return true;
}
}
}
class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
} | Java | ["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"] | 2 seconds | ["5", "4", "3"] | NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$ | Java 8 | standard input | [
"data structures",
"two pointers",
"divide and conquer"
] | 42c4adc1c4a10cc619c05a842e186e60 | The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements. | 1,800 | Print the number of segments in Petya's array with the sum of elements less than $$$t$$$. | standard output | |
PASSED | 9aa85fafe18f6c9764b9ea471d2a54a4 | train_000.jsonl | 1537171500 | Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$. | 256 megabytes | import java.util.*;
public class Encrypt {
public static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
int n = scan.nextInt();
long t = scan.nextLong();
long[] pref = new long[n];
pref[0] = scan.nextInt();
for(int i=1;i<n;++i)
{
pref[i] = pref[i-1] + scan.nextLong();
}
System.out.println(mergeSort(pref, 0, n-1, t));
}
static long mergeSort(long[] a, int p, int r, long t)
{
if(p<r)
{
int q = (p+r)>>1;
long x = mergeSort(a, p, q, t);
long y = mergeSort(a, q+1, r, t);
long z = modifiedMerge(a,p,q,r,t);
return x+y+z;
}
else if (p==r) return a[p]<t?1:0;
else return 0;
}
static long modifiedMerge(long[] a, int p, int q, int r, long t)
{
int n1 = q-p+1;
int n2 = r-q;
long L[] = new long[n1+1];
long R[] = new long[n2+1];
for(int i=0;i<n1;++i)
{
L[i] = a[p+i];
}
for(int j=0;j<n2;++j)
{
R[j] = a[q+j+1];
}
L[n1] = Long.MAX_VALUE;
R[n2] = Long.MAX_VALUE;
int i=0, j=0;
int pref_i = 0, pref_j =0; long cnt=0;
for (int k=p; k<=r;++k)
{
if(L[i]<= R[j]) a[k] = L[i++];
else a[k] = R[j++];
}
while (pref_i < n1 && pref_j < n2)
{
if(R[pref_j] - L[pref_i] < t) {
cnt= cnt + (n1 - pref_i);
++pref_j;
}
else { ++pref_i; }
}
return cnt;
}
}
| Java | ["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"] | 2 seconds | ["5", "4", "3"] | NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$ | Java 8 | standard input | [
"data structures",
"two pointers",
"divide and conquer"
] | 42c4adc1c4a10cc619c05a842e186e60 | The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements. | 1,800 | Print the number of segments in Petya's array with the sum of elements less than $$$t$$$. | standard output | |
PASSED | cf73ed33303c20667b44bf94bf7fb842 | train_000.jsonl | 1537171500 | Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.flush();out.close();
}
static class TaskE {
class pair{
long F,S;
pair(long a,long b){F=a;S=b;}
}
long b[];
long seg[][];
void make(int n,int s,int e){
if(s==e){
seg[n]=new long[1];
seg[n][0]=b[s+1];
return;
}
int m=(s+e)>>1;
make(2*n+1,s,m);make(2*n+2,m+1,e);
seg[n]=new long[e-s+1];
merge(n);
}
void merge(int n){
int n1=2*n+1,n2=2*n+2;
int sz1=seg[n1].length,sz2=seg[n2].length;
int p1=0,p2=0,p=0;
while(p1<sz1&&p2<sz2){
if(seg[n1][p1]<seg[n2][p2]){
seg[n][p++]=seg[n1][p1];
p1++;
}else if(seg[n1][p1]>seg[n2][p2]){
seg[n][p++]=seg[n2][p2];
p2++;
}else{
seg[n][p++]=seg[n1][p1];
seg[n][p++]=seg[n2][p2];
p1++;p2++;
}
}
while(p1<sz1){
seg[n][p++]=seg[n1][p1];
p1++;
}
while(p2<sz2){
seg[n][p++]=seg[n2][p2];
p2++;
}
}
int query(int n,int s,int e,int qs,int qe,long val){
if(qs>e||qe<s)return 0;
if(s>=qs&&e<=qe){
return bs(n,val);
}
int m=(s+e)>>1;
return query(2*n+1,s,m,qs,qe,val)+query(2*n+2,m+1,e,qs,qe,val);
}
int bs(int n,long val){
int l=0,r=seg[n].length-1;
int ans=-1;
while(l<=r){
int m=(l+r)>>1;
if(seg[n][m]>val){
r=m-1;
}else{
ans=m;
l=m+1;
}
}
return ans+1;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n=in.nextInt();long t=in.nextLong();
long a[]=new long[n+2];
seg=new long[4*n][];
b=new long[n+2];
for(int i=1;i<=n;i++){
a[i]=in.nextLong();
}
for(int i=1;i<=n;i++){
b[i]=b[i-1]+a[i];
}
make(0,0,n-1);
int j=0;
long sum=0;
long ans=0;
for(int i=1;i<=n;i++){
// j=Math.max(j,i);
// while(j<=n){
// if(sum+a[j]<t){
// sum+=a[j];++j;
// }else{
// break;
// }
// }
// // out.println(i+" "+j);
// long left=t-sum-1+b[j-1];
// long cnt=query(0,0,n-1,j-1,n-1,left);
// ans+=j-i+cnt;
// if(j>i){
// sum-=a[i];
// }
long left=t-1+b[i-1];
ans+=query(0,0,n-1,i-1,n-1,left);
}
out.print(ans);
}
// pair ja[][];long w[];int from[],to[],c[];
// void make(int n,int m,InputReader in){
// ja=new pair[n+1][];w=new long[m];from=new int[m];to=new int[m];c=new int[n+1];
// for(int i=0;i<m;i++){
// int u=in.nextInt(),v=in.nextInt();long wt=in.nextLong();
// c[u]++;c[v]++;from[i]=u;to[i]=v;w[i]=wt;
// }
// for(int i=1;i<=n;i++){
// ja[i]=new pair[c[i]];c[i]=0;
// }
// for(int i=0;i<m;i++){
// ja[from[i]][c[from[i]]++]=new pair(to[i],w[i]);
// ja[to[i]][c[to[i]]++]=new pair(from[i],w[i]);
// }
// }
// int[] radixSort(int[] f){ return radixSort(f, f.length); }
// int[] radixSort(int[] f, int n)
// {
// int[] to = new int[n];
// {
// int[] b = new int[65537];
// for(int i = 0;i < n;i++)b[1+(f[i]&0xffff)]++;
// for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
// for(int i = 0;i < n;i++)to[b[f[i]&0xffff]++] = f[i];
// int[] d = f; f = to;to = d;
// }
// {
// int[] b = new int[65537];
// for(int i = 0;i < n;i++)b[1+(f[i]>>>16)]++;
// for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
// for(int i = 0;i < n;i++)to[b[f[i]>>>16]++] = f[i];
// int[] d = f; f = to;to = d;
// }
// return f;
// }
}
static class InputReader {
BufferedReader br;
StringTokenizer st;
public InputReader(InputStream stream) {
br = new BufferedReader(new InputStreamReader(stream));
st = null;
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
} | Java | ["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"] | 2 seconds | ["5", "4", "3"] | NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$ | Java 8 | standard input | [
"data structures",
"two pointers",
"divide and conquer"
] | 42c4adc1c4a10cc619c05a842e186e60 | The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements. | 1,800 | Print the number of segments in Petya's array with the sum of elements less than $$$t$$$. | standard output | |
PASSED | 8ef151c9cab222c21af63c8e7f9c0986 | train_000.jsonl | 1537171500 | Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.io.BufferedReader;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author ijxjdjd
*/
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);
PetyaAndArray solver = new PetyaAndArray();
solver.solve(1, in, out);
out.close();
}
static class PetyaAndArray {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int N = in.nextInt();
long T = in.nextLong();
ArrayList<Long> arr = new ArrayList<>();
long pref = 0;
arr.add(0L);
long[] prefixes = new long[N];
HashSet<Long> seen = new HashSet<>();
seen.add(0L);
for (int i = 0; i < N; i++) {
pref += in.nextInt();
prefixes[i] = pref;
if (!seen.contains(pref)) {
arr.add(pref);
seen.add(pref);
}
if (!seen.contains(pref - T + 1)) {
arr.add(pref - T + 1);
seen.add(pref - T + 1);
}
}
Collections.sort(arr);
FenwickTree fen = new FenwickTree(2 * N + 1);
long res = 0;
fen.add(find(arr, 0), 1);
for (int i = 0; i < N; i++) {
res += fen.sum(find(arr, prefixes[i] - T + 1), 2 * N);
fen.add(find(arr, prefixes[i]), 1);
}
out.println(res);
}
int find(ArrayList<Long> arr, long val) {
int low = 0;
int high = arr.size() - 1;
while (low < high) {
int mid = (low + high) / 2;
if (arr.get(mid) < val) {
low = mid + 1;
} else {
high = mid;
}
}
return high;
}
}
static class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
}
static class FenwickTree {
public int[] BIT;
public int size = 0;
public FenwickTree(int N) {
BIT = new int[N];
size = N;
}
public FenwickTree(int[] arr) {
size = arr.length;
BIT = new int[arr.length];
for (int i = 0; i < size; i++) {
add(i, arr[i]);
}
}
public void add(int id, int add) {
for (int i = id; i < size; i |= i + 1) {
BIT[i] += add;
}
}
public int sum(int l, int r) {
return sum(r) - sum(l - 1);
}
public int sum(int r) {
if (r < 0) {
return 0;
}
int res = 0;
for (int i = r; i >= 0; i = ((i) & (i + 1)) - 1) {
res += BIT[i];
}
return res;
}
}
}
| Java | ["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"] | 2 seconds | ["5", "4", "3"] | NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$ | Java 8 | standard input | [
"data structures",
"two pointers",
"divide and conquer"
] | 42c4adc1c4a10cc619c05a842e186e60 | The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements. | 1,800 | Print the number of segments in Petya's array with the sum of elements less than $$$t$$$. | standard output | |
PASSED | 481185b3d4fe3466c55cf1a1f7a93906 | train_000.jsonl | 1537171500 | Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$. | 256 megabytes | import java.awt.*;
import java.io.*;
import java.util.*;
public class Main implements Runnable {
int maxn = (int)2e5+111;
int inf = (int)1e18;
long mod = (long)1e9+7;
int n,m,k;
long pref[] = new long[maxn];
void solve() throws Exception {
n = in.nextInt();
long k = in.nextLong();
TreeSet<Long> set = new TreeSet<>();
set.add(-k);
for (int i=1; i<=n; i++) {
long t = in.nextLong();
pref[i] = pref[i-1] + t;
set.add(pref[i]-k);
set.add(pref[i]);
}
HashMap<Long, Integer> map = new HashMap<>();
int pos = 0;
for (long val : set) {
map.put(val, pos++);
}
pos--;
SegmentTree tree = new SegmentTree(new int[pos+1], 0, pos);
long ans = 0;
for (int i=1; i<=n; i++) {
if (pref[i]<k) ans++;
ans+=tree.getRangeValue(map.get(pref[i]-k)+1, pos);
tree.update(map.get(pref[i]), 1);
}
out.println(ans);
}
public class SegmentTree {
private SegmentTree leftNode;
private SegmentTree rightNode;
private int value;
private int leftBound, rightBound;
public SegmentTree(int arr[], int leftBound, int rightBound) {
this.leftBound = leftBound;
this.rightBound = rightBound;
if (leftBound == rightBound) {
value = arr[leftBound];
return;
}
int mid = (leftBound + rightBound) / 2;
leftNode = new SegmentTree(arr, leftBound, mid);
rightNode = new SegmentTree(arr, mid + 1, rightBound);
value = rangeValue();
}
public int getRangeValue(int l, int r) {
if (rightBound < l || leftBound > r) return 0;
if (l <= leftBound && rightBound <= r) return value;
return leftNode.getRangeValue(l, r) + rightNode.getRangeValue(l, r);
}
public void update(int pos, int val) {
if (leftBound == rightBound) {
value += val;
return;
}
int mid = (leftBound + rightBound) / 2;
if (pos <= mid) leftNode.update(pos, val);
else rightNode.update(pos, val);
value = rangeValue();
}
private int getValue() {
return value;
}
public int rangeValue() {
return leftNode.getValue() + rightNode.getValue();
}
}
public class Pair {
long x,y;
public Pair (long x, long y) {
this.x = x;
this.y = y;
}
}
String fileInName = "";
boolean file = false;
boolean isAcmp = false;
static Throwable throwable;
public static void main (String [] args) throws Throwable {
Thread thread = new Thread(null, new Main(), "", (1 << 26));
thread.start();
thread.join();
thread.run();
if (throwable != null)
throw throwable;
}
FastReader in;
PrintWriter out;
public void run() {
String fileIn = "angle2.in";
String fileOut = "angle2.out";
try {
if (isAcmp) {
if (file) {
in = new FastReader(new BufferedReader(new FileReader(fileIn)));
out = new PrintWriter (fileOut);
} else {
in = new FastReader(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
}
} else if (file) {
in = new FastReader(new BufferedReader(new FileReader(fileInName+".in")));
out = new PrintWriter (fileInName + ".out");
} else {
in = new FastReader(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
}
solve();
} catch(Exception e) {
throwable = e;
} finally {
out.close();
}
}
}
class FastReader {
BufferedReader bf;
StringTokenizer tk = null;
public FastReader(BufferedReader bf) {
this.bf = bf;
}
public Integer nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
public Long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
public Double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
public String nextToken () throws Exception {
if (tk==null || !tk.hasMoreTokens()) {
tk = new StringTokenizer(bf.readLine());
}
if (!tk.hasMoreTokens()) return nextToken();
else
return tk.nextToken();
}
} | Java | ["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"] | 2 seconds | ["5", "4", "3"] | NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$ | Java 8 | standard input | [
"data structures",
"two pointers",
"divide and conquer"
] | 42c4adc1c4a10cc619c05a842e186e60 | The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements. | 1,800 | Print the number of segments in Petya's array with the sum of elements less than $$$t$$$. | standard output | |
PASSED | 51b671507436a545a8841ab126d50a2d | train_000.jsonl | 1537171500 | Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$. | 256 megabytes | import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Comparator;
public class Main {
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
private static boolean debug = false;
private String nextString() {
StringBuilder sb = new StringBuilder();
try {
char c = (char) System.in.read();
while (c == ' ' || c == '\n' || c == '\t') {
c = (char) System.in.read();
}
do {
sb.append(c);
c = (char) System.in.read();
} while (c != ' ' && c != '\n' && c != '\t');
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
private int nextInt() {
int r = 0;
boolean f = false;
try {
int c = System.in.read();
while (c < '0' || c > '9') {
if (c == '-') {
f = true;
}
c = System.in.read();
}
while (c >= '0' && c <= '9') {
r = r * 10 + c - '0';
c = System.in.read();
}
} catch (IOException e) {
e.printStackTrace();
}
if (f) {
r *= -1;
}
return r;
}
private long nextLong() {
long r = 0;
boolean f = false;
try {
int c = System.in.read();
while (c < '0' || c > '9') {
if (c == '-') {
f = true;
}
c = System.in.read();
}
while (c >= '0' && c <= '9') {
r = r * 10 + c - '0';
c = System.in.read();
}
} catch (IOException e) {
e.printStackTrace();
}
if (f) {
r *= -1;
}
return r;
}
private void resolve() {
int n = nextInt();
long m = nextLong();
long ans = 0;
AVL<Long> avl = new AVL<>((a, b) -> a > b ? 1 : (a.equals(b) ? 0 : -1));
long sum = 0;
avl.insert(sum);
while (n-- > 0) {
long d = nextLong();
sum += d;
ans += avl.gt(sum - m);
avl.insert(sum);
}
println(ans);
}
private void println(String s) {
out.write(s);
out.write('\n');
out.flush();
}
private void println(long s) {
println(String.valueOf(s));
}
public class AVL<T> {
private Node<T> root = null;
private final Comparator<T> comparator;
public AVL(Comparator<T> comparator) {
this.comparator = comparator;
}
public void insert(T v) {
if (root == null) {
root = new Node<>(v, this.comparator);
} else {
root = root.insert(v);
}
}
public int gt(T v) {
return root == null ? 0 : root.gt(v);
}
public class Node<T> {
T v;
Comparator<T> comparator;
int size = 1;
int dep = 1;
Node<T> lc = null;
Node<T> rc = null;
public Node(T v, Comparator<T> comparator) {
this.v = v;
this.comparator = comparator;
}
private int getDep(Node node) {
return node == null ? 0 : node.dep;
}
private int getSize(Node node) {
return node == null ? 0 : node.size;
}
public Node<T> insert(T v) {
Node<T> rt = this;
if (comparator.compare(v, this.v) >= 0) {
if (this.rc == null) {
this.rc = new Node<>(v, this.comparator);
} else {
this.rc = this.rc.insert(v);
}
} else {
if (this.lc == null) {
this.lc = new Node<>(v, this.comparator);
} else {
this.lc = this.lc.insert(v);
}
}
if (getDep(this.lc) > getDep(this.rc) + 1) {
Node<T> lc = this.lc;
this.lc = lc.rc;
lc.rc = this;
this.update();
lc.update();
rt = lc;
} else if (getDep(this.rc) > getDep(this.lc) + 1) {
Node<T> rc = this.rc;
this.rc = rc.lc;
rc.lc = this;
this.update();
rc.update();
rt = rc;
} else {
this.update();
}
return rt;
}
private void update() {
this.dep = Math.max(getDep(this.rc), getDep(this.lc)) + 1;
this.size = getSize(this.rc) + getSize(this.lc) + 1;
}
public int gt(T v) {
if (comparator.compare(v, this.v) >= 0) {
return this.rc == null ? 0 : this.rc.gt(v);
} else {
return getSize(this.rc) + 1 + (this.lc == null ? 0 : this.lc.gt(v));
}
}
}
}
public static void main(String[] args) {
new Main().resolve();
}
} | Java | ["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"] | 2 seconds | ["5", "4", "3"] | NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$ | Java 8 | standard input | [
"data structures",
"two pointers",
"divide and conquer"
] | 42c4adc1c4a10cc619c05a842e186e60 | The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements. | 1,800 | Print the number of segments in Petya's array with the sum of elements less than $$$t$$$. | standard output | |
PASSED | cbc71dc57d3688d4a2b0b77db0a17e8d | train_000.jsonl | 1537171500 | Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.StringTokenizer;
public class Solution {
static InputReader in = new InputReader(System.in);
static OutputWriter out = new OutputWriter(System.out);
static int exp = (int) (1e9);
public static void main(String[] args) {
int n = in.nextInt();
long k = in.nextLong();
long[] sum = new long[n + 1];
for (int i = 1; i <= n; i++) {
sum[i] = sum[i - 1] + in.nextInt();
}
long ans = 0;
Treap treap = new Treap();
for (int i = n; i >= 1; i--) {
treap.add(sum[i]);
ans += treap.orderOf(sum[i - 1] + k);
}
System.out.println(ans);
}
static class Treap {
static class Node {
long key;
double priority;
Node left, right;
int size;
Node(long key) {
this.key = key;
priority = Math.random();
size = 1;
}
void update() {
size = 1 + getSize(left) + getSize(right);
}
int getSize(Node root) {
return root == null ? 0 : root.size;
}
}
Node root;
void add(long k) {
root = add(root, k);
}
long get(int k) {
return get(root, k);
}
int getSize(Node root) {
return root == null ? 0 : root.size;
}
int size() {
return getSize(root);
}
int orderOf(long k) {
return orderOf(root, k);
}
int orderOf(Node temp, long k) {
if (temp == null)
return 0;
if (temp.key < k)
return getSize(temp.left) + 1 + orderOf(temp.right, k);
else
return orderOf(temp.left, k);
}
Node splitL, splitR;
void splitRecursive(Node t, long x) {
if (t == null) {
splitL = null;
splitR = null;
return;
}
if (t.key <= x) {
splitRecursive(t.right, x);
t.right = splitL;
splitL = t;
} else {
splitRecursive(t.left, x);
t.left = splitR;
splitR = t;
}
t.update();
}
Node merge(Node left, Node right) {
if (left == null)
return right;
if (right == null)
return left;
if (left.priority > right.priority) {
left.right = merge(left.right, right);
left.update();
return left;
} else {
right.left = merge(left, right.left);
right.update();
return right;
}
}
Node add(Node root, long x) {
splitRecursive(root, x);
return merge(merge(splitL, new Node(x)), splitR);
}
long get(Node n, long k) {
if (n == null)
return -1;
int key = getSize(n.left) + 1;
if (key > k)
return get(n.left, k);
else if (key < k)
return get(n.right, k - key);
return n.key;
}
}
}
class OutputWriter {
public PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object... objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void println(Object... objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public String readLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public char nextChar() {
return next().charAt(0);
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public float nextFloat() {
return Float.parseFloat(next());
}
} | Java | ["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"] | 2 seconds | ["5", "4", "3"] | NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$ | Java 8 | standard input | [
"data structures",
"two pointers",
"divide and conquer"
] | 42c4adc1c4a10cc619c05a842e186e60 | The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements. | 1,800 | Print the number of segments in Petya's array with the sum of elements less than $$$t$$$. | standard output | |
PASSED | 911f8b527977e8c7c809bafa52552f2a | train_000.jsonl | 1537171500 | Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import static java.lang.Math.random;
import static java.util.Arrays.copyOf;
/**
* @author Don Li
*/
public class PetyaAndArray {
int N = (int) 2e5 + 10;
int[] t = new int[N];
Map<Long, Integer> val_to_idx = new HashMap<>();
void solve() {
int n = in.nextInt(); long t = in.nextLong();
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = in.nextInt();
long[] sum = new long[n + 1];
for (int i = 0; i < n; i++) sum[i + 1] = sum[i] + a[i];
sum = unique(sum);
for (int i = 0; i < sum.length; i++) val_to_idx.put(sum[i], i);
long ans = 0, cum = 0;
add(val_to_idx.get(0L), 1);
for (int i = 0; i < n; i++) {
cum += a[i];
int p = upperBound(sum, cum - t);
ans += i + 1 - sum(p - 1);
add(val_to_idx.get(cum), 1);
}
out.println(ans);
}
int upperBound(long[] a, long k) {
int lb = -1, ub = a.length;
while (ub - lb > 1) {
int mid = (lb + ub) >> 1;
if (a[mid] > k) ub = mid;
else lb = mid;
}
return ub;
}
int sum(int i) {
int res = 0;
for (int x = i; x >= 0; x = (x & x + 1) - 1) res += t[x];
return res;
}
void add(int i, int delta) {
for (int x = i; x < t.length; x = x | x + 1) t[x] += delta;
}
long[] unique(long[] a) {
a = a.clone();
sort(a);
int sz = 0;
for (int i = 0; i < a.length; i++) {
if (i == 0 || a[i] != a[i - 1]) a[sz++] = a[i];
}
return copyOf(a, sz);
}
void sort(long[] a) {
int n = a.length;
for (int i = 0; i < n; i++) {
int j = (int) (i + random() * (n - i));
long tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
Arrays.sort(a);
}
public static void main(String[] args) {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
new PetyaAndArray().solve();
out.close();
}
static FastScanner in;
static PrintWriter out;
static class FastScanner {
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
| Java | ["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"] | 2 seconds | ["5", "4", "3"] | NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$ | Java 8 | standard input | [
"data structures",
"two pointers",
"divide and conquer"
] | 42c4adc1c4a10cc619c05a842e186e60 | The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements. | 1,800 | Print the number of segments in Petya's array with the sum of elements less than $$$t$$$. | standard output | |
PASSED | 846d5acd66d57f889ee7b7c2d9830e1c | train_000.jsonl | 1537171500 | Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.TreeMap;
import static java.lang.Math.random;
import static java.util.Arrays.copyOf;
/**
* @author Don Li
*/
public class PetyaAndArray {
int N = (int) 2e5 + 10;
int[] t = new int[N];
TreeMap<Long, Integer> val_to_idx = new TreeMap<>();
void solve() {
int n = in.nextInt(); long t = in.nextLong();
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = in.nextInt();
long[] sum = new long[n + 1];
for (int i = 0; i < n; i++) sum[i + 1] = sum[i] + a[i];
sum = unique(sum);
for (int i = 0; i < sum.length; i++) val_to_idx.put(sum[i], i);
long ans = 0, cum = 0;
add(val_to_idx.get(0L), 1);
for (int i = 0; i < n; i++) {
cum += a[i];
int p = upperBound(sum, cum - t);
ans += i + 1 - sum(p - 1);
add(val_to_idx.get(cum), 1);
}
out.println(ans);
}
int upperBound(long[] a, long k) {
int lb = -1, ub = a.length;
while (ub - lb > 1) {
int mid = (lb + ub) >> 1;
if (a[mid] > k) ub = mid;
else lb = mid;
}
return ub;
}
int sum(int i) {
int res = 0;
for (int x = i; x >= 0; x = (x & x + 1) - 1) res += t[x];
return res;
}
void add(int i, int delta) {
for (int x = i; x < t.length; x = x | x + 1) t[x] += delta;
}
long[] unique(long[] a) {
a = a.clone();
sort(a);
int sz = 0;
for (int i = 0; i < a.length; i++) {
if (i == 0 || a[i] != a[i - 1]) a[sz++] = a[i];
}
return copyOf(a, sz);
}
void sort(long[] a) {
int n = a.length;
for (int i = 0; i < n; i++) {
int j = (int) (i + random() * (n - i));
long tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
Arrays.sort(a);
}
public static void main(String[] args) {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
new PetyaAndArray().solve();
out.close();
}
static FastScanner in;
static PrintWriter out;
static class FastScanner {
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
| Java | ["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"] | 2 seconds | ["5", "4", "3"] | NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$ | Java 8 | standard input | [
"data structures",
"two pointers",
"divide and conquer"
] | 42c4adc1c4a10cc619c05a842e186e60 | The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements. | 1,800 | Print the number of segments in Petya's array with the sum of elements less than $$$t$$$. | standard output | |
PASSED | 854f29807a1d33406f30b2a12a31e6ba | train_000.jsonl | 1537171500 | Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.TreeSet;
public class Solution1 implements Runnable
{
static final long MAX = 464897L;
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
private BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
public static void main(String args[]) throws Exception
{
new Thread(null, new Solution1(),"Solution",1<<26).start();
}
static int gcd(int a, int b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
long MOD = 1000000007;
ArrayList<Integer> adj[];
public void run()
{
//InputReader sc= new InputReader(new FileInputStream("input.txt"));
//PrintWriter w= new PrintWriter(new FileWriter("output.txt"));
InputReader sc = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n = sc.nextInt();
long m = sc.nextLong();
long[] arr= new long[n];
for(int i = 0;i < n;i++) {
arr[i] = sc.nextLong();
}
prefix = new long[n];
segTree = new ArrayList[4*n];
for(int i = 0;i < n;i++) {
if(i == 0) {
prefix[i] =arr[0];
continue;
}
prefix[i] = prefix[i-1] + arr[i];
}
build(0, n-1, 0);
long ans = 0;
for(int i = 0;i < n;i++) {
long temp = query(0, n-1, i, n-1,0,m);
ans += temp;
m = m + arr[i];
}
w.println(ans);
w.close();
}
long[] prefix;
ArrayList<Long> segTree[];
void build(int l,int r,int pos){
if(l == r){
segTree[pos] = new ArrayList();
segTree[pos].add(prefix[l]);
return;
}
int mid = (l+r)/2;
build(l, mid, 2*pos+1);
build(mid+1, r, 2*pos+2);
segTree[pos] = merge(segTree[2*pos+1],segTree[2*pos+2]);
}
ArrayList<Long> merge(ArrayList<Long> a,ArrayList<Long> b){
ArrayList<Long> c = new ArrayList();
int i = 0;
int j = 0;
while(i < a.size() && j < b.size()){
if(a.get(i) <= b.get(j)){
c.add(a.get(i));
i++;
}else{
c.add(b.get(j));
j++;
}
}
while(i < a.size()){
c.add(a.get(i));
i++;
}
while(j < b.size()){
c.add(b.get(j));
j++;
}
return c;
}
long query(int l,int r,int start,int end,int pos,long val){
if(l > end || r < start || l > r){
return 0;
}
if(l >= start && r <= end){
int ans = -1;
l = 0;
r = segTree[pos].size()-1;
while(l <= r){
int mid = (l + r)/2;
if(segTree[pos].get(mid) < val){
ans = mid;
l = mid+1;
}else{
r = mid-1;
}
}
return ans+1;
}
int mid = (l + r)/2;
long p1 = query(l,mid, start, end, 2*pos+1, val);
long p2 = query(mid+1, r, start, end, 2*pos+2, val);
return (p1+p2);
}
class Pair implements Comparable<Pair>{
long a;
int b;
//int c;
Pair(long a,int b){
this.b = b;
this.a = a;
}
public boolean equals(Object o) {
Pair p = (Pair)o;
return this.a == p.a && this.b == p.b;
}
public int hashCode(){
return Long.hashCode(a)*27 + Long.hashCode(b)* 31;
}
public int compareTo(Pair p) {
return Long.compare(this.a,p.a);
}
}
} | Java | ["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"] | 2 seconds | ["5", "4", "3"] | NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$ | Java 8 | standard input | [
"data structures",
"two pointers",
"divide and conquer"
] | 42c4adc1c4a10cc619c05a842e186e60 | The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements. | 1,800 | Print the number of segments in Petya's array with the sum of elements less than $$$t$$$. | standard output | |
PASSED | 341c58a2f347a8181e3d2fcb1276dc92 | train_000.jsonl | 1537171500 | Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class D
{
static int mod = (int) (1e9+7);
static InputReader in;
static PrintWriter out;
static class SegmentTree {
long st[];
SegmentTree(int n) {
st = new long[4*n];
build(0, n - 1, 1);
}
int getMid(int s, int e) {
return (s+e)>>1;
}
long merge(long a,long b){
return a+b;
}
void update(int s, int e, int x, int y, int c, int si){
if(s == x && e == y){
st[si] += c;
}
else{
int mid = getMid(s, e);
if(y <= mid)
update(s, mid, x, y, c, 2*si);
else if(x > mid)
update(mid + 1, e, x ,y ,c ,2*si + 1);
else{
update(s, mid, x, mid, c, 2*si);
update(mid + 1, e, mid + 1, y, c, 2*si + 1);
}
st[si] = merge(st[2*si],st[2*si+1]);
}
}
long get(int s, int e, int x, int y, int si){
if(s == x && e == y){
return st[si];
}
int mid = getMid(s, e);
if(y <= mid)
return get(s, mid, x, y, 2*si);
else if(x > mid)
return get(mid + 1, e, x, y, 2*si + 1);
return merge(get(s, mid, x, mid, 2*si), get(mid + 1, e, mid + 1, y, 2*si + 1));
}
void build(int ss, int se, int si){
if (ss == se) {
st[si] = 0;
return;
}
int mid = getMid(ss, se);
build(ss, mid, si * 2 );
build(mid + 1, se, si * 2 + 1);
st[si] = merge(st[2*si],st[2*si+1]);
}
}
static void solve()
{
in = new InputReader(System.in);
out = new PrintWriter(System.out);
int n = in.nextInt();
long t = in.nextLong();
long[] sum = new long[n + 1];
ArrayList<Long> list = new ArrayList<>();
list.add(0l);
for(int i = 0; i < n; i++) {
sum[i + 1] = sum[i] + in.nextLong();
list.add(sum[i + 1]);
list.add(sum[i + 1] - t + 1);
}
Collections.sort(list);
int j = 0;
HashMap<Long, Integer> map = new HashMap<>();
for(int i = 0; i < list.size(); i++) {
if(i > 0 && list.get(i) == list.get(i - 1) + 0) continue;
map.put(list.get(i), j++);
}
SegmentTree seg = new SegmentTree(j);
seg.update(0, j - 1, map.get(0l), map.get(0l), 1, 1);
long ans = 0;
for(int i = 1; i <= n; i++) {
ans += seg.get(0, j - 1, map.get(sum[i] - t + 1), j - 1, 1);
seg.update(0, j - 1, map.get(sum[i]), map.get(sum[i]), 1, 1);
}
out.println(ans);
out.close();
}
static long add(long a, long b) {
return (a + b) % mod;
}
static long mul(long a, long b) {
return (a * b) % mod;
}
static long sub(long a, long b) {
return (a - b + mod) % mod;
}
public static void main(String[] args)
{
new Thread(null ,new Runnable(){
public void run()
{
try{
solve();
} catch(Exception e){
e.printStackTrace();
}
}
},"1",1<<26).start();
}
static class Pair implements Comparable<Pair>
{
int x,y;
int i;
Pair (int x, int y)
{
this.x = x;
this.y = y;
}
public int compareTo(Pair o)
{
return -Integer.compare(this.x, o.x);
}
public boolean equals(Object o)
{
if (o instanceof Pair)
{
Pair p = (Pair)o;
return p.x == x && p.y==y;
}
return false;
}
@Override
public String toString()
{
return x + " "+ y + " "+i;
}
/*public int hashCode()
{
return new Long(x).hashCode() * 31 + new Long(y).hashCode();
}*/
}
static String rev(String s){
StringBuilder sb=new StringBuilder(s);
sb.reverse();
return sb.toString();
}
static long gcd(long x,long y)
{
if(y==0)
return x;
else
return gcd(y,x%y);
}
static int gcd(int x,int y)
{
if(y==0)
return x;
else
return gcd(y,x%y);
}
static long pow(long n,long p,long m)
{
long result = 1;
if(p==0){
return 1;
}
while(p!=0)
{
if(p%2==1)
result *= n;
if(result >= m)
result %= m;
p >>=1;
n*=n;
if(n >= m)
n%=m;
}
return result;
}
static long pow(long n,long p)
{
long result = 1;
if(p==0)
return 1;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
static void debug(Object... o)
{
System.out.println(Arrays.deepToString(o));
}
static class InputReader
{
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int snext()
{
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars)
{
curChar = 0;
try
{
snumChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = snext();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n)
{
int a[] = new int[n];
for (int i = 0; i < n; i++)
{
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n)
{
long a[] = new long[n];
for (int i = 0; i < n; i++)
{
a[i] = nextLong();
}
return a;
}
public String readString()
{
int c = snext();
while (isSpaceChar(c))
{
c = snext();
}
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c)
{
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"] | 2 seconds | ["5", "4", "3"] | NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$ | Java 8 | standard input | [
"data structures",
"two pointers",
"divide and conquer"
] | 42c4adc1c4a10cc619c05a842e186e60 | The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements. | 1,800 | Print the number of segments in Petya's array with the sum of elements less than $$$t$$$. | standard output | |
PASSED | c78ac44cc04f8f900feabdde55b995fb | train_000.jsonl | 1537171500 | Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
public class Main4 {
static int N;
static long T;
static int[] A;
public static void main(String[] args) {
FastScanner sc = new FastScanner(System.in);
N = sc.nextInt();
T = sc.nextLong();
A = sc.nextIntArray(N);
System.out.println(solve());
}
static long solve() {
long[] C = new long[N];
C[0] = A[0];
for (int i = 1; i < N; i++) {
C[i] = A[i] + C[i-1];
}
long[] D = new long[N+1];
System.arraycopy(C, 0, D, 0, N);
Arrays.sort(D);
Map<Long, Integer> zip = new HashMap<>();
int id = 0;
for (int i = 0; i < N+1; i++) {
if( !zip.containsKey(D[i]) ) {
zip.put(D[i], id);
id++;
}
}
BinaryIndexedTree bit = new BinaryIndexedTree(N+2);
// [L R] = [0 R] - [0 L-1] = C[R] - C[L-1]
// [L R] < T
// => C[R] < T + C[L-1]
long ans = 0;
for (int i = N-1; i >= 0; i--) {
bit.add(zip.get(C[i]), 1);
// [0, L-1]
long prev = i != 0 ? C[i-1] : 0;
int lb = lowerBound(D, prev + T);
if( lb > 0 ) {
ans += bit.sum( zip.get(D[lb-1]) );
}
}
return ans;
}
static int lowerBound(long[] array, long value) {
int low = 0;
int high = array.length;
int mid;
while( low < high ) {
mid = ((high - low) >>> 1) + low; // (high + low) / 2
if( array[mid] < value ) {
low = mid + 1;
} else {
high = mid;
}
}
return low;
}
static class BinaryIndexedTree {
int n;
int[] bit;
BinaryIndexedTree(int n) {
this.n = n;
this.bit = new int[n+1];
}
void add(int i, int v) {
i++; // 0 index -> 1 index
while( i <= n ) {
bit[i] += v;
i += i & -i;
}
}
int sum(int i) {
i++; // 0 index -> 1 index
int ret = 0;
while(i > 0) {
ret += bit[i];
i -= i & -i;
}
return ret;
}
}
@SuppressWarnings("unused")
static class FastScanner {
private BufferedReader reader;
private StringTokenizer tokenizer;
FastScanner(InputStream in) {
reader = new BufferedReader(new InputStreamReader(in));
tokenizer = null;
}
String next() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
String nextLine() {
if (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken("\n");
}
long nextLong() {
return Long.parseLong(next());
}
int nextInt() {
return Integer.parseInt(next());
}
int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = nextInt();
return a;
}
long[] nextLongArray(int n) {
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = nextLong();
return a;
}
}
}
| Java | ["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"] | 2 seconds | ["5", "4", "3"] | NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$ | Java 8 | standard input | [
"data structures",
"two pointers",
"divide and conquer"
] | 42c4adc1c4a10cc619c05a842e186e60 | The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements. | 1,800 | Print the number of segments in Petya's array with the sum of elements less than $$$t$$$. | standard output | |
PASSED | 2442964d26aeb55886a34446f2aefed3 | train_000.jsonl | 1537171500 | Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class CF1042_D {
public static void main(String[] args) throws Throwable {
MyScanner sc = new MyScanner();
PrintWriter pw = new PrintWriter(System.out);
int n = sc.nextInt();
long t = sc.nextLong();
long[] a = new long[n];
TreeSet<Long> set = new TreeSet<>();
set.add(0l);
HashMap<Long, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
a[i] = sc.nextInt();
if (i > 0)
a[i] += a[i - 1];
set.add(a[i]);
set.add(a[i] - t);
}
int id = 1;
for (long x : set)
map.put(x, id++);
add(map.get(0l));
long ans = 0;
// System.err.println(map);
for (int i = 0; i < n; i++) {
ans += i + 1 - get(map.get(a[i] - t));
add(map.get(a[i]));
// System.err.println(ans);
}
pw.println(ans);
pw.flush();
pw.close();
}
static int N = (int) 4e5 + 5;
static int[] ft = new int[N];
static void add(int idx) {
while (idx < N) {
ft[idx]++;
idx += (idx & -idx);
}
}
static int get(int idx) {
int ret = 0;
while (idx > 0) {
ret += ft[idx];
idx -= (idx & -idx);
}
return ret;
}
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 | ["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"] | 2 seconds | ["5", "4", "3"] | NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$ | Java 8 | standard input | [
"data structures",
"two pointers",
"divide and conquer"
] | 42c4adc1c4a10cc619c05a842e186e60 | The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements. | 1,800 | Print the number of segments in Petya's array with the sum of elements less than $$$t$$$. | standard output | |
PASSED | 78e3851e96a5161a1e8b8e335ee8e743 | train_000.jsonl | 1537171500 | Petya has an array $$$a$$$ consisting of $$$n$$$ integers. He has learned partial sums recently, and now he can calculate the sum of elements on any segment of the array really fast. The segment is a non-empty sequence of elements standing one next to another in the array.Now he wonders what is the number of segments in his array with the sum less than $$$t$$$. Help Petya to calculate this number.More formally, you are required to calculate the number of pairs $$$l, r$$$ ($$$l \le r$$$) such that $$$a_l + a_{l+1} + \dots + a_{r-1} + a_r < t$$$. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) throws Exception {
MyScanner scan = new MyScanner();
int n = scan.nextInt();
long t = scan.nextLong();
long[] a = new long[n];
for (int i = 0; i < n; i++)
a[i] = scan.nextLong();
long prefix = 0;
TreeSet<Long> ttt = new TreeSet<>();
ttt.add(prefix);
for (int i = 0; i < n; i++) {
prefix += a[i];
ttt.add(prefix);
}
sums = new long[ttt.size()];
for (int i = 0; i < sums.length; i++)
sums[i] = ttt.pollFirst();
long ans = 0, target;
int index;
prefix = 0;
bit = new int[sums.length + 1];
index = Arrays.binarySearch(sums, prefix);
set(index + 1);
for (int i = 0; i < n; i++) {
prefix += a[i];
target = prefix - t;
index = Arrays.binarySearch(sums, target);
if (index < 0)
index = -(index + 2);
index++;
ans += get(bit.length-1);
if(index > 0)
ans -= get(index);
index = Arrays.binarySearch(sums, prefix);
set(index + 1);
}
System.out.println(ans);
}
static long[] sums;
static int[] bit;
static void set(int i) {
if (i >= bit.length)
return;
bit[i]++;
set(i + next(i));
}
static int get(int i) {
if (i <= 0)
return 0;
return bit[i] + get(i - next(i));
}
static int next(int i) {
return i & (-i);
}
static void sort(Object o) {
Object[] arr = new Object[Array.getLength(o)];
for (int i = 0; i < arr.length; i++)
arr[i] = Array.get(o, i);
for (int i = 0; i < arr.length; i++) {
int j = (int) (Math.random() * (i + 1));
Object temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
Arrays.sort(arr);
for (int i = 0; i < arr.length; i++)
Array.set(o, i, arr[i]);
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer("");
}
public MyScanner(String filename) throws Exception {
br = new BufferedReader(new FileReader(filename));
st = new StringTokenizer("");
}
public String nextLine() throws Exception {
return br.readLine();
}
public String next() throws Exception {
while (!st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws Exception {
return Integer.parseInt(next());
}
public double nextDouble() throws Exception {
return Double.parseDouble(next());
}
public long nextLong() throws Exception {
return Long.parseLong(next());
}
}
}
| Java | ["5 4\n5 -1 3 4 -1", "3 0\n-1 2 -3", "4 -1\n-2 1 -2 3"] | 2 seconds | ["5", "4", "3"] | NoteIn the first example the following segments have sum less than $$$4$$$: $$$[2, 2]$$$, sum of elements is $$$-1$$$ $$$[2, 3]$$$, sum of elements is $$$2$$$ $$$[3, 3]$$$, sum of elements is $$$3$$$ $$$[4, 5]$$$, sum of elements is $$$3$$$ $$$[5, 5]$$$, sum of elements is $$$-1$$$ | Java 8 | standard input | [
"data structures",
"two pointers",
"divide and conquer"
] | 42c4adc1c4a10cc619c05a842e186e60 | The first line contains two integers $$$n$$$ and $$$t$$$ ($$$1 \le n \le 200\,000, |t| \le 2\cdot10^{14}$$$). The second line contains a sequence of integers $$$a_1, a_2, \dots, a_n$$$ ($$$|a_{i}| \le 10^{9}$$$) — the description of Petya's array. Note that there might be negative, zero and positive elements. | 1,800 | Print the number of segments in Petya's array with the sum of elements less than $$$t$$$. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.