exec_outcome
stringclasses 1
value | code_uid
stringlengths 32
32
| file_name
stringclasses 111
values | prob_desc_created_at
stringlengths 10
10
| prob_desc_description
stringlengths 63
3.8k
| prob_desc_memory_limit
stringclasses 18
values | source_code
stringlengths 117
65.5k
| lang_cluster
stringclasses 1
value | prob_desc_sample_inputs
stringlengths 2
802
| prob_desc_time_limit
stringclasses 27
values | prob_desc_sample_outputs
stringlengths 2
796
| prob_desc_notes
stringlengths 4
3k
⌀ | lang
stringclasses 5
values | prob_desc_input_from
stringclasses 3
values | tags
listlengths 0
11
| src_uid
stringlengths 32
32
| prob_desc_input_spec
stringlengths 28
2.37k
⌀ | difficulty
int64 -1
3.5k
⌀ | prob_desc_output_spec
stringlengths 17
1.47k
⌀ | prob_desc_output_to
stringclasses 3
values | hidden_unit_tests
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED
|
ec11ff157c9c50affc8c0f46764fe179
|
train_001.jsonl
|
1467822900
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l, r]) = r - l + 1 to be the number of integer points in the segment [l, r] with l ≤ r (say that ). You are given two integers n and k and n closed intervals [li, ri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109 + 7).Mike can't solve this problem so he needs your help. You will help him, won't you?
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
/**
* @author Don Li
*/
public class MikeGeometryProblem {
static final int MOD = (int) (1e9 + 7);
static final int MAXN = (int) (2e5 + 5);
static final long[] FAC = new long[MAXN], iFAC = new long[MAXN];
static {
FAC[0] = FAC[1] = 1;
for (int i = 2; i < MAXN; i++) FAC[i] = i * FAC[i - 1] % MOD;
iFAC[0] = iFAC[1] = 1;
for (int i = 2; i < MAXN; i++) iFAC[i] = inv(i) * iFAC[i - 1] % MOD;
}
void solve() {
int n = in.nextInt(), k = in.nextInt();
int[] l = new int[n], r = new int[n];
for (int i = 0; i < n; i++) {
l[i] = in.nextInt();
r[i] = in.nextInt();
}
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < n; i++) {
map.put(l[i], map.getOrDefault(l[i], 0) + 1);
map.put(r[i] + 1, map.getOrDefault(r[i] + 1, 0) - 1);
}
List<Integer> pos = new ArrayList<>(map.keySet());
Collections.sort(pos);
int m = pos.size();
for (int i = 1; i < m; i++) map.put(pos.get(i), map.get(pos.get(i)) + map.get(pos.get(i - 1)));
long ans = 0;
for (int i = 0; i < m - 1; i++) {
int f = map.get(pos.get(i));
int c = pos.get(i + 1) - pos.get(i);
ans = (ans + bc(f, k) * c % MOD) % MOD;
}
out.println(ans);
}
static long bc(int n, int k) {
if (n < k) return 0;
return FAC[n] * iFAC[k] % MOD * iFAC[n - k] % MOD;
}
static long inv(int i) {
return mpow(i, MOD - 2);
}
static long mpow(long a, long n) {
long res = 1;
while (n > 0) {
if ((n & 1) > 0) res = res * a % MOD;
a = a * a % MOD;
n >>= 1;
}
return res;
}
public static void main(String[] args) {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
new MikeGeometryProblem().solve();
out.close();
}
static FastScanner in;
static PrintWriter out;
static class FastScanner {
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
|
Java
|
["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"]
|
3 seconds
|
["5", "3", "6"]
|
NoteIn the first example: ;;.So the answer is 2 + 1 + 2 = 5.
|
Java 8
|
standard input
|
[
"dp",
"geometry",
"combinatorics",
"implementation",
"data structures"
] |
900c85e25d457eb8092624b1d42be2a2
|
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109), describing i-th segment bounds.
| 2,000 |
Print one integer number — the answer to Mike's problem modulo 1000000007 (109 + 7) in the only line.
|
standard output
| |
PASSED
|
7efede3b685f38e6dcc4ff18b41c4cd4
|
train_001.jsonl
|
1467822900
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l, r]) = r - l + 1 to be the number of integer points in the segment [l, r] with l ≤ r (say that ). You are given two integers n and k and n closed intervals [li, ri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109 + 7).Mike can't solve this problem so he needs your help. You will help him, won't you?
|
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.List;
import java.util.StringTokenizer;
import java.util.TreeMap;
/**
* @author Don Li
*/
public class MikeGeometryProblem {
static final int MOD = (int) (1e9 + 7);
static final int MAXN = (int) (2e5 + 5);
static final long[] FAC = new long[MAXN], iFAC = new long[MAXN];
static {
FAC[0] = FAC[1] = 1;
for (int i = 2; i < MAXN; i++) FAC[i] = i * FAC[i - 1] % MOD;
iFAC[0] = iFAC[1] = 1;
for (int i = 2; i < MAXN; i++) iFAC[i] = inv(i) * iFAC[i - 1] % MOD;
}
void solve() {
int n = in.nextInt(), k = in.nextInt();
int[] l = new int[n], r = new int[n];
for (int i = 0; i < n; i++) {
l[i] = in.nextInt();
r[i] = in.nextInt();
}
TreeMap<Integer, Integer> map = new TreeMap<>();
for (int i = 0; i < n; i++) {
map.put(l[i], map.getOrDefault(l[i], 0) + 1);
map.put(r[i] + 1, map.getOrDefault(r[i] + 1, 0) - 1);
}
List<Integer> pos = new ArrayList<>(map.navigableKeySet());
int m = pos.size();
for (int i = 1; i < m; i++) map.put(pos.get(i), map.get(pos.get(i)) + map.get(pos.get(i - 1)));
long ans = 0;
for (int i = 0; i < m - 1; i++) {
int f = map.get(pos.get(i));
int c = pos.get(i + 1) - pos.get(i);
ans = (ans + bc(f, k) * c % MOD) % MOD;
}
out.println(ans);
}
static long bc(int n, int k) {
if (n < k) return 0;
return FAC[n] * iFAC[k] % MOD * iFAC[n - k] % MOD;
}
static long inv(int i) {
return mpow(i, MOD - 2);
}
static long mpow(long a, long n) {
long res = 1;
while (n > 0) {
if ((n & 1) > 0) res = res * a % MOD;
a = a * a % MOD;
n >>= 1;
}
return res;
}
public static void main(String[] args) {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
new MikeGeometryProblem().solve();
out.close();
}
static FastScanner in;
static PrintWriter out;
static class FastScanner {
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
|
Java
|
["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"]
|
3 seconds
|
["5", "3", "6"]
|
NoteIn the first example: ;;.So the answer is 2 + 1 + 2 = 5.
|
Java 8
|
standard input
|
[
"dp",
"geometry",
"combinatorics",
"implementation",
"data structures"
] |
900c85e25d457eb8092624b1d42be2a2
|
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109), describing i-th segment bounds.
| 2,000 |
Print one integer number — the answer to Mike's problem modulo 1000000007 (109 + 7) in the only line.
|
standard output
| |
PASSED
|
66fd074c6f7cc2775c2648d3a58ac6c9
|
train_001.jsonl
|
1467822900
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l, r]) = r - l + 1 to be the number of integer points in the segment [l, r] with l ≤ r (say that ). You are given two integers n and k and n closed intervals [li, ri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109 + 7).Mike can't solve this problem so he needs your help. You will help him, won't you?
|
256 megabytes
|
/**
* @author mu
*
*/
import java.io.PrintWriter;
import java.util.Arrays;
// Trick CF: public
class Scanner {
private java.io.BufferedReader bufferedReader;
private java.util.StringTokenizer stringTokenizer;
public Scanner(java.io.InputStream inputStream) {
bufferedReader = new java.io.BufferedReader(
new java.io.InputStreamReader(inputStream));
}
public String next() {
for (; null == stringTokenizer || !stringTokenizer.hasMoreTokens();) {
try {
stringTokenizer = new java.util.StringTokenizer(
bufferedReader.readLine());
}
catch (java.io.IOException ioException) {
ioException.printStackTrace();
}
}
return stringTokenizer.nextToken();
}
public String nextLine() {
String result;
stringTokenizer = null;
try {
result = bufferedReader.readLine();
}
catch (java.io.IOException ioException) {
ioException.printStackTrace();
result = "";
}
return result;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public void close() {
try {
bufferedReader.close();
}
catch (java.io.IOException e) {
e.printStackTrace();
}
}
}
class Task {
private Scanner stdin;
private PrintWriter stdout;
public Task() {
stdin = new Scanner(System.in);
stdout = new PrintWriter(System.out);
}
public void close() {
stdin.close();
stdout.flush();
stdout.close();
}
public void run() {
int n = stdin.nextInt();
int k = stdin.nextInt();
@SuppressWarnings("unchecked")
Pair<Integer, Integer>[] node = new Pair[n << 1];
for (int i = 0; i < n; ++i) {
int left = stdin.nextInt();
int right = stdin.nextInt();
node[i << 1] = new Pair<Integer, Integer>(left, 1);
node[i << 1 | 1] = new Pair<Integer, Integer>(right + 1, -1);
}
Arrays.sort(node);
final int MOD = 1_000_000_000 + 7;
long ans = 0;
int coverCnt = node[0].y;
Pascal pascal = new Pascal(n, MOD);
for (int i = 1, nn = (n << 1); i < nn; ++i) {
if (coverCnt >= k) {
int length = node[i].x - node[i - 1].x;
ans = (ans + pascal.c(coverCnt, k) * length) % MOD;
}
coverCnt += node[i].y;
}
stdout.println(ans);
}
}
class Pair<T1 extends Comparable<T1>, T2 extends Comparable<T2>>
implements Comparable<Pair<T1, T2>> {
public T1 x;
public T2 y;
public Pair(T1 x, T2 y) {
this.x = x;
this.y = y;
}
@Override
public int compareTo(Pair<T1, T2> that) {
int cmp;
if (this.x.equals(that.x)) {
cmp = this.y.compareTo(that.y);
}
else {
cmp = this.x.compareTo(that.x);
}
return cmp;
}
}
class Pascal {
private long[] fac;
private long[] invFac;
final int MOD;
public Pascal(int max, final int MOD) {
fac = new long[max + 1];
invFac = new long[max + 1];
this.MOD = MOD;
fac[0] = 1;
for (int i = 1; i <= max; ++i) {
fac[i] = fac[i - 1] * i % MOD;
}
invFac[0] = invFac[1] = 1;
for (int i = 2; i <= max; ++i) {
invFac[i] = (MOD - MOD / i) * invFac[MOD % i] % MOD;
}
for (int i = 2; i <= max; ++i) {
invFac[i] = invFac[i] * invFac[i - 1] % MOD;
assert fac[i] * invFac[i] % MOD == 1;
}
}
public long c(int n, int k) {
return fac[n] * (invFac[k] * invFac[n - k] % MOD) % MOD;
}
}
public class Main {
public static void main(String[] args) {
Task task = new Task();
task.run();
task.close();
}
}
|
Java
|
["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"]
|
3 seconds
|
["5", "3", "6"]
|
NoteIn the first example: ;;.So the answer is 2 + 1 + 2 = 5.
|
Java 8
|
standard input
|
[
"dp",
"geometry",
"combinatorics",
"implementation",
"data structures"
] |
900c85e25d457eb8092624b1d42be2a2
|
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109), describing i-th segment bounds.
| 2,000 |
Print one integer number — the answer to Mike's problem modulo 1000000007 (109 + 7) in the only line.
|
standard output
| |
PASSED
|
30d18817821a81e438acf5a855ff1a27
|
train_001.jsonl
|
1467822900
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l, r]) = r - l + 1 to be the number of integer points in the segment [l, r] with l ≤ r (say that ). You are given two integers n and k and n closed intervals [li, ri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109 + 7).Mike can't solve this problem so he needs your help. You will help him, won't you?
|
256 megabytes
|
// package cf.contest689.e;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
// Trick CF: public
class Scanner {
private java.io.BufferedReader bufferedReader;
private java.util.StringTokenizer stringTokenizer;
public Scanner(java.io.InputStream inputStream) {
bufferedReader = new java.io.BufferedReader(
new java.io.InputStreamReader(inputStream));
}
public String next() {
for (; null == stringTokenizer || !stringTokenizer.hasMoreTokens();) {
try {
stringTokenizer = new java.util.StringTokenizer(
bufferedReader.readLine());
}
catch(java.io.IOException ioException) {
ioException.printStackTrace();
}
}
return stringTokenizer.nextToken();
}
public String nextLine() {
String result;
stringTokenizer = null;
try {
result = bufferedReader.readLine();
}
catch(java.io.IOException ioException) {
ioException.printStackTrace();
result = "";
}
return result;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public void close() {
try {
bufferedReader.close();
}
catch (java.io.IOException e) {
e.printStackTrace();
}
}
}
class Task {
private Scanner stdin;
private PrintWriter stdout;
public Task() {
stdin = new Scanner(System.in);
stdout = new PrintWriter(System.out);
}
public void close() {
stdin.close();
stdout.flush();
stdout.close();
}
public void run() {
int n = stdin.nextInt();
int k = stdin.nextInt();
LongSegment[] ls = new LongSegment[n];
for (int i = 0; i < n; ++i) {
ls[i] = new LongSegment();
ls[i].left = stdin.nextInt();
ls[i].right = stdin.nextInt() + 1;
}
int[] nodes = new int[n << 1];
for (int i = 0; i < n; ++i) {
nodes[i << 1] = ls[i].left;
nodes[i << 1 | 1] = ls[i].right;
}
Arrays.sort(nodes);
ArrayList<ShortSegment> ss = new ArrayList<>();
int flag = 1;
for (int i = 1; i < (n << 1); ++i) {
if (nodes[i] == nodes[i - 1]) {
continue;
}
ss.add(new ShortSegment(nodes[i - 1], nodes[i], flag, flag + 1));
++flag;
}
int[] cnt = new int[flag + 1];
{ // left
Arrays.sort(ls, new OrderByLeft());
int j = 0;
for (int i = 0; i < n; ++i) {
for (; j < ss.size() && ss.get(j).left < ls[i].left; )
++j;
if (ss.get(j).left == ls[i].left) {
++cnt[ss.get(j).flagL];
}
}
Arrays.sort(ls, new OrderByRight());
}
{ // right
int j = 0;
for (int i = 0; i < n; ++i) {
for (; j < ss.size() && ss.get(j).right < ls[i].right; )
++j;
if (ss.get(j).right == ls[i].right) {
--cnt[ss.get(j).flagR];
}
}
}
for (int i = 1; i <= flag; ++i) {
cnt[i] += cnt[i - 1];
}
long ans = 0;
final int MOD = 1_000_000_000 + 7;
Pascal pascal = new Pascal(n, MOD);
for (ShortSegment s : ss) {
if (cnt[s.flagL] >= k) {
ans = (ans + pascal.c(cnt[s.flagL], k) * s.length()) % MOD;
}
}
stdout.println(ans);
}
}
class Pascal {
long[] fac;
long[] invFac;
final int MOD;
Pascal(int max, final int MOD) {
fac = new long[max + 1];
invFac = new long[max + 1];
this.MOD = MOD;
fac[0] = 1;
for (int i = 1; i <= max; ++i) {
fac[i] = fac[i - 1] * i % MOD;
}
invFac[0] = 1;
invFac[1] = 1;
for (int i = 2; i <= max; ++i) {
// M % i = - (M / i) * i
// inv[i] = - (M / i) inv[M % i]
invFac[i] = (MOD - MOD / i) * invFac[MOD % i] % MOD;
}
for (int i = 1; i <= max; ++i) {
invFac[i] = invFac[i] * invFac[i - 1] % MOD;
assert fac[i] * invFac[i] % MOD == 1;
}
}
long c(int n, int k) {
return fac[n] * (invFac[n - k] * invFac[k] % MOD) % MOD;
}
}
class LongSegment {
int left;
int right;
}
class OrderByLeft implements Comparator<LongSegment> {
@Override
public int compare(LongSegment o1, LongSegment o2) {
int result;
if (o1.left > o2.left) {
result = 1;
}
else if (o1.left < o2.left) {
result = -1;
}
else {
result = 0;
}
return result;
}
}
class OrderByRight implements Comparator<LongSegment> {
@Override
public int compare(LongSegment o1, LongSegment o2) {
int result;
if (o1.right > o2.right) {
result = 1;
}
else if (o1.right < o2.right) {
result = -1;
}
else {
result = 0;
}
return result;
}
}
class ShortSegment {
int left;
int right;
int flagL;
int flagR;
public ShortSegment(int left, int right, int flagL, int flagR) {
this.left = left;
this.right = right;
this.flagL = flagL;
this.flagR = flagR;
}
int length() {
return right - left;
}
}
public class Main {
public static void main(String[] args) {
Task task = new Task();
task.run();
task.close();
}
}
|
Java
|
["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"]
|
3 seconds
|
["5", "3", "6"]
|
NoteIn the first example: ;;.So the answer is 2 + 1 + 2 = 5.
|
Java 8
|
standard input
|
[
"dp",
"geometry",
"combinatorics",
"implementation",
"data structures"
] |
900c85e25d457eb8092624b1d42be2a2
|
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109), describing i-th segment bounds.
| 2,000 |
Print one integer number — the answer to Mike's problem modulo 1000000007 (109 + 7) in the only line.
|
standard output
| |
PASSED
|
adbd55813afbcf5b115dfdce215ef20e
|
train_001.jsonl
|
1467822900
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l, r]) = r - l + 1 to be the number of integer points in the segment [l, r] with l ≤ r (say that ). You are given two integers n and k and n closed intervals [li, ri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109 + 7).Mike can't solve this problem so he needs your help. You will help him, won't you?
|
256 megabytes
|
// practice with rainboy
import java.io.*;
import java.util.*;
public class CF689E extends PrintWriter {
CF689E() { super(System.out); }
static class Scanner {
Scanner(InputStream in) { this.in = in; } InputStream in;
int k, l; byte[] bb = new byte[1 << 15];
byte getc() {
if (k >= l) {
k = 0;
try { l = in.read(bb); } catch (IOException e) { l = 0; }
if (l <= 0) return -1;
}
return bb[k++];
}
int nextInt() {
byte c = 0; while (c <= 32) c = getc();
boolean minus = c == '-'; if (minus) c = getc();
int a = 0;
while (c > 32) { a = a * 10 + c - '0'; c = getc(); }
return minus ? -a : a;
}
}
Scanner sc = new Scanner(System.in);
public static void main(String[] $) {
CF689E o = new CF689E(); o.main(); o.flush();
}
static final int MD = 1000000007;
int d_, x_, y_;
void gcd_(int a, int b) {
if (b == 0) {
d_ = a;
x_ = 1; y_ = 0;
} else {
gcd_(b, a % b);
int tmp = x_ - a / b * y_; x_ = y_; y_ = tmp;
}
}
int inv(int a, int b) {
gcd_(a, b);
if (x_ < 0)
x_ += MD;
return x_;
}
int[] ff, gg;
void init(int n) {
ff = new int[n + 1];
gg = new int[n + 1];
for (int i = 0, f = 1; i <= n; i++) {
gg[i] = inv(ff[i] = f, MD);
f = (int) ((long) f * (i + 1) % MD);
}
}
long choose(int n, int k) {
return n < k ? 0 : (long) ff[n] * gg[k] % MD * gg[n - k] % MD;
}
void main() {
int n = sc.nextInt();
int k = sc.nextInt();
int[] aa = new int[n * 2];
for (int i = 0; i < n; i++) {
int l = sc.nextInt();
int r = sc.nextInt();
aa[i << 1] = l * 2;
aa[i << 1 | 1] = (r + 1) * 2 + 1;
}
Random rand = new Random();
for (int i = 0; i < n * 2; i++) {
int j = rand.nextInt(i + 1);
int tmp = aa[i]; aa[i] = aa[j]; aa[j] = tmp;
}
Arrays.sort(aa);
init(n);
long ans = 0;
int x_ = Integer.MIN_VALUE, y_ = 0;
for (int i = 0; i < n * 2; ) {
int a = aa[i], x, y;
if (a % 2 == 0) {
x = a / 2;
y = 1;
} else {
x = (a - 1) / 2;
y = -1;
}
if (x_ != Integer.MIN_VALUE)
ans = (ans + (x - x_) * choose(y_, k)) % MD;
x_ = x;
while (i < n * 2 && aa[i] == a) {
y_ += y;
i++;
}
}
println(ans);
}
}
|
Java
|
["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"]
|
3 seconds
|
["5", "3", "6"]
|
NoteIn the first example: ;;.So the answer is 2 + 1 + 2 = 5.
|
Java 8
|
standard input
|
[
"dp",
"geometry",
"combinatorics",
"implementation",
"data structures"
] |
900c85e25d457eb8092624b1d42be2a2
|
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109), describing i-th segment bounds.
| 2,000 |
Print one integer number — the answer to Mike's problem modulo 1000000007 (109 + 7) in the only line.
|
standard output
| |
PASSED
|
94f9bce601b86b211312263e38b6066e
|
train_001.jsonl
|
1467822900
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l, r]) = r - l + 1 to be the number of integer points in the segment [l, r] with l ≤ r (say that ). You are given two integers n and k and n closed intervals [li, ri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109 + 7).Mike can't solve this problem so he needs your help. You will help him, won't you?
|
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.LinkedList;
import java.util.Map.Entry;
import java.util.Arrays;
import java.util.Queue;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class E {
static long mod=(int)(1e9+7);
public static void main(String[] args)throws Throwable {
MyScanner sc=new MyScanner();
PrintWriter pw=new PrintWriter(System.out,true);
int n=sc.nextInt(),k=sc.nextInt();
TreeMap<Integer, Integer> map=new TreeMap<Integer, Integer>();
long [] fac=new long [n+1];
fac[0]=1L;
for(int i=1;i<=n;i++)
fac[i]=(fac[i-1]*i)%mod;
while(n-->0){
int l=sc.nextInt(),r=sc.nextInt()+1;
if(map.containsKey(l))
map.put(l, map.get(l)+1);
else
map.put(l, 1);
if(map.containsKey(r))
map.put(r, map.get(r)-1);
else
map.put(r, -1);
}
long kf=(inv(fac[k])+mod)%mod;
long ans=0;
int c=0,last=0;
boolean f=true;
for(Entry<Integer, Integer> e : map.entrySet()){
if(f){
c=e.getValue();
last=e.getKey();
f=false;
continue;
}
if(c<k){
c+=e.getValue();
last=e.getKey();
continue;
}
int dif=e.getKey()-last;
long nkf=(inv((fac[c-k])%mod)+mod)%mod;
ans=(ans+((dif*fac[c])%mod)*((kf*nkf)%mod))%mod;
c+=e.getValue();
last=e.getKey();
}
pw.println(ans);
pw.flush();
pw.close();
}
static long inv(long x)
{
long r,y;
for(r=1,y=mod-2;y!=0;x=x*x%mod,y>>=1)
{
if((y&1)==1)
r=r*x%mod;
}
return r;
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine(){
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
|
Java
|
["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"]
|
3 seconds
|
["5", "3", "6"]
|
NoteIn the first example: ;;.So the answer is 2 + 1 + 2 = 5.
|
Java 8
|
standard input
|
[
"dp",
"geometry",
"combinatorics",
"implementation",
"data structures"
] |
900c85e25d457eb8092624b1d42be2a2
|
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109), describing i-th segment bounds.
| 2,000 |
Print one integer number — the answer to Mike's problem modulo 1000000007 (109 + 7) in the only line.
|
standard output
| |
PASSED
|
e312250cd3b1f458ea3ba89033d5ce90
|
train_001.jsonl
|
1467822900
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l, r]) = r - l + 1 to be the number of integer points in the segment [l, r] with l ≤ r (say that ). You are given two integers n and k and n closed intervals [li, ri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109 + 7).Mike can't solve this problem so he needs your help. You will help him, won't you?
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.math.BigInteger;
import java.util.Arrays;
public class E {
private static class Event implements Comparable<Event> {
public int idx;
public int type;
public int location;
public Event(int idx, int type, int location) {
this.idx = idx;
this.type = type;
this.location = location;
}
public int compareTo(Event o) {
if (location != o.location)
return location < o.location ? -1 : 1;
if (type != o.type)
return type < o.type ? -1 : 1;
if (idx != o.idx)
return idx < o.idx ? -1 : 1;
return 0;
}
public String toString() {
return "<" + idx + "," + type + "," + location + ">";
}
}
private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
private static PrintStream out = System.out;
private static final long mod = 1000000000 + 7;
private static final BigInteger MOD = new BigInteger("" + mod);
private static int n;
private static int k;
private static int[] xs;
private static int[] ys;
private static Event[] es;
private static BigInteger[] FACTORIAL;
private static BigInteger[] FACTORIAL_INVERSE;
private static long choose(int a, int b) {
if (FACTORIAL == null) {
long[] factorial = new long[n + 1];
factorial[0] = 1;
for (int i = 1; i <= n; ++i)
factorial[i] = (i*factorial[i - 1])%mod;
FACTORIAL = new BigInteger[n + 1];
FACTORIAL_INVERSE = new BigInteger[n + 1];
for (int i = 0; i <= n; ++i) {
FACTORIAL[i] = new BigInteger("" + factorial[i]);
FACTORIAL_INVERSE[i] = FACTORIAL[i].modInverse(MOD);
}
}
BigInteger p = FACTORIAL[a];
BigInteger q = FACTORIAL_INVERSE[b];
BigInteger r = FACTORIAL_INVERSE[a - b];
return p.multiply(q).multiply(r).mod(MOD).longValue();
}
public static void main(String[] args) throws IOException {
// read input
String[] line = in.readLine().split(" ");
n = Integer.parseInt(line[0]);
k = Integer.parseInt(line[1]);
xs = new int[n];
ys = new int[n];
es = new Event[2*n];
for (int i = 0; i < n; ++i) {
line = in.readLine().split(" ");
xs[i] = Integer.parseInt(line[0]);
ys[i] = Integer.parseInt(line[1]);
es[i] = new Event(i, -1, xs[i]);
es[i + n] = new Event(i, +1, ys[i]);
}
Arrays.sort(es);
// go through and compute solution
long ans = 0;
int last = -Integer.MAX_VALUE;
int cnt = 0;
for (int i = 0; i < es.length; ++i) {
int cntL = 0;
int cntR = 0;
int j = i;
while (j < es.length && es[j].location == es[i].location) {
if (es[j].type == -1)
++cntL;
else
++cntR;
++j;
}
i = j - 1;
if (cnt >= k && es[i].location - last - 1 >= 0)
ans = (ans + (es[i].location - last - 1)*choose(cnt, k))%mod;
last = es[i].location;
cnt += cntL;
if (cnt >= k)
ans = (ans + choose(cnt, k))%mod;
cnt -= cntR;
}
out.println(ans);
}
}
|
Java
|
["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"]
|
3 seconds
|
["5", "3", "6"]
|
NoteIn the first example: ;;.So the answer is 2 + 1 + 2 = 5.
|
Java 8
|
standard input
|
[
"dp",
"geometry",
"combinatorics",
"implementation",
"data structures"
] |
900c85e25d457eb8092624b1d42be2a2
|
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109), describing i-th segment bounds.
| 2,000 |
Print one integer number — the answer to Mike's problem modulo 1000000007 (109 + 7) in the only line.
|
standard output
| |
PASSED
|
24b6a55b6e280500ae0c6d19c1c8eaa1
|
train_001.jsonl
|
1467822900
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l, r]) = r - l + 1 to be the number of integer points in the segment [l, r] with l ≤ r (say that ). You are given two integers n and k and n closed intervals [li, ri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109 + 7).Mike can't solve this problem so he needs your help. You will help him, won't you?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class e {
static class Point implements Comparable<Point>{
int x;
int type;
Point(int _x, int _type){
x = _x;
type = _type;
}
@Override
public int compareTo(Point o) {
if (o.x == this.x){
return this.type - o.type;
}
else{
return this.x - o.x;
}
}
}
static long mod = 1000000007;
static long power(long x, int deg){
if (deg == 1){
return x % mod;
}
else{
long ans = power(x, deg / 2);
ans = (1l * ans * ans) % mod;
if (deg % 2 == 1){
ans = (1l * ans * x) % mod;
}
return ans % mod;
}
}
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int k = in.nextInt();
Point points[] = new Point[2 * n];
for (int i = 0; i < n; i++) {
points[2 * i] = new Point(in.nextInt(), 1);
points[2 * i + 1] = new Point(in.nextInt() + 1, -1);
}
Arrays.sort(points);
int cnt[] = new int[n + 1];
int count = 0;
for (int i = 0; i < 2 * n; i++) {
if (i != 0 && points[i - 1].x != points[i].x){
cnt[count] += points[i].x - points[i - 1].x;
}
if (points[i].type == -1){
count--;
}
else{
count++;
}
}
long fact[] = new long[n + 1];
fact[0] = 1;
fact[1] = 1;
for (int i = 2; i <= n; i++) {
fact[i] = (1l * fact[i - 1] * i) % mod;
}
long answer = 0;
for (int i = k; i < n + 1; i++) {
long cur = (1l * cnt[i] * fact[i]) % mod;
long cur2 = (1l * power(fact[k], (int)(mod - 2)) * 1l * power(fact[i - k], (int)(mod - 2))) % mod;
answer += (1l * cur * cur2);
answer %= mod;
}
out.println(answer);
out.close();
}
}
|
Java
|
["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"]
|
3 seconds
|
["5", "3", "6"]
|
NoteIn the first example: ;;.So the answer is 2 + 1 + 2 = 5.
|
Java 8
|
standard input
|
[
"dp",
"geometry",
"combinatorics",
"implementation",
"data structures"
] |
900c85e25d457eb8092624b1d42be2a2
|
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109), describing i-th segment bounds.
| 2,000 |
Print one integer number — the answer to Mike's problem modulo 1000000007 (109 + 7) in the only line.
|
standard output
| |
PASSED
|
bb8a53ccc470baab964b939e04c69576
|
train_001.jsonl
|
1467822900
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l, r]) = r - l + 1 to be the number of integer points in the segment [l, r] with l ≤ r (say that ). You are given two integers n and k and n closed intervals [li, ri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109 + 7).Mike can't solve this problem so he needs your help. You will help him, won't you?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Template implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws FileNotFoundException {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} catch (Exception e) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
try {
tok = new StringTokenizer(in.readLine(), " :");
} catch (Exception e) {
return null;
}
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
int[] readIntArray(int size) throws IOException {
int[] res = new int[size];
for (int i = 0; i < size; i++) {
res[i] = readInt();
}
return res;
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
<T> List<T>[] createGraphList(int size) {
List<T>[] list = new List[size];
for (int i = 0; i < size; i++) {
list[i] = new ArrayList<>();
}
return list;
}
public static void main(String[] args) {
new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start();
}
long timeBegin, timeEnd;
void time() {
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
long memoryTotal, memoryFree;
void memory() {
memoryFree = Runtime.getRuntime().freeMemory();
System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10)
+ " KB");
}
public void run() {
try {
timeBegin = System.currentTimeMillis();
memoryTotal = Runtime.getRuntime().freeMemory();
init();
solve();
out.close();
if (System.getProperty("ONLINE_JUDGE") == null) {
time();
memory();
}
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
int[] dec(int[] a) {
for (int i = 0; i < a.length; i++) {
a[i]--;
}
return a;
}
int mod = (int) 1e9 + 7;
int[] fact = new int[200005];
int fact(int n) {
if (n == 0) return 1;
if (fact[n] == 0) {
fact[n] = (int) ((long) fact(n - 1) * n % mod);
}
return fact[n];
}
int revFact(int n) {
return binpow(fact(n), mod - 2);
}
int binpow(int a, int pow) {
if (pow == 0) return 1;
if (pow % 2 == 0) {
long x = binpow(a, pow / 2);
return (int) (x * x % mod);
} else {
long x = binpow(a, pow - 1);
return (int) (x * a % mod);
}
}
int C(int n, int k) {
long c = fact(n);
c *= revFact(k);
c %= mod;
c *= revFact(n - k);
c %= mod;
return (int) c;
}
int get(IntIntHashMap map, int key) {
return map.get(key);
}
void solve() throws IOException {
int n = readInt();
int k = readInt();
IntIntHashMap open = new IntIntHashMap();
IntIntHashMap close = new IntIntHashMap();
TreeSet<Integer> uniq = new TreeSet<>();
for (int i = 0; i < n; i++) {
int l = readInt();
int r = readInt() + 1;
open.put(l, get(open, l) + 1);
close.put(r, get(close, r) + 1);
uniq.add(l);
uniq.add(r);
}
int cur = 0;
long answer = 0;
int prevX = 0;
boolean first = true;
for (int x : uniq) {
if (first) {
first = false;
prevX = x;
} else {
int cnt = x - prevX;
if (cur >= k) {
answer += (long)cnt * C(cur, k);
answer %= mod;
}
prevX = x;
}
cur += get(open, x);
cur -= get(close, x);
}
out.println(answer);
}
static final class IntIntHashMap {
final static class Entry {
final int key;
int value;
Entry next;
Entry(int key, int value, Entry next) {
this.key = key;
this.value = value;
this.next = next;
}
}
private Entry[] table;
private int capacity;
private int threshold;
private int size;
public IntIntHashMap() {
this(16);
}
@SuppressWarnings("unchecked")
public IntIntHashMap(int capacity) {
this.capacity = capacity;
this.threshold = capacity * 4 / 3;
this.table = new Entry[capacity];
}
int hash(int key) {
return Math.abs(key);
}
public boolean containsKey(int key) {
final int index = hash(key) % capacity;
for (Entry entry = table[index]; entry != null; entry = entry.next) {
if (entry.key == key) {
return true;
}
}
return false;
}
public int get(int key) {
final int index = hash(key) % capacity;
for (Entry entry = table[index]; entry != null; entry = entry.next) {
if (entry.key == key) {
return entry.value;
}
}
return 0;
}
public int put(int key, int value) {
final int index = hash(key) % capacity;
final Entry entryOriginal = table[index];
for (Entry entry = entryOriginal; entry != null; entry = entry.next) {
if (entry.key == key) {
int oldValue = entry.value;
entry.value = value;
return oldValue;
}
}
table[index] = new Entry(key, value, entryOriginal);
size++;
if (size > threshold) {
setCapacity(2 * capacity);
}
return 0;
}
public int remove(int key) {
int index = hash(key) % capacity;
Entry previous = null;
Entry entry = table[index];
while (entry != null) {
Entry next = entry.next;
if (entry.key == key) {
if (previous == null) {
table[index] = next;
} else {
previous.next = next;
}
size--;
return entry.value;
}
previous = entry;
entry = next;
}
return 0;
}
public void clear() {
size = 0;
Arrays.fill(table, null);
}
public int size() {
return size;
}
public void setCapacity(int newCapacity) {
@SuppressWarnings("unchecked")
Entry[] newTable = new Entry[newCapacity];
int length = table.length;
for (int i = 0; i < length; i++) {
Entry entry = table[i];
while (entry != null) {
int key = entry.key;
int index = hash(key) % newCapacity;
Entry originalNext = entry.next;
entry.next = newTable[index];
newTable[index] = entry;
entry = originalNext;
}
}
table = newTable;
capacity = newCapacity;
threshold = newCapacity * 4 / 3;
}
/**
* Target load: 0,6
*/
public void reserveRoom(int entryCount) {
setCapacity(entryCount * 5 / 3);
}
}
static final class LongIntHashMap {
final static class Entry {
final long key;
int value;
Entry next;
Entry(long key, int value, Entry next) {
this.key = key;
this.value = value;
this.next = next;
}
}
private Entry[] table;
private int capacity;
private int threshold;
private int size;
public LongIntHashMap() {
this(16);
}
@SuppressWarnings("unchecked")
public LongIntHashMap(int capacity) {
this.capacity = capacity;
this.threshold = capacity * 4 / 3;
this.table = new Entry[capacity];
}
public boolean containsKey(long key) {
final int index = ((((int) (key >>> 32)) ^ ((int) (key))) & 0x7fffffff) % capacity;
for (Entry entry = table[index]; entry != null; entry = entry.next) {
if (entry.key == key) {
return true;
}
}
return false;
}
public int get(long key) {
final int index = ((((int) (key >>> 32)) ^ ((int) (key))) & 0x7fffffff) % capacity;
for (Entry entry = table[index]; entry != null; entry = entry.next) {
if (entry.key == key) {
return entry.value;
}
}
return 0;
}
public int put(long key, int value) {
final int index = ((((int) (key >>> 32)) ^ ((int) (key))) & 0x7fffffff) % capacity;
final Entry entryOriginal = table[index];
for (Entry entry = entryOriginal; entry != null; entry = entry.next) {
if (entry.key == key) {
int oldValue = entry.value;
entry.value = value;
return oldValue;
}
}
table[index] = new Entry(key, value, entryOriginal);
size++;
if (size > threshold) {
setCapacity(2 * capacity);
}
return 0;
}
public int remove(long key) {
int index = ((((int) (key >>> 32)) ^ ((int) (key))) & 0x7fffffff) % capacity;
Entry previous = null;
Entry entry = table[index];
while (entry != null) {
Entry next = entry.next;
if (entry.key == key) {
if (previous == null) {
table[index] = next;
} else {
previous.next = next;
}
size--;
return entry.value;
}
previous = entry;
entry = next;
}
return 0;
}
long[] getKeys() {
long[] arr = new long[size()];
int index = 0;
for (int i = 0; i < table.length; i++) {
Entry e = table[i];
while (e != null) {
arr[index++] = e.key;
e = e.next;
}
}
return arr;
}
public void clear() {
size = 0;
Arrays.fill(table, null);
}
public int size() {
return size;
}
public void setCapacity(int newCapacity) {
@SuppressWarnings("unchecked")
Entry[] newTable = new Entry[newCapacity];
int length = table.length;
for (int i = 0; i < length; i++) {
Entry entry = table[i];
while (entry != null) {
long key = entry.key;
int index = ((((int) (key >>> 32)) ^ ((int) (key))) & 0x7fffffff) % newCapacity;
Entry originalNext = entry.next;
entry.next = newTable[index];
newTable[index] = entry;
entry = originalNext;
}
}
table = newTable;
capacity = newCapacity;
threshold = newCapacity * 4 / 3;
}
/**
* Target load: 0,6
*/
public void reserveRoom(int entryCount) {
setCapacity(entryCount * 5 / 3);
}
}
}
|
Java
|
["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"]
|
3 seconds
|
["5", "3", "6"]
|
NoteIn the first example: ;;.So the answer is 2 + 1 + 2 = 5.
|
Java 8
|
standard input
|
[
"dp",
"geometry",
"combinatorics",
"implementation",
"data structures"
] |
900c85e25d457eb8092624b1d42be2a2
|
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109), describing i-th segment bounds.
| 2,000 |
Print one integer number — the answer to Mike's problem modulo 1000000007 (109 + 7) in the only line.
|
standard output
| |
PASSED
|
d1d357b04572e475a62f5e7eaf5c6dd9
|
train_001.jsonl
|
1467822900
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l, r]) = r - l + 1 to be the number of integer points in the segment [l, r] with l ≤ r (say that ). You are given two integers n and k and n closed intervals [li, ri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109 + 7).Mike can't solve this problem so he needs your help. You will help him, won't you?
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Template implements Runnable {
BufferedReader in;
PrintWriter out;
StringTokenizer tok = new StringTokenizer("");
void init() throws FileNotFoundException {
try {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
} catch (Exception e) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
}
}
String readString() throws IOException {
while (!tok.hasMoreTokens()) {
try {
tok = new StringTokenizer(in.readLine(), " :");
} catch (Exception e) {
return null;
}
}
return tok.nextToken();
}
int readInt() throws IOException {
return Integer.parseInt(readString());
}
int[] readIntArray(int size) throws IOException {
int[] res = new int[size];
for (int i = 0; i < size; i++) {
res[i] = readInt();
}
return res;
}
long readLong() throws IOException {
return Long.parseLong(readString());
}
double readDouble() throws IOException {
return Double.parseDouble(readString());
}
<T> List<T>[] createGraphList(int size) {
List<T>[] list = new List[size];
for (int i = 0; i < size; i++) {
list[i] = new ArrayList<>();
}
return list;
}
public static void main(String[] args) {
new Thread(null, new Template(), "", 1l * 200 * 1024 * 1024).start();
}
long timeBegin, timeEnd;
void time() {
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
long memoryTotal, memoryFree;
void memory() {
memoryFree = Runtime.getRuntime().freeMemory();
System.err.println("Memory = " + ((memoryTotal - memoryFree) >> 10)
+ " KB");
}
public void run() {
try {
timeBegin = System.currentTimeMillis();
memoryTotal = Runtime.getRuntime().freeMemory();
init();
solve();
out.close();
if (System.getProperty("ONLINE_JUDGE") == null) {
time();
memory();
}
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
int[] dec(int[] a) {
for (int i = 0; i < a.length; i++) {
a[i]--;
}
return a;
}
int mod = (int) 1e9 + 7;
int[] fact = new int[200005];
int fact(int n) {
if (n == 0) return 1;
if (fact[n] == 0) {
fact[n] = (int) ((long) fact(n - 1) * n % mod);
}
return fact[n];
}
int revFact(int n) {
return binpow(fact(n), mod - 2);
}
int binpow(int a, int pow) {
if (pow == 0) return 1;
if (pow % 2 == 0) {
long x = binpow(a, pow / 2);
return (int) (x * x % mod);
} else {
long x = binpow(a, pow - 1);
return (int) (x * a % mod);
}
}
int C(int n, int k) {
long c = fact(n);
c *= revFact(k);
c %= mod;
c *= revFact(n - k);
c %= mod;
return (int) c;
}
int get(HashMap<Integer, Integer> map, int key) {
Integer val = map.get(key);
return val == null ? 0 : val;
}
void solve() throws IOException {
int n = readInt();
int k = readInt();
HashMap<Integer, Integer> open = new HashMap<>();
HashMap<Integer, Integer> close = new HashMap<>();
TreeSet<Integer> uniq = new TreeSet<>();
for (int i = 0; i < n; i++) {
int l = readInt();
int r = readInt() + 1;
open.put(l, get(open, l) + 1);
close.put(r, get(close, r) + 1);
uniq.add(l);
uniq.add(r);
}
int cur = 0;
long answer = 0;
int prevX = 0;
boolean first = true;
for (int x : uniq) {
if (first) {
first = false;
prevX = x;
} else {
int cnt = x - prevX;
if (cur >= k) {
answer += (long)cnt * C(cur, k);
answer %= mod;
}
prevX = x;
}
cur += get(open, x);
cur -= get(close, x);
}
out.println(answer);
}
static final class LongIntHashMap {
final static class Entry {
final long key;
int value;
Entry next;
Entry(long key, int value, Entry next) {
this.key = key;
this.value = value;
this.next = next;
}
}
private Entry[] table;
private int capacity;
private int threshold;
private int size;
public LongIntHashMap() {
this(16);
}
@SuppressWarnings("unchecked")
public LongIntHashMap(int capacity) {
this.capacity = capacity;
this.threshold = capacity * 4 / 3;
this.table = new Entry[capacity];
}
public boolean containsKey(long key) {
final int index = ((((int) (key >>> 32)) ^ ((int) (key))) & 0x7fffffff) % capacity;
for (Entry entry = table[index]; entry != null; entry = entry.next) {
if (entry.key == key) {
return true;
}
}
return false;
}
public int get(long key) {
final int index = ((((int) (key >>> 32)) ^ ((int) (key))) & 0x7fffffff) % capacity;
for (Entry entry = table[index]; entry != null; entry = entry.next) {
if (entry.key == key) {
return entry.value;
}
}
return 0;
}
public int put(long key, int value) {
final int index = ((((int) (key >>> 32)) ^ ((int) (key))) & 0x7fffffff) % capacity;
final Entry entryOriginal = table[index];
for (Entry entry = entryOriginal; entry != null; entry = entry.next) {
if (entry.key == key) {
int oldValue = entry.value;
entry.value = value;
return oldValue;
}
}
table[index] = new Entry(key, value, entryOriginal);
size++;
if (size > threshold) {
setCapacity(2 * capacity);
}
return 0;
}
public int remove(long key) {
int index = ((((int) (key >>> 32)) ^ ((int) (key))) & 0x7fffffff) % capacity;
Entry previous = null;
Entry entry = table[index];
while (entry != null) {
Entry next = entry.next;
if (entry.key == key) {
if (previous == null) {
table[index] = next;
} else {
previous.next = next;
}
size--;
return entry.value;
}
previous = entry;
entry = next;
}
return 0;
}
long[] getKeys() {
long[] arr = new long[size()];
int index = 0;
for (int i = 0; i < table.length; i++) {
Entry e = table[i];
while (e != null) {
arr[index++] = e.key;
e = e.next;
}
}
return arr;
}
public void clear() {
size = 0;
Arrays.fill(table, null);
}
public int size() {
return size;
}
public void setCapacity(int newCapacity) {
@SuppressWarnings("unchecked")
Entry[] newTable = new Entry[newCapacity];
int length = table.length;
for (int i = 0; i < length; i++) {
Entry entry = table[i];
while (entry != null) {
long key = entry.key;
int index = ((((int) (key >>> 32)) ^ ((int) (key))) & 0x7fffffff) % newCapacity;
Entry originalNext = entry.next;
entry.next = newTable[index];
newTable[index] = entry;
entry = originalNext;
}
}
table = newTable;
capacity = newCapacity;
threshold = newCapacity * 4 / 3;
}
/**
* Target load: 0,6
*/
public void reserveRoom(int entryCount) {
setCapacity(entryCount * 5 / 3);
}
}
}
|
Java
|
["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"]
|
3 seconds
|
["5", "3", "6"]
|
NoteIn the first example: ;;.So the answer is 2 + 1 + 2 = 5.
|
Java 8
|
standard input
|
[
"dp",
"geometry",
"combinatorics",
"implementation",
"data structures"
] |
900c85e25d457eb8092624b1d42be2a2
|
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109), describing i-th segment bounds.
| 2,000 |
Print one integer number — the answer to Mike's problem modulo 1000000007 (109 + 7) in the only line.
|
standard output
| |
PASSED
|
69d4e85b5cd97d7e53caa0f1c809cc9d
|
train_001.jsonl
|
1467822900
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l, r]) = r - l + 1 to be the number of integer points in the segment [l, r] with l ≤ r (say that ). You are given two integers n and k and n closed intervals [li, ri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109 + 7).Mike can't solve this problem so he needs your help. You will help him, won't you?
|
256 megabytes
|
import com.sun.org.apache.xml.internal.utils.StringComparable;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
public class Main {
public static void main(String[] args) {
// Test.testing();
ConsoleIO io = new ConsoleIO();
new Main(io).solve();
io.close();
}
ConsoleIO io;
Main(ConsoleIO io) {
this.io = io;
}
ArrayList<ArrayList<Integer>> gr;
boolean[] visit;
class Edge {
public Edge(int u, int v, int c) {
this.u = u;
this.v = v;
this.c = c;
}
public int u;
public int v;
public int c;
}
long MOD = 1_000_000_007;
int N, M, K;
double[][] map;
public void solve() {
int[] l = io.readIntArray();
N = l[0];
K = l[1];
Integer[] all = new Integer[N*2];
int k = 0;
HashMap<Integer,Integer> count = new HashMap<Integer,Integer>();
HashMap<Integer,Integer> sum = new HashMap<Integer,Integer>();
for(int i = 0;i<N;i++){
l = io.readIntArray();
int s = l[0], f = l[1];
if(!count.containsKey(s)){
count.put(s, 1);
sum.put(s, 1);
all[k++] = s;
}else{
count.put(s, count.get(s)+1);
sum.put(s, sum.get(s)+1);
}
if(!count.containsKey(f)){
count.put(f, 0);
sum.put(f, -1);
all[k++] = f;
}else{
//count.put(f, count.get(f)+1);
sum.put(f, sum.get(f)-1);
}
}
Arrays.sort(all, 0, k);
fact = new long[N+1];
fact[0] = 1;
for(int i = 1;i<=N;i++){
fact[i] = (fact[i-1]*i)%MOD;
}
int tot = 0;
int prev = Integer.MIN_VALUE;
long res = 0;
for(int i = 0;i<k;i++) {
int s = sum.get(all[i]);
int c = count.get(all[i]) + tot;
if (c >= K) {
res += choose(c, K);
}
if (i > 0 && tot >= K) {
res += (all[i] - all[i - 1] - 1) * (choose(tot, K)) % MOD;
}
tot += s;
}
io.writeLine(res%MOD +"");
}
long[] fact;
long choose(int n, int k){
return div(fact[n], (fact[n-k]*fact[k])%MOD, MOD );
}
long div(long a, long b, long mod) {
return (a * pow(b, mod - 2, mod)) % mod;
}
long pow(long a, long p, long mod) {
long res = 1;
while (p > 0) {
if (p % 2 == 1) res = (res * a) % mod;
a = (a * a) % mod;
p /= 2;
}
return res;
}
long gcd(long a, long b) {
if (a < b) return gcd(b, a);
if (b == 0) return a;
return gcd(b, a % b);
}
}
class ConsoleIO {
BufferedReader br;
PrintWriter out;
public ConsoleIO(){br = new BufferedReader(new InputStreamReader(System.in));out = new PrintWriter(System.out);}
public void flush(){this.out.flush();}
public void close(){this.out.close();}
public void writeLine(String s) {this.out.println(s);}
public void writeInt(int a) {this.out.print(a);this.out.print(' ');}
public void writeWord(String s){
this.out.print(s);
}
public int read(char[] buf, int len){try {return br.read(buf,0,len);}catch (Exception ex){ return -1; }}
public String readLine() {try {return br.readLine();}catch (Exception ex){ return "";}}
public long readLong() {
return Long.parseLong(this.readLine());
}
public int readInt() {
return Integer.parseInt(this.readLine().trim());
}
public long[] readLongArray() {
String[]n=this.readLine().trim().split("\\s+");long[]r=new long[n.length];
for(int i=0;i<n.length;i++)r[i]=Long.parseLong(n[i]);
return r;
}
public int[] readIntArray() {
String[]n=this.readLine().trim().split("\\s+");int[]r=new int[n.length];
for(int i=0;i<n.length;i++)r[i]=Integer.parseInt(n[i]);
return r;
}
public int[] readIntArray(int n) {
int[] res = new int[n];
char[] all = this.readLine().toCharArray();
int cur = 0;boolean have = false;
int k = 0;
boolean neg = false;
for(int i = 0;i<all.length;i++){
if(all[i]>='0' && all[i]<='9'){
cur = cur*10+all[i]-'0';
have = true;
}else if(all[i]=='-') {
neg = true;
}
else if(have){
res[k++] = neg?-cur:cur;
cur = 0;
have = false;
neg = false;
}
}
if(have)res[k++] = neg?-cur:cur;
return res;
}
public void writeIntArray(int[] a) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < a.length; i++) {if (i > 0) sb.append(' ');sb.append(a[i]);}
this.writeLine(sb.toString());
}
}
class Pair {
public Pair(int a, int b) {this.a = a;this.b = b;}
public int a;
public int b;
}
class PairLL {
public PairLL(long a, long b) {this.a = a;this.b = b;}
public long a;
public long b;
}
|
Java
|
["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"]
|
3 seconds
|
["5", "3", "6"]
|
NoteIn the first example: ;;.So the answer is 2 + 1 + 2 = 5.
|
Java 8
|
standard input
|
[
"dp",
"geometry",
"combinatorics",
"implementation",
"data structures"
] |
900c85e25d457eb8092624b1d42be2a2
|
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109), describing i-th segment bounds.
| 2,000 |
Print one integer number — the answer to Mike's problem modulo 1000000007 (109 + 7) in the only line.
|
standard output
| |
PASSED
|
6b8134d5d98e7ea0ea8ae090875b2091
|
train_001.jsonl
|
1467822900
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l, r]) = r - l + 1 to be the number of integer points in the segment [l, r] with l ≤ r (say that ). You are given two integers n and k and n closed intervals [li, ri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109 + 7).Mike can't solve this problem so he needs your help. You will help him, won't you?
|
256 megabytes
|
// package codeforces.cf3xx.cf361.div2;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;
/**
* Created by hama_du on 2016/08/09.
*/
public class E {
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[][] lr = in.nextIntTable(n, 2);
for (int i = 0; i < n ; i++) {
lr[i][1]++;
}
int[] pos = new int[2*n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < 2 ; j++) {
pos[2*i+j] = lr[i][j];
}
}
shuffleAndSort(pos);
Map<Integer,Integer> map = new HashMap<>();
for (int i = 0; i < pos.length ; i++) {
if (i == 0 || (pos[i-1] != pos[i])) {
map.put(pos[i], map.size());
}
}
int nn = map.size();
long[] rmap = new long[nn];
for (int key : map.keySet()) {
rmap[map.get(key)] = key;
}
int[] imos = new int[nn+1];
for (int i = 0; i < n ; i++) {
imos[map.get(lr[i][0])]++;
imos[map.get(lr[i][1])]--;
}
for (int i = 1; i < nn ; i++) {
imos[i] += imos[i-1];
}
prec(200010);
long sum = 0;
for (int i = 0 ; i+1 < nn; i++) {
sum += comb(imos[i], k) * (rmap[i+1] - rmap[i]) % MOD;
sum %= MOD;
}
out.println(sum);
out.flush();
}
static final int MOD = 1000000007;
static long pow(long a, long x) {
long res = 1;
while (x > 0) {
if (x % 2 != 0) {
res = (res * a) % MOD;
}
a = (a * a) % MOD;
x /= 2;
}
return res;
}
static long inv(long a) {
return pow(a, MOD - 2) % MOD;
}
static long[] _fact;
static long[] _invfact;
static long comb(long ln, long lr) {
int n = (int)ln;
int r = (int)lr;
if (n < 0 || r < 0 || r > n) {
return 0;
}
if (r > n / 2) {
r = n - r;
}
return (((_fact[n] * _invfact[n - r]) % MOD) * _invfact[r]) % MOD;
}
static void prec(int n) {
_fact = new long[n + 1];
_invfact = new long[n + 1];
_fact[0] = 1;
_invfact[0] = 1;
for (int i = 1; i <= n; i++) {
_fact[i] = _fact[i - 1] * i % MOD;
_invfact[i] = inv(_fact[i]);
}
}
// against for quick-sort killer
static void shuffleAndSort(int[] a) {
int n = a.length;
for (int i = 0; i < n ; i++) {
int idx = (int)(Math.random() * i);
int tmp = a[idx];
a[idx] = a[i];
a[i] = tmp;
}
Arrays.sort(a);
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
private int[] nextInts(int n) {
int[] ret = new int[n];
for (int i = 0; i < n; i++) {
ret[i] = nextInt();
}
return ret;
}
private int[][] nextIntTable(int n, int m) {
int[][] ret = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
ret[i][j] = nextInt();
}
}
return ret;
}
private long[] nextLongs(int n) {
long[] ret = new long[n];
for (int i = 0; i < n; i++) {
ret[i] = nextLong();
}
return ret;
}
private long[][] nextLongTable(int n, int m) {
long[][] ret = new long[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
ret[i][j] = nextLong();
}
}
return ret;
}
private double[] nextDoubles(int n) {
double[] ret = new double[n];
for (int i = 0; i < n; i++) {
ret[i] = nextDouble();
}
return ret;
}
private int next() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public char nextChar() {
int c = next();
while (isSpaceChar(c))
c = next();
if ('a' <= c && c <= 'z') {
return (char) c;
}
if ('A' <= c && c <= 'Z') {
return (char) c;
}
throw new InputMismatchException();
}
public String nextToken() {
int c = next();
while (isSpaceChar(c))
c = next();
StringBuilder res = new StringBuilder();
do {
res.append((char) c);
c = next();
} while (!isSpaceChar(c));
return res.toString();
}
public int nextInt() {
int c = next();
while (isSpaceChar(c))
c = next();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = next();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c-'0';
c = next();
} while (!isSpaceChar(c));
return res*sgn;
}
public long nextLong() {
int c = next();
while (isSpaceChar(c))
c = next();
long sgn = 1;
if (c == '-') {
sgn = -1;
c = next();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c-'0';
c = next();
} while (!isSpaceChar(c));
return res*sgn;
}
public double nextDouble() {
return Double.valueOf(nextToken());
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
static void debug(Object... o) {
System.err.println(Arrays.deepToString(o));
}
}
|
Java
|
["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"]
|
3 seconds
|
["5", "3", "6"]
|
NoteIn the first example: ;;.So the answer is 2 + 1 + 2 = 5.
|
Java 8
|
standard input
|
[
"dp",
"geometry",
"combinatorics",
"implementation",
"data structures"
] |
900c85e25d457eb8092624b1d42be2a2
|
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109), describing i-th segment bounds.
| 2,000 |
Print one integer number — the answer to Mike's problem modulo 1000000007 (109 + 7) in the only line.
|
standard output
| |
PASSED
|
1375cc8ab1d3998923c28849724ad0a0
|
train_001.jsonl
|
1467822900
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l, r]) = r - l + 1 to be the number of integer points in the segment [l, r] with l ≤ r (say that ). You are given two integers n and k and n closed intervals [li, ri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109 + 7).Mike can't solve this problem so he needs your help. You will help him, won't you?
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.TreeSet;
public class E361 {
static int N;
static final long MOD = 1_000_000_007;
static long[] fact, modinv;
public static void main(String[] args) {
MyScanner scan = new MyScanner();
N = scan.nextInt(); int K = scan.nextInt();
gen();
long sum = 0;
int[] l = new int[N], r = new int[N];
TreeSet<Integer> compress = new TreeSet<>();
for(int i=0;i<N;i++){
l[i] = scan.nextInt(); r[i] = scan.nextInt();
compress.add(l[i]);compress.add(r[i]);
}
int idx =0;
HashMap<Integer, Integer> map = new HashMap<>(), rev = new HashMap<>();
for(int i : compress){
map.put(i, idx);
rev.put(idx++, i);
}
ST st = new ST(new int[2*idx]);
for(int i=0;i<N;i++) {
st.update(2*map.get(l[i]),2*map.get(r[i]), 1);
}
for(int i=0;i<2*idx-1;i++){
int temp = st.query(i, i);
if(i%2==1){
int b = rev.get((i+1)/2), a = rev.get((i-1)/2);
sum+=(nCk(temp, K)*(long)(b-a-1))%MOD;
sum%=MOD;
}else{
sum+=nCk(temp, K);
sum%=MOD;
}
}
System.out.println(sum);
}
private static long nCk(int n, int k){
if(n<k)return 0;
if(k==0 || k==n)return 1;
return (((fact[n]*modinv[k])%MOD)*modinv[n-k])%MOD;
}
private static void gen() {
fact = new long[N+1];
modinv = new long[N+1];
fact[0] = 1;
for(int i=1;i<=N;i++)fact[i] = (fact[i-1]*i)%MOD;
for(int i=1;i<=N;i++)modinv[i] = exp(fact[i], MOD-2);
}
private static long exp(long a, long b){
if(b==0)return 1;
long temp = exp(a,b/2);
if(b%2==0) return (temp*temp)%MOD;
else return (a*((temp*temp)%MOD))%MOD;
}
//Range Sum + Dynamic Range update O(lg(N))
private static class ST {
int K;
int[] val, delta;
public ST(int[] list){
K = (int)Math.ceil(Math.log(list.length)/Math.log(2));
val = new int[4*list.length];
delta = new int[4*list.length];
build(list, 0, (1<<K)-1, 1);
}
private void build(int[] list, int L, int R, int idx) {
if(L==R){
if(L>=list.length)return;
val[idx] = list[L];return;
}
int mid = (R+L)/2;
build(list,L,mid,idx*2);
build(list,mid+1,R,idx*2+1);
val[idx] = val[idx*2]+val[idx*2+1];
}
public int update(int L, int R, int V){return update(L,R,0,(1<<K)-1,1,V);}
public int query(int L, int R) {return query(L,R,0,(1<<K)-1,1);}
private int query(int L, int R, int tL, int tR, int idx) {
if(tL<L&&tR<L||tL>R&&tR>R)return 0;
if(tL>=L&&tR<=R){
return val[idx];
}
prop(tL,tR,idx);
int mid = (tL+tR)/2;
return query(L,R,tL,mid,idx*2)+query(L,R,mid+1,tR,idx*2+1);
}
private int update(int L, int R, int tL, int tR, int idx, int V) {
if(tL<L&&tR<L||tL>R&&tR>R)return 0;
if(tL>=L&&tR<=R){
val[idx] += (long)(tR-tL+1)*V;
if(tL!=tR)delta[idx] += V;
return (tR-tL+1)*V;
}
prop(tL,tR,idx);
int mid = (tR+tL)/2;
int temp = update(L,R,tL,mid,idx*2,V)+update(L,R,mid+1,tR,idx*2+1,V);
val[idx] +=temp;
return temp;
}
private void prop(int L, int R, int idx) {
if(delta[idx] == 0)return;
int mid = (R+L)/2;
update(L,R,L,mid,idx*2,delta[idx]);
update(L,R,mid+1,R,idx*2+1,delta[idx]);
delta[idx] =0;
}
}
private 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());}
}
}
|
Java
|
["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"]
|
3 seconds
|
["5", "3", "6"]
|
NoteIn the first example: ;;.So the answer is 2 + 1 + 2 = 5.
|
Java 8
|
standard input
|
[
"dp",
"geometry",
"combinatorics",
"implementation",
"data structures"
] |
900c85e25d457eb8092624b1d42be2a2
|
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109), describing i-th segment bounds.
| 2,000 |
Print one integer number — the answer to Mike's problem modulo 1000000007 (109 + 7) in the only line.
|
standard output
| |
PASSED
|
cca22c9e55df52e510d0a39ceb230245
|
train_001.jsonl
|
1467822900
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l, r]) = r - l + 1 to be the number of integer points in the segment [l, r] with l ≤ r (say that ). You are given two integers n and k and n closed intervals [li, ri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109 + 7).Mike can't solve this problem so he needs your help. You will help him, won't you?
|
256 megabytes
|
import java.util.*;
import java.io.*;
import java.math.*;
public class Main
{
public static final long P = 1000000007;
public static long[] pre;
public static long inv( long a )
{
a = a % P;
long res = 1;
for ( long p = P - 2; p > 0; p >>= 1 )
{
if ( p % 2 == 1 )
res = ( res * a ) % P;
a = ( a * a ) % P;
}
return res;
}
public static long C( int a, int b )
{
return a < b ? 0 : a == b ? 1 : ( ( ( pre[a] * inv( pre[a - b] ) ) % P ) * inv( pre[b] ) ) % P;
}
public static void main( String[] args )
{
Scan sc = new Scan();
int n = sc.nextInt();
int k = sc.nextInt();
pre = new long[ n + 1 ];
pre[1] = 1;
for ( int i = 2; i <= n; i ++ )
pre[i] = ( pre[i - 1] * i ) % P;
ArrayList<Poi> a = new ArrayList<>();
for ( int i = 0; i < n; i ++ )
{
long l = sc.nextLong();
long r = sc.nextLong();
Poi poi = new Poi();
poi.x = l;
poi.val = 1;
a.add( poi );
poi = new Poi();
poi.x = r + 1;
poi.val = -1;
a.add( poi );
}
Collections.sort( a, (l, r)
->
{
long res = l.x - r.x;
return res < 0 ? -1 : res == 0 ? 0 : 1;
} );
long cur = -1, precur = -1;
int siz = 0, presiz = -1;
long ans = 0;
for ( int p = 0; p < a.size(); )
{
cur = a.get( p ).x;
while ( p < a.size() && a.get( p ).x == cur )
siz += a.get( p ++ ).val;
if ( precur != -1 )
ans = ( ( cur - precur ) * ( C( presiz, k ) ) + ans ) % P;
precur = cur;
presiz = siz;
}
System.out.println( ans );
}
}
class Poi
{
long x;
int val;
}
class Scan
{
BufferedReader br;
StringTokenizer st;
Scan()
{
br = new BufferedReader( new InputStreamReader( System.in ) );
}
boolean hasNext()
{
while ( st == null || ! st.hasMoreElements() )
{
try
{
st = new StringTokenizer( br.readLine() );
}
catch ( Exception e )
{
return false;
}
}
return true;
}
int nextInt()
{
return hasNext() ? Integer.parseInt( st.nextToken() ) : -1;
}
long nextLong()
{
return hasNext() ? Long.parseLong( st.nextToken() ) : -1;
}
}
|
Java
|
["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"]
|
3 seconds
|
["5", "3", "6"]
|
NoteIn the first example: ;;.So the answer is 2 + 1 + 2 = 5.
|
Java 8
|
standard input
|
[
"dp",
"geometry",
"combinatorics",
"implementation",
"data structures"
] |
900c85e25d457eb8092624b1d42be2a2
|
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109), describing i-th segment bounds.
| 2,000 |
Print one integer number — the answer to Mike's problem modulo 1000000007 (109 + 7) in the only line.
|
standard output
| |
PASSED
|
9467d14d31c39a131b80432ff719aa36
|
train_001.jsonl
|
1467822900
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l, r]) = r - l + 1 to be the number of integer points in the segment [l, r] with l ≤ r (say that ). You are given two integers n and k and n closed intervals [li, ri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109 + 7).Mike can't solve this problem so he needs your help. You will help him, won't you?
|
256 megabytes
|
//package round361;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.InputMismatchException;
public class E {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni(), K = ni();
int[][] rs = new int[n][];
for(int i = 0;i < n;i++){
rs[i] = new int[]{ni(), ni()+1};
}
int mod = 1000000007;
int[][] es = new int[2*n][];
for(int i = 0;i < n;i++){
es[i] = new int[]{rs[i][0], 1};
es[i+n] = new int[]{rs[i][1], -1};
}
Arrays.sort(es, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
if(a[0] != b[0])return a[0] - b[0];
return a[1] - b[1];
}
});
int[][] fif = enumFIF(1000000, mod);
int h = 0;
int x = -1;
long ret = 0;
for(int[] e : es){
if(x < e[0] && h >= K){
ret += C(h, K, mod, fif) * (e[0]-x) % mod;
}
h += e[1];
x = e[0];
}
out.println(ret%mod);
}
public static long C(int n, int r, int mod, int[][] fif) {
if (n < 0 || r < 0 || r > n)
return 0;
return (long) fif[0][n] * fif[1][r] % mod * fif[1][n - r] % mod;
}
public static int[][] enumFIF(int n, int mod) {
int[] f = new int[n + 1];
int[] invf = new int[n + 1];
f[0] = 1;
for (int i = 1; i <= n; i++) {
f[i] = (int) ((long) f[i - 1] * i % mod);
}
long a = f[n];
long b = mod;
long p = 1, q = 0;
while (b > 0) {
long c = a / b;
long d;
d = a;
a = b;
b = d % b;
d = p;
p = q;
q = d - c * q;
}
invf[n] = (int) (p < 0 ? p + mod : p);
for (int i = n - 1; i >= 0; i--) {
invf[i] = (int) ((long) invf[i + 1] * (i + 1) % mod);
}
return new int[][] { f, invf };
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new E().run(); }
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
|
Java
|
["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"]
|
3 seconds
|
["5", "3", "6"]
|
NoteIn the first example: ;;.So the answer is 2 + 1 + 2 = 5.
|
Java 8
|
standard input
|
[
"dp",
"geometry",
"combinatorics",
"implementation",
"data structures"
] |
900c85e25d457eb8092624b1d42be2a2
|
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109), describing i-th segment bounds.
| 2,000 |
Print one integer number — the answer to Mike's problem modulo 1000000007 (109 + 7) in the only line.
|
standard output
| |
PASSED
|
5b550c749d772100067863790a63366f
|
train_001.jsonl
|
1467822900
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l, r]) = r - l + 1 to be the number of integer points in the segment [l, r] with l ≤ r (say that ). You are given two integers n and k and n closed intervals [li, ri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109 + 7).Mike can't solve this problem so he needs your help. You will help him, won't you?
|
256 megabytes
|
import java.io.*;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
private FastScanner in;
private PrintWriter out;
// private Timer timer = new Timer();
class E {
int pos, type;
static final int START = 1;
static final int END = 0;
public E(int pos, int type) {
this.pos = pos;
this.type = type;
}
}
private void solve() throws IOException {
int n = in.nextInt();
int k = in.nextInt();
E[] a = new E[2 * n];
for (int i = 0; i < a.length; i += 2) {
a[i] = new E(in.nextInt(), E.START);
a[i + 1] = new E(in.nextInt() + 1, E.END);
}
Arrays.sort(a, (o1, o2) -> {
if (o1.pos != o2.pos) {
return o1.pos - o2.pos;
}
return o1.type - o2.type;
});
int cnt = 0;
int last = a[0].pos;
long ans = 0;
for (int i = 0; i < a.length; i++) {
int cur = a[i].pos;
{
ans += ((long)cur - last) * C(cnt, k);
ans %= MOD;
}
cnt = getCnt(a[i], cnt);
while (i + 1 < a.length && a[i + 1].pos == cur) {
cnt = getCnt(a[++i], cnt);
}
last = cur;
}
out.println(ans);
}
class T {
long v, x, y;
public T(long v, long x, long y) {
this.v = v;
this.x = x;
this.y = y;
}
}
T gcd(long a, long b) {
if (a == 0) return new T(b, 0, 1);
T p = gcd(b % a, a);
return new T(p.v, p.y - (((b / a) * p.x) % MOD + MOD) % MOD, p.x);
}
final int MOD = (int) 1e9 + 7;
long[] fact = new long[222_222];
long[] rev = new long[222_222];
{
fact[0] = 1;
for (int i = 1; i < fact.length; i++) {
fact[i] = (fact[i - 1] * i) % MOD;
}
for (int i = 0; i < fact.length; i++) {
rev[i] = getRev(fact[i]);
}
}
long C(int n, int k) {
if (n < k) return 0;
if (k == 0 || n == k) return 1;
long res = fact[n];
res *= rev[k];
res %= MOD;
res *= rev[n - k];
return res % MOD;
}
private long getRev(long a) {
T v = gcd(a, MOD);
return (v.x % MOD + MOD) % MOD;
}
private int getCnt(E e, int cnt) {
if (e.type == E.END) {
cnt--;
} else {
cnt++;
}
return cnt;
}
private void run() throws IOException {
in = new FastScanner();
out = new PrintWriter(System.out, false);
new Thread(null, () -> {
try {
solve();
} catch (IOException e) {
e.printStackTrace();
}
}, "xyz", 1 << 27).run();
out.close();
}
public static void main(String[] args) throws IOException {
new Main().run();
}
}
class FastScanner {
private final BufferedReader br;
private StringTokenizer st;
private String last;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public FastScanner(String path) throws IOException {
br = new BufferedReader(new FileReader(path));
}
public FastScanner(String path, String decoder) throws IOException {
br = new BufferedReader(new InputStreamReader(new FileInputStream(path), decoder));
}
String next() throws IOException {
while (st == null || !st.hasMoreElements())
st = new StringTokenizer(br.readLine());
last = null;
return st.nextToken();
}
String nextLine() throws IOException {
st = null;
return (last == null) ? br.readLine() : last;
}
boolean hasNext() {
if (st != null && st.hasMoreElements())
return true;
try {
while (st == null || !st.hasMoreElements()) {
last = br.readLine();
st = new StringTokenizer(last);
}
} catch (Exception e) {
return false;
}
return true;
}
String[] nextStrings(int n) throws IOException {
String[] arr = new String[n];
for (int i = 0; i < n; i++)
arr[i] = next();
return arr;
}
String[] nextLines(int n) throws IOException {
String[] arr = new String[n];
for (int i = 0; i < n; i++)
arr[i] = nextLine();
return arr;
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
int[] nextInts(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
Integer[] nextIntegers(int n) throws IOException {
Integer[] arr = new Integer[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
int[][] next2Ints(int n, int m) throws IOException {
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;
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
long[] nextLongs(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nextLong();
return arr;
}
long[][] next2Longs(int n, int m) throws IOException {
long[][] arr = new long[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
arr[i][j] = nextLong();
return arr;
}
double nextDouble() throws IOException {
return Double.parseDouble(next().replace(',', '.'));
}
double[] nextDoubles(int size) throws IOException {
double[] arr = new double[size];
for (int i = 0; i < size; i++)
arr[i] = nextDouble();
return arr;
}
boolean nextBool() throws IOException {
String s = next();
if (s.equalsIgnoreCase("true") || s.equals("1"))
return true;
if (s.equalsIgnoreCase("false") || s.equals("0"))
return false;
throw new IOException("Boolean expected, String found!");
}
}
|
Java
|
["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"]
|
3 seconds
|
["5", "3", "6"]
|
NoteIn the first example: ;;.So the answer is 2 + 1 + 2 = 5.
|
Java 8
|
standard input
|
[
"dp",
"geometry",
"combinatorics",
"implementation",
"data structures"
] |
900c85e25d457eb8092624b1d42be2a2
|
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109), describing i-th segment bounds.
| 2,000 |
Print one integer number — the answer to Mike's problem modulo 1000000007 (109 + 7) in the only line.
|
standard output
| |
PASSED
|
3c668514f84c45d68764f64ca35210ef
|
train_001.jsonl
|
1467822900
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l, r]) = r - l + 1 to be the number of integer points in the segment [l, r] with l ≤ r (say that ). You are given two integers n and k and n closed intervals [li, ri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109 + 7).Mike can't solve this problem so he needs your help. You will help him, won't you?
|
256 megabytes
|
import static java.lang.Math.*;
import static java.util.Arrays.*;
import java.util.*;
import java.io.*;
public class Main {
void solve() {
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();
b[i] = sc.nextInt() + 1;
}
Range[] ranges = prune(a, b);
int M = orgIndex.length;
int[] acc = new int[M];
for (int i = 0; i < N; i++) {
acc[ranges[i].a]++;
acc[ranges[i].b]--;
}
for (int i = 1; i < M; i++) acc[i] += acc[i-1];
long ans = 0;
for (int i = 0; i + 1 < M; i++) {
long x = C(acc[i], K);
ans = (ans + (orgIndex[i+1] - orgIndex[i]) * x) % MOD;
}
out.println(ans);
}
static final long MOD = 1000000007;
static final long[] fact = new long[200000 + 10];
static final long[] fact_inv = new long[200000 + 10];
static {
long[] inv = new long[200000 + 10];
inv[1] = fact[0] = fact_inv[0] = 1;
for (int i = 2; i < inv.length; i++) inv[i] = inv[(int)(MOD % i)] * (MOD - MOD / i) % MOD;
for (int i = 1; i < fact.length; i++) fact[i] = (fact[i-1] * i) % MOD;
for (int i = 1; i < fact_inv.length; i++) fact_inv[i] = (fact_inv[i-1] * inv[i]) % MOD;
}
long C(long n, long k) {
if ( n < 0 || k < 0 || n < k) return 0;
return fact[(int)n] * fact_inv[(int)(n - k)] % MOD * fact_inv[(int)k] % MOD;
}
int[] orgIndex; // 座標圧縮前の座標
static class Range {
int id;
int a, b;
Range(int id, int a, int b) {
this.id = id;
this.a = a;
this.b = b;
}
@Override
public String toString() {
return String.format("id=%d : [%d,%d);", id, a, b);
}
}
public int[] normalize(int[] v) {
int[] res = new int[v.length];
int[][] t = new int[v.length][2];
for (int i = 0; i < v.length; i++) {
t[i][0] = v[i];
t[i][1] = i;
}
Arrays.sort(t, 0, t.length, new Comparator<int[]>(){
public int compare(int[] a, int[] b){
if (a[0] != b[0]) return a[0] < b[0] ? -1 : 1;
return 0;
}
});
orgIndex = new int[2 * v.length];
int r = 0;
for (int i = 0; i < v.length; i++) {
r += (i > 0 && t[i - 1][0] != t[i][0]) ? 1 : 0;
res[(int)t[i][1]] = r;
orgIndex[r] = t[i][0];
}
orgIndex = Arrays.copyOf(orgIndex, r+1);
return res;
}
Range[] prune(int[] as, int[] bs) {
int n = as.length;
Range[] ranges = new Range[n];
int[] v = new int[2 * n];
for (int i = 0; i < n; i++) { v[2*i] = as[i]; v[2*i+1] = bs[i]; }
v = normalize(v);
for (int i = 0; i < n; i++) ranges[i] = new Range(i, v[i*2], v[i*2+1]);
Arrays.sort(ranges, new Comparator<Range>(){
@Override
public int compare(Range a, Range b) {
if (a.a != b.a) return a.a < b.a ? -1 : 1;
if (a.b != b.b) return a.b > b.b ? -1 : 1;
return Integer.compare(a.id, b.id);
}
});
return Arrays.copyOf(ranges, n);
}
static void tr(Object... os) { System.err.println(deepToString(os)); }
static void tr(int[][] as) { for (int[] a : as) tr(a); }
void print(int[] a) {
if (a.length > 0) out.print(a[0]);
for (int i = 1; i < a.length; i++) out.print(" " + a[i]);
out.println();
}
public static void main(String[] args) throws Exception {
new Main().run();
}
MyScanner sc = null;
PrintWriter out = null;
public void run() throws Exception {
sc = new MyScanner(System.in);
out = new PrintWriter(System.out);
for (;sc.hasNext();) {
solve();
out.flush();
}
out.close();
}
class MyScanner {
String line;
BufferedReader reader;
StringTokenizer tokenizer;
public MyScanner(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public void eat() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
line = reader.readLine();
if (line == null) {
tokenizer = null;
return;
}
tokenizer = new StringTokenizer(line);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
public String next() {
eat();
return tokenizer.nextToken();
}
public String nextLine() {
try {
return reader.readLine();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public boolean hasNext() {
eat();
return (tokenizer != null && tokenizer.hasMoreElements());
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public int[] nextIntArray(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = nextInt();
return a;
}
}
}
|
Java
|
["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"]
|
3 seconds
|
["5", "3", "6"]
|
NoteIn the first example: ;;.So the answer is 2 + 1 + 2 = 5.
|
Java 8
|
standard input
|
[
"dp",
"geometry",
"combinatorics",
"implementation",
"data structures"
] |
900c85e25d457eb8092624b1d42be2a2
|
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109), describing i-th segment bounds.
| 2,000 |
Print one integer number — the answer to Mike's problem modulo 1000000007 (109 + 7) in the only line.
|
standard output
| |
PASSED
|
defb56fbb4f0470c1ad733eb5980ae6e
|
train_001.jsonl
|
1467822900
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l, r]) = r - l + 1 to be the number of integer points in the segment [l, r] with l ≤ r (say that ). You are given two integers n and k and n closed intervals [li, ri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109 + 7).Mike can't solve this problem so he needs your help. You will help him, won't you?
|
256 megabytes
|
import java.util.*;
import java.util.function.Supplier;
import java.io.*;
import java.awt.Point;
import java.math.BigDecimal;
import java.math.BigInteger;
import static java.lang.Math.*;
public class __AAAAA implements Runnable{
final static Random rnd = new Random();
// SOLUTION!!!
// HACK ME PLEASE IF YOU CAN!!!
// PLEASE!!!
// PLEASE!!!
// PLEASE!!!
static final int START = 0, END = 1;
class SegmentPoint {
int type;
int x;
SegmentPoint(int type, int x) {
this.type = type;
this.x = x;
}
}
void solve() {
int n = readInt();
int k = readInt();
Point[] segments = new Point[n];
for (int i = 0; i < n; ++i) {
segments[i] = readPoint();
}
long answer = getAnswer(n, k, segments);
out.println(answer);
}
static final long MODULO = 1000 * 1000 * 1000 + 7;
long getAnswer(int n, int k, Point[] segments) {
// c(n, k) = n! / k! / (n - k)!
long[] factorials = new long[n + 1];
factorials[0] = 1;
for (int i = 1; i <= n; ++i) {
factorials[i] = factorials[i - 1] * i % MODULO;
}
long[] inverseFactorials = new long[n + 1];
for (int i = 0; i <= n; ++i) {
inverseFactorials[i] = inverse(factorials[i]);
}
SortedMap<Integer, Integer> segmentStarts = new TreeMap<Integer, Integer>();
SortedMap<Integer, Integer> segmentEnds = new TreeMap<Integer, Integer>();
for (Point segment : segments) {
inc(segmentStarts, segment.x - 1);
inc(segmentEnds, segment.y);
}
SortedSet<Integer> segmentXs = new TreeSet<Integer>();
segmentXs.addAll(segmentStarts.keySet());
segmentXs.addAll(segmentEnds.keySet());
int openSegments = 0;
int lastX = segmentXs.first();
long answer = 0;
for (int x : segmentXs) {
Integer segmentStartsForX = segmentStarts.get(x);
if (segmentStartsForX == null) segmentStartsForX = 0;
Integer segmentEndsForX = segmentEnds.get(x);
if (segmentEndsForX == null) segmentEndsForX = 0;
int length = x - lastX;
if (k <= openSegments) {
long combinations = factorials[openSegments] * inverseFactorials[k] % MODULO;
combinations = combinations * inverseFactorials[openSegments - k] % MODULO;
long count = combinations * length % MODULO;
answer = (answer + count) % MODULO;
}
openSegments += segmentStartsForX;
openSegments -= segmentEndsForX;
lastX = x;
}
return answer;
}
long inverse(long x) {
return binpow(x, MODULO - 2);
}
long binpow(long x, long pow) {
if (pow == 0) return 1;
if ((pow % 2 == 0)) {
long half = binpow(x, pow >> 1);
return half * half % MODULO;
} else {
long prev = binpow(x, pow - 1);
return prev * x % MODULO;
}
}
void inc(SortedMap<Integer, Integer> segmentPoints, int x) {
Integer segmentPointsForX = segmentPoints.get(x);
if (segmentPointsForX == null) {
segmentPointsForX = 0;
}
segmentPoints.put(x, segmentPointsForX + 1);
}
/////////////////////////////////////////////////////////////////////
final boolean STRESS = false;
final boolean FIRST_INPUT_STRING = false;
final boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
final static int MAX_STACK_SIZE = 128;
/////////////////////////////////////////////////////////////////////
public void run(){
try{
timeBegin = System.currentTimeMillis();
Locale.setDefault(Locale.US);
init();
if (ONLINE_JUDGE) {
solve();
} else if (STRESS) {
for (int iteration = 0; iteration < 100; ++iteration) {
// STRESS
}
out.println("The end");
} else {
while (true) {
try {
solve();
out.println();
} catch (NumberFormatException e) {
break;
} catch (NullPointerException e) {
if (FIRST_INPUT_STRING) break;
else throw e;
}
}
}
out.close();
time();
}catch (Exception e){
e.printStackTrace(System.err);
System.exit(-1);
}
}
/////////////////////////////////////////////////////////////////////
BufferedReader in;
OutputWriter out;
StringTokenizer tok = new StringTokenizer("");
public static void main(String[] args){
new Thread(null, new __AAAAA(), "", MAX_STACK_SIZE * (1L << 20)).start();
}
/////////////////////////////////////////////////////////////////////
void init() throws FileNotFoundException{
Locale.setDefault(Locale.US);
if (ONLINE_JUDGE){
in = new BufferedReader(new InputStreamReader(System.in));
out = new OutputWriter(System.out);
}else{
in = new BufferedReader(new FileReader("input.txt"));
out = new OutputWriter("output.txt");
}
}
////////////////////////////////////////////////////////////////
long timeBegin, timeEnd;
void time(){
timeEnd = System.currentTimeMillis();
System.err.println("Time = " + (timeEnd - timeBegin));
}
void debug(Object... objects){
if (ONLINE_JUDGE){
for (Object o: objects){
System.err.println(o.toString());
}
}
}
/////////////////////////////////////////////////////////////////////
String delim = " ";
String readLine() {
try {
return in.readLine();
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
String readString() {
try {
while(!tok.hasMoreTokens()){
tok = new StringTokenizer(readLine());
}
return tok.nextToken(delim);
} catch (NullPointerException e) {
return null;
}
}
/////////////////////////////////////////////////////////////////
final char NOT_A_SYMBOL = '\0';
char readChar() {
try {
int intValue = in.read();
if (intValue == -1){
return NOT_A_SYMBOL;
}
return (char) intValue;
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
char[] readCharArray() {
return readLine().toCharArray();
}
char[][] readCharField(int rowsCount) {
char[][] field = new char[rowsCount][];
for (int row = 0; row < rowsCount; ++row) {
field[row] = readCharArray();
}
return field;
}
/////////////////////////////////////////////////////////////////
int readInt() {
return Integer.parseInt(readString());
}
int[] readIntArray(int size) {
int[] array = new int[size];
for (int index = 0; index < size; ++index){
array[index] = readInt();
}
return array;
}
int[] readSortedIntArray(int size) {
Integer[] array = new Integer[size];
for (int index = 0; index < size; ++index) {
array[index] = readInt();
}
Arrays.sort(array);
int[] sortedArray = new int[size];
for (int index = 0; index < size; ++index) {
sortedArray[index] = array[index];
}
return sortedArray;
}
int[] readIntArrayWithDecrease(int size) {
int[] array = readIntArray(size);
for (int i = 0; i < size; ++i) {
array[i]--;
}
return array;
}
///////////////////////////////////////////////////////////////////
int[][] readIntMatrix(int rowsCount, int columnsCount) {
int[][] matrix = new int[rowsCount][];
for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
matrix[rowIndex] = readIntArray(columnsCount);
}
return matrix;
}
int[][] readIntMatrixWithDecrease(int rowsCount, int columnsCount) {
int[][] matrix = new int[rowsCount][];
for (int rowIndex = 0; rowIndex < rowsCount; ++rowIndex) {
matrix[rowIndex] = readIntArrayWithDecrease(columnsCount);
}
return matrix;
}
///////////////////////////////////////////////////////////////////
long readLong() {
return Long.parseLong(readString());
}
long[] readLongArray(int size) {
long[] array = new long[size];
for (int index = 0; index < size; ++index){
array[index] = readLong();
}
return array;
}
////////////////////////////////////////////////////////////////////
double readDouble() {
return Double.parseDouble(readString());
}
double[] readDoubleArray(int size) {
double[] array = new double[size];
for (int index = 0; index < size; ++index){
array[index] = readDouble();
}
return array;
}
////////////////////////////////////////////////////////////////////
BigInteger readBigInteger() {
return new BigInteger(readString());
}
BigDecimal readBigDecimal() {
return new BigDecimal(readString());
}
/////////////////////////////////////////////////////////////////////
Point readPoint() {
int x = readInt();
int y = readInt();
return new Point(x, y);
}
Point[] readPointArray(int size) {
Point[] array = new Point[size];
for (int index = 0; index < size; ++index){
array[index] = readPoint();
}
return array;
}
/////////////////////////////////////////////////////////////////////
List<Integer>[] readGraph(int vertexNumber, int edgeNumber) {
@SuppressWarnings("unchecked")
List<Integer>[] graph = new List[vertexNumber];
for (int index = 0; index < vertexNumber; ++index){
graph[index] = new ArrayList<Integer>();
}
while (edgeNumber-- > 0){
int from = readInt() - 1;
int to = readInt() - 1;
graph[from].add(to);
graph[to].add(from);
}
return graph;
}
/////////////////////////////////////////////////////////////////////
static class IntIndexPair {
static Comparator<IntIndexPair> increaseComparator = new Comparator<IntIndexPair>() {
@Override
public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) {
int value1 = indexPair1.value;
int value2 = indexPair2.value;
if (value1 != value2) return value1 - value2;
int index1 = indexPair1.index;
int index2 = indexPair2.index;
return index1 - index2;
}
};
static Comparator<IntIndexPair> decreaseComparator = new Comparator<IntIndexPair>() {
@Override
public int compare(IntIndexPair indexPair1, IntIndexPair indexPair2) {
int value1 = indexPair1.value;
int value2 = indexPair2.value;
if (value1 != value2) return -(value1 - value2);
int index1 = indexPair1.index;
int index2 = indexPair2.index;
return index1 - index2;
}
};
int value, index;
public IntIndexPair(int value, int index) {
super();
this.value = value;
this.index = index;
}
public int getRealIndex() {
return index + 1;
}
}
IntIndexPair[] readIntIndexArray(int size) {
IntIndexPair[] array = new IntIndexPair[size];
for (int index = 0; index < size; ++index) {
array[index] = new IntIndexPair(readInt(), index);
}
return array;
}
/////////////////////////////////////////////////////////////////////
static class OutputWriter extends PrintWriter {
final int DEFAULT_PRECISION = 12;
protected int precision;
protected String format, formatWithSpace;
{
precision = DEFAULT_PRECISION;
format = createFormat(precision);
formatWithSpace = format + " ";
}
public OutputWriter(OutputStream out) {
super(out);
}
public OutputWriter(String fileName) throws FileNotFoundException {
super(fileName);
}
public int getPrecision() {
return precision;
}
public void setPrecision(int precision) {
precision = max(0, precision);
this.precision = precision;
format = createFormat(precision);
formatWithSpace = format + " ";
}
private String createFormat(int precision){
return "%." + precision + "f";
}
@Override
public void print(double d){
printf(format, d);
}
public void printWithSpace(double d){
printf(formatWithSpace, d);
}
public void printAll(double...d){
for (int i = 0; i < d.length - 1; ++i){
printWithSpace(d[i]);
}
print(d[d.length - 1]);
}
@Override
public void println(double d){
printlnAll(d);
}
public void printlnAll(double... d){
printAll(d);
println();
}
}
/////////////////////////////////////////////////////////////////////
static class RuntimeIOException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = -6463830523020118289L;
public RuntimeIOException(Throwable cause) {
super(cause);
}
}
/////////////////////////////////////////////////////////////////////
//////////////// Some useful constants and functions ////////////////
/////////////////////////////////////////////////////////////////////
static final int[][] steps = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
static final int[][] steps8 = {
{-1, 0}, {1, 0}, {0, -1}, {0, 1},
{-1, -1}, {1, 1}, {1, -1}, {-1, 1}
};
static final boolean checkCell(int row, int rowsCount, int column, int columnsCount) {
return checkIndex(row, rowsCount) && checkIndex(column, columnsCount);
}
static final boolean checkIndex(int index, int lim){
return (0 <= index && index < lim);
}
/////////////////////////////////////////////////////////////////////
static final boolean checkBit(int mask, int bit){
return (mask & (1 << bit)) != 0;
}
/////////////////////////////////////////////////////////////////////
static final long getSum(int[] array) {
long sum = 0;
for (int value: array) {
sum += value;
}
return sum;
}
static final Point getMinMax(int[] array) {
int min = array[0];
int max = array[0];
for (int index = 0, size = array.length; index < size; ++index, ++index) {
int value = array[index];
if (index == size - 1) {
min = min(min, value);
max = max(max, value);
} else {
int otherValue = array[index + 1];
if (value <= otherValue) {
min = min(min, value);
max = max(max, otherValue);
} else {
min = min(min, otherValue);
max = max(max, value);
}
}
}
return new Point(min, max);
}
/////////////////////////////////////////////////////////////////////
static class IdMap<KeyType> extends HashMap<KeyType, Integer> {
/**
*
*/
private static final long serialVersionUID = -3793737771950984481L;
public IdMap() {
super();
}
int getId(KeyType key) {
Integer id = super.get(key);
if (id == null) {
super.put(key, id = size());
}
return id;
}
}
}
|
Java
|
["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"]
|
3 seconds
|
["5", "3", "6"]
|
NoteIn the first example: ;;.So the answer is 2 + 1 + 2 = 5.
|
Java 8
|
standard input
|
[
"dp",
"geometry",
"combinatorics",
"implementation",
"data structures"
] |
900c85e25d457eb8092624b1d42be2a2
|
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109), describing i-th segment bounds.
| 2,000 |
Print one integer number — the answer to Mike's problem modulo 1000000007 (109 + 7) in the only line.
|
standard output
| |
PASSED
|
752547d2f41a6deed98453b38d7aaf44
|
train_001.jsonl
|
1467822900
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l, r]) = r - l + 1 to be the number of integer points in the segment [l, r] with l ≤ r (say that ). You are given two integers n and k and n closed intervals [li, ri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109 + 7).Mike can't solve this problem so he needs your help. You will help him, won't you?
|
256 megabytes
|
import java.io.ByteArrayInputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.concurrent.ThreadLocalRandom;
public class Main {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
new Main().solve(new Scanner(System.in));
// new Main().solve(new Scanner(new ByteArrayInputStream(("3 2\n" +
// "1 2\n" +
// "1 3\n" +
// "2 3").getBytes())));
// new Main().solve(new Scanner(new ByteArrayInputStream(("3 3\n" +
// "1 3\n" +
// "1 3\n" +
// "1 3").getBytes())));
// System.out.println(System.currentTimeMillis() - startTime + "ms");
}
public static int mod = 1_000_000_007;
public int[] fact;
public int[] comb;
public int binom(int n, int k) {
int res = (int) (((long) fact[n] * (long) comb[k]) % mod);
return (int) (((long) res * (long) comb[n - k]) % mod);
}
public int pow(int a, int b, int mod) {
int res = 1;
while (b > 0) {
if ((b & 1) == 1) res = (int) ((((long) res) * (long) a) % mod);
a = (int) (((long) a * (long) a) % mod);
b /= 2;
}
return res;
}
public void init(int n) {
fact = new int[n + 1];
comb = new int[n + 1];
fact[0] = comb[0] = 1;
for (int i = 1; i <= n; ++i) {
fact[i] = (int) (((long) fact[i - 1] * (long) i) % mod);
comb[i] = pow(fact[i], mod - 2, mod);
}
}
private void solve(Scanner sc) {
int n = sc.nextInt(); // num of segments
int k = sc.nextInt(); //
// int n = 200_000;
// int k = 1;
init(n);
TreeMap<Integer, Integer> mapS = new TreeMap<>();
for (int i = 0; i < n; i++) {
int l = sc.nextInt();
int r = sc.nextInt();
// int l = ThreadLocalRandom.current().nextInt(-1_000_000_000, 1_000_000_000 + 1); // -10^9 <= x <= 10^9;
// int r = ThreadLocalRandom.current().nextInt(l, 1_000_000_000 + 1);
int count = mapS.containsKey(l) ? mapS.get(l) : 0;
mapS.put(l, count + 1);
count = mapS.containsKey(r + 1) ? mapS.get(r + 1) : 0;
mapS.put(r + 1, count - 1);
}
int segmetsNum = 0;
int left = Integer.MIN_VALUE;
int sum = 0;
for (Integer x : mapS.keySet()) {
if(segmetsNum >= k) {
sum += ((long)(x-left) * (long)binom(segmetsNum,k))%mod;
sum %= mod;
}
left = x;
segmetsNum += mapS.get(x);
}
System.out.println(sum);
}
}
|
Java
|
["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"]
|
3 seconds
|
["5", "3", "6"]
|
NoteIn the first example: ;;.So the answer is 2 + 1 + 2 = 5.
|
Java 8
|
standard input
|
[
"dp",
"geometry",
"combinatorics",
"implementation",
"data structures"
] |
900c85e25d457eb8092624b1d42be2a2
|
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109), describing i-th segment bounds.
| 2,000 |
Print one integer number — the answer to Mike's problem modulo 1000000007 (109 + 7) in the only line.
|
standard output
| |
PASSED
|
f7e0318445f7853a3e7a854bf05205e6
|
train_001.jsonl
|
1467822900
|
Mike wants to prepare for IMO but he doesn't know geometry, so his teacher gave him an interesting geometry problem. Let's define f([l, r]) = r - l + 1 to be the number of integer points in the segment [l, r] with l ≤ r (say that ). You are given two integers n and k and n closed intervals [li, ri] on OX axis and you have to find: In other words, you should find the sum of the number of integer points in the intersection of any k of the segments. As the answer may be very large, output it modulo 1000000007 (109 + 7).Mike can't solve this problem so he needs your help. You will help him, won't you?
|
256 megabytes
|
import java.util.ArrayList;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Comparator;
import java.io.IOException;
import java.util.StringTokenizer;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Igor Kraskevich
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskE solver = new TaskE();
solver.solve(1, in, out);
out.close();
}
}
class TaskE {
final long MOD = 1000 * 1000 * 1000 + 7;
final int N = 200 * 1000 + 10;
long[] f;
long binPow(long x, long n) {
long res = 1;
while (n > 0) {
if (n % 2 == 1)
res = res * x % MOD;
x = x * x % MOD;
n /= 2;
}
return res;
}
long inverse(long x) {
return binPow(x, MOD - 2);
}
void prec() {
f = new long[N];
f[0] = 1;
for (int i = 1; i < N; i++)
f[i] = f[i - 1] * i % MOD;
}
long cnk(int n, int k) {
long res = f[n];
res = res * inverse(f[k]) % MOD;
return res * inverse(f[n - k]) % MOD;
}
class Event {
int x;
int delta;
Event(int x, int delta) {
this.x = x;
this.delta = delta;
}
}
public void solve(int testNumber, FastScanner in, PrintWriter out) {
prec();
int n = in.nextInt();
int k = in.nextInt();
ArrayList<Event> events = new ArrayList<>();
for (int i = 0; i < n; i++) {
int l = in.nextInt();
int r = in.nextInt() + 1;
events.add(new Event(l, 1));
events.add(new Event(r, -1));
}
Collections.sort(events, new Comparator<Event>() {
public int compare(Event o1, Event o2) {
return Integer.compare(o1.x, o2.x);
}
});
int open = 0;
long res = 0;
for (int i = 0; i < events.size() - 1; i++) {
Event e = events.get(i);
open += e.delta;
int len = events.get(i + 1).x - e.x;
if (open >= k && len != 0) {
long cur = cnk(open, k);
cur = cur * len % MOD;
res = (res + cur) % MOD;
}
}
out.println(res);
}
}
class FastScanner {
private StringTokenizer tokenizer;
private BufferedReader reader;
public FastScanner(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String line = null;
try {
line = reader.readLine();
} catch (IOException e) {
}
if (line == null)
return null;
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
|
Java
|
["3 2\n1 2\n1 3\n2 3", "3 3\n1 3\n1 3\n1 3", "3 1\n1 2\n2 3\n3 4"]
|
3 seconds
|
["5", "3", "6"]
|
NoteIn the first example: ;;.So the answer is 2 + 1 + 2 = 5.
|
Java 8
|
standard input
|
[
"dp",
"geometry",
"combinatorics",
"implementation",
"data structures"
] |
900c85e25d457eb8092624b1d42be2a2
|
The first line contains two integers n and k (1 ≤ k ≤ n ≤ 200 000) — the number of segments and the number of segments in intersection groups respectively. Then n lines follow, the i-th line contains two integers li, ri ( - 109 ≤ li ≤ ri ≤ 109), describing i-th segment bounds.
| 2,000 |
Print one integer number — the answer to Mike's problem modulo 1000000007 (109 + 7) in the only line.
|
standard output
| |
PASSED
|
ff09a39e6bd11702ee38a7c6ac3a1daf
|
train_001.jsonl
|
1549208100
|
Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are $$$n$$$ superheroes in avengers team having powers $$$a_1, a_2, \ldots, a_n$$$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $$$1$$$. They can do at most $$$m$$$ operations. Also, on a particular superhero at most $$$k$$$ operations can be done.Can you help the avengers team to maximize the average power of their crew?
|
256 megabytes
|
import java.util.Arrays;
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
long k = scanner.nextInt();
long m = scanner.nextInt();
int[] a = new int[n];
long s = 0;
for(int i = 0; i < n ; ++i) {
a[i] = scanner.nextInt();
s += a[i];
}
Arrays.sort(a);
double max = (s + Math.min(m, n * k)) / (double)n;
for(int i = 1; i <= Math.min(n - 1, m); ++i) {
s -= a[i - 1];
double res = (s + Math.min(m - i, (n - i) * k)) / (double)(n - i);
// System.out.println(res);
max = Math.max(max, res);
}
System.out.printf("%.20f", max);
}
}
|
Java
|
["2 4 6\n4 7", "4 2 6\n1 3 2 3"]
|
1 second
|
["11.00000000000000000000", "5.00000000000000000000"]
|
NoteIn the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by $$$2$$$ each.
|
Java 8
|
standard input
|
[
"implementation",
"brute force",
"math"
] |
d6e44bd8ac03876cb03be0731f7dda3d
|
The first line contains three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \le n \le 10^{5}$$$, $$$1 \le k \le 10^{5}$$$, $$$1 \le m \le 10^{7}$$$) — the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^{6}$$$) — the initial powers of the superheroes in the cast of avengers.
| 1,700 |
Output a single number — the maximum final average power. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
3ed6df6d938e5c3be79a8c6c15d74add
|
train_001.jsonl
|
1549208100
|
Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are $$$n$$$ superheroes in avengers team having powers $$$a_1, a_2, \ldots, a_n$$$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $$$1$$$. They can do at most $$$m$$$ operations. Also, on a particular superhero at most $$$k$$$ operations can be done.Can you help the avengers team to maximize the average power of their crew?
|
256 megabytes
|
import java.util.Arrays;
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
long k = scanner.nextInt();
long m = scanner.nextInt();
int[] a = new int[n];
long s = 0;
for(int i = 0; i < n ; ++i) {
a[i] = scanner.nextInt();
s += a[i];
}
Arrays.sort(a);
double max = (double)(s + Math.min(m, n * k)) / (double)n;
for(int i = 1; i <= Math.min(n - 1, m); ++i) {
s -= a[i - 1];
double res =(double) (s + Math.min(m - i, (n - i) * k)) / (double)(n - i);
// System.out.println(res);
max = Math.max(max, res);
}
System.out.printf("%.20f", max);
}
}
|
Java
|
["2 4 6\n4 7", "4 2 6\n1 3 2 3"]
|
1 second
|
["11.00000000000000000000", "5.00000000000000000000"]
|
NoteIn the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by $$$2$$$ each.
|
Java 8
|
standard input
|
[
"implementation",
"brute force",
"math"
] |
d6e44bd8ac03876cb03be0731f7dda3d
|
The first line contains three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \le n \le 10^{5}$$$, $$$1 \le k \le 10^{5}$$$, $$$1 \le m \le 10^{7}$$$) — the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^{6}$$$) — the initial powers of the superheroes in the cast of avengers.
| 1,700 |
Output a single number — the maximum final average power. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
5141eebe06a5b4c00eaa369a726185c0
|
train_001.jsonl
|
1549208100
|
Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are $$$n$$$ superheroes in avengers team having powers $$$a_1, a_2, \ldots, a_n$$$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $$$1$$$. They can do at most $$$m$$$ operations. Also, on a particular superhero at most $$$k$$$ operations can be done.Can you help the avengers team to maximize the average power of their crew?
|
256 megabytes
|
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class B2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), k = sc.nextInt(), m = sc.nextInt();
// New idea: instead of simulating the process, use that the two types of operations commute, i.e. whether we add and then remove or the other way around has the same result.
// Try all possible amounts of removal and then use rest of operations on addition. Pick the max.
List<Integer> powers = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
powers.add(sc.nextInt());
}
Collections.sort(powers);
boolean thatCase = n == 100000 && k == 25987 && m == 37;
//if (thatCase) {
// for (int i = n - 1; i >= 0; i--) {
// System.out.println(powers.get(i));
// }
//}
double best = 0;
List<Long> prefixSums = new ArrayList<>(n);
prefixSums.add(powers.get(0).longValue());
for (int i = 1; i < n; i++) {
prefixSums.add(prefixSums.get(i - 1) + powers.get(i));
}
for (int i = 0; i <= Math.min(m, n - 1); i++) {
long sumRemaining = prefixSums.get(n - 1);
if (i > 0) // Can avoid this time penalty by adding an extra start value of 0 to prefixSums
sumRemaining -= prefixSums.get(i - 1);
long capacityForImprovement = ((long) n - i) * k; // This overflows. Although right hand side is long, the cast to long only happens after the computation of purely integers. We therefore have to cast before doing the computation, so it happens on longs instead of ints
double avg = (((double) sumRemaining) + Math.min(m - i, capacityForImprovement)) / ((double) (n - i));
//if (thatCase) {
// count++;
// if (count > 20)
// System.out.println(avg);
//}
best = Math.max(best, avg);
}
// Time using prefix sums: from O(n^2) to O(n) + O(n)
System.out.println(best);
}
}
|
Java
|
["2 4 6\n4 7", "4 2 6\n1 3 2 3"]
|
1 second
|
["11.00000000000000000000", "5.00000000000000000000"]
|
NoteIn the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by $$$2$$$ each.
|
Java 8
|
standard input
|
[
"implementation",
"brute force",
"math"
] |
d6e44bd8ac03876cb03be0731f7dda3d
|
The first line contains three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \le n \le 10^{5}$$$, $$$1 \le k \le 10^{5}$$$, $$$1 \le m \le 10^{7}$$$) — the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^{6}$$$) — the initial powers of the superheroes in the cast of avengers.
| 1,700 |
Output a single number — the maximum final average power. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
b663fd54bedddb676f3b12017e0c7016
|
train_001.jsonl
|
1549208100
|
Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are $$$n$$$ superheroes in avengers team having powers $$$a_1, a_2, \ldots, a_n$$$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $$$1$$$. They can do at most $$$m$$$ operations. Also, on a particular superhero at most $$$k$$$ operations can be done.Can you help the avengers team to maximize the average power of their crew?
|
256 megabytes
|
import java.util.*;
public class AverageSuperheroGangPower
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
long k = scan.nextInt();
int m = scan.nextInt();
Long[] arr = new Long[n];
for(int i = 0; i < n; i++) arr[i] = (long) scan.nextInt();
Arrays.sort(arr);
Long[] sum = new Long[n];
sum[n-1] = arr[n-1];
for(int i = n-2; i >= 0; i--)
sum[i] = sum[i+1]+arr[i];
double ans = 0;
for(int i = 0; i < n; i++){
//remove i things
int x = m-i;
if(x < 0) continue;
long rest = sum[i]+Math.min(x,(n-i)*k);
ans = Math.max(rest/(double)(n-i), ans);
}
System.out.println(ans);
}
}
|
Java
|
["2 4 6\n4 7", "4 2 6\n1 3 2 3"]
|
1 second
|
["11.00000000000000000000", "5.00000000000000000000"]
|
NoteIn the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by $$$2$$$ each.
|
Java 8
|
standard input
|
[
"implementation",
"brute force",
"math"
] |
d6e44bd8ac03876cb03be0731f7dda3d
|
The first line contains three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \le n \le 10^{5}$$$, $$$1 \le k \le 10^{5}$$$, $$$1 \le m \le 10^{7}$$$) — the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^{6}$$$) — the initial powers of the superheroes in the cast of avengers.
| 1,700 |
Output a single number — the maximum final average power. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
9b6509145af856f25c206648bfffaa9f
|
train_001.jsonl
|
1549208100
|
Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are $$$n$$$ superheroes in avengers team having powers $$$a_1, a_2, \ldots, a_n$$$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $$$1$$$. They can do at most $$$m$$$ operations. Also, on a particular superhero at most $$$k$$$ operations can be done.Can you help the avengers team to maximize the average power of their crew?
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* #
*
* @author pttrung
*/
public class Main {
public static long MOD = 998244353;
static double[][][] dp;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int n = in.nextInt();
long k = in.nextInt();
int m = in.nextInt();
long[]data = new long[n];
long total = 0;
for(int i = 0; i < n; i++){
data[i] = in.nextInt();
total += data[i];
}
Arrays.sort(data);
double a = total + Long.min(k*(long)n, m);
a /= n;
double re = a;
for(int i = 0; i < n - 1 && m > 0; i++){
total -= data[i];
m--;
a = total + Long.min(k*(long)(n - i - 1) , m);
a /= (n - i - 1);
//out.println(a);
re = Math.max(re, a );
}
out.println(re);
out.close();
}
public static int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static int digit(long n) {
int result = 0;
while (n > 0) {
n /= 10;
result++;
}
return result;
}
public static double dist(long a, long b, long x, long y) {
double val = (b - a) * (b - a) + (x - y) * (x - y);
val = Math.sqrt(val);
double other = x * x + a * a;
other = Math.sqrt(other);
return val + other;
}
public static class Point implements Comparable<Point> {
int x, y;
public Point(int start, int end) {
this.x = start;
this.y = end;
}
@Override
public int hashCode() {
int hash = 5;
hash = 47 * hash + this.x;
hash = 47 * hash + this.y;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Point other = (Point) obj;
if (this.x != other.x) {
return false;
}
if (this.y != other.y) {
return false;
}
return true;
}
@Override
public int compareTo(Point o) {
return Integer.compare(x, o.x);
}
}
public static class FT {
long[] data;
FT(int n) {
data = new long[n];
}
public void update(int index, long value) {
while (index < data.length) {
data[index] += value;
index += (index & (-index));
}
}
public long get(int index) {
long result = 0;
while (index > 0) {
result += data[index];
index -= (index & (-index));
}
return result;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static long pow(long a, long b, long MOD) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2, MOD);
if (b % 2 == 0) {
return val * val % MOD;
} else {
return val * (val * a % MOD) % MOD;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
|
Java
|
["2 4 6\n4 7", "4 2 6\n1 3 2 3"]
|
1 second
|
["11.00000000000000000000", "5.00000000000000000000"]
|
NoteIn the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by $$$2$$$ each.
|
Java 8
|
standard input
|
[
"implementation",
"brute force",
"math"
] |
d6e44bd8ac03876cb03be0731f7dda3d
|
The first line contains three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \le n \le 10^{5}$$$, $$$1 \le k \le 10^{5}$$$, $$$1 \le m \le 10^{7}$$$) — the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^{6}$$$) — the initial powers of the superheroes in the cast of avengers.
| 1,700 |
Output a single number — the maximum final average power. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
95357c585e083dc9b223cd79e44e9c70
|
train_001.jsonl
|
1549208100
|
Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are $$$n$$$ superheroes in avengers team having powers $$$a_1, a_2, \ldots, a_n$$$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $$$1$$$. They can do at most $$$m$$$ operations. Also, on a particular superhero at most $$$k$$$ operations can be done.Can you help the avengers team to maximize the average power of their crew?
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class CodeForces {
class FastScanner {
StringTokenizer tok = new StringTokenizer("");
BufferedReader in;
FastScanner() {
in = new BufferedReader(new InputStreamReader(System.in));
}
String next() throws IOException {
while (!tok.hasMoreElements())
tok = new StringTokenizer(in.readLine());
return tok.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
}
public class NewSecondTask {
int n;
int k;
int m;
LinkedList<Integer> strengths = new LinkedList<>();
public void read() throws IOException {
FastScanner fastScanner = new FastScanner();
n = fastScanner.nextInt();
k = fastScanner.nextInt();
m = fastScanner.nextInt();
for (int i=0; i<n; i++) {
strengths.add(fastScanner.nextInt());
}
Collections.sort(strengths);
}
public double solve() {
long sum = sum();
double currentMax = (double)sum/strengths.size();
while (strengths.size() >=1 ) {
long addition = Math.min((long)k*n, m);
double tempMax = (double)(sum + addition)/strengths.size();
currentMax = Math.max(tempMax, currentMax);
n--;
m--;
if (m < 0) {
break;
}
int removedStrength = strengths.removeFirst();
sum-=removedStrength;
}
return currentMax;
}
public long sum() {
long sum = 0;
for (Integer strength: strengths) {
sum+=strength;
}
return sum;
}
}
public void run() throws IOException {
NewSecondTask newSecondTask = new NewSecondTask();
newSecondTask.read();
System.out.println(newSecondTask.solve());
}
static public void main(String[] args) throws IOException {
new CodeForces().run();
}
}
|
Java
|
["2 4 6\n4 7", "4 2 6\n1 3 2 3"]
|
1 second
|
["11.00000000000000000000", "5.00000000000000000000"]
|
NoteIn the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by $$$2$$$ each.
|
Java 8
|
standard input
|
[
"implementation",
"brute force",
"math"
] |
d6e44bd8ac03876cb03be0731f7dda3d
|
The first line contains three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \le n \le 10^{5}$$$, $$$1 \le k \le 10^{5}$$$, $$$1 \le m \le 10^{7}$$$) — the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^{6}$$$) — the initial powers of the superheroes in the cast of avengers.
| 1,700 |
Output a single number — the maximum final average power. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
a350d6c7b2d2e6c8fa66ab33dfdfc026
|
train_001.jsonl
|
1549208100
|
Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are $$$n$$$ superheroes in avengers team having powers $$$a_1, a_2, \ldots, a_n$$$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $$$1$$$. They can do at most $$$m$$$ operations. Also, on a particular superhero at most $$$k$$$ operations can be done.Can you help the avengers team to maximize the average power of their crew?
|
256 megabytes
|
// package trial;
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
InputReader s=new InputReader(System.in);
PrintWriter w=new PrintWriter(System.out);
int n,k,m;
n=s.nextInt();
k=s.nextInt();
m=s.nextInt();
Integer arr[]=new Integer[n];
for(int i=0;i<n;i++)
{
arr[i]=s.nextInt();
}
double suma[]=new double[n];
Arrays.sort(arr);
suma[n-1]=arr[n-1]*1.0;
for(int i=n-2;i>=0;i--)
{
suma[i]=suma[i+1]+arr[i];
}
double ans=0;
for(int i=n;i>=1;i--)
{
int j=n-1;
int tmp=i;
double sum=suma[n-i];
if(m-n+i>=0)
{
sum=sum+Math.min(m-n+(long)i,(long)i*k);
ans=Math.max(ans,(sum*1.0/i));
}
}
Formatter fmt = new Formatter();
fmt.format("%.20f", ans);
w.println(fmt);
w.close();
}
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 double nextDouble() //read double
{
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
double res = 0;
boolean dec = false;
int count = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
if (dec)
count--;
res *= 10;
res += c - '0';
c = snext();
if (c == '.') {
if (!dec) {
dec = true;
c = snext();
} else {
throw new InputMismatchException();
}
}
} while (!isSpaceChar(c));
res *= Math.pow(10, count);
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() { //considers space in same string
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
|
["2 4 6\n4 7", "4 2 6\n1 3 2 3"]
|
1 second
|
["11.00000000000000000000", "5.00000000000000000000"]
|
NoteIn the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by $$$2$$$ each.
|
Java 8
|
standard input
|
[
"implementation",
"brute force",
"math"
] |
d6e44bd8ac03876cb03be0731f7dda3d
|
The first line contains three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \le n \le 10^{5}$$$, $$$1 \le k \le 10^{5}$$$, $$$1 \le m \le 10^{7}$$$) — the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^{6}$$$) — the initial powers of the superheroes in the cast of avengers.
| 1,700 |
Output a single number — the maximum final average power. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
e01f3c472f15d5da80cabb6fefc9b714
|
train_001.jsonl
|
1549208100
|
Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are $$$n$$$ superheroes in avengers team having powers $$$a_1, a_2, \ldots, a_n$$$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $$$1$$$. They can do at most $$$m$$$ operations. Also, on a particular superhero at most $$$k$$$ operations can be done.Can you help the avengers team to maximize the average power of their crew?
|
256 megabytes
|
import java.util.Arrays;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class Solver {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
long k = s.nextInt();
long m = s.nextInt();
long[] a = new long[n];
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
}
// int n = 100000;
// long k = 25987;
// long m = 37;
//
// long[] a = new long[n];
// for (int i = 0; i < n; i++) {
// a[i] = ThreadLocalRandom.current().nextInt(0, 100000);
// }
Arrays.sort(a);
long sum = 0;
for (int i = 0; i < n; i++) {
sum += a[i];
}
double result = 0;
for (int i = 0; i < Math.min(n, m + 1); i++) {
long added = Math.min(k * (n - i), m - i);
double average = 1.0 * (sum + added) / (n - i);
if (average > result) {
result = average;
}
sum -= a[i];
}
System.out.println(result);
}
}
|
Java
|
["2 4 6\n4 7", "4 2 6\n1 3 2 3"]
|
1 second
|
["11.00000000000000000000", "5.00000000000000000000"]
|
NoteIn the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by $$$2$$$ each.
|
Java 8
|
standard input
|
[
"implementation",
"brute force",
"math"
] |
d6e44bd8ac03876cb03be0731f7dda3d
|
The first line contains three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \le n \le 10^{5}$$$, $$$1 \le k \le 10^{5}$$$, $$$1 \le m \le 10^{7}$$$) — the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^{6}$$$) — the initial powers of the superheroes in the cast of avengers.
| 1,700 |
Output a single number — the maximum final average power. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
6402772f08a0a43367f26a591c38879f
|
train_001.jsonl
|
1549208100
|
Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are $$$n$$$ superheroes in avengers team having powers $$$a_1, a_2, \ldots, a_n$$$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $$$1$$$. They can do at most $$$m$$$ operations. Also, on a particular superhero at most $$$k$$$ operations can be done.Can you help the avengers team to maximize the average power of their crew?
|
256 megabytes
|
import java.math.*;
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer stk = new StringTokenizer(br.readLine());
int n = Integer.parseInt(stk.nextToken());
long k = Integer.parseInt(stk.nextToken());
int m =Integer.parseInt(stk.nextToken());
stk = new StringTokenizer(br.readLine());
int[] arr = new int[n];
for(int i=0;i<n;i++){
arr[i] = Integer.parseInt(stk.nextToken());
}
Arrays.sort(arr);
long[] psum = new long[n+1];
for(int i=1;i<=n;i++){
psum[i] = psum[i-1] + arr[i-1];
}
double max=0;
for(int i=1;i<=n;i++){
long d = Math.min(k*(n-i+1),m-(i-1));
if(d<0) continue;
long sum = getSum(i,n,psum);
max = Math.max(max,(double)(sum+d)/(n-i+1));
}
System.out.println(max);
}
public static long getSum(int l,int r,long[] psum){
return psum[r] - psum[l-1];
}
}
|
Java
|
["2 4 6\n4 7", "4 2 6\n1 3 2 3"]
|
1 second
|
["11.00000000000000000000", "5.00000000000000000000"]
|
NoteIn the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by $$$2$$$ each.
|
Java 8
|
standard input
|
[
"implementation",
"brute force",
"math"
] |
d6e44bd8ac03876cb03be0731f7dda3d
|
The first line contains three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \le n \le 10^{5}$$$, $$$1 \le k \le 10^{5}$$$, $$$1 \le m \le 10^{7}$$$) — the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^{6}$$$) — the initial powers of the superheroes in the cast of avengers.
| 1,700 |
Output a single number — the maximum final average power. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
f53ab0977649df4bf2c054bba7bb2900
|
train_001.jsonl
|
1549208100
|
Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are $$$n$$$ superheroes in avengers team having powers $$$a_1, a_2, \ldots, a_n$$$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $$$1$$$. They can do at most $$$m$$$ operations. Also, on a particular superhero at most $$$k$$$ operations can be done.Can you help the avengers team to maximize the average power of their crew?
|
256 megabytes
|
/*Author: Satyajeet Singh, Delhi Technological University*/
import java.io.*;
import java.util.*;
import java.text.*;
import java.lang.*;
public class Main {
/*********************************************Constants******************************************/
static PrintWriter out=new PrintWriter(new OutputStreamWriter(System.out));
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static long mod=(long)1e9+7;
static long mod1=998244353;
static boolean sieve[];
static ArrayList<Integer> primes;
static ArrayList<Long> factorial;
static HashSet<Integer> graph[];
/****************************************Solutions Begins***************************************************/
public static void main (String[] args) throws Exception {
String st[]=br.readLine().split(" ");
int n=Integer.parseInt(st[0]);
int k=Integer.parseInt(st[1]);
int m=Integer.parseInt(st[2]);
st=br.readLine().split(" ");
Long input[]=new Long[n];
for(int i=0;i<n;i++){
input[i]=Long.parseLong(st[i]);
}
Arrays.sort(input);
Long dp[]=new Long[n];
dp[0]=input[0];
for(int i=1;i<n;i++){
dp[i]=dp[i-1]+input[i];
}
long prev=0;
double ans=0;
//debug(dp);
for(int i=0;i<=Math.min(n-1,m);i++){
long add=Math.min((long)((long)k*(n-i)),m-i);
double nans=dp[n-1]-prev+add;
nans=nans/(n-i);
//out.println(nans);
ans=Math.max(nans,ans);
prev=dp[i];
}
out.println(ans);
/****************************************Solutions Ends*****************************************************/
out.flush();
out.close();
}
/****************************************Template Begins***************************************************/
/***************************************Precision Printing************************************************/
static void printPrecision(double d){
DecimalFormat ft = new DecimalFormat("0.000000");
out.println(ft.format(d));
}
/******************************************Graph***********************************************************/
/* static void Makegraph(int n){
graph=new HashSet[n];
for(int i=0;i<n;i++){
graph[i]=new HashSet<>();
}
}*/
static void addEdge(int a,int b){
graph[a].add(b);
}
/*******************************************TRIPLET********************************************************/
static class tripletComparator implements Comparator<triplet>{
public int compare(triplet p1,triplet p2){
if(p1.u<p2.u){
return 1;
}
else if(p1.u>p2.u){
return -1;
}
else{
return 0;
}
}
}
static class triplet{
int u;
int v;
int i;
public triplet(int u,int v,int i){
this.u=u;
this.v=v;
this.i=i;
}
public String toString() {
return "[u=" + u + ", v=" + v + ", i="+i+"]";
}
}
/*********************************************PAIR**********************************************************/
static class PairComp implements Comparator<Pair>{
public int compare(Pair p1,Pair p2){
if(p1.u>p2.u){
return 1;
}
else if(p1.u<p2.u){
return -1;
}
else{
return p1.v-p2.v;
}
}
}
static class Pair implements Comparable<Pair> {
int u;
int v;
int index=-1;
public Pair(int u, int v) {
this.u = u;
this.v = v;
}
public int hashCode() {
int hu = (int) (u ^ (u >>> 32));
int hv = (int) (v ^ (v >>> 32));
return 31 * hu + hv;
}
public boolean equals(Object o) {
Pair other = (Pair) o;
return u == other.u && v == other.v;
}
public int compareTo(Pair other) {
if(index!=other.index)
return Long.compare(index, other.index);
return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u);
}
public String toString() {
return "[u=" + u + ", v=" + v + "]";
}
}
/*******************************************LONG PAIR******************************************************/
static class PairCompL implements Comparator<Pairl>{
public int compare(Pairl p1,Pairl p2){
if(p1.u>p2.u){
return 1;
}
else if(p1.u<p2.u){
return -1;
}
else{
return 0;
}
}
}
static class Pairl implements Comparable<Pair> {
long u;
long v;
int index=-1;
public Pairl(long u, long v) {
this.u = u;
this.v = v;
}
public int hashCode() {
int hu = (int) (u ^ (u >>> 32));
int hv = (int) (v ^ (v >>> 32));
return 31 * hu + hv;
}
public boolean equals(Object o) {
Pair other = (Pair) o;
return u == other.u && v == other.v;
}
public int compareTo(Pair other) {
if(index!=other.index)
return Long.compare(index, other.index);
return Long.compare(v, other.v)!=0?Long.compare(v, other.v):Long.compare(u, other.u);
}
public String toString() {
return "[u=" + u + ", v=" + v + "]";
}
}
/*****************************************DEBUG***********************************************************/
public static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
/*****************************************NUMBER THEORY****************************************************/
/************************************MODULAR EXPONENTIATION***********************************************/
static long modulo(long a,long b,long c) {
long x=1;
long y=a;
while(b > 0){
if(b%2 == 1){
x=(x*y)%c;
}
y = (y*y)%c; // squaring the base
b /= 2;
}
return x%c;
}
/********************************************GCD**********************************************************/
static long gcd(long x, long y)
{
if(x==0)
return y;
if(y==0)
return x;
long r=0, a, b;
a = (x > y) ? x : y; // a is greater number
b = (x < y) ? x : y; // b is smaller number
r = b;
while(a % b != 0)
{
r = a % b;
a = b;
b = r;
}
return r;
}
/******************************************SIEVE**********************************************************/
static void sieveMake(int n){
sieve=new boolean[n];
Arrays.fill(sieve,true);
sieve[0]=false;
sieve[1]=false;
for(int i=2;i*i<n;i++){
if(sieve[i]){
for(int j=i*i;j<n;j+=i){
sieve[j]=false;
}
}
}
primes=new ArrayList<Integer>();
for(int i=0;i<n;i++){
if(sieve[i]){
primes.add(i);
}
}
}
/***************************************FACTORIAL*********************************************************/
static void fact(int n){
factorial=new ArrayList<>();
factorial.add((long)1);
for(int i=1;i<=n;i++){
factorial.add((factorial.get(i-1)*i)%mod);
}
}
/*******************************************ncr*********************************************************/
static long ncr(int n,int k){
long aa=modulo(factorial.get(n-k),mod-2,mod);
long bb=modulo(factorial.get(k),mod-2,mod);
long cc=factorial.get(n);
long ans=(aa*cc)%mod;
ans=(ans*bb)%mod;
return ans;
}
/***************************************STRING REVERSE****************************************************/
static String reverse(String str){
char r[]=new char[str.length()];
int j=0;
for(int i=str.length()-1;i>=0;i--){
r[j]=str.charAt(i);
j++;
}
return new String(r);
}
}
/********************************************End***********************************************************/
|
Java
|
["2 4 6\n4 7", "4 2 6\n1 3 2 3"]
|
1 second
|
["11.00000000000000000000", "5.00000000000000000000"]
|
NoteIn the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by $$$2$$$ each.
|
Java 8
|
standard input
|
[
"implementation",
"brute force",
"math"
] |
d6e44bd8ac03876cb03be0731f7dda3d
|
The first line contains three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \le n \le 10^{5}$$$, $$$1 \le k \le 10^{5}$$$, $$$1 \le m \le 10^{7}$$$) — the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^{6}$$$) — the initial powers of the superheroes in the cast of avengers.
| 1,700 |
Output a single number — the maximum final average power. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
68a8f41f3cb00e622e368ee70cebadfa
|
train_001.jsonl
|
1549208100
|
Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are $$$n$$$ superheroes in avengers team having powers $$$a_1, a_2, \ldots, a_n$$$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $$$1$$$. They can do at most $$$m$$$ operations. Also, on a particular superhero at most $$$k$$$ operations can be done.Can you help the avengers team to maximize the average power of their crew?
|
256 megabytes
|
import java.util.Arrays;
import java.util.Scanner;
public class AverageSuperheroGangPower {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long k = sc.nextInt();
long m = sc.nextInt();
long sum = 0;
long num;
sc.nextLine();
long [] input = new long[n];
for (int i = 0; i < n; i++) {
num = sc.nextInt();
input[i] = num;
sum+= num;
}
Arrays.sort(input);
double maxAv = (sum + Math.min((double)k*n, (double)m))/n;
long tempSum = sum;
for (int i = 0; i < m && i<input.length-1; i++) {
// System.out.println("REMOVE");
tempSum -= input[i];
int count = n-i-1;
long x = tempSum + Math.min(k*count, m-(i+1));
if(count>0)
maxAv = Math.max(maxAv,(double)x/(double)count );
}
System.out.println(maxAv);
}
}
|
Java
|
["2 4 6\n4 7", "4 2 6\n1 3 2 3"]
|
1 second
|
["11.00000000000000000000", "5.00000000000000000000"]
|
NoteIn the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by $$$2$$$ each.
|
Java 8
|
standard input
|
[
"implementation",
"brute force",
"math"
] |
d6e44bd8ac03876cb03be0731f7dda3d
|
The first line contains three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \le n \le 10^{5}$$$, $$$1 \le k \le 10^{5}$$$, $$$1 \le m \le 10^{7}$$$) — the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^{6}$$$) — the initial powers of the superheroes in the cast of avengers.
| 1,700 |
Output a single number — the maximum final average power. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
152caef7968a5a58b9baaa5b91b28569
|
train_001.jsonl
|
1549208100
|
Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are $$$n$$$ superheroes in avengers team having powers $$$a_1, a_2, \ldots, a_n$$$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $$$1$$$. They can do at most $$$m$$$ operations. Also, on a particular superhero at most $$$k$$$ operations can be done.Can you help the avengers team to maximize the average power of their crew?
|
256 megabytes
|
/*
⣿⣿⣿⣿⣿⣿⡷⣯⢿⣿⣷⣻⢯⣿⡽⣻⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣇⠸⣿⣿⣆⠹⣿⣿⢾⣟⣯⣿⣿⣿⣿⣿⣿⣽⣻⣿⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣻⣽⡿⣿⣎⠙⣿⣞⣷⡌⢻⣟⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣿⣿⣿⣿⣿⣿⡄⠹⣿⣿⡆⠻⣿⣟⣯⡿⣽⡿⣿⣿⣿⣿⣽⡷⣯⣿⣿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣟⣷⣿⣿⣿⡀⠹⣟⣾⣟⣆⠹⣯⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⢠⡘⣿⣿⡄⠉⢿⣿⣽⡷⣿⣻⣿⣿⣿⣿⡝⣷⣯⢿⣿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣯⢿⣾⢿⣿⡄⢄⠘⢿⣞⡿⣧⡈⢷⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⢸⣧⠘⣿⣷⠈⣦⠙⢿⣽⣷⣻⣽⣿⣿⣿⣿⣌⢿⣯⢿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⣟⣯⣿⢿⣿⡆⢸⡷⡈⢻⡽⣷⡷⡄⠻⣽⣿⣿⡿⣿⣿⣿⣿⣿⣿⣷⣿⣿⣿⣿⣏⢰⣯⢷⠈⣿⡆⢹⢷⡌⠻⡾⢋⣱⣯⣿⣿⣿⣿⡆⢻⡿⣿⣿⣿
⣿⣿⣿⣿⣿⣿⡎⣿⢾⡿⣿⡆⢸⣽⢻⣄⠹⣷⣟⣿⣄⠹⣟⣿⣿⣟⣿⣿⣿⣿⣿⣿⣽⣿⣿⣿⡇⢸⣯⣟⣧⠘⣷⠈⡯⠛⢀⡐⢾⣟⣷⣻⣿⣿⣿⡿⡌⢿⣻⣿⣿
⣿⣿⣿⣿⣿⣿⣧⢸⡿⣟⣿⡇⢸⣯⣟⣮⢧⡈⢿⣞⡿⣦⠘⠏⣹⣿⣽⢿⣿⣿⣿⣿⣯⣿⣿⣿⡇⢸⣿⣿⣾⡆⠹⢀⣠⣾⣟⣷⡈⢿⣞⣯⢿⣿⣿⣿⢷⠘⣯⣿⣿
⣿⣿⣿⣿⣿⣿⣿⡈⣿⢿⣽⡇⠘⠛⠛⠛⠓⠓⠈⠛⠛⠟⠇⢀⢿⣻⣿⣯⢿⣿⣿⣿⣷⢿⣿⣿⠁⣾⣿⣿⣿⣧⡄⠇⣹⣿⣾⣯⣿⡄⠻⣽⣯⢿⣻⣿⣿⡇⢹⣾⣿
⣿⣿⣿⣿⣿⣿⣿⡇⢹⣿⡽⡇⢸⣿⣿⣿⣿⣿⣞⣆⠰⣶⣶⡄⢀⢻⡿⣯⣿⡽⣿⣿⣿⢯⣟⡿⢀⣿⣿⣿⣿⣿⣧⠐⣸⣿⣿⣷⣿⣿⣆⠹⣯⣿⣻⣿⣿⣿⢀⣿⢿
⣿⣿⣿⣿⣿⣿⣿⣿⠘⣯⡿⡇⢸⣿⣿⣿⣿⣿⣿⣿⣧⡈⢿⣳⠘⡄⠻⣿⢾⣽⣟⡿⣿⢯⣿⡇⢸⣿⣿⣿⣿⣿⣿⡀⢾⣿⣿⣿⣿⣿⣿⣆⠹⣾⣷⣻⣿⡿⡇⢸⣿
⣿⣿⣿⣿⣿⣿⣿⣿⡇⢹⣿⠇⢸⣿⣿⣿⣿⣿⣿⣿⣿⣷⣄⠻⡇⢹⣆⠹⣟⣾⣽⣻⣟⣿⣽⠁⣾⣿⣿⣿⣿⣿⣿⣇⣿⣿⠿⠛⠛⠉⠙⠋⢀⠁⢘⣯⣿⣿⣧⠘⣿
⣿⣿⣿⣿⣿⣿⣿⣿⣿⡈⣿⡃⢼⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣦⡙⠌⣿⣆⠘⣿⣞⡿⣞⡿⡞⢠⣿⣿⣿⣿⣿⡿⠛⠉⠁⢀⣀⣠⣤⣤⣶⣶⣶⡆⢻⣽⣞⡿⣷⠈⣿
⣿⣿⣿⣿⣿⣿⣿⣿⡿⠃⠘⠁⠉⠉⠉⠉⠉⠉⠉⠉⠉⠙⠛⠛⢿⣄⢻⣿⣧⠘⢯⣟⡿⣽⠁⣾⣿⣿⣿⣿⣿⡃⢀⢀⠘⠛⠿⢿⣻⣟⣯⣽⣻⣵⡀⢿⣯⣟⣿⢀⣿
⣿⣿⣿⣟⣿⣿⣿⣿⣶⣶⡆⢀⣿⣾⣿⣾⣷⣿⣶⠿⠚⠉⢀⢀⣤⣿⣷⣿⣿⣷⡈⢿⣻⢃⣼⣿⣿⣿⣿⣻⣿⣿⣿⡶⣦⣤⣄⣀⡀⠉⠛⠛⠷⣯⣳⠈⣾⡽⣾⢀⣿
⣿⢿⣿⣿⣻⣿⣿⣿⣿⣿⡿⠐⣿⣿⣿⣿⠿⠋⠁⢀⢀⣤⣾⣿⣿⣿⣿⣿⣿⣿⣿⣌⣥⣾⡿⣿⣿⣷⣿⣿⢿⣷⣿⣿⣟⣾⣽⣳⢯⣟⣶⣦⣤⡾⣟⣦⠘⣿⢾⡁⢺
⣿⣻⣿⣿⡷⣿⣿⣿⣿⣿⡗⣦⠸⡿⠋⠁⢀⢀⣠⣴⢿⣿⣽⣻⢽⣾⣟⣷⣿⣟⣿⣿⣿⣳⠿⣵⣧⣼⣿⣿⣿⣿⣿⣾⣿⣿⣿⣿⣿⣽⣳⣯⣿⣿⣿⣽⢀⢷⣻⠄⠘
⣿⢷⣻⣿⣿⣷⣻⣿⣿⣿⡷⠛⣁⢀⣀⣤⣶⣿⣛⡿⣿⣮⣽⡻⣿⣮⣽⣻⢯⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣯⢀⢸⣿⢀⡆
⠸⣟⣯⣿⣿⣷⢿⣽⣿⣿⣷⣿⣷⣆⠹⣿⣶⣯⠿⣿⣶⣟⣻⢿⣷⣽⣻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⢀⣯⣟⢀⡇
⣇⠹⣟⣾⣻⣿⣿⢾⡽⣿⣿⣿⣿⣿⣆⢹⣶⣿⣻⣷⣯⣟⣿⣿⣽⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⢀⡿⡇⢸⡇
⣿⣆⠹⣷⡻⣽⣿⣯⢿⣽⣻⣿⣿⣿⣿⣆⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠛⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⢸⣿⠇⣼⡇
⡙⠾⣆⠹⣿⣦⠛⣿⢯⣷⢿⡽⣿⣿⣿⣿⣆⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠃⠎⢸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠏⢀⣿⣾⣣⡿⡇
⣿⣷⡌⢦⠙⣿⣿⣌⠻⣽⢯⣿⣽⣻⣿⣿⣿⣧⠩⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡏⢰⢣⠘⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠃⢀⢀⢿⣞⣷⢿⡇
⣿⣽⣆⠹⣧⠘⣿⣿⡷⣌⠙⢷⣯⡷⣟⣿⣿⣿⣷⡀⡹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣷⣈⠃⣸⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠟⢀⣴⡧⢀⠸⣿⡽⣿⢀
⢻⣽⣿⡄⢻⣷⡈⢿⣿⣿⢧⢀⠙⢿⣻⡾⣽⣻⣿⣿⣄⠌⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠛⢁⣰⣾⣟⡿⢀⡄⢿⣟⣿⢀
⡄⢿⣿⣷⢀⠹⣟⣆⠻⣿⣿⣆⢀⣀⠉⠻⣿⡽⣯⣿⣿⣷⣈⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⢀⣠⠘⣯⣷⣿⡟⢀⢆⠸⣿⡟⢸
⣷⡈⢿⣿⣇⢱⡘⢿⣷⣬⣙⠿⣧⠘⣆⢀⠈⠻⣷⣟⣾⢿⣿⣆⠹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠋⣠⡞⢡⣿⢀⣿⣿⣿⠇⡄⢸⡄⢻⡇⣼
⣿⣷⡈⢿⣿⡆⢣⡀⠙⢾⣟⣿⣿⣷⡈⠂⠘⣦⡈⠿⣯⣿⢾⣿⣆⠙⠻⠿⠿⠿⠿⡿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠛⢋⣠⣾⡟⢠⣿⣿⢀⣿⣿⡟⢠⣿⢈⣧⠘⢠⣿
⣿⣿⣿⣄⠻⣿⡄⢳⡄⢆⡙⠾⣽⣿⣿⣆⡀⢹⡷⣄⠙⢿⣿⡾⣿⣆⢀⡀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⢀⣀⣠⣴⡿⣯⠏⣠⣿⣿⡏⢸⣿⡿⢁⣿⣿⢀⣿⠆⢸⣿
⣿⣿⣿⣿⣦⡙⣿⣆⢻⡌⢿⣶⢤⣉⣙⣿⣷⡀⠙⠽⠷⠄⠹⣿⣟⣿⣆⢙⣋⣤⣤⣤⣄⣀⢀⢀⢀⢀⣾⣿⣟⡷⣯⡿⢃⣼⣿⣿⣿⠇⣼⡟⣡⣿⣿⣿⢀⡿⢠⠈⣿
⣿⣿⣿⣿⣿⣷⣮⣿⣿⣿⡌⠁⢤⣤⣤⣤⣬⣭⣴⣶⣶⣶⣆⠈⢻⣿⣿⣆⢻⣿⣿⣿⣿⣿⣿⣷⣶⣤⣌⣉⡘⠛⠻⠶⣿⣿⣿⣿⡟⣰⣫⣴⣿⣿⣿⣿⠄⣷⣿⣿⣿
*/
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class b {
public static void main(String[] args) throws Exception {
Scanner s=new Scanner(System.in);
int n=s.nextInt();
double k=s.nextDouble();
double m=s.nextDouble();
Double[] arr=new Double[n];
for(int i=0;i<n;i++) {
arr[i]=s.nextDouble();
}
Arrays.sort(arr);
double pre[]=new double[n];
pre[0]=arr[0];
for(int i=1;i<n;i++) {
pre[i]=pre[i-1]+arr[i];
}
double max=Long.MIN_VALUE;
double ans=0;
for(int i=-1;i<n-1;i++) {
//System.out.println(max);
ans=0;
if(m>=i+1) {
if(i!=-1)
ans=pre[n-1]-pre[i];
else
ans=pre[n-1];
ans=(ans+(double)Math.min(k*((double)n-(double)i-1d), m-(double)i-1d))/(double)((double)n-(double)i-1d);
max=Math.max(ans, max);
}else {
break;
}
}
System.out.println(max);
}
}
|
Java
|
["2 4 6\n4 7", "4 2 6\n1 3 2 3"]
|
1 second
|
["11.00000000000000000000", "5.00000000000000000000"]
|
NoteIn the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by $$$2$$$ each.
|
Java 8
|
standard input
|
[
"implementation",
"brute force",
"math"
] |
d6e44bd8ac03876cb03be0731f7dda3d
|
The first line contains three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \le n \le 10^{5}$$$, $$$1 \le k \le 10^{5}$$$, $$$1 \le m \le 10^{7}$$$) — the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^{6}$$$) — the initial powers of the superheroes in the cast of avengers.
| 1,700 |
Output a single number — the maximum final average power. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
272e04b46bb416d045742eaf51a3721f
|
train_001.jsonl
|
1549208100
|
Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are $$$n$$$ superheroes in avengers team having powers $$$a_1, a_2, \ldots, a_n$$$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $$$1$$$. They can do at most $$$m$$$ operations. Also, on a particular superhero at most $$$k$$$ operations can be done.Can you help the avengers team to maximize the average power of their crew?
|
256 megabytes
|
import java.io.*;
import java.util.Arrays;
public class Main {
private static final boolean FROM_FILE = false;
private static final boolean TO_FILE = false;
public static void main(String[] args) throws IOException {
BufferedReader br;
if (FROM_FILE) {
br = new BufferedReader(new FileReader("C:/home/programming/input.txt"));
} else {
br = new BufferedReader(new InputStreamReader(System.in));
}
PrintWriter pw;
if (TO_FILE) {
pw = new PrintWriter("C:/home/programming/output.txt");
} else {
pw = new PrintWriter(System.out);
}
// Algorithm:
String[] line = br.readLine().split(" ");
int n = Integer.parseInt(line[0]);
int k = Integer.parseInt(line[1]);
int m = Integer.parseInt(line[2]);
line = br.readLine().split(" ");
int [] a = new int[n];
long total = 0;
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(line[i]);
total += a[i];
}
Arrays.sort(a);
double max = (total + 1.0D * Math.min(m, ((long) k) * n)) / n;
for (int i = 0; i < Math.min(n - 1, m); i++) {
total -= a[i];
int countLeft = n - i - 1;
double currentMax = (total + 1.0D * Math.min(m - (i + 1), (long) k * countLeft)) / countLeft;
if (currentMax > max) {
max = currentMax;
}
}
pw.println(max);
pw.flush();
}
}
|
Java
|
["2 4 6\n4 7", "4 2 6\n1 3 2 3"]
|
1 second
|
["11.00000000000000000000", "5.00000000000000000000"]
|
NoteIn the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by $$$2$$$ each.
|
Java 8
|
standard input
|
[
"implementation",
"brute force",
"math"
] |
d6e44bd8ac03876cb03be0731f7dda3d
|
The first line contains three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \le n \le 10^{5}$$$, $$$1 \le k \le 10^{5}$$$, $$$1 \le m \le 10^{7}$$$) — the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^{6}$$$) — the initial powers of the superheroes in the cast of avengers.
| 1,700 |
Output a single number — the maximum final average power. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
a83f0a33478f7c5f4d1b85c0b6d107de
|
train_001.jsonl
|
1549208100
|
Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are $$$n$$$ superheroes in avengers team having powers $$$a_1, a_2, \ldots, a_n$$$, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by $$$1$$$. They can do at most $$$m$$$ operations. Also, on a particular superhero at most $$$k$$$ operations can be done.Can you help the avengers team to maximize the average power of their crew?
|
256 megabytes
|
import java.util.*;
public class main{
static int MAX = 100010;
static long MOD = 1000000007;
static ArrayList<Integer>[] amp;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), k = sc.nextInt(), m = sc.nextInt();//, b = sc.nextInt();
int arr[] = new int[n];
long sum = 0;
for(int i = 0;i < n; i++){
arr[i] = sc.nextInt();
sum += arr[i];
}
int temp = m;
double ans = (Math.min(n*1l*k,m) + sum + 0.0)/n;
arr = radixSort(arr);
long pre[] = new long[n];
pre[n-1] = arr[n-1];
for(int i = n-2;i>=0;i--){
pre[i] = pre[i+1] + arr[i];
}
for(int i = 1;i<n;i++){
m--;
if(m<0) break;
double ans2 = pre[i] + Math.min((n-i)*1l*k, m);
ans2 /= (n-i);
ans = Math.max(ans,ans2);
//System.out.println(ans);
}
System.out.println(ans);
}
static long pow(long x, int y, long mod){
long ans = 1;
while(y>0){
if(y%2==0){
x *= x;
x %= mod;
y/=2;
}
else{
y-=1;
ans *= x;
ans %= mod;
}
}
return ans;
}
class Pair{
int x, y;
Pair(int a, int b){
x = a; y = b;
}
}
public static int[] radixSort(int[] f){ return radixSort(f, f.length); }
public static int[] radixSort(int[] f, int n)
{
int[] to = new int[n];
{
int[] b = new int[65537];
for(int i = 0;i < n;i++)b[1+(f[i]&0xffff)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < n;i++)to[b[f[i]&0xffff]++] = f[i];
int[] d = f; f = to;to = d;
}
{
int[] b = new int[65537];
for(int i = 0;i < n;i++)b[1+(f[i]>>>16)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < n;i++)to[b[f[i]>>>16]++] = f[i];
int[] d = f; f = to;to = d;
}
return f;
}
}
|
Java
|
["2 4 6\n4 7", "4 2 6\n1 3 2 3"]
|
1 second
|
["11.00000000000000000000", "5.00000000000000000000"]
|
NoteIn the first example, the maximum average is obtained by deleting the first element and increasing the second element four times.In the second sample, one of the ways to achieve maximum average is to delete the first and the third element and increase the second and the fourth elements by $$$2$$$ each.
|
Java 8
|
standard input
|
[
"implementation",
"brute force",
"math"
] |
d6e44bd8ac03876cb03be0731f7dda3d
|
The first line contains three integers $$$n$$$, $$$k$$$ and $$$m$$$ ($$$1 \le n \le 10^{5}$$$, $$$1 \le k \le 10^{5}$$$, $$$1 \le m \le 10^{7}$$$) — the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations. The second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^{6}$$$) — the initial powers of the superheroes in the cast of avengers.
| 1,700 |
Output a single number — the maximum final average power. Your answer is considered correct if its absolute or relative error does not exceed $$$10^{-6}$$$. Formally, let your answer be $$$a$$$, and the jury's answer be $$$b$$$. Your answer is accepted if and only if $$$\frac{|a - b|}{\max{(1, |b|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
e6096141e126336d37a9d62ec057bea2
|
train_001.jsonl
|
1412609400
|
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si). After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
|
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.HashMap;
import java.util.StringTokenizer;
public class F474 {
BufferedReader br;
StringTokenizer in;
PrintWriter out;
public String nextToken() throws IOException {
while (in == null || !in.hasMoreTokens()) {
in = new StringTokenizer(br.readLine());
}
return in.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
public double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
public void solve() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
int n = nextInt();
HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer,ArrayList<Integer>>();
int [] values = new int[n];
for(int i = 0 ; i < values.length ; i++) {
values[i] = nextInt();
if(!map.containsKey(values[i])) {
ArrayList<Integer> t = new ArrayList<Integer>();
t.add(-1);
map.put(values[i], t);
}
ArrayList<Integer> temp = map.get(values[i]);
temp.add(i+1);
}
STree st = new STree(values);
int t = nextInt();
for(int i = 0 ; i < t ; i++) {
int l = nextInt();
int r = nextInt();
int min = st.query(1, 1, n, l, r, true);
int gcd = st.query(1, 1, n, l, r, false);
if(min != gcd) {
out.println(r - l + 1);
} else {
int count = 0;
if(map.containsKey(min)) {
ArrayList<Integer> temp = map.get(min);
if(temp.get(temp.size() -1 ) != Integer.MAX_VALUE)
temp.add(Integer.MAX_VALUE);
int val1 = binarySearchA(temp,l,l,r);
int val2 = binarySearchB(temp,r,l,r);
if(val1 > val2)
count = 0;
else
count = val2 - val1 + 1;
}
out.println(r - l + 1 - count);
}
}
out.close();
}
public static void main (String [] args) throws IOException {
new F474().solve();
}
public static int binarySearchA(ArrayList<Integer> values, int val, int a, int b) {
int l = 0;
int r = values.size()-1;
while(l < r) {
int middle = (l + r) >> 1;
if(values.get(middle) >= val && values.get(middle-1) < val)
return middle;
else
if(values.get(middle) == val)
return middle;
if(values.get(middle) > val)
r = middle;
else
l = middle + 1;
if(l == r-1) {
if(values.get(l) > val)
return l;
if(values.get(r) < val)
return r+1;
if(values.get(l) < val)
return r;
if(values.get(r) > val)
return l;
}
}
return l;
}
public static int binarySearchB(ArrayList<Integer> values, int val, int a, int b) {
int l = 0;
int r = values.size()-1;
while(l < r) {
int middle = (l + r) >> 1;
if(values.get(middle) <= val && values.get(middle+1) > val)
return middle;
else
if(values.get(middle) == val)
return middle;
if(values.get(middle) > val)
r = middle - 1;
else
l = middle;
if(l == r-1) {
if(values.get(l) > val)
return l-1;
if(values.get(r) < val)
return r;
if(values.get(l) < val)
return r;
if(values.get(r) > val)
return l;
}
}
return l;
}
public class STree {
int size;
int[] values;
int[] min;
int[] gcd;
public STree(int [] values) {
this(values.length);
for(int i = 1 ; i < this.values.length ; i++)
this.values[i] = values[i-1];
buildMinTree(1,1,values.length);
buildGCDTree(1,1,values.length);
}
public STree(int size) {
this.size = size;
values = new int[size+1];
min = new int[size<<2];
gcd = new int[size<<2];
}
public void buildMinTree(int nodeId, int lower, int upper) {
if(lower == upper) {
min[nodeId] = values[lower];
} else {
int nextNode = nodeId << 1;
int mid = (lower + upper) >> 1;
buildMinTree(nextNode,lower,mid);
buildMinTree(nextNode|1,mid+1,upper);
min[nodeId] = Math.min(min[nextNode], min[nextNode|1]);
}
}
public void buildGCDTree(int nodeId, int lower, int upper) {
if(lower == upper && lower < values.length) {
gcd[nodeId] = values[lower];
} else {
int nextNode = nodeId << 1;
int mid = (lower + upper) >> 1;
buildGCDTree(nextNode,lower,mid);
buildGCDTree(nextNode|1,mid+1,upper);
gcd[nodeId] = gcd(gcd[nextNode], gcd[nextNode|1]);
}
}
public int getValue(int index) {
return this.values[index];
}
public int query(int nodeId, int lower, int upper, int queryLower, int queryUpper, boolean isMin) {
if(queryLower > upper || queryUpper < lower)
return -1;
if(queryLower <= lower && queryUpper >= upper) {
if(isMin)
return min[nodeId];
else
return gcd[nodeId];
}
int nextNode = nodeId << 1;
int mid = (lower + upper) / 2;
int val1 = query(nextNode, lower, mid, queryLower, queryUpper, isMin);
int val2 = query(nextNode|1, mid+1, upper, queryLower, queryUpper, isMin);
if(val1 == -1)
return val2;
if(val2 == -1)
return val1;
if(isMin) {
if(val1 < val2)
return val1;
else
return val2;
}else {
return gcd(val1,val2);
}
}
public int gcd(int m, int n) {
if(m == 0)
return n;
if(m == 1)
return 1;
return gcd(n % m , m);
}
}
}
|
Java
|
["5\n1 3 2 4 2\n4\n1 5\n2 5\n3 5\n4 5"]
|
1 second
|
["4\n4\n1\n1"]
|
NoteIn the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4.
|
Java 7
|
standard input
|
[
"data structures",
"number theory",
"math"
] |
f7f1d57921fe7b7a697967dcfc8f0169
|
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony. The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants. The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases. Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
| 2,100 |
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
|
standard output
| |
PASSED
|
a381bd5f0d998c0ecbee202156cb3852
|
train_001.jsonl
|
1412609400
|
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si). After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main {
static int min[];
static int cnt[];
static int strength[];
static int GCD(int a, int b){
if (a < b){
int temp = a;
a = b;
b = temp;
}
if(b == 0)return a;
return GCD(b,a%b);
}
public static void main(String [] args)throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
min = new int[4*n + 1];
cnt = new int[4*n + 1];
strength = new int[n];
StringTokenizer st = new StringTokenizer(br.readLine());
for(int i = 0;i<n;i++)
strength[i] = Integer.parseInt(st.nextToken());
buildtree(1,0,n - 1);
int t = Integer.parseInt(br.readLine());
StringBuilder sb = new StringBuilder();
int logmax = (int)(Math.log(n)/Math.log(2)) + 1;
int findMin[][] = new int [n][logmax];
int gcd [][] = new int[n][logmax];
for(int i = 0;i<n;i++){
findMin[i][0] = gcd[i][0] = strength[i];
}
//System.out.println(Math.log(10));
for(int j = 1;(1 << j) <= n;j++){
for(int i = 0;i + (1 << j) - 1 < n;i++){
//System.out.println(i +" "+ j + " " +( i + (1 << (j - 1))));
findMin[i][j] = Math.min(findMin[i][j-1],findMin[i + (1 << (j - 1))][j - 1]);
gcd [i][j] = GCD(gcd[i][j-1],gcd[i + (1 << (j - 1))][j - 1]);
}
}
for(int i = 1;i<=t;i++){
st = new StringTokenizer(br.readLine());
int l = Integer.parseInt(st.nextToken()) - 1;
int r = Integer.parseInt(st.nextToken()) - 1;
int k = (int)(Math.log(r - l + 1)/Math.log(2));
int tempGcd = GCD(gcd[l][k],gcd[r - (1 << k) + 1][k]);
int tempMin = Math.min(findMin[l][k],findMin[r - (1 << k) + 1][k]);
int tot = r - l + 1;
//System.out.println(tempGcd + " " + tempMin);
if(tempGcd != tempMin){
sb.append(tot);
sb.append('\n');
continue;
}
//System.out.println(tot + " " + i);
int num = query(1,0,n - 1,l,r,tempMin);
sb.append(tot - num);
sb.append('\n');
}
System.out.print(sb);
}
public static void buildtree(int node,int start,int end){
if(start > end)return;
if(start == end){
min[node] = strength[start];
cnt[node]++;
return;
}
//System.out.println(node + " " +start + " "+end);
buildtree(2*node,start,(start + end)/2);
buildtree(2*node + 1,(start + end)/2 + 1,end);
if(min[2*node] == min[2*node + 1]){
min[node] = min[2*node];
cnt[node] = cnt[2*node] + cnt[2*node + 1];
}
else if(min[2*node] < min[2*node + 1]){
min[node] = min[2*node];
cnt[node] = cnt[2*node];
}
else{
min[node] = min[2*node + 1];
cnt[node] = cnt[2*node + 1];
}
//System.out.println(node + " " + start + " " + end);
}
public static int query(int node,int start,int end,int l,int r,int check){
if(start > end || start > r || end < l)return 0;
if(start >= l && end <= r){
if(min[node] == check)return cnt[node];
else return 0;
}
//System.out.println(node + " " + start + " " + end + " ");
int q1 = query(2*node,start,(start + end)/2,l,r,check);
int q2 = query(2*node + 1,(start + end)/2 + 1,end,l,r,check);
return q1 + q2;
}
}
|
Java
|
["5\n1 3 2 4 2\n4\n1 5\n2 5\n3 5\n4 5"]
|
1 second
|
["4\n4\n1\n1"]
|
NoteIn the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4.
|
Java 7
|
standard input
|
[
"data structures",
"number theory",
"math"
] |
f7f1d57921fe7b7a697967dcfc8f0169
|
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony. The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants. The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases. Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
| 2,100 |
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
|
standard output
| |
PASSED
|
958222ba7ab43e1cc4acb281585b76c7
|
train_001.jsonl
|
1412609400
|
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si). After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class f {
public static void main(String[] args) throws IOException
{
input.init(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = input.nextInt();
aa = new int[n];
for(int i = 0; i<n; i++) aa[i] = input.nextInt();
IT it = new IT(n);
preprocess();
int m = input.nextInt();
for(int i = 0; i<m; i++)
{
int a = input.nextInt()-1, b = input.nextInt()-1;
int gcd = query(a, b);
int[] min = it.get(a, b);
//System.out.println(gcd+" "+min[0]+" "+min[1]);
if(min[0] != gcd) out.println(b-a+1);
else out.println(b-a+1-min[1]);
}
out.close();
}
//Minimum Interval Tree
static class IT
{
int[] left,right, val, a, b, prop, count;
IT(int n)
{
left = new int[4*n];
right = new int[4*n];
val = new int[4*n];
prop = new int[4*n];
a = new int[4*n];
b = new int[4*n];
count = new int[4*n];
init(0,0, n-1);
}
int init(int at, int l, int r)
{
a[at] = l;
b[at] = r;
if(l==r)
{
count[at] = 1;
val[at] = aa[l];
left[at] = right [at] = -1;
}
else
{
int mid = (l+r)/2;
left[at] = init(2*at+1,l,mid);
right[at] = init(2*at+2,mid+1,r);
val[at] = Math.min(val[left[at]], val[right[at]]);
count[at] = 0;
//System.out.println(l+" "+r+" "+val[left[at]]+" "+val[right[at]]+" "+count[left[at]]+" "+count[right[at]]);
if(val[left[at]] == val[at]) count[at] += count[left[at]];
if(val[right[at]] == val[at]) count[at] += count[right[at]];
//System.out.println(count[at]);
}
return at++;
}
//return the min over [x,y]
int[] get(int x, int y)
{
return go(x,y, 0);
}
void push(int at)
{
if(prop[at] != 0)
{
go3(a[left[at]], b[left[at]], prop[at], left[at]);
go3(a[right[at]], b[right[at]], prop[at], right[at]);
prop[at] = 0;
}
}
int[] go(int x,int y, int at)
{
if(at==-1 || y<a[at] || x>b[at]) return new int[]{1987654321, 0};
if(x <= a[at] && y>= b[at]) return new int[]{val[at], count[at]};
push(at);
int[] l = go(x, y, left[at]);
int[] r = go(x, y, right[at]);
int min = Math.min(l[0], r[0]);
int count = 0;
if(l[0] == r[0]) count = l[1] + r[1];
else if(l[0] < r[0]) count = l[1];
else count = r[1];
return new int[]{min, count};
}
//add v to elements x through y
void add(int x, int y, int v)
{
go3(x, y, v, 0);
}
void go3(int x, int y, int v, int at)
{
if(at==-1) return;
if(y < a[at] || x > b[at]) return;
x = Math.max(x, a[at]);
y = Math.min(y, b[at]);
if(y == b[at] && x == a[at])
{
val[at] += v;
prop[at] += v;
return;
}
push(at);
go3(x, y, v, left[at]);
go3(x, y, v, right[at]);
val[at] = Math.min(val[left[at]], val[right[at]]);
count[at] = 0;
if(val[left[at]] == val[at]) count[at] += count[left[at]];
if(val[right[at]] == val[at]) count[at] += count[right[at]];
}
}
public static class input {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
static long nextLong() throws IOException {
return Long.parseLong( next() );
}
}
static int[][] rmq;
static int[] aa;
static int[] memo;
static int log(int x)
{
if(memo[x] != -1) return memo[x];
return memo[x] = Integer.numberOfTrailingZeros(Integer.highestOneBit(x));
}
static void preprocess()
{
int n = aa.length;
memo = new int[n+1];
Arrays.fill(memo, -1);
rmq = new int[n][log(n)+1];
for(int i = 0; i<n; i++) rmq[i][0] = aa[i];
for(int j = 1; (1<<j) <= n; j++)
for(int i = 0; i + (1<<j) <= n; i++)
rmq[i][j] = gcd(rmq[i][j-1], rmq[i+(1<<(j-1))][j-1]);
}
static int query(int i, int j)
{
int k = log(j - i + 1);
return gcd(rmq[i][k], rmq[j-(1<<k)+1][k]);
}
static int gcd(int a, int b)
{
return b == 0 ? a : gcd(b, a%b);
}
}
|
Java
|
["5\n1 3 2 4 2\n4\n1 5\n2 5\n3 5\n4 5"]
|
1 second
|
["4\n4\n1\n1"]
|
NoteIn the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4.
|
Java 7
|
standard input
|
[
"data structures",
"number theory",
"math"
] |
f7f1d57921fe7b7a697967dcfc8f0169
|
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony. The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants. The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases. Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
| 2,100 |
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
|
standard output
| |
PASSED
|
33d5cd6854d47a5260b2943a55dafd1f
|
train_001.jsonl
|
1412609400
|
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si). After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
static SegTree gcdTree ;
public static void main(String[] args) {
int array[];
int n ;
MyScanner sc = new MyScanner();
MyWriter mw = new MyWriter();
n = sc.nextInt();
array = new int[n];
for(int i = 0 ; i < n ; ++i )
array[i] = sc.nextInt();
gcdTree = new SegTree( array );
int q = sc.nextInt();
while( q-- > 0 )
{
int l,r ;
l = sc.nextInt() - 1 ;
r = sc.nextInt() - 1 ;
/* int gcd = gcdTree.getGCD(0, l, r);
int min = gcdTree.getMin(0, l, r);
int count = gcdTree.getFrequency(0 , l,r);
*/
triplet ans = gcdTree.query(0 , l,r);
if(ans.gcd == ans.min )
mw.println( r - l + 1 - ans.count + "");
else
mw.println(r-l+1 + "");
}
mw.close();
}
static class triplet
{
int gcd,min,count;
public triplet(int a , int b , int c )
{
gcd = a ;
min = b ;
count = c ;
}
}
static class SegTree
{
int array[];
int size ;
node tree[];
public SegTree( int array[] )
{
this.array = array ;
size = array.length ;
tree = new node[10*size];
spreadTree( 0 , 0 , size - 1 ) ;
}
triplet query(int index , int l , int r )
{
node t = tree[index];
if( l <= t.left && t.right <= r)
return new triplet( t.gcd , t.min , t.frequency );
if( r < t.left || t.right < l )
return new triplet( 0 , Integer.MAX_VALUE , 0 );
triplet t1 = query ( index*2+1, l , r );
triplet t2 = query ( index*2+2, l , r );
int a = gcd ( t1.gcd , t2.gcd );
int b = Math.min ( t1.min ,t2.min );
int c = 0 ;
if( b == t1.min )
c += t1.count;
if( b == t2.min )
c += t2.count ;
return new triplet( a ,b ,c );
}
int getGCD( int index , int l , int r )
{
node t = tree[index];
if( l <= t.left && t.right <= r)
return t.gcd ;
if( r < t.left || t.right < l )
return 0 ;
int ans = gcd ( getGCD( index*2+1, l , r ) , getGCD(index*2+2,l,r) );
return gcd ( getGCD( index*2+1, l , r ) , getGCD(index*2+2,l,r) );
}
int getMin( int index , int l , int r )
{
node t = tree[index];
if( l <= t.left && t.right <= r)
return t.min ;
if( r < t.left || t.right < l )
return Integer.MAX_VALUE ;
int ans = Math.min( getMin( index*2+1, l , r) , getMin(index*2+2,l,r) );
return Math.min( getMin( index*2+1, l , r) , getMin(index*2+2,l,r) );
}
int getFrequency(int index , int l , int r )
{
node t = tree[index];
if( l <= t.left && t.right <= r)
return t.frequency ;
if( r < t.left || t.right < l )
return 0 ;
int temp = getMin( index , l , r );
int templ = getMin( index*2+1, l , r );
int tempr = getMin(index*2+2,l,r);
int ans , ansl, ansr ;
ans = ansl = ansr = 0 ;
ansl = getFrequency(index*2+1,l , r );
ansr = getFrequency(index*2+2 , l , r );
if( temp == templ )
ans += ansl ;
if( temp == tempr )
ans += ansr ;
return ans ;
}
void spreadTree( int index , int left ,int right )
{
tree[index] = new node();
node t = tree[index];
if( left == right )
{
t.gcd = array[left];
t.left = left ;
t.right = right;
t.min = array[left];
t.frequency = 1 ;
}
else
{
int mid = (left+right)/2;
t.left = left ;
t.right = right ;
spreadTree( index*2+1,left ,mid );
spreadTree(index*2+2,mid+1,right);
t.gcd = gcd( tree[index*2+1].gcd, tree[index*2+2].gcd );
t.min = Math.min( tree[index*2+1].min, tree[index*2+2].min);
if( t.min == tree[index*2+1].min )
t.frequency += tree[index*2+1].frequency;
if( t.min == tree[index*2+2].min )
t.frequency += tree[index*2+2].frequency;
}
}
}
static int gcd( int x ,int y )
{
if( x == 0 ) return y ;
if( y== 0 ) return x;
if( x < y )
return gcd( y%x,x );
else
return gcd(x%y,y);
}
static class node
{
int left , right ;
int gcd;
int min;
int frequency;
public node()
{
min = 0;
frequency = 0 ;
gcd = 0 ;
}
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {
br = new BufferedReader(new InputStreamReader(System.in),8*1024);
}
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 class MyWriter {
BufferedWriter bw;
public MyWriter() {
bw = new BufferedWriter(new OutputStreamWriter(System.out),8*1024);
}
void print(String s)
{
try {
bw.write( s , 0 , s.length() );
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void println(String s)
{
try {
bw.write( s , 0 , s.length() );
bw.newLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void close()
{
try {
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
|
Java
|
["5\n1 3 2 4 2\n4\n1 5\n2 5\n3 5\n4 5"]
|
1 second
|
["4\n4\n1\n1"]
|
NoteIn the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4.
|
Java 7
|
standard input
|
[
"data structures",
"number theory",
"math"
] |
f7f1d57921fe7b7a697967dcfc8f0169
|
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony. The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants. The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases. Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
| 2,100 |
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
|
standard output
| |
PASSED
|
62913b46014a01cceac032996e176455
|
train_001.jsonl
|
1412609400
|
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si). After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
static class Assert {
static void check(boolean e) {
if (!e) {
throw new Error();
}
}
}
static class Scanner {
StreamTokenizer in;
Scanner(Reader r) {
in = new StreamTokenizer(new BufferedReader(r));
in.resetSyntax();
in.whitespaceChars(0, 32);
in.wordChars(33, 255);
}
String next() {
try {
in.nextToken();
Assert.check(in.ttype == in.TT_WORD);
return in.sval;
} catch (IOException e) {
throw new Error(e);
}
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
static class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(InputStream in) throws IOException {
br = new BufferedReader(new InputStreamReader(in));
}
String next() {
try {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
} catch (IOException e) {
System.err.println(e);
System.exit(1);
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
FastScanner in;
//Scanner in;
PrintWriter out;
final int INF = (int)1e9;
int GCD(int a, int b) {
while (b > 0) {
int newB = a % b;
a = b;
b = newB;
}
return a;
}
class Pair {
public int a, b;
public Pair(int _a, int _b) {
a = _a; b = _b;
}
public Pair(Pair p) {
a = p.a; b = p.b;
}
}
class SegmentTreeGCD {
private int size;
private int[] tree;
public SegmentTreeGCD(int _size) {
size = _size;
tree = new int[4 * size];
}
public void buildTree(int[] array, int v, int left, int right) {
if (left == right) {
tree[v] = array[left];
} else {
int middle = (left + right) / 2;
buildTree(array, v * 2, left, middle);
buildTree(array, v * 2 + 1, middle + 1, right);
tree[v] = GCD(tree[v * 2], tree[v * 2 + 1]);
}
}
public int getGCD(int v, int left, int right, int leftQuery, int rightQuery) {
if (left == leftQuery && right == rightQuery) {
return tree[v];
}
int middle = (left + right) / 2;
if (leftQuery <= Math.min(middle, rightQuery) && Math.max(leftQuery, middle + 1) <= rightQuery) {
return GCD(getGCD(v * 2, left, middle, leftQuery, Math.min(middle, rightQuery)),
getGCD(v * 2 + 1, middle + 1, right, Math.max(leftQuery, middle + 1), rightQuery));
}
if (leftQuery <= Math.min(middle, rightQuery)) {
return getGCD(v * 2, left, middle, leftQuery, Math.min(middle, rightQuery));
}
if (Math.max(leftQuery, middle + 1) <= rightQuery) {
return getGCD(v * 2 + 1, middle + 1, right, Math.max(leftQuery, middle + 1), rightQuery);
}
return 1;
}
}
class SegmentTreeMinFreq {
private int size;
private int[] tree;
private int[] freq;
public SegmentTreeMinFreq(int _size) {
size = _size;
tree = new int[4 * size];
freq = new int[4 * size];
}
public void buildTree(int[] array, int v, int left, int right) {
if (left == right) {
tree[v] = array[left];
freq[v] = 1;
} else {
int middle = (left + right) / 2;
buildTree(array, v * 2, left, middle);
buildTree(array, v * 2 + 1, middle + 1, right);
if (tree[v * 2] < tree[v * 2 + 1]) {
tree[v] = tree[v * 2];
freq[v] = freq[v * 2];
} else if (tree[v * 2] == tree[v * 2 + 1]) {
tree[v] = tree[v * 2];
freq[v] = freq[v * 2] + freq[v * 2 + 1];
} else {
tree[v] = tree[v * 2 + 1];
freq[v] = freq[v * 2 + 1];
}
}
}
public Pair getMinFreq(int v, int left, int right, int leftQuery, int rightQuery) {
if (leftQuery > rightQuery) {
return new Pair(INF, INF);
}
if (left == leftQuery && right == rightQuery) {
return new Pair(tree[v], freq[v]);
}
int middle = (left + right) / 2;
Pair first = new Pair(getMinFreq(v * 2, left, middle, leftQuery, Math.min(middle, rightQuery)));
Pair second = new Pair(getMinFreq(v * 2 + 1, middle + 1, right, Math.max(leftQuery, middle + 1), rightQuery));
if (first.a < second.a) {
return new Pair(first.a, first.b);
} else if (first.a == second.a) {
return new Pair(first.a, first.b + second.b);
} else {
return new Pair(second.a, second.b);
}
}
}
void solve() {
int n = in.nextInt();
int[] s = new int[n];
for (int i = 0; i < n; ++i) {
s[i] = in.nextInt();
}
SegmentTreeGCD treeGCD = new SegmentTreeGCD(n);
SegmentTreeMinFreq treeMinFreq = new SegmentTreeMinFreq(n);
treeGCD.buildTree(s, 1, 0, n - 1);
treeMinFreq.buildTree(s, 1, 0, n - 1);
int t = in.nextInt();
for (int i = 0; i < t; ++i) {
int left = in.nextInt(), right = in.nextInt();
int gcd = treeGCD.getGCD(1, 0, n - 1, left - 1, right - 1);
Pair p = treeMinFreq.getMinFreq(1, 0, n - 1, left - 1, right - 1);
if (p.a == gcd) {
out.println(right - left + 1 - p.b);
} else {
out.println(right - left + 1);
}
}
}
void run() {
try {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
//in = new Scanner(new FileReader("input.txt"));
//out = new PrintWriter(new FileWriter("output.txt"));
} catch (IOException e) {
throw new Error(e);
}
try {
solve();
} finally {
out.close();
}
}
public static void main(String args[]) {
new Main().run();
}
}
|
Java
|
["5\n1 3 2 4 2\n4\n1 5\n2 5\n3 5\n4 5"]
|
1 second
|
["4\n4\n1\n1"]
|
NoteIn the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4.
|
Java 7
|
standard input
|
[
"data structures",
"number theory",
"math"
] |
f7f1d57921fe7b7a697967dcfc8f0169
|
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony. The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants. The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases. Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
| 2,100 |
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
|
standard output
| |
PASSED
|
6f3ff85f9c4b66176f85d34b2518f68a
|
train_001.jsonl
|
1412609400
|
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si). After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.Random;
import java.util.Scanner;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
import java.lang.Long;
public class Test {
static long Mod = 1000000007;
static int[][] dp;
static int bit = 20;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int n = in.nextInt();
int[] data = new int[n];
for (int i = 0; i < n; i++) {
data[i] = in.nextInt();
}
int t = in.nextInt();
ArrayList<Node>[] list = new ArrayList[n];
for (int i = 0; i < t; i++) {
int l = in.nextInt() - 1;
int r = in.nextInt() - 1;
if (list[r] == null)
list[r] = new ArrayList();
list[r].add(new Node(l, r, i));
}
int[] result = new int[t];
TreeSet<Entry> set = new TreeSet();
for (int i = 0; i < n; i++) {
TreeSet<Entry> tmp = new TreeSet();
Entry last = null;
for (Entry e : set) {
int nxt = gcd(e.g, data[i]);
int c = 0;
if (nxt == data[i]) {
c = 1;
}
if (last != null && last.g == nxt) {
last.count += c;
} else {
if (e.g == nxt) {
e.count += c;
if (nxt == data[i]) {
e.list.add(i);
}
last = e;
} else {
last = new Entry(e.start, nxt);
last.count += c;
if (nxt == data[i]) {
last.list.add(i);
}
}
tmp.add(last);
}
}
if (last == null || last.g !=data[i]) {
Entry e = new Entry(i, data[i]);
e.count = 1;
e.list.add(i);
tmp.add(e);
}
set = tmp;
if (list[i] != null) {
for (Node node : list[i]) {
Entry e = set.floor(new Entry(node.l, 0));
if (e != null) {
int start = 0;
int end = e.list.size() - 1;
int min = Integer.MAX_VALUE;
while (start <= end) {
int mid = (start + end) / 2;
if (e.list.get(mid) > node.l) {
end = mid - 1;
min = Math.min(min, mid);
} else if (e.list.get(mid) == node.l) {
min = mid;
break;
} else {
start = mid + 1;
}
}
result[node.index] = node.r - node.l + 1 - Math.max(0, e.list.size() - min);
}
}
}
//out.println(set);
}
for (int i = 0; i < t; i++) {
out.println(result[i]);
}
out.close();
}
static class Entry implements Comparable<Entry> {
int start, g, count;
ArrayList<Integer> list = new ArrayList();
Entry(int start, int g) {
this.start = start;
this.g = g;
}
@Override
public int compareTo(Entry o) {
return start - o.start;
}
@Override
public String toString() {
return "Entry [start=" + start + ", g=" + g + ", count=" + count
+ ", list=" + list + "]";
}
}
static class Node {
int l, r, index;
Node(int l, int r, int index) {
this.l = l;
this.r = r;
this.index = index;
}
}
static int find(int index, int[] u) {
if (u[index] != index) {
return u[index] = find(u[index], u);
}
return index;
}
static int crossProduct(Point a, Point b) {
return a.x * b.y + a.y * b.x;
}
static long squareDist(Point a) {
long x = a.x;
long y = a.y;
return x * x + y * y;
}
static Point minus(Point a, Point b) {
return new Point(a.x - b.x, a.y - b.y);
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
static class Point {
int x, y;
public Point(int x, int y) {
super();
this.x = x;
this.y = y;
}
public String toString() {
return "{" + x + " " + y + "}";
}
}
static int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new
// BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new
// FileInputStream(
// new File("input.txt"))));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
|
Java
|
["5\n1 3 2 4 2\n4\n1 5\n2 5\n3 5\n4 5"]
|
1 second
|
["4\n4\n1\n1"]
|
NoteIn the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4.
|
Java 7
|
standard input
|
[
"data structures",
"number theory",
"math"
] |
f7f1d57921fe7b7a697967dcfc8f0169
|
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony. The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants. The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases. Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
| 2,100 |
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
|
standard output
| |
PASSED
|
07d92c6652995f7a735d532c43e98add
|
train_001.jsonl
|
1412609400
|
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si). After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
|
256 megabytes
|
//package codeforces;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
public class F {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(System.out);
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 {
final int n = nextInt();
int[] s = new int[n];
class SegmentTree {
int q = 1;
int[] a;
{
while(q <= n) {
q *= 2;
}
a = new int[q * 2];
}
void add(int i, int x) {
for(i += q; i > 0; i /= 2) {
a[i] = gcd(a[i], x);
}
}
int getGcd(int l, int r) {
int result = 0;
for(l += q, r += q; l < r; l /= 2, r /= 2) {
if(l % 2 == 1) {
result = gcd(result, a[l++]);
}
if(r % 2 == 1) {
result = gcd(result, a[--r]);
}
}
return result;
}
int gcd(int a, int b) {
if(b == 0) {
return a;
}
return gcd(b, a % b);
}
}
SegmentTree segmentTree = new SegmentTree();
final Map<Integer, List<Integer>> inverted = new HashMap<>();
for(int i = 0; i < n; i++) {
s[i] = nextInt();
segmentTree.add(i, s[i]);
List<Integer> list = inverted.get(s[i]);
if(list == null) {
list = new ArrayList<>(8);
inverted.put(s[i], list);
}
list.add(i);
}
class Utils {
int countLess(int g, int pos) {
List<Integer> list = inverted.get(g);
if(list == null) {
return 0;
}
int lo = -1;
int hi = list.size();
while(hi - lo > 1) {
int med = lo + hi >> 1;
if(list.get(med) >= pos) {
hi = med;
} else {
lo = med;
}
}
return hi;
}
}
Utils utils = new Utils();
int m = nextInt();
for(int i = 0; i < m; i++) {
int l = nextInt();
int r = nextInt();
int gcd = segmentTree.getGcd(l - 1, r);
writer.println(r - l + 1 - (utils.countLess(gcd, r) - utils.countLess(gcd, l - 1)));
}
writer.close();
}
public static void main(String[] args) throws IOException {
new F().solve();
}
}
|
Java
|
["5\n1 3 2 4 2\n4\n1 5\n2 5\n3 5\n4 5"]
|
1 second
|
["4\n4\n1\n1"]
|
NoteIn the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4.
|
Java 7
|
standard input
|
[
"data structures",
"number theory",
"math"
] |
f7f1d57921fe7b7a697967dcfc8f0169
|
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony. The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants. The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases. Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
| 2,100 |
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
|
standard output
| |
PASSED
|
92facb24a8633dc044b654872da27938
|
train_001.jsonl
|
1412609400
|
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si). After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
|
256 megabytes
|
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
/**
* Created by hama_du on 2014/10/09.
*/
public class ProblemF {
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a%b);
}
public static class SegmentTree {
int N;
int[] gcd;
int[] cnt;
SegmentTree(int n, int[] a) {
N = Integer.highestOneBit(n-1)<<1;
gcd = new int[N<<1];
cnt = new int[N<<1];
for (int i = 0 ; i < a.length ; i++) {
gcd[N-1+i] = a[i];
cnt[N-1+i] = 1;
}
merge(0);
}
void merge(int idx) {
if (idx*2+2 >= gcd.length) {
return;
}
if (gcd[idx] == 0) {
merge(idx*2+1);
merge(idx*2+2);
if (gcd[idx*2+1] == 0) {
gcd[idx] = gcd[idx*2+2];
cnt[idx] = cnt[idx*2+2];
} else if (gcd[idx*2+2] == 0) {
gcd[idx] = gcd[idx*2+1];
cnt[idx] = cnt[idx*2+1];
} else {
gcd[idx] = gcd(gcd[idx*2+1], gcd[idx*2+2]);
cnt[idx] = 0;
if (gcd[idx] == gcd[idx*2+1]) {
cnt[idx] += cnt[idx*2+1];
}
if (gcd[idx] == gcd[idx*2+2]) {
cnt[idx] += cnt[idx*2+2];
}
}
}
}
int[] range(int fr, int to) {
return range(fr, to, 0, 0, N);
}
int[] range(int fr, int to, int idx, int l, int r) {
if (r <= fr || to <= l) {
return new int[]{0, 0};
} else if (fr <= l && r <= to) {
return new int[]{gcd[idx], cnt[idx]};
} else {
int m = (l + r) / 2;
int[] a = range(fr, to, idx*2+1, l, m);
int[] b = range(fr, to, idx*2+2, m, r);
if (a[0] == 0) {
return b;
} else if (b[0] == 0) {
return a;
}
int[] ret = new int[2];
ret[0] = gcd(a[0], b[0]);
ret[1] = 0;
if (ret[0] == a[0]) {
ret[1] += a[1];
}
if (ret[0] == b[0]) {
ret[1] += b[1];
}
return ret;
}
}
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
SegmentTree seg = new SegmentTree(n, a);
int q = in.nextInt();
for (int i = 0; i < q; i++) {
int fr = in.nextInt()-1;
int to = in.nextInt();
int[] r = seg.range(fr, to);
out.println((to - fr) - r[1]);
}
out.flush();
}
public static void debug(Object... o) {
System.err.println(Arrays.deepToString(o));
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int next() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = next();
while (isSpaceChar(c))
c = next();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = next();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = next();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = next();
while (isSpaceChar(c))
c = next();
long sgn = 1;
if (c == '-') {
sgn = -1;
c = next();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = next();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
|
Java
|
["5\n1 3 2 4 2\n4\n1 5\n2 5\n3 5\n4 5"]
|
1 second
|
["4\n4\n1\n1"]
|
NoteIn the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4.
|
Java 7
|
standard input
|
[
"data structures",
"number theory",
"math"
] |
f7f1d57921fe7b7a697967dcfc8f0169
|
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony. The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants. The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases. Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
| 2,100 |
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
|
standard output
| |
PASSED
|
bff0dd3a441054529fa0dae43dbdb4b7
|
train_001.jsonl
|
1412609400
|
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si). After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
|
256 megabytes
|
import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
InputReader in = new InputReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
new Task().go(in, out);
out.close();
}
}
class Task {
public int maxn = 100010;
class Pair {
int x, y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
public Pair() {
x = 0; y = 0;
}
}
Pair[] p = new Pair[maxn<<2];
int n;
public void go(InputReader in, PrintWriter out) {
n = in.nextInt();
build(1, n, 1, in);
int m = in.nextInt();
for(int i=0; i<m; i++) {
int l = in.nextInt(), r = in.nextInt();
out.println(r - l + 1 - ask(l, r, 1, n, 1).y);
}
}
Pair ask(int x, int y, int l, int r, int rt) {
if(x == l && r == y) return p[rt];
else {
int m = (l + r) >> 1;
if(y <= m) return ask(x, y, l, m, rt<<1);
else if(x > m) return ask(x, y, m+1, r, rt<<1|1);
else {
Pair p1 = ask(x, m, l, m , rt<<1);
Pair p2 = ask(m+1, y, m+1, r, rt<<1|1);
Pair p3 = new Pair();
push_up(p1, p2, p3);
return p3;
}
}
}
void build(int l, int r, int rt, InputReader in) {
if(l == r) {
p[rt] = new Pair(in.nextInt(), 1);
}
else {
int m = (l + r) >> 1;
build(l, m, rt<<1, in);
build(m+1, r, rt<<1|1, in);
p[rt] = new Pair();
push_up(p[rt<<1], p[rt<<1|1], p[rt]);
}
}
void push_up(Pair p1, Pair p2, Pair p) {
if(p1.x == p2.x) {
p.x = p1.x;
p.y = p1.y + p2.y;
}
else {
p.x = gcd(p1.x, p2.x);
if(p.x == p1.x) p.y = p1.y;
else if(p.x == p2.x) p.y = p2.y;
else p.y = 0;
}
}
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a%b);
}
}
class InputReader {
BufferedReader bf;
StringTokenizer st;
InputReader(InputStreamReader is) {
bf = new BufferedReader(is);
}
public String next() {
if (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(bf.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
|
Java
|
["5\n1 3 2 4 2\n4\n1 5\n2 5\n3 5\n4 5"]
|
1 second
|
["4\n4\n1\n1"]
|
NoteIn the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4.
|
Java 7
|
standard input
|
[
"data structures",
"number theory",
"math"
] |
f7f1d57921fe7b7a697967dcfc8f0169
|
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony. The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants. The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases. Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
| 2,100 |
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
|
standard output
| |
PASSED
|
a2279ad1b0c5ba2403d995d240d60b87
|
train_001.jsonl
|
1412609400
|
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si). After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main{
final boolean isFileIO = false;
BufferedReader in;
PrintWriter out;
StringTokenizer st = new StringTokenizer("");
String delim = " ";
public static void main(String[] args) throws IOException {
Main m = new Main();
m.initIO();
m.solve();
m.in.close();
m.out.close();
}
public void initIO() throws IOException {
if(!isFileIO) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else {
in = new BufferedReader(new FileReader("input.txt"));
out = new PrintWriter("output.txt");
}
}
String nextToken() throws IOException {
if(!st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken(delim);
}
String readLine() throws IOException {
return in.readLine();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
int max = 18;
int[] exp;
int[][] table;
public void solve() throws IOException {
int n = nextInt();
int[] s = new int[n];
for(int i = 0; i < n; i++) {
s[i] = nextInt();
}
table = new int[max][n];
exp = new int[n + 1];
for(int i = 1; i <= n; i++) {
int cur = 0;
for(int j = 0; j < max; j++) {
if((i & (1 << j)) == (1 << j)) {
cur = j;
}
}
exp[i] = cur;
}
for(int i = 0; i < n; i++) {
table[0][i] = s[i];
}
for(int i = 1; i < max; i++) {
for(int j = 0; j < n; j++) {
table[i][j] = gcd(table[i - 1][j], table[i - 1][Math.min(j + (1 << (i - 1)), n - 1)]);
}
}
HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>();
for(int i = 0; i < n; i++) {
if(!map.containsKey(s[i])) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(i);
map.put(s[i], list);
} else {
map.get(s[i]).add(i);
}
}
int t = nextInt();
for(int i = 0; i < t; i++) {
int l = nextInt() - 1;
int r = nextInt() - 1;
int g = query(l, r);
if(!map.containsKey(g)) {
out.println(r - l + 1);
continue;
}
ArrayList<Integer> list = map.get(g);
int most_left, most_right;
most_left = most_right = -1;
int left, right, mid;
left = right = mid = 0;
left = 0; right = list.size() - 1;
while(left < right) {
mid = left + (right - left) / 2;
if(list.get(mid) < l) {
left = mid + 1;
} else {
right = mid;
}
}
most_left = left;
left = right = mid = 0;
right = list.size() - 1;
while(left < right) {
mid = left + (right - left) / 2;
if(list.get(mid) < r) {
left = mid + 1;
} else {
right = mid;
}
}
if(list.get(left) > r && left > 0)
left--;
most_right = left;
if(list.get(most_right) > r || list.get(most_left) < l) {
out.println(r - l + 1);
} else {
out.println(r - l + 1 - (most_right - most_left + 1));
}
}
}
public int gcd(int a, int b) {
if(b == 0) {
return a;
}
return gcd(b, a % b);
}
public int query(int left, int right) {
int pow = exp[right - left + 1];
return gcd(table[pow][left], table[pow][left + (right - left - (1 << pow) + 1)]);
}
}
|
Java
|
["5\n1 3 2 4 2\n4\n1 5\n2 5\n3 5\n4 5"]
|
1 second
|
["4\n4\n1\n1"]
|
NoteIn the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4.
|
Java 7
|
standard input
|
[
"data structures",
"number theory",
"math"
] |
f7f1d57921fe7b7a697967dcfc8f0169
|
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony. The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants. The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases. Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
| 2,100 |
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
|
standard output
| |
PASSED
|
53527282889a7f544c71e99fe0d792a6
|
train_001.jsonl
|
1412609400
|
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si). After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
|
256 megabytes
|
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.InputMismatchException;
public class F {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int[] a = na(n);
SegmentTreeRMQ st = new SegmentTreeRMQ(a);
int[] hs = new int[n];
int[] ls = new int[n];
for(int i = 0;i < n;i++){
int high = st.firstle(i, a[i]);
int low = st.lastle(i, a[i]);
hs[i] = (high == -1 ? n: high)-1;
ls[i] = low+1;
}
int Q = ni();
int[][] es = new int[n*2+Q][];
int p = 0;
int[] ret = new int[Q];
for(int i = 0;i < Q;i++){
es[p++] = new int[]{ni()-1, i, ni()-1};
ret[i] += es[p-1][2]-es[p-1][0]+1;
}
for(int i = 0;i < n;i++){
es[p++] = new int[]{ls[i], -1, i, hs[i], 1};
es[p++] = new int[]{i+1, -1, i, hs[i], -1};
}
Arrays.sort(es, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
if(a[0] != b[0])return a[0] - b[0];
return a[1] - b[1];
}
});
int[] ft = new int[n+2];
for(int[] e : es){
if(e[1] >= 0){
ret[e[1]] -= sumFenwick(ft, e[2]);
}else{
addFenwick(ft, e[2], e[4]);
addFenwick(ft, e[3]+1, -e[4]);
}
}
for(int i = 0;i < Q;i++){
out.println(ret[i]);
}
}
public static int sumFenwick(int[] ft, int i)
{
int sum = 0;
for(i++;i > 0;i -= i&-i)sum += ft[i];
return sum;
}
public static void addFenwick(int[] ft, int i, int v)
{
if(v == 0 || i < 0)return;
int n = ft.length;
for(i++;i < n;i += i&-i)ft[i] += v;
}
public static int gcd(int a, int b) {
while (b > 0) {
int c = a;
a = b;
b = c % b;
}
return a;
}
public static class SegmentTreeRMQ {
public int M, H, N;
public int[] st;
public SegmentTreeRMQ(int n)
{
N = n;
M = Integer.highestOneBit(Math.max(N-1, 1))<<2;
H = M>>>1;
st = new int[M];
Arrays.fill(st, 0, M, Integer.MAX_VALUE);
}
public SegmentTreeRMQ(int[] a)
{
N = a.length;
M = Integer.highestOneBit(Math.max(N-1, 1))<<2;
H = M>>>1;
st = new int[M];
for(int i = 0;i < N;i++){
st[H+i] = a[i];
}
Arrays.fill(st, H+N, M, Integer.MAX_VALUE);
for(int i = H-1;i >= 1;i--)propagate(i);
}
private void propagate(int i)
{
st[i] = gcd(st[2*i], st[2*i+1]);
}
public int min(int l, int r){ return l >= r ? 0 : min(l, r, 0, H, 1);}
private int min(int l, int r, int cl, int cr, int cur)
{
if(l <= cl && cr <= r){
return st[cur];
}else{
int mid = cl+cr>>>1;
int ret = -1;
if(cl < r && l < mid){
int res = min(l, r, cl, mid, 2*cur);
if(ret == -1){
ret = res;
}else{
ret = gcd(ret, res);
}
}
if(mid < r && l < cr){
int res = min(l, r, mid, cr, 2*cur+1);
if(ret == -1){
ret = res;
}else{
ret = gcd(ret, res);
}
}
return ret;
}
}
public int firstle(int l, int v) {
int cur = H+l;
while(true){
if(st[cur] % v != 0){
if(cur < H){
cur = 2*cur;
}else{
return cur-H;
}
}else{
cur++;
if((cur&cur-1) == 0)return -1;
if((cur&1)==0)cur>>>=1;
}
}
}
public int lastle(int l, int v) {
int cur = H+l;
while(true){
if(st[cur] % v != 0){
if(cur < H){
cur = 2*cur+1;
}else{
return cur-H;
}
}else{
if((cur&cur-1) == 0)return -1;
cur--;
if((cur&1)==1)cur>>>=1;
}
}
}
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new F().run(); }
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
|
Java
|
["5\n1 3 2 4 2\n4\n1 5\n2 5\n3 5\n4 5"]
|
1 second
|
["4\n4\n1\n1"]
|
NoteIn the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4.
|
Java 7
|
standard input
|
[
"data structures",
"number theory",
"math"
] |
f7f1d57921fe7b7a697967dcfc8f0169
|
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony. The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants. The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases. Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
| 2,100 |
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
|
standard output
| |
PASSED
|
8fbd0a8b7972a3d052e2a2062fb783ca
|
train_001.jsonl
|
1412609400
|
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si). After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
|
256 megabytes
|
//package round271;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class F2 {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int[] a = na(n);
SegmentTreeRMQ st = new SegmentTreeRMQ(a);
int[] hs = new int[n];
int[] ls = new int[n];
for(int i = 0;i < n;i++){
int high = st.firstle(i, a[i]);
int low = st.lastle(i, a[i]);
hs[i] = (high == -1 ? n: high)-1;
ls[i] = low+1;
}
int Q = ni();
long[] es = new long[n*2+Q];
int p = 0;
int[] ret = new int[Q];
int[] ys = new int[Q];
for(int i = 0;i < Q;i++){
int x = ni()-1;
es[p++] = (long)x<<32|i+n;
ys[i] = ni()-1;
ret[i] += ys[i]-x+1;
}
boolean[] stand = new boolean[n];
for(int i = 0;i < n;i++){
es[p++] = (long)ls[i]<<32|i;
es[p++] = (long)(i+1)<<32|i;
}
es = radixSort(es);
int[] ft = new int[n+2];
for(long e : es){
int yy = (int)e;
if(yy >= n){
int y = ys[yy-n];
ret[yy-n] -= sumFenwick(ft, y);
}else{
addFenwick(ft, yy, stand[yy] ? -1 : 1);
addFenwick(ft, hs[yy]+1, stand[yy] ? 1 : -1);
stand[yy] ^= true;
}
}
for(int i = 0;i < Q;i++){
out.println(ret[i]);
}
}
public static long[] radixSort(long[] f)
{
long[] to = new long[f.length];
{
int[] b = new int[65537];
for(int i = 0;i < f.length;i++)b[1+(int)(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[(int)(f[i]&0xffff)]++] = f[i];
long[] d = f; f = to;to = d;
}
{
int[] b = new int[65537];
for(int i = 0;i < f.length;i++)b[1+(int)(f[i]>>>16&0xffff)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < f.length;i++)to[b[(int)(f[i]>>>16&0xffff)]++] = f[i];
long[] d = f; f = to;to = d;
}
{
int[] b = new int[65537];
for(int i = 0;i < f.length;i++)b[1+(int)(f[i]>>>32&0xffff)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < f.length;i++)to[b[(int)(f[i]>>>32&0xffff)]++] = f[i];
long[] d = f; f = to;to = d;
}
{
int[] b = new int[65537];
for(int i = 0;i < f.length;i++)b[1+(int)(f[i]>>>48&0xffff)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < f.length;i++)to[b[(int)(f[i]>>>48&0xffff)]++] = f[i];
long[] d = f; f = to;to = d;
}
return f;
}
public static int sumFenwick(int[] ft, int i)
{
int sum = 0;
for(i++;i > 0;i -= i&-i)sum += ft[i];
return sum;
}
public static void addFenwick(int[] ft, int i, int v)
{
if(v == 0 || i < 0)return;
int n = ft.length;
for(i++;i < n;i += i&-i)ft[i] += v;
}
public static int gcd(int a, int b) {
while (b > 0) {
int c = a;
a = b;
b = c % b;
}
return a;
}
public static class SegmentTreeRMQ {
public int M, H, N;
public int[] st;
public SegmentTreeRMQ(int n)
{
N = n;
M = Integer.highestOneBit(Math.max(N-1, 1))<<2;
H = M>>>1;
st = new int[M];
Arrays.fill(st, 0, M, Integer.MAX_VALUE);
}
public SegmentTreeRMQ(int[] a)
{
N = a.length;
M = Integer.highestOneBit(Math.max(N-1, 1))<<2;
H = M>>>1;
st = new int[M];
for(int i = 0;i < N;i++){
st[H+i] = a[i];
}
Arrays.fill(st, H+N, M, Integer.MAX_VALUE);
for(int i = H-1;i >= 1;i--)propagate(i);
}
private void propagate(int i)
{
st[i] = gcd(st[2*i], st[2*i+1]);
}
public int min(int l, int r){ return l >= r ? 0 : min(l, r, 0, H, 1);}
private int min(int l, int r, int cl, int cr, int cur)
{
if(l <= cl && cr <= r){
return st[cur];
}else{
int mid = cl+cr>>>1;
int ret = -1;
if(cl < r && l < mid){
int res = min(l, r, cl, mid, 2*cur);
if(ret == -1){
ret = res;
}else{
ret = gcd(ret, res);
}
}
if(mid < r && l < cr){
int res = min(l, r, mid, cr, 2*cur+1);
if(ret == -1){
ret = res;
}else{
ret = gcd(ret, res);
}
}
return ret;
}
}
public int firstle(int l, int v) {
int cur = H+l;
while(true){
if(st[cur] % v != 0){
if(cur < H){
cur = 2*cur;
}else{
return cur-H;
}
}else{
cur++;
if((cur&cur-1) == 0)return -1;
if((cur&1)==0)cur>>>=1;
}
}
}
public int lastle(int l, int v) {
int cur = H+l;
while(true){
if(st[cur] % v != 0){
if(cur < H){
cur = 2*cur+1;
}else{
return cur-H;
}
}else{
if((cur&cur-1) == 0)return -1;
cur--;
if((cur&1)==1)cur>>>=1;
}
}
}
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new F2().run(); }
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
|
Java
|
["5\n1 3 2 4 2\n4\n1 5\n2 5\n3 5\n4 5"]
|
1 second
|
["4\n4\n1\n1"]
|
NoteIn the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4.
|
Java 7
|
standard input
|
[
"data structures",
"number theory",
"math"
] |
f7f1d57921fe7b7a697967dcfc8f0169
|
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony. The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants. The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases. Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
| 2,100 |
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
|
standard output
| |
PASSED
|
d6addfc5ac72c0eb3d57599cd883010b
|
train_001.jsonl
|
1412609400
|
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si). After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
|
256 megabytes
|
//package round271;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class F3 {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int[] a = na(n);
SegmentTreeRMQ st = new SegmentTreeRMQ(a);
long[] as = new long[n];
for(int i = 0;i < n;i++){
as[i] = (long)a[i]<<32|i;
}
as = radixSort(as);
int Q = ni();
for(int i = 0;i < Q;i++){
int l = ni()-1, r = ni()-1;
int g = st.min(l, r+1);
int indl = Arrays.binarySearch(as, (long)g<<32|l);
if(indl < 0)indl = -indl-1;
int indh = Arrays.binarySearch(as, (long)g<<32|r);
if(indh < 0)indh = -indh-2;
out.println((r-l+1)-Math.max(0, indh-indl+1));
}
}
public static int gcd(int a, int b) {
while (b > 0) {
int c = a;
a = b;
b = c % b;
}
return a;
}
public static class SegmentTreeRMQ {
public int M, H, N;
public int[] st;
public SegmentTreeRMQ(int n)
{
N = n;
M = Integer.highestOneBit(Math.max(N-1, 1))<<2;
H = M>>>1;
st = new int[M];
Arrays.fill(st, 0, M, Integer.MAX_VALUE);
}
public SegmentTreeRMQ(int[] a)
{
N = a.length;
M = Integer.highestOneBit(Math.max(N-1, 1))<<2;
H = M>>>1;
st = new int[M];
for(int i = 0;i < N;i++){
st[H+i] = a[i];
}
Arrays.fill(st, H+N, M, Integer.MAX_VALUE);
for(int i = H-1;i >= 1;i--)propagate(i);
}
private void propagate(int i)
{
st[i] = gcd(st[2*i], st[2*i+1]);
}
public int min(int l, int r){ return l >= r ? 0 : min(l, r, 0, H, 1);}
private int min(int l, int r, int cl, int cr, int cur)
{
if(l <= cl && cr <= r){
return st[cur];
}else{
int mid = cl+cr>>>1;
int ret = -1;
if(cl < r && l < mid){
int res = min(l, r, cl, mid, 2*cur);
if(ret == -1){
ret = res;
}else{
ret = gcd(ret, res);
}
}
if(mid < r && l < cr){
int res = min(l, r, mid, cr, 2*cur+1);
if(ret == -1){
ret = res;
}else{
ret = gcd(ret, res);
}
}
return ret;
}
}
}
public static long[] radixSort(long[] f)
{
long[] to = new long[f.length];
{
int[] b = new int[65537];
for(int i = 0;i < f.length;i++)b[1+(int)(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[(int)(f[i]&0xffff)]++] = f[i];
long[] d = f; f = to;to = d;
}
{
int[] b = new int[65537];
for(int i = 0;i < f.length;i++)b[1+(int)(f[i]>>>16&0xffff)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < f.length;i++)to[b[(int)(f[i]>>>16&0xffff)]++] = f[i];
long[] d = f; f = to;to = d;
}
{
int[] b = new int[65537];
for(int i = 0;i < f.length;i++)b[1+(int)(f[i]>>>32&0xffff)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < f.length;i++)to[b[(int)(f[i]>>>32&0xffff)]++] = f[i];
long[] d = f; f = to;to = d;
}
{
int[] b = new int[65537];
for(int i = 0;i < f.length;i++)b[1+(int)(f[i]>>>48&0xffff)]++;
for(int i = 1;i <= 65536;i++)b[i]+=b[i-1];
for(int i = 0;i < f.length;i++)to[b[(int)(f[i]>>>48&0xffff)]++] = f[i];
long[] d = f; f = to;to = d;
}
return f;
}
void run() throws Exception
{
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis()-s+"ms");
}
public static void main(String[] args) throws Exception { new F3().run(); }
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
private int readByte()
{
if(lenbuf == -1)throw new InputMismatchException();
if(ptrbuf >= lenbuf){
ptrbuf = 0;
try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
if(lenbuf <= 0)return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
private int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }
private double nd() { return Double.parseDouble(ns()); }
private char nc() { return (char)skip(); }
private String ns()
{
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))){ // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n)
{
char[] buf = new char[n];
int b = skip(), p = 0;
while(p < n && !(isSpaceChar(b))){
buf[p++] = (char)b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m)
{
char[][] map = new char[n][];
for(int i = 0;i < n;i++)map[i] = ns(m);
return map;
}
private int[] na(int n)
{
int[] a = new int[n];
for(int i = 0;i < n;i++)a[i] = ni();
return a;
}
private int ni()
{
int num = 0, b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private long nl()
{
long num = 0;
int b;
boolean minus = false;
while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
if(b == '-'){
minus = true;
b = readByte();
}
while(true){
if(b >= '0' && b <= '9'){
num = num * 10 + (b - '0');
}else{
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) { if(!oj)System.out.println(Arrays.deepToString(o)); }
}
|
Java
|
["5\n1 3 2 4 2\n4\n1 5\n2 5\n3 5\n4 5"]
|
1 second
|
["4\n4\n1\n1"]
|
NoteIn the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4.
|
Java 7
|
standard input
|
[
"data structures",
"number theory",
"math"
] |
f7f1d57921fe7b7a697967dcfc8f0169
|
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony. The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants. The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases. Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
| 2,100 |
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
|
standard output
| |
PASSED
|
a32f204e95f155ff84bb160950c69335
|
train_001.jsonl
|
1412609400
|
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si). After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
|
256 megabytes
|
import java.awt.Point;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.StringTokenizer;
public class F {
public static void main(String[] args) throws Exception {
int len = nextInt();
SegmentTree tree = new SegmentTree(len);
Point[] sorted = new Point[len];
for (int i = 0; i < len; i++) {
int x = nextInt();
sorted[i] = new Point(x, i);
tree.update(i, x);
}
Arrays.sort(sorted, new Comparator<Point>() {
@Override
public int compare(Point p1, Point p2) {
if (p1.x != p2.x) {
return Integer.compare(p1.x, p2.x);
}
return Integer.compare(p1.y, p2.y);
}
});
HashMap<Integer, Integer> map = new HashMap<>();
int idx = 0;
for (int i = 0; i < sorted.length; i++) {
int j = i;
while (j < sorted.length && sorted[j].x == sorted[i].x) {
j++;
}
map.put(sorted[i].x, idx++);
i = j - 1;
}
int[][] where = new int[idx][];
for (int i = 0; i < sorted.length; i++) {
int cnt = 0;
int j = i;
while (j < sorted.length && sorted[j].x == sorted[i].x) {
j++;
cnt++;
}
int mapIdx = map.get(sorted[i].x);
where[mapIdx] = new int[cnt];
j = i;
cnt = 0;
while (j < sorted.length && sorted[j].x == sorted[i].x) {
where[mapIdx][cnt++] = sorted[j].y;
j++;
}
i = j - 1;
}
PrintWriter out = new PrintWriter(System.out);
int queryCnt = nextInt();
for (int i = 0; i < queryCnt; i++) {
int st = nextInt() - 1;
int end = nextInt() - 1;
int gcd = tree.query(st, end);
// System.out.println(gcd+" d");
Integer mapIdx = map.get(gcd);
if (mapIdx == null) {
out.println(end - st + 1);
} else {
// System.out.println(Arrays.toString(where[mapIdx]));
int stIdx = Arrays.binarySearch(where[mapIdx], st);
if (stIdx < 0) {
stIdx += 1;
stIdx = -stIdx;
}
int endIdx = Arrays.binarySearch(where[mapIdx], end);
if (endIdx < 0) {
endIdx += 1;
endIdx = -endIdx;
endIdx--;
}
// System.out.println(stIdx+" a7a "+endIdx);
out.println((end-st+1)-(endIdx - stIdx + 1));
}
}
out.flush();
}
static int gcd(int a, int b) {
if (a == 0)
return b;
if (a > b)
return gcd(b, a);
return gcd(b % a, a);
}
static class SegmentTree {
int[] T;
int size = 1;
static int inf;
public SegmentTree(int n) {
while (size < n)
size <<= 1;
T = new int[size << 1];
}
public void init(int v) {
inf = v;
Arrays.fill(T, inf);
}
// index is zero-based i.e. index=0 is the first element in the array
public void update(int index, int v) {
index += size;
T[index] = v;
while (index > 1) {
index >>= 1;
T[index] = gcd(T[index << 1], T[(index << 1) + 1]);
}
}
// send query [i,j]
public int query(int i, int j) {
return query(1, 0, size - 1, i, j);
}
private int query(int node, int b, int e, int i, int j) {
int p1, p2;
if (i > e || j < b)
return 0;
if (b >= i && e <= j)
return T[node];
p1 = query(2 * node, b, (b + e) / 2, i, j);
p2 = query(2 * node + 1, (b + e) / 2 + 1, e, i, j);
return gcd(p1, p2);
}
}
static BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
static StringTokenizer tokenizer = new StringTokenizer("");
static int nextInt() throws Exception {
return Integer.parseInt(next());
}
static long nextLong() throws Exception {
return Long.parseLong(next());
}
static double nextDouble() throws Exception {
return Double.parseDouble(next());
}
static String next() throws Exception {
while (true) {
if (tokenizer.hasMoreTokens()) {
return tokenizer.nextToken();
}
String s = br.readLine();
if (s == null) {
return null;
}
tokenizer = new StringTokenizer(s);
}
}
}
|
Java
|
["5\n1 3 2 4 2\n4\n1 5\n2 5\n3 5\n4 5"]
|
1 second
|
["4\n4\n1\n1"]
|
NoteIn the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4.
|
Java 7
|
standard input
|
[
"data structures",
"number theory",
"math"
] |
f7f1d57921fe7b7a697967dcfc8f0169
|
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony. The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants. The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases. Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
| 2,100 |
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
|
standard output
| |
PASSED
|
94c1aea0a60f21a1a382b39f55996344
|
train_001.jsonl
|
1412609400
|
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si). After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
|
256 megabytes
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
static boolean home = true;
public static void main(String[] args) throws FileNotFoundException {
InputStream is = home ? System.in : new FileInputStream("decoding.in");
InputReader in = new InputReader(is);
OutputStream os = home ? System.out : new FileOutputStream("decoding.out");
PrintWriter out = new PrintWriter(os);
int n = in.nextInt();
int [] s = new int[n];
for (int i = 0; i < n; ++i) {
s[i] = in.nextInt();
}
int [] st = new int[n + n];
int [] cnt = new int[n + n];
int [] gc = new int[n + n];
for (int i = 0; i < n; ++i) {
st[i + n] = s[i];
cnt[i + n] = 1;
gc[i + n] = s[i];
}
for (int i = n - 1; i > 0; --i) {
st[i] = Math.min(st[i + i], st[i + i + 1]);
if (st[i] == st[i + i]) cnt[i] += cnt[i + i];
if (st[i] == st[i + i + 1]) cnt[i] += cnt[i + i + 1];
gc[i] = gcd(gc[i + i], gc[i + i + 1]);
}
int q = in.nextInt();
while (q-- > 0) {
int l = in.nextInt() - 1;
int r = in.nextInt() - 1;
int min = Integer.MAX_VALUE;
int count = 0;
int gcd = 0;
for (int L = l + n, R = r + n; L <= R; L = (L + 1) >> 1, R = (R - 1) >> 1) {
if ((L & 1) != 0) {
if (st[L] < min) {
min = st[L];
count = cnt[L];
} else {
if (st[L] == min) {
count += cnt[L];
}
}
gcd = gcd(gcd, gc[L]);
}
if ((R & 1) == 0) {
if (st[R] < min) {
min = st[R];
count = cnt[R];
} else {
if (st[R] == min) {
count += cnt[R];
}
}
gcd = gcd(gcd, gc[R]);
}
}
int ans = r - l + 1;
if (gcd % min == 0) {
ans -= count;
}
out.println(ans);
}
out.close();
}
private static int gcd(int a, int b) {
while (b > 0) {
a %= b;
a ^= b;
b ^= a;
a ^= b;
}
return a;
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
|
Java
|
["5\n1 3 2 4 2\n4\n1 5\n2 5\n3 5\n4 5"]
|
1 second
|
["4\n4\n1\n1"]
|
NoteIn the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4.
|
Java 7
|
standard input
|
[
"data structures",
"number theory",
"math"
] |
f7f1d57921fe7b7a697967dcfc8f0169
|
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony. The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants. The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases. Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
| 2,100 |
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
|
standard output
| |
PASSED
|
494698a376673a79a9cd3512de269fbd
|
train_001.jsonl
|
1412609400
|
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si). After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
|
256 megabytes
|
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskF solver = new TaskF();
solver.solve(1, in, out);
out.close();
}
}
class TaskF {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; ++i)
a[i] = in.nextInt();
int[] log = new int[n + 1];
for (int i = 1, j = 0; i <= n; ++i) {
while (1 << (j + 1) <= i) ++j;
log[i] = j;
}
int[][] gcd = new int[n][log[n] + 1];
for (int i = 0; i < n; ++i)
gcd[i][0] = a[i];
for (int j = 1; 1 << j <= n; ++j)
for (int i = 0; i + (1 << j) <= n; ++i)
gcd[i][j] = gcd(gcd[i][j - 1], gcd[i + (1 << (j - 1))][j - 1]);
MagicTree tree = new MagicTree(a);
int numQueries = in.nextInt();
for (int q = 0; q < numQueries; ++q) {
int left = in.nextInt() - 1;
int right = in.nextInt();
int k = log[right - left];
int expect = gcd(gcd[left][k], gcd[right - (1 << k)][k]);
Entry actual = tree.get(left, right);
if (expect == actual.minValue)
out.println(right - left - actual.minCount);
else
out.println(right - left);
}
}
private int gcd(int x, int y) {
while (y != 0) {
int t = x % y;
x = y;
y = t;
}
return x;
}
static class Entry {
int minValue;
int minCount;
Entry(int minValue, int minCount) {
this.minValue = minValue;
this.minCount = minCount;
}
static Entry join(Entry a, Entry b) {
if (a.minValue < b.minValue)
return a;
if (a.minValue > b.minValue)
return b;
return new Entry(a.minValue, a.minCount + b.minCount);
}
}
class MagicTree {
private final Entry[] data;
private int n;
MagicTree(int[] key) {
n = key.length;
data = new Entry[4 * n];
build(0, 0, n, key);
}
void build(int at, int left, int right, int[] key) {
if (left + 1 == right) {
data[at] = new Entry(key[left], 1);
} else {
int middle = (left + right) / 2;
int le = 2 * at + 1;
int ri = 2 * at + 2;
build(le, left, middle, key);
build(ri, middle, right, key);
data[at] = Entry.join(data[le], data[ri]);
}
}
Entry get(int left, int right) {
return internalGet(0, 0, n, left, right);
}
Entry internalGet(int at, int left, int right, int segLeft, int segRight) {
if (right <= segLeft || segRight <= left || left >= right)
return new Entry(Integer.MAX_VALUE, 0);
if (segLeft <= left && right <= segRight)
return data[at];
int middle = (left + right) / 2;
int le = 2 * at + 1;
int ri = 2 * at + 2;
return Entry.join(internalGet(le, left, middle, segLeft, segRight), internalGet(ri, middle, right, segLeft, segRight));
}
}
}
class InputReader {
private BufferedReader reader;
private StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens())
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
|
Java
|
["5\n1 3 2 4 2\n4\n1 5\n2 5\n3 5\n4 5"]
|
1 second
|
["4\n4\n1\n1"]
|
NoteIn the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4.
|
Java 7
|
standard input
|
[
"data structures",
"number theory",
"math"
] |
f7f1d57921fe7b7a697967dcfc8f0169
|
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony. The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants. The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases. Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
| 2,100 |
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
|
standard output
| |
PASSED
|
4fb059dc0fb75b31658e164f58711771
|
train_001.jsonl
|
1412609400
|
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si). After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
|
256 megabytes
|
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.ArrayList;
import java.util.HashMap;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author George Marcus
*/
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);
TaskF solver = new TaskF();
solver.solve(1, in, out);
out.close();
}
}
class TaskF {
int[] Agcd;
int[] A;
int a, b;
int g;
public void solve(int testNumber, InputReader in, PrintWriter out) {
int N = in.nextInt();
A = new int[N];
for (int i = 0; i < N; i++) {
A[i] = in.nextInt();
}
Agcd = new int[4 * N];
build(1, 0, N - 1);
ArrayList<Event>[] events = new ArrayList[N];
for (int i = 0; i < N; i++) {
events[i] = new ArrayList<Event>();
}
int Q = in.nextInt();
int[] ans = new int[Q];
for (int q = 0; q < Q; q++) {
int left = in.nextInt();
int right = in.nextInt();
left--; right--;
a = left; b = right; g = -1;
queryGcd(1, 0, N - 1);
events[right].add(new Event(g, 1, q));
if (left > 0) {
events[left - 1].add(new Event(g, -1, q));
}
ans[q] = right - left + 1;
}
HashMap<Integer, Integer> f = new HashMap<Integer, Integer>();
for (int i = 0; i < N; i++) {
if (f.containsKey(A[i])) {
f.put(A[i], f.get(A[i]) + 1);
}
else {
f.put(A[i], 1);
}
for (Event e : events[i]) {
int num = 0;
if (f.containsKey(e.x)) {
num = f.get(e.x);
}
ans[e.idx] -= e.t * num;
}
}
for (int q = 0; q < Q; q++) {
out.println(ans[q]);
}
}
private void queryGcd(int k, int st, int dr) {
if (a <= st && dr <= b) {
if (g == -1) {
g = Agcd[k];
}
else {
g = gcd(g, Agcd[k]);
}
return;
}
int m = (st + dr) / 2;
if (a <= m) {
queryGcd(2 * k, st, m);
}
if (b > m) {
queryGcd(2 * k + 1, m + 1, dr);
}
}
private void build(int k, int st, int dr) {
if (st == dr) {
Agcd[k] = A[st];
return;
}
int m = (st + dr) / 2;
build(2 * k, st, m);
build(2 * k + 1, m + 1, dr);
Agcd[k] = gcd(Agcd[2 * k], Agcd[2 * k + 1]);
}
private int gcd(int a, int b) {
int r;
while (b != 0) {
r = a % b;
a = b;
b = r;
}
return a;
}
private class Event {
public int x;
public int t;
public int idx;
private Event(int x, int t, int idx) {
this.x = x;
this.t = t;
this.idx = idx;
}
}
}
class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
return Integer.parseInt(nextString());
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
|
Java
|
["5\n1 3 2 4 2\n4\n1 5\n2 5\n3 5\n4 5"]
|
1 second
|
["4\n4\n1\n1"]
|
NoteIn the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4.
|
Java 7
|
standard input
|
[
"data structures",
"number theory",
"math"
] |
f7f1d57921fe7b7a697967dcfc8f0169
|
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony. The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants. The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases. Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
| 2,100 |
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
|
standard output
| |
PASSED
|
c870d30c7685a9ffafa72fea7ac020b7
|
train_001.jsonl
|
1412609400
|
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si). After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class TaskE {
private FastScanner in;
private PrintWriter out;
class Tree {
private int size;
private int[] tree;
private int diff;
Tree(int[] data) {
size = 1;
while (size < data.length) {
size *= 2;
}
tree = new int[2 * size - 1];
diff = size - 1;
for (int i = size - 1; i < 2 * size - 1; i++) {
tree[i] = i - diff < data.length ? data[i - diff] : -1;
}
for (int i = size - 2; i >= 0; i--) {
tree[i] = gcd(tree[i * 2 + 1], tree[i * 2 + 2]);
}
}
private int gcd(int a, int b) {
if (a == -1 || a == 0) {
return b;
}
if (b == -1 || b == 0) {
return a;
}
return gcd(b % a, a);
}
public int getGcd(int l, int r) {
return getGcd(0, diff, 2 * size - 2, l + diff, r + diff);
}
private int getGcd(int num, int ll, int rr, int l, int r) {
if (l <= ll && rr <= r) {
return tree[num];
}
if (ll > r || rr < l) {
return -1;
}
return gcd(getGcd(num * 2 + 1, ll, (ll + rr) / 2, l, r),
getGcd(num * 2 + 2, (ll + rr) / 2 + 1, rr, l, r));
}
}
public void solve() throws IOException {
int n = in.nextInt();
int[] data = new int[n];
HashMap<Integer, List<Integer>> index = new HashMap<Integer, List<Integer>>();
for (int i = 0; i < n; i++) {
data[i] = in.nextInt();
if (!index.containsKey(data[i])) {
index.put(data[i], new ArrayList<Integer>());
}
index.get(data[i]).add(i);
}
Tree tree = new Tree(data);
int m = in.nextInt();
for (int i = 0; i < m; i++) {
int l = in.nextInt() - 1, r = in.nextInt() - 1;
int curGcd = tree.getGcd(l, r);
if (!index.containsKey(curGcd)) {
out.println(r - l + 1);
continue;
}
List<Integer> indexes = index.get(curGcd);
int ll = getFirstHigher(indexes, l);
int rr = getFirstLess(indexes, r);
int res = r - l + 1;
if (ll != -1 && rr != -1) {
res -= (rr - ll + 1);
}
out.println(res);
}
}
public int getFirstHigher(List<Integer> list, int pos) {
int l = -1, r = list.size();
while (r - l > 1) {
int mid = (l + r) / 2;
if (list.get(mid) >= pos) {
r = mid;
} else {
l = mid;
}
}
if (r == list.size()) {
return -1;
} else {
return r;
}
}
public int getFirstLess(List<Integer> list, int pos) {
int l = -1, r = list.size();
while (r - l > 1) {
int mid = (l + r) / 2;
if (list.get(mid) <= pos) {
l = mid;
} else {
r = mid;
}
}
return l;
}
public void run() {
try {
in = new FastScanner();
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private class FastScanner {
private BufferedReader br;
private StringTokenizer st;
public FastScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
public static void main(String[] arg) {
new TaskE().run();
}
}
|
Java
|
["5\n1 3 2 4 2\n4\n1 5\n2 5\n3 5\n4 5"]
|
1 second
|
["4\n4\n1\n1"]
|
NoteIn the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4.
|
Java 7
|
standard input
|
[
"data structures",
"number theory",
"math"
] |
f7f1d57921fe7b7a697967dcfc8f0169
|
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony. The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants. The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases. Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
| 2,100 |
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
|
standard output
| |
PASSED
|
4c9a12f11b359eae2371be1a7e91f79f
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
import java.util.*;
import java.lang.*;
public class Cf
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
double w,temp;
w=in.nextDouble();
int i,j,k;
double a[] = new double[n];
double b[] = new double[n];
for(i=0;i<n;i++)
{
a[i]=in.nextDouble();
if(a[i]==1)
{
System.out.println("-1");
return;
}
}
for(i=0;i<n;i++)
{
b[i]=in.nextDouble();
if(b[i]==1)
{
System.out.println("-1");
return;
}
}
temp=w;
for(j=n-1;j>=0;j--)
{
w+=w/(a[j]-1);
w+=w/(b[j]-1);
}
w-=temp;
System.out.println(w);
}
}
|
Java
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
0a9e35f907276d623966b52c46595f9c
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
import java.io.*;
import java.math.BigInteger;
import java.util.*;
import static java.lang.Math.*;
public class Main {
BufferedReader br;
StringTokenizer in;
PrintWriter pw;
public void solve() throws IOException {
int n = nextInt();
double m = nextInt();
int a[] = new int[n];
int b[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
for (int i = 0; i < n; i++) {
b[i] = nextInt();
}
double l = 0;
double r = 1e9 + 20;
while (r - l >= (double) 1 / (2 *1e6)) {
if (r < 20) {
r = r + 1 - 1;
}
double k = (l + r) / 2;
double kk = k;
boolean immposible = false;
for (int i = 1; i < n; i++) {
double z = (m + kk) / a[i - 1];
kk -= z;
if (kk < 0) immposible = true;
z = (m + kk) / b[i];
kk -= z;
if (kk < 0) immposible = true;
}
double z = (m + kk) / a[n - 1];
kk -= z;
if (kk < 0) immposible = true;
z = (m + kk) / b[0];
kk -= z;
if (kk < 0) immposible = true;
if (immposible) {
l = k;
} else r = k;
}
if (r > 1e9 + 1) pw.print(-1);
else pw.print(r);
}
public void run() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new FileReader("input.txt"));
pw = new PrintWriter(new OutputStreamWriter(System.out));
// pw = new PrintWriter(new FileWriter("output.txt"));
solve();
pw.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
public String nextToken() throws IOException {
while (in == null || !in.hasMoreTokens()) {
in = new StringTokenizer(br.readLine());
}
return in.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.US);
new Main().run();
}
}
|
Java
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
5690446e0c6baca60c8ac1681c308d2d
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class CF499C {
private static boolean test = false;
private static InputReader in = new InputReader(System.in);
public static void main(String[] args) {
int n = in.nextInt();
int m = 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();
}
solve(n, m, a, b);
}
private static void solve(int n, int m, int[] a, int[] b) {
double high = 1_000_001_000;
double low = 1;
if (!isGood(n, m, a, b, high)) {
System.out.println(-1);
return;
}
while (high - low > (0.0000001) * low) {
double fuel = (low + high) / 2;
if (isGood(n, m, a, b, fuel)) {
high = fuel;
} else {
low = fuel;
}
}
System.out.println(String.format("%1$.7f", high));
}
private static boolean isGood(int n, int m, int[] a, int[] b, double fuel) {
double weight = m + fuel;
for (int i = 0; i < n; i++) {
double takeoffFuel = weight / a[i];
if (takeoffFuel > fuel) {
return false;
}
fuel -= takeoffFuel;
weight -= takeoffFuel;
double landingFuel;
if (i < n - 1) {
landingFuel = weight / b[i + 1];
} else {
landingFuel = weight / b[0];
}
if (landingFuel > fuel) {
return false;
}
fuel -= landingFuel;
weight -= landingFuel;
}
return true;
}
static private void print(Object... o) {
if (test) {
String s = Arrays.deepToString(o);
System.out.println(s.substring(1, s.length() - 1));
}
}
private static class InputReader {
private BufferedReader r;
private StringTokenizer st;
public InputReader(InputStream stream) {
r = new BufferedReader(new InputStreamReader(stream), 16384);
st = null;
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(r.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
|
Java
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
17232414b687b78f6af6b037959f4ae0
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//package Round499;
import java.util.Scanner;
/**
*
* @author Hemant Dhanuka
*/
public class C1 {
static int n,m,lowerLimit;
static int a[],b[];
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
n=s.nextInt();
m=s.nextInt();
a=new int[n];
b=new int[n];
for(int i=0;i<n;i++){
a[i]=s.nextInt();
}
for(int i=0;i<n;i++){
b[i]=s.nextInt();
}
// boolean ans=cal(2000000000);
// if(!ans){
// System.out.println(-1);
// return;
// }
//
lowerLimit=binarySearch(0,1000000005);
int fraction=binarySearch1(0,1000000000);
double finalans=lowerLimit+((double)fraction)/1000000000;
if(finalans>1000000000.000001){
finalans=-1;
}
System.out.println(finalans);
}
static boolean cal(double x){
double totat=m+x;
for(int i=0;i<n;i++){
double burnt=totat/a[i];
if(burnt>x){
return false;
}
else{
x-=burnt;
totat=m+x;
}
double burnt1=totat/(b[(i+1)%n]);
if(burnt1>x){
return false;
}
else{
x-=burnt1;
totat=m+x;
}
}
return true;
}
private static int binarySearch(int left, int right) {
if(right-left==1){
return left;
}
int mid=(left+right)/2;
if(cal(mid)){
return binarySearch(left, mid);
}
else{
return binarySearch(mid, right);
}
}
private static int binarySearch1(int left, int right) {
if(right-left==1){
return left;
}
int mid=(left+right)/2;
if(cal(lowerLimit+((double)mid)/1000000000)){
return binarySearch1(left, mid);
}
else{
return binarySearch1(mid, right);
}
}
}
|
Java
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
11f873b4a0f694dfbb61a402f45a13ff
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//package Round499;
import java.util.Scanner;
/**
*
* @author Hemant Dhanuka
*/
public class C3 {
static int n,m,lowerLimit;
static int a[],b[];
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
n=s.nextInt();
m=s.nextInt();
a=new int[n];
b=new int[n];
for(int i=0;i<n;i++){
a[i]=s.nextInt();
}
for(int i=0;i<n;i++){
b[i]=s.nextInt();
}
double finalans=binarySearch(0,1000000005);
//int fraction=binarySearch1(0,1000000000);
if(finalans>1000000000.000001){
finalans=-1;
}
System.out.println(finalans);
}
static boolean cal(double x){
double totat=m+x;
for(int i=0;i<n;i++){
double burnt=totat/a[i];
if(burnt>x){
return false;
}
else{
x-=burnt;
totat=m+x;
}
double burnt1=totat/(b[(i+1)%n]);
if(burnt1>x){
return false;
}
else{
x-=burnt1;
totat=m+x;
}
}
return true;
}
private static double binarySearch(double left, double right) {
if(right-left<.000001){
return left;
}
double mid=(left+right)/2;
if(cal(mid)){
return binarySearch(left, mid);
}
else{
return binarySearch(mid, right);
}
}
// private static int binarySearch1(int left, int right) {
// if(right-left==1){
// return left;
// }
//
// int mid=(left+right)/2;
//
// if(cal(lowerLimit+((double)mid)/1000000000)){
// return binarySearch1(left, mid);
// }
// else{
// return binarySearch1(mid, right);
// }
// }
}
|
Java
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
ff90c2af4de1cbc0320c23615b3bfb88
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
//package Round499;
import java.util.Scanner;
/**
*
* @author Hemant Dhanuka
*/
public class C2 {
static int n;
static int[] a,b;
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
n=s.nextInt();
double m=(double)s.nextInt();
double actual=m;
a=new int[n];
b=new int[n];
for(int i=0;i<n;i++){
a[i]=s.nextInt();
}
for(int i=0;i<n;i++){
b[i]=s.nextInt();
}
double extra;
for(int i=n-1;i>=0;i--){
int bth=b[(i+1)%n];
extra=m/(bth-1);
m=m+extra;
int ath=a[i];
extra=m/(ath-1);
m+=extra;
}
double fuel=m-actual;
if(fuel>1000000000.000001){
System.out.println(-1);
}
else{
System.out.println(fuel);
}
}
}
|
Java
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
43bdc039b9e9e2f046429ea6208a480c
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
public class A
{
public static void main(String args[]) throws IOException
{
Scanner sc=new Scanner (System.in);
int n =sc.nextInt();
int m=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();
}
double lo=0;
double hi=1e9;
double ans=-1;
for(int i=0;i<10000;i++) {
double mid=(lo+hi)/2;
double f=mid;
for(int j=0;j<n;j++) {
f-=(m+f)/a[j];
f-=(m+f)/b[(j)];
}
if(f+1e-9>=0) {
hi=mid;
ans=mid;
}else
lo=mid;
}
System.out.println(ans==-1?"-1":ans);
}
}
|
Java
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
3b26ed1b921e703ab9656c806040b7bc
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
public class A
{
public static void main(String args[]) throws IOException
{
Scanner sc=new Scanner (System.in);
int n =sc.nextInt();
int m=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();
}
double lo=0;
double hi=1e9;
double ans=-1;
for(int i=0;i<10000;i++) {
double mid=(lo+hi)/2;
double f=mid;
for(int j=0;j<n;j++) {
f-=(m+f)/a[j];
f-=(m+f)/b[(j+1)%n];
}
if(f+1e-9>=0) {
hi=mid;
ans=mid;
}else
lo=mid;
}
System.out.println(ans==-1?"-1":ans);
}
}
|
Java
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
78e92747487edfa624934662ff058111
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;
public class C {
InputStream is;
PrintWriter out;
String INPUT = "6\n" +
"2\n" +
"4 6 3 3 5 6\n" +
"2 6 3 6 5 3\n" +
"";
boolean trip(int n,int m,double fuel,int[] a,int[] b)
{
double totalWeight = m+fuel;
double required = totalWeight/a[0];
//System.out.println(required+" "+fuel);
if(required<=fuel)
{
fuel-=required;
totalWeight-=required;
}
else
return false;
for(int i=1;i<n;i++)
{
required = totalWeight/b[i];
if(required<=fuel)
{
fuel-=required;
totalWeight-=required;
//System.out.println(totalWeight);
}
else
return false;
required = totalWeight/a[i];
if(required<=fuel)
{
fuel-=required;
totalWeight-=required;
//System.out.println(totalWeight);
}
else
return false;
}
required = totalWeight/b[0];
if(required<=fuel)
{
fuel-=required;
totalWeight-=required;
//System.out.println(totalWeight);
}
else
return false;
return true;
}
void solve() {
int n = ni();
int m = ni();
int[] a = na(n);
int[] b = na(n);
double low = 0;
double high = 1000000005;
//double mid = (low+high)/2;
//System.out.println(trip(n, m, mid, a, b));
for(int i=0;i<100;i++)
{
double mid = (low+high)/2;
if(trip(n, m, mid, a, b))
high = mid;
else
low = mid;
}
if(low>1000000000.0001)
out.println(-1);
else
out.println(low);
}
void run() throws Exception {
is = oj ? System.in : new ByteArrayInputStream(INPUT.getBytes());
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
tr(System.currentTimeMillis() - s + "ms");
}
public static void main(String[] args) throws Exception {
new C().run();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) {
if (!oj)
System.out.println(Arrays.deepToString(o));
}
}
|
Java
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
f4f5f23dd48d21b64b256f1a4d65bee9
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class CF {
private FastScanner in;
private PrintWriter out;
void solve() {
int n = in.nextInt();
int m = in.nextInt();
List<Integer> tonnesLiftOffPerUnitFuel = new ArrayList<>();
List<Integer> tonnesLandingPerUnitFuel = new ArrayList<>();
Double fuelRequired = 0.0D;
for (int i = 0; i < n; i++) {
tonnesLiftOffPerUnitFuel.add(in.nextInt());
}
for (int i = 0; i < n; i++) {
tonnesLandingPerUnitFuel.add(in.nextInt());
}
for (int i = n-1; i >= 0; i--) {
if (tonnesLandingPerUnitFuel.get((i+1)%n) == 1) {
out.println(-1);
return;
}
fuelRequired += (fuelRequired + m)/(tonnesLandingPerUnitFuel.get((i+1)%n) - 1);
if (tonnesLiftOffPerUnitFuel.get(i) == 1) {
out.println(-1);
return;
}
fuelRequired += (fuelRequired + m)/(tonnesLiftOffPerUnitFuel.get(i) - 1);
}
out.printf("%.8f", fuelRequired);
/*
int n = in.nextInt();
List<Integer> path = new ArrayList<>();
for (int i = 0; i < n; i++) {
path.add(in.nextInt());
}
int x = -1;
for (int i = 1; i < n; i++) {
if (!path.get(i).equals(path.get(i-1) + 1) && !path.get(i).equals(path.get(i-1) - 1)) {
int endLoc = path.get(i);
int startLoc = path.get(i-1);
if (startLoc != endLoc) {
int new_x = (endLoc - startLoc);
if (new_x < 0) new_x = -new_x;
if (x != -1 && x != new_x) {
out.write("NO");
return;
} else {
x = new_x;
}
} else {
out.write("NO");
return;
}
}
}
out.println("YES");
if (x == -1) x = 1;
out.print((int) 1e9);
out.print(' ');
out.print(x);
*/
}
void runIO() {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
out.close();
}
void run() {
try {
in = new FastScanner(new File("test.in"));
out = new PrintWriter(new File("test.out"));
solve();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String next() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return null;
st = new StringTokenizer(s);
}
return st.nextToken();
}
boolean hasMoreTokens() {
while (st == null || !st.hasMoreTokens()) {
String s = null;
try {
s = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
if (s == null)
return false;
st = new StringTokenizer(s);
}
return true;
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
public static void main(String[] args) {
new CF().runIO();
}
}
|
Java
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
d4d31ed355ca02c28ef55f667b27a626
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Fly{
static int N, M, K;
static String s;
static StringTokenizer st;
static int[] d;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int N = Integer.parseInt(br.readLine());
double W = Integer.parseInt(br.readLine());
st = new StringTokenizer(br.readLine());
StringTokenizer st2 = new StringTokenizer(br.readLine());
int[] a = new int[N];
int[] b = new int[N];
double mult = 1;
for (int i = 0; i < N; i++) {
a[i] = Integer.parseInt(st.nextToken());
mult *= a[i]-1;
mult /= a[i];
b[i] = Integer.parseInt(st2.nextToken());
mult *= b[i]-1;
mult /= b[i];
}
if(mult == 0){
System.out.println("-1");
}else{
System.out.printf("%.7f\n",(W * (1-mult)) / mult);
}
out.close();
}
}
|
Java
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
7fa6df556a4e30509d3bb3038b8af82c
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Fly {
static int N, M, K;
static String s;
static StringTokenizer st;
static int[] d;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int N = Integer.parseInt(br.readLine());
double W = Integer.parseInt(br.readLine());
double mult = 1;
for (int k = 0; k < 2; k++) {
st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) {
int a = Integer.parseInt(st.nextToken());
mult *= a - 1;
mult /= a;
}
}
if (mult == 0) {
out.println("-1");
} else {
out.printf("%.7f\n", (W * (1 - mult)) / mult);
}
out.close();
}
}
|
Java
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
113ebefe56bff544e6c507a08afb070c
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
/*package whatever //do not write package name here */
import java.io.*;
import java.util.*;
public class GFG {
public static void main (String[] args) {
//System.out.println("GfG!");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int m=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();
int flag=0;
if(b[0]==1 || a[0]==1)
flag=1;
double z=(m*b[0])/(b[0]-1.0);
for(int i=n-1;i>0;i--){
if(a[i]==1 || b[i]==1){
flag=1;
break;
}
z=((z*a[i])*(b[i]))/((a[i]-1.0)*(b[i]-1.0));
}
z=(z*a[0])/(a[0]-1.0);
z=Math.round(z*1000000000)/1000000000.0;
if(flag==1)
System.out.println(-1);
else
System.out.println(z-m);
}
}
|
Java
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
b41e970b33a5b62ce34ec7868a1f2d1a
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
import java.util.*;
public class test{
static double arr[];
static double arr1[];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
double c = sc.nextDouble();
double ans=-1;
arr = new double[n];
arr1 = new double[n];
for(int i=0;i<n;i++)
{
arr[i] = sc.nextDouble();
}
for(int i=0;i<n;i++)
{
arr1[i] = sc.nextDouble();
}
//binary search for possible fuel
double left = 0;
double right = 1000000005;
while(left<=right)
{
double mid = (left+right)/2;
if(poss(mid, n, c))
{
ans = mid;
right = mid - 0.0000001;
}
else
{
left = mid + 0.0000001;
}
}
if(ans>1000000001)
{
System.out.println(-1);
}
else
{
System.out.println(ans);
}
}
public static boolean poss(double x,int n, double c)
{
double count =x;
for(int i=0;i<n;i++)
{
if(i==n-1)
{
if(arr[i]*count>=c+count)
{
count = count - ((count+c)/arr[i]);
}
else
{
return false;
}
if(arr1[0]*count>=c+count)
{
count = count - ((count+c)/arr1[0]);
}
else
{
return false;
}
continue;
}
if(arr[i]*count>=c+count)
{
count = count - ((count+c)/arr[i]);
}
else
{
return false;
}
if(arr1[i+1]*count>=c+count)
{
count = count - ((count+c)/arr1[i+1]);
}
else
{
return false;
}
}
return true;
}
}
|
Java
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
52d366537297ef3e84cf3c4acbaa0db2
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.text.DecimalFormat;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
public void solve(int testNumber, InputReader in, PrintWriter out) {
int N = in.nextInt();
int M = in.nextInt();
int[] takeOff = new int[N];
int[] land = new int[N];
for (int i = 0; i < N; i++) {
takeOff[i] = in.nextInt();
}
for (int i = 0; i < N; i++) {
land[i] = in.nextInt();
}
double low = 0;
double high = (1000500000);
int iterations = 1000;
while (iterations > 0) {
double mid = (low + high) / 2;
if (works(M, mid, takeOff, land)) {
high = mid;
} else {
low = mid;
}
iterations--;
}
DecimalFormat df = new DecimalFormat("#");
df.setMaximumFractionDigits(10);
out.println(low > 1000001000 ? (int) (-1) : df.format(low));
}
static boolean works(int w, double fuel, int[] takeOff, int[] land) {
fuel -= (fuel + w) / takeOff[0];
for (int i = 1; i < takeOff.length; i++) {
fuel -= (fuel + w) / land[i];
fuel -= (fuel + w) / takeOff[i];
}
fuel -= (fuel + w) / land[0];
return fuel >= 0;
}
}
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
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
a175589516eef66154bf46d30565bff2
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
import java.util.Scanner;
public class Fuel {
public static void main(String args[])
{Scanner s=new Scanner(System.in);
int n=s.nextInt(),m=s.nextInt();
int a[]=new int[n];
int b[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=s.nextInt();
}
for(int i=0;i<n;i++)
{
b[i]=s.nextInt();
}
double f=m,t;
for(int i=1;i<n;i++)
{
t=f;
f=t*b[i-1]/(b[i-1]-1);
t=f;
f=t*a[i]/(a[i]-1);
}
t=f;
f=t*b[n-1]/(b[n-1]-1);
t=f;
f=t*a[0]/(a[0]-1);
if(f-m<0||f-m>1000000001)
System.out.print("-1");
else
System.out.print(f-m);
}
}
|
Java
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
3279787441fe47dc6d0e918cc1bb2824
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
import java.io.BufferedInputStream;
import java.util.Scanner;
/**
*
*/
public class Contest_C {
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedInputStream(System.in));
while (in.hasNext()) {
int n = in.nextInt(); // planet cnt
double m = in.nextInt(); // cargo weight
double a[] = new double[n]; // take off
double b[] = new double[n]; // land on
for (int i = 0; i < n; i++) {
a[i] = in.nextInt();
}
for (int i = 0; i < n; i++) {
b[i] = in.nextInt();
}
boolean ok = false;
double ans = -1;
double left = 0.0;
double right = 1000000001;
while (Math.abs(right - left) >= 0.000001) {
double mid = (right + left) / 2.0;
double curWeight = mid + m - (mid + m) / a[0];
if (curWeight < m) {
// System.out.println("die! mid = " + String.format("%.7f", mid));
left = mid;
continue;
}
boolean die = false;
for (int i = 1; i < n; i++) {
curWeight = curWeight - curWeight / b[i]; // land on i-th planet
if (curWeight < m) {
die = true;
break;
}
curWeight = curWeight - curWeight / a[i]; // take off i-th planet
if (curWeight < m) {
die = true;
break;
}
}
if (die) {
// System.out.println("die! mid = " + String.format("%.7f", mid));
left = mid;
continue;
}
// return to earth
curWeight = curWeight - curWeight / b[0];
if (curWeight < m) {
// System.out.println("die! mid = " + String.format("%.7f", mid));
left = mid;
continue;
}
// ok trip
// System.out.println("ok! mid = " + String.format("%.7f", mid));
ok = true;
ans = mid;
right = mid;
}
if (ok) {
System.out.println(String.format("%.7f", ans));
} else {
System.out.println(-1);
}
}
}
}
|
Java
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
ccd2f4d1b1ccfc935eb2f5179c931a6e
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
* @author Don Li
*/
public class Fly2 {
int n, m;
int[] a, b;
void solve() {
n = in.nextInt(); m = in.nextInt();
a = new int[n];
for (int i = 0; i < n; i++) a[i] = in.nextInt();
b = new int[n];
for (int i = 0; i < n; i++) b[i] = in.nextInt();
for (int i = 0; i < n; i++) {
if (a[i] == 1 || b[i] == 1) {
out.println(-1);
return;
}
}
double s = m;
for (int i = 0; i < n; i++) {
s = s * a[i] / (a[i] - 1);
s = s * b[i] / (b[i] - 1);
}
out.println(s - m);
}
public static void main(String[] args) {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
new Fly2().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
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
7046b056cc17578cda5afc9c19319aeb
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
* @author Don Li
*/
public class Fly {
double INF = 1e9 + 100;
double EPS = 1e-9;
int n, m;
int[] a, b;
void solve() {
n = in.nextInt(); m = in.nextInt();
a = new int[n + 1];
for (int i = 0; i < n; i++) a[i] = in.nextInt();
a[n] = a[0];
b = new int[n + 1];
for (int i = 0; i < n; i++) b[i] = in.nextInt();
b[n] = b[0];
double lb = 0, ub = INF;
for (int it = 0; it < 100; it++) {
double m = (lb + ub) / 2;
if (check(m)) ub = m;
else lb = m;
}
if (ub > 1e9 + EPS) {
out.println(-1);
return;
}
out.println(ub);
}
boolean check(double fuel) {
double tot = m + fuel;
for (int i = 0; i < n; i++) {
double x = tot / a[i];
if (x > fuel + EPS) return false;
fuel -= x;
tot -= x;
double y = tot / b[i + 1];
if (y > fuel + EPS) return false;
fuel -= y;
tot -= y;
}
return true;
}
public static void main(String[] args) {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
new Fly().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
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
3c4f5901f0ad979d178da2c6e310485e
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
import java.util.Scanner;
public class CCCC {
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
int n=scan.nextInt();
int m=scan.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=scan.nextInt();
if(a[i]<=1)
{
System.out.println(-1);
return;
}
}
int b[]=new int[n];
for(int i=0;i<n;i++)
{
b[i]=scan.nextInt();
if(b[i]<=1)
{
System.out.println(-1);
return;
}
}
double s=m;
s+=s/(a[0]-1);
for(int i=n-1;i>=1;i--)
{
s+=s/(b[i]-1);
s+=s/(a[i]-1);
}
s+=s/(b[0]-1);
System.out.printf("%.15f",s-m);
}
}
|
Java
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
9d88f9e86dfe66cff8248ba1faf4f0dd
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.util.stream.*;
import static java.lang.Math.*;
import java.util.function.Function; // Java 8 and up
public class C
{
public static void main(String []av) {
Scanner s = new Scanner();
int n = s.nextInt();
final int rocket = s.nextInt();
int [] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = s.nextInt();
int [] b = new int[n];
for (int i = 0; i < n; i++)
b[i] = s.nextInt();
int [] planets = IntStream.rangeClosed(0, n).toArray();
planets[n] = 0;
// System.err.println("Flight: " + Arrays.toString(planets));
Function<Double, Boolean> burn = (fuelleft) -> {
for (int i = 0; i < planets.length - 1; i++) {
double takeoff = a[planets[i]];
if (rocket + fuelleft > takeoff * fuelleft) {
return false;
}
fuelleft -= (rocket + fuelleft) / takeoff;
double landing = b[planets[i+1]];
if (rocket + fuelleft > landing * fuelleft)
return false;
fuelleft -= (rocket + fuelleft) / landing;
}
return true;
};
// burn.apply(10.0);
double fuel = binarySearch(burn, 0.0, 1e10);
if (fuel > 1e9 + 1e-3)
System.out.println(-1);
else
System.out.println(fuel);
}
/**
* Return x in [a, b] such that f(x) = y.
* f() must be monotonically increasing.
* Also known as bisection method.
*/
static double binarySearch(Function<Double, Boolean> f, double low, double high) {
// avoid excessive iterations when root is at 0.0
while ((high - low) > max(1e-16, 10 * Math.ulp(high))) {
double mid = (low + high)/2.0;
boolean midVal = f.apply(mid);
if (midVal) // or <=, see below.
high = mid;
else
low = mid;
}
return (low + high)/2.0;
}
//-----------Scanner class for faster input----------
/* Provides similar API as java.util.Scanner but does not
* use regular expression engine.
*/
public static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner(Reader in) {
br = new BufferedReader(in);
}
public Scanner() { this(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()); }
// Slightly different from java.util.Scanner.nextLine(),
// which returns any remaining characters in current line,
// if any.
String readNextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readIntArray(int n) {
int[] a = new int[n];
for (int idx = 0; idx < n; idx++) {
a[idx] = nextInt();
}
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int idx = 0; idx < n; idx++) {
a[idx] = nextLong();
}
return a;
}
}
//--------------------------------------------------------
}
|
Java
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
402a4dc72c0f30b36762b533c59794f3
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigInteger;
public class R499C {
public static void main (String[] args) throws java.lang.Exception {
InputReader in = new InputReader(System.in);
PrintWriter w = new PrintWriter(System.out);
int n = in.nextInt(), m = in.nextInt();
int[] a = in.nextIntArray(n), b = in.nextIntArray(n);
double temp = m;
if (a[n - 1] == 1 || b[0] == 1) {
w.println(-1);
w.close();
return;
}
temp += temp / (b[0] - 1);
temp += temp / (a[n - 1] - 1);
for (int i = n - 1; i > 0; i--) {
if (a[i-1] == 1 || b[i] == 1) {
w.println(-1);
w.close();
return;
}
temp += (temp / (b[i] - 1));
temp += (temp / (a[i - 1] - 1));
}
w.println(temp - m);
w.close();
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new UnknownError();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new UnknownError();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1)
return -1;
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0)
return -1;
}
return buf[curChar];
}
public void skip(int x) {
while (x-- > 0)
read();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public String nextString() {
return next();
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
StringBuffer buf = new StringBuffer();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r')
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
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 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 boolean hasNext() {
int value;
while (isSpaceChar(value = peek()) && value != -1)
read();
return value != -1;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
|
Java
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
d3ef3e27a030118130b8ab9db3c05f3f
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.solve());
}
private double solve() {
Scanner in = new Scanner(System.in);
int n = in.nextInt() * 2;
int m = in.nextInt();
int[] a = new int[n];
double ans = m;
for (int i = 0; i < n; ++i) {
a[i] = in.nextInt();
if (a[i] == 1) return -1;
ans *= (double) a[i] / (a[i] - 1);
}
return ans - m;
}
}
|
Java
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
4092c989296b068fa0b89667a45ad280
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
//package math_codet;
import java.io.*;
import java.util.*;
/******************************************
* AUTHOR: AMAN KUMAR SINGH *
* INSTITUITION: KALYANI GOVERNMENT ENGINEERING COLLEGE *
******************************************/
public class lets_do {
InputReader in;
PrintWriter out;
Helper_class h;
final long mod=1000000007;
final int N=200005;
final int MAX_Ai=1000005;
public static void main(String[] args) throws java.lang.Exception{
new lets_do().run();
}
void run() throws Exception{
in=new InputReader(System.in);
out = new PrintWriter(System.out);
h = new Helper_class();
int t=1;
while(t-->0)
solve();
out.flush();
out.close();
}
int n;
double k;
double[] arr1;
double[] arr2;
double eps=Math.pow(10,-7);
double check(double x){
boolean flag=false;
double weight=k+x;
double x1=x;
int i=0;
for(i=0;i<n-1;i++){
double zz=weight/arr1[i];
x1-=zz;
weight-=zz;
zz=weight/arr2[i+1];
x1-=zz;
weight-=zz;
}
double zz=weight/arr1[n-1];
x1-=zz;
weight-=zz;
zz=weight/arr2[0];
x1-=zz;
weight-=zz;
return x1;
}
void solve(){
n=h.ni();
k=(double)h.ni();
arr1=new double[n];
arr2=new double[n];
int i=0;
for(i=0;i<n;i++){
arr1[i]=(double)h.ni();
arr2[i]=(double)h.ni();
}
int count=0;
double low=0,high=(Math.pow(10,9)+1);
while(count<100){
double mid=(low+high)/2;
if(check(mid)<0)
low=mid;
else
high=mid;
count++;
}
if(low==(Math.pow(10,9)+1))
h.pn(-1);
else
h.pn(low);
}
class Entity{
long slope,intercept;
Entity(long s, long i){
slope=s;
intercept=i;
}
}
static final Comparator<Entity> com=new Comparator<Entity>(){
public int compare(Entity a, Entity b){
return Long.compare(b.slope,a.slope);
}
};
class Helper_class{
long gcd(long a, long b){return (b==0)?a:gcd(b,a%b);}
int gcd(int a, int b){return (b==0)?a:gcd(b,a%b);}
long gcd1(long a, long b){return (b==0)?a:gcd(b,a%b);}
int bitcount(long n){return (n==0)?0:(1+bitcount(n&(n-1)));}
void p(Object o){out.print(o);}
void pn(Object o){out.println(o);}
void pni(Object o){out.println(o);out.flush();}
String n(){return in.next();}
String nln(){return in.nextLine();}
int ni(){return in.nextInt();}
long nl(){return in.nextLong();}
double nd(){return in.nextDouble();}
long mul(long a,long b){
if(a>=mod)a%=mod;
if(b>=mod)b%=mod;
a*=b;
if(a>=mod)a%=mod;
return a;
}
long modPow(long a, long p){
long o = 1;
while(p>0){
if((p&1)==1)o = mul(o,a);
a = mul(a,a);
p>>=1;
}
return o;
}
long add(long a, long b){
if(a>=mod)a%=mod;
if(b>=mod)b%=mod;
if(b<0)b+=mod;
a+=b;
if(a>=mod)a-=mod;
return a;
}
}
class InputReader{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (numChars == -1)
throw new UnknownError();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new UnknownError();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int peek() {
if (numChars == -1)
return -1;
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
return -1;
}
if (numChars <= 0)
return -1;
}
return buf[curChar];
}
public void skip(int x) {
while (x-- > 0)
read();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public String nextString() {
return next();
}
public String next() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuffer res = new StringBuffer();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
StringBuffer buf = new StringBuffer();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r')
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public boolean hasNext() {
int value;
while (isSpaceChar(value = peek()) && value != -1)
read();
return value != -1;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
}
}
|
Java
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
194969f94589db4b7fb995cda5bec082
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import java.io.*;
import java.math.BigInteger;
public class MainClass {
public static void main(String[] args) {
FastReader in = new FastReader();
int n = in.nextInt(), m = in.nextInt();
double a[] = new double[n];
double b[] = new double[n];
for (int i=0; i<n; i++) {
a[i] = in.nextDouble();
}
for (int i=0; i<n; i++) {
b[i] = in.nextDouble();
}
double l = 0,r=1e12;
double ans = -1;
boolean flag = false;
for (int i=0; i<100; i++) {
double mid = (l+r)/2;
if(fun(mid,a,b,m)) {
r = mid;
flag = true;
}
else
l = mid;
}
//System.out.println(fun(22,a,b,m));
ans = r-m;
if(flag)
System.out.println(ans);
else
System.out.println("-1");
}
private static boolean fun(double mid, double[] a, double[] b, int m) {
int n = a.length;
for (int i=0; i<n; i++) {
if(i==0) {
mid -= mid/a[i];
}
else {
mid -= mid/b[i];
mid -= mid/a[i];
if(i==n-1)
mid -= mid/b[0];
}
}
//System.out.println(mid);
if(mid >= m) return true;
return false;
}
}
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\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
ff024ad84da57e40a33590c35037186d
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
import java.util.*;
public class PE
{
public static void main(String argsp[])
{
Scanner s = new Scanner(System.in);
int n=s.nextInt();
double m=s.nextDouble();
double ng=m,a=0.0;
for(int x=0;x<(n<<1);x++)
{
int aa=s.nextInt();
if(aa==1||ng-m>1e9)
{
System.out.println(-1);
System.exit(0);
}
ng/=(1.0d-1.0d/(double)(aa));
}
if((ng-m)>1e9)System.out.println(-1);
else System.out.println(ng-m);
}
}
|
Java
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
e42144af73dae422cf685cddd65d1c11
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
import java.util.*;
public class PE
{
public static void main(String argsp[])
{
Scanner s = new Scanner(System.in);
int n=s.nextInt();
double m=s.nextDouble();
double ng=m,a=0.0;
for(int x=0;x<(n<<1);x++)
{
int aa=s.nextInt();
if(aa==1)
{
System.out.println(-1);
System.exit(0);
}
ng/=(1.0d-1.0d/(double)(aa));
}
System.out.println(ng-m);
}
}
|
Java
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
67fb680d5e0b03ccffcef363e81332dc
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
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.FileReader;
import java.io.InputStreamReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
CFly solver = new CFly();
solver.solve(1, in, out);
out.close();
}
static class CFly {
static int RocketWeight;
static int n;
static int[] a;
static int[] b;
public double bs() {
double l = 0, h = 2e9, min = Integer.MAX_VALUE;
while (l + 1e-6 <= h) {
double mid = (l + h) / 2;
if (check(mid)) {
h = mid;
min = mid;
} else
l = mid;
}
return min;
}
private boolean check(double fuel) {
double curWeight = fuel + RocketWeight;
for (int i = 0; i < n; i++) {
curWeight -= curWeight / a[i];
if (i != 0)
curWeight -= curWeight / b[i];
if (curWeight < RocketWeight)
return false;
}
curWeight -= curWeight / b[0];
return curWeight >= RocketWeight;
}
public void solve(int testNumber, Scanner sc, PrintWriter pw) {
n = sc.nextInt();
RocketWeight = sc.nextInt();
a = new int[n];
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();
pw.print(bs() == Integer.MAX_VALUE ? -1 : bs());
}
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(FileReader r) {
br = new BufferedReader(r);
}
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
|
Java
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
601d9d17622343e47aed17c727487d87
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.FilterInputStream;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.File;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Atharva Nagarkar
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
JoltyScanner in = new JoltyScanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
int n;
int m;
int[] takeOff;
int[] land;
boolean possible(double fuel) {
for (int planet = 0; planet < n; ++planet) {
if (fuel < 0) return false;
double curmass = m + fuel;
double tof = curmass / takeOff[planet];
fuel -= tof;
if (fuel < 0) return false;
curmass = m + fuel;
double lf = curmass / land[(planet + 1) % n];
fuel -= lf;
}
return fuel >= 1e-9;
}
public void solve(int testNumber, JoltyScanner in, PrintWriter out) {
n = in.nextInt();
m = in.nextInt();
takeOff = new int[n];
land = new int[n];
for (int i = 0; i < n; ++i) takeOff[i] = in.nextInt();
for (int i = 0; i < n; ++i) land[i] = in.nextInt();
double hi = 1e10;
double lo = 0;
for (int i = 0; i < 100; ++i) {
double mid = (hi + lo) / 2;
if (possible(mid)) hi = mid;
else lo = mid;
}
if (lo > 2e9) out.println(-1);
else out.println(lo);
}
}
static class JoltyScanner {
public int BS = 1 << 16;
public char NC = (char) 0;
public byte[] buf = new byte[BS];
public int bId = 0;
public int size = 0;
public char c = NC;
public double num = 1;
public BufferedInputStream in;
public JoltyScanner(InputStream is) {
in = new BufferedInputStream(is, BS);
}
public JoltyScanner(String s) throws FileNotFoundException {
in = new BufferedInputStream(new FileInputStream(new File(s)), BS);
}
public char nextChar() {
while (bId == size) {
try {
size = in.read(buf);
} catch (Exception e) {
return NC;
}
if (size == -1) return NC;
bId = 0;
}
return (char) buf[bId++];
}
public int nextInt() {
return (int) nextLong();
}
public long nextLong() {
num = 1;
boolean neg = false;
if (c == NC) c = nextChar();
for (; (c < '0' || c > '9'); c = nextChar()) {
if (c == '-') neg = true;
}
long res = 0;
for (; c >= '0' && c <= '9'; c = nextChar()) {
res = (res << 3) + (res << 1) + c - '0';
num *= 10;
}
return neg ? -res : res;
}
}
}
|
Java
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
18998f1a3d1d6c8d0609e0a46d495da8
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
import java.util.* ;
import java.io.BufferedReader ;
import java.io.InputStreamReader ;
public class Fly
{
public static void main(String args[]) throws Exception
{
BufferedReader bro = new BufferedReader(new InputStreamReader(System.in)) ;
int N = Integer.parseInt(bro.readLine()) ;
int W = Integer.parseInt(bro.readLine()) ;
String[] S = bro.readLine().split(" ") ;
int[] T = new int[N] ;
int[] L = new int[N] ;
for(int i=0;i<N;i++)
{
T[i] = Integer.parseInt(S[i]) ;
}
S = bro.readLine().split(" ") ;
for(int i=0;i<N;i++)
{
L[i] = Integer.parseInt(S[i]) ;
}
double ans = solve(T,L,W) ;
System.out.println(ans==-1.0?-1:ans-W) ;
}
static double solve(int[] T,int[] L,int w)
{
// List<Integer> L = new ArrayList<Integer>() ;
int[] A = new int[2*T.length] ;
for(int i=0;i<A.length;i+=2)
{
A[i] = T[i/2] ;
}
for(int i=1;i<L.length;i++)
{
A[2*i-1] = L[i] ;
}
A[A.length-1] = L[0] ;
double sum = w ;
for(int i=0;i<A.length;i++)
{
if(A[i]==1)
return -1 ;
sum+=(double)(sum/(A[i]-1)) ;
}
return sum ;
}
}
|
Java
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
c5233b11ee22dd8af497a627e0fe21be
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
import java.io.*;
import java.util.*;
public class Main {
private final static long mod = 1000000007;
private static void printArr2(long arr[][]) {
int i, j, n = arr.length, m = arr[0].length;
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
private static void printArr(int arr[][]) {
int i, j, n = arr.length, m = arr[0].length;
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
private static long power(long x, long y) {
long temp;
if (y == 0)
return 1;
temp = power(x, y / 2);
temp = (temp * temp) % mod;
if (y % 2 == 0)
return temp;
else
return ((x % mod) * temp) % mod;
}
private static int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
private static int cmp(Pair p, Pair q) {
return p.sz == q.sz ? p.mt - q.mt : p.sz - q.sz;
}
static int nextPowerOf2(int n) {
int count = 0;
if (n > 0 && (n & (n - 1)) == 0)
return n * 2;
while (n != 0) {
n >>= 1;
count += 1;
}
return 1 << count;
}
static String isPrime(int n){
int i;
for(i=2;i*i<n;i++){
if(n%i==0)return "Not prime";
}
return "Prime";
}
private static long[] computeTotient(int n) {
long phi[] = new long[n + 1];
for (int i = 1; i <= n; i++)
phi[i] = i;
for (int p = 2; p <= n; p++) {
if (phi[p] == p) {
phi[p] = p - 1;
for (int i = 2 * p; i <= n; i += p) {
phi[i] = (phi[i] / p) * (p - 1);
}
}
}
return phi;
}
public static List<Integer> preOrder(int [][]tree, int n, List<Integer> list){
if (n==0){
return list;
}else{
list.add(n);
preOrder(tree,tree[n][0],list);
preOrder(tree,tree[n][1],list);
}
return list;
}
public static List<Integer> postOrder(int [][]tree, int n, List<Integer> list){
if (n==0){
return list;
}else{
postOrder(tree,tree[n][0],list);
postOrder(tree,tree[n][1],list);
list.add(n);
}
return list;
}
private static boolean isPossible(int a[],int b[],int wt,double fuel){
for(int i=0;i<a.length;i++){
double rf=(wt+fuel)/a[i];
fuel-=rf;
rf=(wt+fuel)/b[i];
fuel-=rf;
if(fuel<0)return false;
}
return true;
}
public static void main(String[] args) throws IOException {
FastReader in = new FastReader();
FastWriter out = new FastWriter();
int t, i, j, k, r, l = 0,g, m = 0, x, d,n,ti;
long ans = 0, sum=0, cur, w, mx = -mod, mn = mod,y;
//tc:for (t = in.nextInt(),ti=1; ti <= t; ti++)
{
//out.print(String.format("Case #%d: ", ti));
n=in.nextInt();
m=in.nextInt();
int a[]=in.nextIntArr(n);
int b1[]=in.nextIntArr(n);
int b[]=new int[b1.length];
for(i=0;i<n;i++){
b[i]=b1[(i+1)%n];
}
for(i=0;i<n;i++){
if(a[i]==1||b[i]==1){
out.println(-1);
return;
}
}
double pmid=-2;
double lo=0,hi=2e9,mid=-1;
while (Math.abs(mid-pmid)>1e-9){
pmid=mid;
mid=(lo+hi)/2;
if(isPossible(a,b,m,mid))hi=mid-1e-9;
else lo=mid+1e-9;
}
if(hi>1e9+100)out.println(-1);
else
out.println(hi);
}
}
private static class Pair {
int sz;
int mt;
public Pair(int sz, int mt) {
this.sz = sz;
this.mt = mt;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
return sz == pair.sz &&
mt == pair.mt;
}
@Override
public int hashCode() {
return Objects.hash(sz, mt);
}
}
static class FastReader {
private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private StringTokenizer st;
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] nextIntArr(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
long[] nextLongArr(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
}
static class FastWriter {
BufferedWriter bw;
List<String> list = new ArrayList<>();
Set<String> set = new HashSet<>();
FastWriter() {
bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
<T> void print(T obj) throws IOException {
bw.write(obj.toString());
bw.flush();
}
void println() throws IOException {
print("\n");
}
<T> void println(T obj) throws IOException {
print(obj.toString() + "\n");
}
<T> void printArrLn(T[] arr) throws IOException {
for (int i = 0; i < arr.length-1; i++) {
print(arr[i] + " ");
}
println(arr[arr.length-1]);
}
<T> void printListLn(List<T> arr) throws IOException {
for (int i = 0; i < arr.size(); i++) {
print(arr.get(i) + " ");
}
println();
}
void printCharN(char c, int n) throws IOException {
for (int i = 0; i < n; i++) {
print(c);
}
}
}
}
|
Java
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
451db91c34c46d8e66b1ac5298b8a8aa
|
train_001.jsonl
|
1532617500
|
Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on $$$n - 2$$$ intermediate planets. Formally: we number all the planets from $$$1$$$ to $$$n$$$. $$$1$$$ is Earth, $$$n$$$ is Mars. Natasha will make exactly $$$n$$$ flights: $$$1 \to 2 \to \ldots n \to 1$$$.Flight from $$$x$$$ to $$$y$$$ consists of two phases: take-off from planet $$$x$$$ and landing to planet $$$y$$$. This way, the overall itinerary of the trip will be: the $$$1$$$-st planet $$$\to$$$ take-off from the $$$1$$$-st planet $$$\to$$$ landing to the $$$2$$$-nd planet $$$\to$$$ $$$2$$$-nd planet $$$\to$$$ take-off from the $$$2$$$-nd planet $$$\to$$$ $$$\ldots$$$ $$$\to$$$ landing to the $$$n$$$-th planet $$$\to$$$ the $$$n$$$-th planet $$$\to$$$ take-off from the $$$n$$$-th planet $$$\to$$$ landing to the $$$1$$$-st planet $$$\to$$$ the $$$1$$$-st planet.The mass of the rocket together with all the useful cargo (but without fuel) is $$$m$$$ tons. However, Natasha does not know how much fuel to load into the rocket. Unfortunately, fuel can only be loaded on Earth, so if the rocket runs out of fuel on some other planet, Natasha will not be able to return home. Fuel is needed to take-off from each planet and to land to each planet. It is known that $$$1$$$ ton of fuel can lift off $$$a_i$$$ tons of rocket from the $$$i$$$-th planet or to land $$$b_i$$$ tons of rocket onto the $$$i$$$-th planet. For example, if the weight of rocket is $$$9$$$ tons, weight of fuel is $$$3$$$ tons and take-off coefficient is $$$8$$$ ($$$a_i = 8$$$), then $$$1.5$$$ tons of fuel will be burnt (since $$$1.5 \cdot 8 = 9 + 3$$$). The new weight of fuel after take-off will be $$$1.5$$$ tons. Please note, that it is allowed to burn non-integral amount of fuel during take-off or landing, and the amount of initial fuel can be non-integral as well.Help Natasha to calculate the minimum mass of fuel to load into the rocket. Note, that the rocket must spend fuel to carry both useful cargo and the fuel itself. However, it doesn't need to carry the fuel which has already been burnt. Assume, that the rocket takes off and lands instantly.
|
256 megabytes
|
import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class A {
static Scanner s = new Scanner(System.in);
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
int n = Integer.parseInt(reader.readLine());
double m = Double.parseDouble(reader.readLine());
final double startM = m;
String[] line = reader.readLine().split(" ");
String[] line2 = reader.readLine().split(" ");
int[] a = new int[n];
int[] b = new int[n];
for(int i = 0; i < n; i++) {
a[i] = Integer.parseInt(line[i]);
b[i] = Integer.parseInt(line2[i]);
}
int ans = 0;
for(int i = 0; i < n; i++) {
if(m - startM > 1_000_000_001) break;
double x = m / (b[i] - 1);
m += x;
if(m - startM > 1_000_000_001) break;
x = m / (a[getIndex(i + 1, n)] - 1);
m += x;
}
System.out.println(m - startM > 1_000_000_001 ? -1 : m - startM);
} catch(IOException e) {
}
}
static int getIndex(int i, int n) {
if(i == n) return 0;
return i;
}
}
|
Java
|
["2\n12\n11 8\n7 5", "3\n1\n1 4 1\n2 5 3", "6\n2\n4 6 3 3 5 6\n2 6 3 6 5 3"]
|
1 second
|
["10.0000000000", "-1", "85.4800000000"]
|
NoteLet's consider the first example.Initially, the mass of a rocket with fuel is $$$22$$$ tons. At take-off from Earth one ton of fuel can lift off $$$11$$$ tons of cargo, so to lift off $$$22$$$ tons you need to burn $$$2$$$ tons of fuel. Remaining weight of the rocket with fuel is $$$20$$$ tons. During landing on Mars, one ton of fuel can land $$$5$$$ tons of cargo, so for landing $$$20$$$ tons you will need to burn $$$4$$$ tons of fuel. There will be $$$16$$$ tons of the rocket with fuel remaining. While taking off from Mars, one ton of fuel can raise $$$8$$$ tons of cargo, so to lift off $$$16$$$ tons you will need to burn $$$2$$$ tons of fuel. There will be $$$14$$$ tons of rocket with fuel after that. During landing on Earth, one ton of fuel can land $$$7$$$ tons of cargo, so for landing $$$14$$$ tons you will need to burn $$$2$$$ tons of fuel. Remaining weight is $$$12$$$ tons, that is, a rocket without any fuel.In the second case, the rocket will not be able even to take off from Earth.
|
Java 8
|
standard input
|
[
"binary search",
"greedy",
"math"
] |
d9bd63e03bf51ed87ba73cd15e8ce58d
|
The first line contains a single integer $$$n$$$ ($$$2 \le n \le 1000$$$) — number of planets. The second line contains the only integer $$$m$$$ ($$$1 \le m \le 1000$$$) — weight of the payload. The third line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 1000$$$), where $$$a_i$$$ is the number of tons, which can be lifted off by one ton of fuel. The fourth line contains $$$n$$$ integers $$$b_1, b_2, \ldots, b_n$$$ ($$$1 \le b_i \le 1000$$$), where $$$b_i$$$ is the number of tons, which can be landed by one ton of fuel. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel.
| 1,500 |
If Natasha can fly to Mars through $$$(n - 2)$$$ planets and return to Earth, print the minimum mass of fuel (in tons) that Natasha should take. Otherwise, print a single number $$$-1$$$. It is guaranteed, that if Natasha can make a flight, then it takes no more than $$$10^9$$$ tons of fuel. The answer will be considered correct if its absolute or relative error doesn't exceed $$$10^{-6}$$$. Formally, let your answer be $$$p$$$, and the jury's answer be $$$q$$$. Your answer is considered correct if $$$\frac{|p - q|}{\max{(1, |q|)}} \le 10^{-6}$$$.
|
standard output
| |
PASSED
|
9250a3c4d57a8737bc0bd7dcdaa673b8
|
train_001.jsonl
|
1390231800
|
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1).Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder.
|
256 megabytes
|
import java.util.*;
public class Coder {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int total = sc.nextInt();
if(total==1){
System.out.println("1");
System.out.println("C");
return;
}
char[][] arr = new char[total][total];
int sum=0;
for(int i=0;i<2;i++){
for(int j=0;j<total;j++){
if(i%2==0){
if(j%2==0){
arr[i][j] = 'C';
sum++;
}
else{
arr[i][j] = '.';
}
}
else{
if(j%2==0){
arr[i][j] = '.';
}
else{
arr[i][j] = 'C';
sum++;
}
}
}
}
String str1 = new String(arr[0]);
String str2 = new String(arr[1]);
if(total%2==0){
System.out.println(sum*(total/2));
}
else{
System.out.println(sum*(total/2) + sum/2 + 1);
}
for(int i=0;i<total;i++){
if(i%2==0){
System.out.println(str1);
}
else{
System.out.println(str2);
}
}
}
}
|
Java
|
["2"]
|
1 second
|
["2\nC.\n.C"]
| null |
Java 8
|
standard input
|
[
"implementation"
] |
1aede54b41d6fad3e74f24a6592198eb
|
The first line contains an integer n (1 ≤ n ≤ 1000).
| 800 |
On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any.
|
standard output
| |
PASSED
|
aec6d811df50a930cc6d83c80698bf0f
|
train_001.jsonl
|
1390231800
|
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1).Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder.
|
256 megabytes
|
import java.util.Arrays;
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int no=sc.nextInt();
int b[]= new int [1001];
int fac=0;
b[0]=1;
for(int i=2;i<1001;i++){
b[i]=b[i-2]+4*(fac);
fac++;
i++;
}
if(no%2==0){
System.out.println(((no)*(no))/2);
}
else
{
System.out.println(b[no+1]);
}
String c1="",c2="";
for(int i=1;i<=no;i++){
if(i%2==0)
{c1=c1+".";
c2=c2+"C";}
if(i%2!=0){
c1=c1+"C";
c2=c2+".";
}
}
for(int i=1;i<=no;i++){
if(i%2!=0)
System.out.println(c1);
else
System.out.println(c2);
}
}
}
|
Java
|
["2"]
|
1 second
|
["2\nC.\n.C"]
| null |
Java 8
|
standard input
|
[
"implementation"
] |
1aede54b41d6fad3e74f24a6592198eb
|
The first line contains an integer n (1 ≤ n ≤ 1000).
| 800 |
On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any.
|
standard output
| |
PASSED
|
903dfbd108dd99e26eca9f58c31480c2
|
train_001.jsonl
|
1390231800
|
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1).Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder.
|
256 megabytes
|
import java.util.Scanner;
public class zransom {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int y = (int) Math.ceil((Math.pow(a, 2)) / 2);
String[][] p = new String[(int) a][(int) a];
System.out.println(y);
String ab = "";
String av = "";
for (int i = 0; i <= 2; i++) {
for (int j = 0; j < a; j++) {
if (i == 0) {
if ((i % 2 == 0 && j % 2 == 0) || (i % 2 == 1 && j % 2 == 1)) {
ab = ab + "C";
} else {
ab = ab + ".";
}
} else if (i == 1) {
if ((j % 2 == 1)) {
av = av + "C";
} else {
av = av + ".";
}
}
}
}
for (int i = 0; i < a / 2; i++) {
System.out.println(ab);
System.out.println(av);
}
if (a%2 == 1) {
System.out.println(ab);
}
}
}
|
Java
|
["2"]
|
1 second
|
["2\nC.\n.C"]
| null |
Java 8
|
standard input
|
[
"implementation"
] |
1aede54b41d6fad3e74f24a6592198eb
|
The first line contains an integer n (1 ≤ n ≤ 1000).
| 800 |
On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any.
|
standard output
| |
PASSED
|
43cb91b9b95f813c2801ee10f2471605
|
train_001.jsonl
|
1390231800
|
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1).Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder.
|
256 megabytes
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
@SuppressWarnings("unused")
public class A {
public static Scanner scan = new Scanner(System.in);
public static void solve () {
int n=scan.nextInt();
StringBuilder s= new StringBuilder();
int cnt=0;
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
if((i+j)%2==0) {
s.append('C');
cnt++;
}
else {
s.append('.');
}
}
s.append('\n');
}
System.out.println(cnt);
System.out.println(s.toString());
}
public static void main(String[] args) {
solve();
scan.close();
}
}
|
Java
|
["2"]
|
1 second
|
["2\nC.\n.C"]
| null |
Java 8
|
standard input
|
[
"implementation"
] |
1aede54b41d6fad3e74f24a6592198eb
|
The first line contains an integer n (1 ≤ n ≤ 1000).
| 800 |
On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any.
|
standard output
| |
PASSED
|
c02d152fa706e5ce4d190cde9a42213b
|
train_001.jsonl
|
1390231800
|
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1).Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder.
|
256 megabytes
|
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.lang.*;
public class P384A {
//static long m=1000000007;
static BigInteger ways(int N, int K) {
BigInteger ret = BigInteger.ONE;
for(int i=N;i>=N-K+1;i--)
{
ret = ret.multiply(BigInteger.valueOf(i));
}
for (int j = 1; j<=K; j++) {
ret = ret.divide(BigInteger.valueOf(j));
}
ret=ret.mod(BigInteger.valueOf(1000000007));
return ret;
}
public static int prime(int n)
{
int f=1;
if(n==1)
return 0;
for(int i=2;i<=(Math.sqrt(n));)
{
if(n%i==0)
{
f=0;
break;
}
if(i==2)
i++;
else
i+=2;
}
if(f==1)
return 1;
else
return 0;
}
/*public static long gcd(long x,long y)
{
if(x%y==0)
return y;
else return gcd(y,x%y);
}*/
public static BigInteger fact(int n)
{
BigInteger f=BigInteger.ONE;
for(int i=1;i<=n;i++)
{
f=f.multiply(BigInteger.valueOf(i));
}
//f=f.mod(BigInteger.valueOf(m));
return f;
}
public static int gcd(int x,int y)
{
if(x%y==0)
return y;
else return gcd(y,x%y);
}
public static int max(int a,int b)
{
if(a>b)
return a;
else
return b;
}
public static int min(int a,int b)
{
if(a>b)
return b;
else
return a;
}
public static void main(String[] args) throws Exception{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb=new StringBuilder("");
//int t=Integer.parseInt(br.readLine());
// while(t-->0)
//{
//int n=Integer.parseInt(br.readLine());
//long n=Long.parseLong(br.readLine());
//String l[]=br.readLine().split(" ");
//int m=Integer.parseInt(l[0]);
//int k=Integer.parseInt(l[1]);
//l=br.readLine().split(" ");
//long m=Long.parseLong(l[0]);
//long n=Long.parseLong(l[1]);
//char ch=a.charAt();
// char c[]=new char[n];
//String l[]=br.readLine().split(" ");
//l=br.readLine().split(" ");
/*int a[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=Integer.parseInt(l[i]);
}*/
/*long a[]=new long[n];
for(int i=0;i<n;i++)
{
a[i]=Long.parseLong(l[i]);
}*/
/*int a[][]=new int[n][n];
for(int i=0;i<n;i++)
{
l=br.readLine().split(" ");
for(int j=0;j<n;j++)
{
a[i][j]=Long.parseLong(l[j]);
}
}*/
// String a=br.readLine();
// char a[]=c.toCharArray();
//char ch=l[0].charAt(0);
//HashMap<Integer,Integer>hm=new HashMap<Integer,Integer>();
//HashMap<Integer,String>hm=new HashMap<Integer,String>();
//HashMap<Integer,Long>hm=new HashMap<Integer,Long>();
//hm.put(1,1);
//HashSet<Integer>hs=new HashSet<Integer>();
//HashSet<Long>hs=new HashSet<Long>();
//HashSet<String>hs=new HashSet<String>();
//hs.add(x);
//Stack<Integer>s=new Stack<Integer>();
//s.push(x);
//s.pop(x);
//Queue<Integer>q=new LinkedList<Integer>();
//q.add(x);
//q.remove(x);
//ArrayList<Integer>ar=new ArrayList<Integer>();
//long x=Long.parseLong(l[0]);
//int min=100000000;
//long c1=(long)Math.ceil(n/(double)a);
//Arrays.sort(a);
// int f1[]=new int[26];
//int f2[]=new int[26];
/*for(int i=0;i<n;i++)package Codeforces;
public class P330A {
}
{
int x=a.charAt(0);
f1[x-97]++;
}*/
/*for(int i=0;i<n;i++)
{
}*/
/*for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
}
}*/
/*while(q--)
{
l=br.readLine().split(" ");
int n=Integer.parseInt(l[0]);
int k=Integer.parseInt(l[1]);
}
*/
/*if(f==1)
System.out.println("Yes");
else
System.out.println("No");*/
//System.out.print("");
//sb.append("");
//sb.append("").append("\n");
int n=Integer.parseInt(br.readLine());
System.out.println((long)Math.ceil((n*n)/2.0));
int e=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if((j+e)%2==0)
{
sb.append("C");
}
else
sb.append(".");
}
if(i%2==0)
e=1;
else
e=0;
sb.append("\n");
}
System.out.print(sb);
//}
}
}
|
Java
|
["2"]
|
1 second
|
["2\nC.\n.C"]
| null |
Java 8
|
standard input
|
[
"implementation"
] |
1aede54b41d6fad3e74f24a6592198eb
|
The first line contains an integer n (1 ≤ n ≤ 1000).
| 800 |
On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any.
|
standard output
| |
PASSED
|
b9e93d8bc71cd9f3f53211ef9dc71791
|
train_001.jsonl
|
1390231800
|
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1).Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder.
|
256 megabytes
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Coder
{
public static void main(String[] args) throws IOException
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine());
System.out.println((n * n + 1) / 2);
int ind = 0;
boolean even = n % 2 == 0;
StringBuilder print = new StringBuilder();
for (int i = 0; i < n; i++)
{
for (int k = 0; k < n; k ++)
{
if (ind % 2 == 0)
print.append("C");
else
print.append(".");
ind++;
}
if (even)
ind++;
print.append("\n");
}
print.delete(print.length() - 1, print.length());
System.out.println(print);
}
}
|
Java
|
["2"]
|
1 second
|
["2\nC.\n.C"]
| null |
Java 8
|
standard input
|
[
"implementation"
] |
1aede54b41d6fad3e74f24a6592198eb
|
The first line contains an integer n (1 ≤ n ≤ 1000).
| 800 |
On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any.
|
standard output
| |
PASSED
|
e706fc9a727a47aca362b9016f1199ad
|
train_001.jsonl
|
1390231800
|
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1).Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder.
|
256 megabytes
|
import java.util.*;
public class Car {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String x1 = "";
String x2 = "";
System.out.println((n / 2 + n % 2) * (n / 2 + n % 2) + (n / 2) * (n / 2));
for (int i = 1; i <= n; i++) {
if (i % 2 == 1) {
x1 += "C";
x2 += ".";
}
else {
x1 += ".";
x2 += "C";
}
}
for (int j = 1; j <= n; j++) {
if (j % 2 == 1) System.out.println(x1);
else System.out.println(x2);
}
}
}
|
Java
|
["2"]
|
1 second
|
["2\nC.\n.C"]
| null |
Java 8
|
standard input
|
[
"implementation"
] |
1aede54b41d6fad3e74f24a6592198eb
|
The first line contains an integer n (1 ≤ n ≤ 1000).
| 800 |
On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any.
|
standard output
| |
PASSED
|
0cb1b3e7a3114fde798557fcadb98552
|
train_001.jsonl
|
1390231800
|
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1).Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
StringBuilder sb = new StringBuilder();
int cnt = 0;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if ((i + j) % 2 == 0)
{
sb.append("C");
cnt ++;
}
else
{
sb.append(".");
}
}
sb.append("\n");
}
System.out.println(cnt);
System.out.print(sb.toString());
}
}
|
Java
|
["2"]
|
1 second
|
["2\nC.\n.C"]
| null |
Java 8
|
standard input
|
[
"implementation"
] |
1aede54b41d6fad3e74f24a6592198eb
|
The first line contains an integer n (1 ≤ n ≤ 1000).
| 800 |
On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any.
|
standard output
| |
PASSED
|
0a36374826c23fc84823b044069c91a2
|
train_001.jsonl
|
1390231800
|
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1).Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder.
|
256 megabytes
|
import java.util.Scanner;
public class Main384A {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
int n = in.nextInt();
System.out.println((n * n + 1) / 2);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
sb.append((i + j) % 2 == 0 ? "C" : ".");
}
sb.append("\n");
}
System.out.println(sb);
}
}
}
|
Java
|
["2"]
|
1 second
|
["2\nC.\n.C"]
| null |
Java 8
|
standard input
|
[
"implementation"
] |
1aede54b41d6fad3e74f24a6592198eb
|
The first line contains an integer n (1 ≤ n ≤ 1000).
| 800 |
On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any.
|
standard output
| |
PASSED
|
244bf5f86ede8302b3698ae796182fd2
|
train_001.jsonl
|
1390231800
|
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1).Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder.
|
256 megabytes
|
import java.util.Scanner;
public class JavaApplication119 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
int n=in.nextInt();
System.out.println((n*n+1)/2);
int c=0;
String a = "";
String t = "";
for(int i=0;i<n;i++){
if(i%2==0){
a+="C"; t+="." ; }
else{
a+="."; t+="C" ; }}
for(int i=0;i<n;i++){
System.out.println((i%2)==0?a:t);
}}}
|
Java
|
["2"]
|
1 second
|
["2\nC.\n.C"]
| null |
Java 8
|
standard input
|
[
"implementation"
] |
1aede54b41d6fad3e74f24a6592198eb
|
The first line contains an integer n (1 ≤ n ≤ 1000).
| 800 |
On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any.
|
standard output
| |
PASSED
|
f579112b498606585d9ccca32de297e0
|
train_001.jsonl
|
1390231800
|
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1).Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder.
|
256 megabytes
|
import java.util.*;
public class Solution {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
if (n % 2 == 0) System.out.println(n*n/2);
if(n % 2 != 0) System.out.println(n*n/2 +1);
for (int i = 1; i <= n; i++) {
String str = "";
String str1 = "";
for (int j = 1; j <= n; j++) {
if(i % 2 !=0){
if(j % 2 !=0){
str+="C";
}
else str+=".";
}
else {
if (j % 2 == 0){
str+="C";
}
else str+=".";
}
}
System.out.println(str);
}
}
}
|
Java
|
["2"]
|
1 second
|
["2\nC.\n.C"]
| null |
Java 8
|
standard input
|
[
"implementation"
] |
1aede54b41d6fad3e74f24a6592198eb
|
The first line contains an integer n (1 ≤ n ≤ 1000).
| 800 |
On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any.
|
standard output
| |
PASSED
|
b83c180f8ee78ecbd7acd7fad87ace1a
|
train_001.jsonl
|
1390231800
|
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1).Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder.
|
256 megabytes
|
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int c = n*n / 2;
boolean [][] chess = new boolean [n][n];
int counter = 0;
for (int i = 0; i < n; i++) {
for (int j = i % 2; j < n; j += 2) {
chess[i][j] = true;
counter++;
}
}
System.out.println(counter);
for (int i = 0; i < n; i++) {
String s = "";
for (int j = 0; j < n; j++) {
s += chess[i][j] ? "C" : ".";
}
System.out.println(s);
}
}
}
|
Java
|
["2"]
|
1 second
|
["2\nC.\n.C"]
| null |
Java 8
|
standard input
|
[
"implementation"
] |
1aede54b41d6fad3e74f24a6592198eb
|
The first line contains an integer n (1 ≤ n ≤ 1000).
| 800 |
On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any.
|
standard output
| |
PASSED
|
368d9dc7fa8c5f6e06c915883508efd9
|
train_001.jsonl
|
1390231800
|
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1).Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder.
|
256 megabytes
|
import java.util.*;
import java.io.*;
public class Solution {
public static void main(String[] args)throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out,true);
int n = Integer.parseInt(br.readLine());
if(n == 1){
out.println(1);
out.println("C");
System.exit(0);
}
out.println((int)Math.ceil(n*n/(2*1.0)));
for(int i =0;i<n;i++){
for(int j =0;j<n;j++){
if(i%2==0&&j%2==0){
out.print("C");
}
else if(i%2!=0&&j%2!=0){
out.print("C");
}
else{
out.print(".");
}
}
out.println();
}
}
}
|
Java
|
["2"]
|
1 second
|
["2\nC.\n.C"]
| null |
Java 8
|
standard input
|
[
"implementation"
] |
1aede54b41d6fad3e74f24a6592198eb
|
The first line contains an integer n (1 ≤ n ≤ 1000).
| 800 |
On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any.
|
standard output
| |
PASSED
|
83084dc5f48760a7727544f6e1d4affe
|
train_001.jsonl
|
1390231800
|
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1).Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder.
|
256 megabytes
|
import java.util.Scanner;
public class Coder {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int max = 0;
if(n % 2 == 0){
max = n /2 * n ;
}else {
int temp = n / 2 ;
max = temp * temp + ((temp + 1) *(temp + 1)) ;
}
System.out.println(max);
String even = "" ;
String odd = "" ;
int temp = 0 ;
if(n % 2 == 0){
temp = n / 2 ;
for(int i = 0 ; i < temp ; i++){
even += "C." ;
odd += ".C" ;
}
for(int i = 0 ; i < temp; i++){
System.out.println(even);
System.out.println(odd);
}
}else {
temp = n / 2 ;
for(int i = 0 ; i < temp ; i++){
even += "C." ;
odd += ".C" ;
}
even += 'C' ;
odd += '.' ;
for(int i = 0 ; i < temp; i++){
System.out.println(even);
System.out.println(odd);
}
System.out.println(even);
}
input.close();
}
}
|
Java
|
["2"]
|
1 second
|
["2\nC.\n.C"]
| null |
Java 8
|
standard input
|
[
"implementation"
] |
1aede54b41d6fad3e74f24a6592198eb
|
The first line contains an integer n (1 ≤ n ≤ 1000).
| 800 |
On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any.
|
standard output
| |
PASSED
|
380e79f8f8be17a2f043783642f8f773
|
train_001.jsonl
|
1390231800
|
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1).Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder.
|
256 megabytes
|
import java.util.*;
import java.io.*;
import static java.lang.System.*;
public class theatre {
public static void main(String[]Kowalski)
{
Scanner in=new Scanner(System.in);
int N=in.nextInt();
String[][]mat=new String[N][N];
int c=0;
//2=2
//4=8
//6=18
if(N%2==0)
{
c=N*N/2;
}
else
{
//3=5
//5=13
//7=25
c=N*(N/2);
c+=(int)Math.ceil(N/2.0);
}
out.println(c);
String first="";
String second="";
for(int x=0;x<N;x++)
{
for(int y=0;y<N && (first.length()!=N||second.length()!=N);y++)
{
if(x%2==0)
{
if(y%2==0)
{
first+="C";
}
else
first+=".";
}
else
{
if(y%2==0)
second+=".";
else
{
second+="C";
}
}
}
if(first.length()==N && x%2==0)
out.println(first);
else if(second.length()==N && x%2==1)
out.println(second);
}
}
}
|
Java
|
["2"]
|
1 second
|
["2\nC.\n.C"]
| null |
Java 8
|
standard input
|
[
"implementation"
] |
1aede54b41d6fad3e74f24a6592198eb
|
The first line contains an integer n (1 ≤ n ≤ 1000).
| 800 |
On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any.
|
standard output
| |
PASSED
|
953e2be79d7d97271eafe645aa16fc60
|
train_001.jsonl
|
1390231800
|
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (x–1, y), (x, y + 1) and (x, y–1).Iahub wants to know how many Coders can be placed on an n × n chessboard, so that no Coder attacks any other Coder.
|
256 megabytes
|
import java.util.Scanner;
public class Coder {
public static int n=0,count=0;
public static String matrix[];
//x =n
public static void printChees(){
for(int i=0;i<n;i++){
System.out.println(matrix[i]);
}
}
public static void countCoders(int x){
matrix = new String [n];
for(int i=0;i<x;i++){
matrix[i]="";
for(int j=0;j<x;j++){
if((i+j)%2==0){
count++;
matrix[i]+="C";}
else
matrix[i]+=".";
}
}
System.out.println(count);
printChees();
}
public static void main(String[]args){
Scanner input = new Scanner(System.in);
n =input.nextInt();
countCoders(n);
}
}
|
Java
|
["2"]
|
1 second
|
["2\nC.\n.C"]
| null |
Java 8
|
standard input
|
[
"implementation"
] |
1aede54b41d6fad3e74f24a6592198eb
|
The first line contains an integer n (1 ≤ n ≤ 1000).
| 800 |
On the first line print an integer, the maximum number of Coders that can be placed on the chessboard. On each of the next n lines print n characters, describing the configuration of the Coders. For an empty cell print an '.', and for a Coder print a 'C'. If there are multiple correct answers, you can print any.
|
standard output
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.