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 | cf3bc50bd84960c9c4c2a982e6ae4eeb | train_003.jsonl | 1314633600 | Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.One day Petya encountered a tree with n vertexes. Besides, the tree was weighted, i. e. each edge of the tree has weight (a positive integer). An edge is lucky if its weight is a lucky number. Note that a tree with n vertexes is an undirected connected graph that has exactly n - 1 edges.Petya wondered how many vertex triples (i, j, k) exists that on the way from i to j, as well as on the way from i to k there must be at least one lucky edge (all three vertexes are pairwise distinct). The order of numbers in the triple matters, that is, the triple (1, 2, 3) is not equal to the triple (2, 1, 3) and is not equal to the triple (1, 3, 2). Find how many such triples of vertexes exist. | 256 megabytes | /**
* Created with IntelliJ IDEA.
* User: yuantian
* Date: 4/29/13
* Time: 11:08 PM
* Copyright (c) 2013 All Right Reserved, http://github.com/tyuan73
*/
import java.util.*;
public class LuckyTree84Div2 {
static long total = 0;
static boolean[] visited;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
long n = in.nextLong();
List<Integer>[] tree = new List[(int)n];
for(int i = 0; i < n; i++)
tree[i] = new ArrayList<Integer>();
for(int i = 0; i < n-1; i++) {
int from = in.nextInt()-1;
int to = in.nextInt() - 1;
int w = in.nextInt();
if(!isLucky(w)) {
tree[from].add(to);
tree[to].add(from);
}
}
visited = new boolean[(int)n];
long res = n*(n-1)*(n-2);
for(int i = 0; i < n; i++) {
if(tree[i].size() == 0)
visited[i] = true;
if(!visited[i]) {
total = 0;
dfs(tree, i);
//res -= total*(total-1)*(n-total)*2;
//res -= total*(total-1)*(total-2);
res -= total*(total-1)*(2*n-total-2);
}
}
System.out.println(res);
}
static void dfs(List<Integer>[] tree, int i) {
visited[i] = true;
total++;
for(int x : tree[i]) {
if(!visited[x]) {
dfs(tree, x);
}
}
}
static boolean isLucky(int w) {
while(w > 0) {
int x = w % 10;
if(x != 4 && x != 7)
return false;
w /= 10;
}
return true;
}
}
| Java | ["4\n1 2 4\n3 1 2\n1 4 7", "4\n1 2 4\n1 3 47\n1 4 7447"] | 2 seconds | ["16", "24"] | NoteThe 16 triples of vertexes from the first sample are: (1, 2, 4), (1, 4, 2), (2, 1, 3), (2, 1, 4), (2, 3, 1), (2, 3, 4), (2, 4, 1), (2, 4, 3), (3, 2, 4), (3, 4, 2), (4, 1, 2), (4, 1, 3), (4, 2, 1), (4, 2, 3), (4, 3, 1), (4, 3, 2).In the second sample all the triples should be counted: 4·3·2 = 24. | Java 6 | standard input | [
"combinatorics",
"dfs and similar",
"trees"
] | 6992db71923a01211b5073ee0f8a193a | The first line contains the single integer n (1 ≤ n ≤ 105) — the number of tree vertexes. Next n - 1 lines contain three integers each: ui vi wi (1 ≤ ui, vi ≤ n, 1 ≤ wi ≤ 109) — the pair of vertexes connected by the edge and the edge's weight. | 1,900 | On the single line print the single number — the answer. Please do not use the %lld specificator to read or write 64-bit numbers in С++. It is recommended to use the cin, cout streams or the %I64d specificator. | standard output | |
PASSED | 79195685301854fb60cedd873132032d | train_003.jsonl | 1314633600 | Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.One day Petya encountered a tree with n vertexes. Besides, the tree was weighted, i. e. each edge of the tree has weight (a positive integer). An edge is lucky if its weight is a lucky number. Note that a tree with n vertexes is an undirected connected graph that has exactly n - 1 edges.Petya wondered how many vertex triples (i, j, k) exists that on the way from i to j, as well as on the way from i to k there must be at least one lucky edge (all three vertexes are pairwise distinct). The order of numbers in the triple matters, that is, the triple (1, 2, 3) is not equal to the triple (2, 1, 3) and is not equal to the triple (1, 3, 2). Find how many such triples of vertexes exist. | 256 megabytes | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class LuckyTree {
static ArrayList<ArrayList<int[]>> tree;
static int[] f;
static int[] g;
static int[] c;
static boolean[] p;
static int time = 0;
static int[] inTime;
public static void main(String[] args)throws Exception {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
f = new int[n];
g = new int[n];
c = new int[n];
inTime = new int[n];
p = new boolean[n];
Arrays.fill(p, false);
Arrays.fill(f, -1);
Arrays.fill(g, -1);
tree = new ArrayList<ArrayList<int[]>>(n);
for (int i = 0; i < n; i++){
tree.add(new ArrayList<int[]>(0));
}
int v1;
int v2;
int w;
for (int i = 1; i < n; i++){
v1 = in.nextInt() - 1;
v2 = in.nextInt() - 1;
w = in.nextInt();
int[] e1 = {v2, w};
int[] e2 = {v1, w};
tree.get(v1).add(e1);
tree.get(v2).add(e2);
}
c[0] = n;
dfs(0);
Arrays.fill(p, false);
ff(0);
Arrays.fill(p, false);
g[0] = 0;
countG(0);
long s = 0;
for (int i = 0; i < n; i++){
s += ((long)f[i] * ((long)f[i] - 1)) + ((long)g[i] * ((long)g[i] - 1)) + (2 * (long)f[i] * (long)g[i]);
}
System.out.print(s);
in.close();
}
static boolean isLucky(int a){
boolean t = true;
while (t && (a > 0)){
int b = a % 10;
t = ((b == 4) || (b == 7));
a /= 10;
}
return t;
}
static int ff(int k){
if (f[k] < 0){
p[k] = true;
ArrayList<int[]> v = tree.get(k);
f[k] = 0;
for (int[] next : v){
if (!p[next[0]]){
if (isLucky(next[1])){
f[k] += c[next[0]];
f[next[0]] = ff(next[0]);
} else {
f[k] += ff(next[0]);
}
}
}
}
return f[k];
}
static void countG(int k){
p[k] = true;
for (int[] t : tree.get(k)){
if (!p[t[0]]){
if (isLucky(t[1])){
g[t[0]] = c[0] - c[t[0]];
} else {
g[t[0]] = g[k] + f[k] - f[t[0]];
}
countG(t[0]);
}
}
}
static void dfs(int v){
time++;
p[v] = true;
for (int[] t : tree.get(v)){
if (!p[t[0]]){
inTime[t[0]] = time;
dfs(t[0]);
c[t[0]] = time - inTime[t[0]];
}
}
}
}
| Java | ["4\n1 2 4\n3 1 2\n1 4 7", "4\n1 2 4\n1 3 47\n1 4 7447"] | 2 seconds | ["16", "24"] | NoteThe 16 triples of vertexes from the first sample are: (1, 2, 4), (1, 4, 2), (2, 1, 3), (2, 1, 4), (2, 3, 1), (2, 3, 4), (2, 4, 1), (2, 4, 3), (3, 2, 4), (3, 4, 2), (4, 1, 2), (4, 1, 3), (4, 2, 1), (4, 2, 3), (4, 3, 1), (4, 3, 2).In the second sample all the triples should be counted: 4·3·2 = 24. | Java 6 | standard input | [
"combinatorics",
"dfs and similar",
"trees"
] | 6992db71923a01211b5073ee0f8a193a | The first line contains the single integer n (1 ≤ n ≤ 105) — the number of tree vertexes. Next n - 1 lines contain three integers each: ui vi wi (1 ≤ ui, vi ≤ n, 1 ≤ wi ≤ 109) — the pair of vertexes connected by the edge and the edge's weight. | 1,900 | On the single line print the single number — the answer. Please do not use the %lld specificator to read or write 64-bit numbers in С++. It is recommended to use the cin, cout streams or the %I64d specificator. | standard output | |
PASSED | f8109ba8f0ab90c4c034c4b374e66169 | train_003.jsonl | 1314633600 | Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.One day Petya encountered a tree with n vertexes. Besides, the tree was weighted, i. e. each edge of the tree has weight (a positive integer). An edge is lucky if its weight is a lucky number. Note that a tree with n vertexes is an undirected connected graph that has exactly n - 1 edges.Petya wondered how many vertex triples (i, j, k) exists that on the way from i to j, as well as on the way from i to k there must be at least one lucky edge (all three vertexes are pairwise distinct). The order of numbers in the triple matters, that is, the triple (1, 2, 3) is not equal to the triple (2, 1, 3) and is not equal to the triple (1, 3, 2). Find how many such triples of vertexes exist. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
public class E{
Scanner sc=new Scanner(System.in);
int INF=1<<28;
double EPS=1e-9;
int n;
void run(){
n=sc.nextInt();
make(n);
for(int i=0; i<n-1; i++){
int u=sc.nextInt()-1;
int v=sc.nextInt()-1;
int w=sc.nextInt();
if(!isLucky(w)){
union(u, v);
}
}
// debug(p);
long ans=0;
for(int i=0; i<n; i++){
long s=size(i);
if(p[i]>=0){
continue;
}
if(s>=3){
ans+=s*(s-1)*(s-2);
}
if(s>=2){
ans+=s*(s-1)*(n-s)*2;
}
}
// debug(n*(n-1)*(n-2));
// debug(ans);
ans=(long)n*(n-1)*(n-2)-ans;
println(ans+"");
}
boolean isLucky(int n){
for(; n>0; n/=10){
if(n%10!=4&&n%10!=7){
return false;
}
}
return true;
}
int[] p;
void make(int n){
p=new int[n];
fill(p, -1);
}
int find(int x){
return p[x]<0?x:(p[x]=find(p[x]));
}
boolean union(int x, int y){
x=find(x);
y=find(y);
if(x!=y){
if(p[y]<p[x]){
int t=x;
x=y;
y=t;
}
p[x]+=p[y];
p[y]=x;
}
return x!=y;
}
int size(int x){
return -p[find(x)];
}
void println(String s){
System.out.println(s);
}
void print(String s){
System.out.print(s);
}
void debug(Object... os){
System.err.println(Arrays.deepToString(os));
}
public static void main(String[] args){
new E().run();
}
}
| Java | ["4\n1 2 4\n3 1 2\n1 4 7", "4\n1 2 4\n1 3 47\n1 4 7447"] | 2 seconds | ["16", "24"] | NoteThe 16 triples of vertexes from the first sample are: (1, 2, 4), (1, 4, 2), (2, 1, 3), (2, 1, 4), (2, 3, 1), (2, 3, 4), (2, 4, 1), (2, 4, 3), (3, 2, 4), (3, 4, 2), (4, 1, 2), (4, 1, 3), (4, 2, 1), (4, 2, 3), (4, 3, 1), (4, 3, 2).In the second sample all the triples should be counted: 4·3·2 = 24. | Java 6 | standard input | [
"combinatorics",
"dfs and similar",
"trees"
] | 6992db71923a01211b5073ee0f8a193a | The first line contains the single integer n (1 ≤ n ≤ 105) — the number of tree vertexes. Next n - 1 lines contain three integers each: ui vi wi (1 ≤ ui, vi ≤ n, 1 ≤ wi ≤ 109) — the pair of vertexes connected by the edge and the edge's weight. | 1,900 | On the single line print the single number — the answer. Please do not use the %lld specificator to read or write 64-bit numbers in С++. It is recommended to use the cin, cout streams or the %I64d specificator. | standard output | |
PASSED | 3ed2a6ad9ae55a0ec181006fcc224242 | train_003.jsonl | 1314633600 | Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.One day Petya encountered a tree with n vertexes. Besides, the tree was weighted, i. e. each edge of the tree has weight (a positive integer). An edge is lucky if its weight is a lucky number. Note that a tree with n vertexes is an undirected connected graph that has exactly n - 1 edges.Petya wondered how many vertex triples (i, j, k) exists that on the way from i to j, as well as on the way from i to k there must be at least one lucky edge (all three vertexes are pairwise distinct). The order of numbers in the triple matters, that is, the triple (1, 2, 3) is not equal to the triple (2, 1, 3) and is not equal to the triple (1, 3, 2). Find how many such triples of vertexes exist. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.math.*;
import java.io.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;
// Lucky Tree
// 2011/8/30
public class P109C{
Scanner sc=new Scanner(System.in);
int n;
void run(){
n=sc.nextInt();
make(n);
for(int i=0; i<n-1; i++){
int u=sc.nextInt()-1;
int v=sc.nextInt()-1;
int w=sc.nextInt();
if(!isLucky(w)){
union(u, v);
}
}
long ans=0;
for(int i=0; i<n; i++){
long s=size(i);
if(p[i]>=0){
continue;
}
if(s>=3){
ans+=s*(s-1)*(s-2);
}
if(s>=2){
ans+=s*(s-1)*(n-s)*2;
}
}
ans=(long)n*(n-1)*(n-2)-ans;
println(ans+"");
}
boolean isLucky(int n){
for(; n>0; n/=10){
if(n%10!=4&&n%10!=7){
return false;
}
}
return true;
}
int[] p;
void make(int n){
p=new int[n];
fill(p, -1);
}
int find(int x){
return p[x]<0?x:(p[x]=find(p[x]));
}
boolean union(int x, int y){
x=find(x);
y=find(y);
if(x!=y){
if(p[y]<p[x]){
int t=x;
x=y;
y=t;
}
p[x]+=p[y];
p[y]=x;
}
return x!=y;
}
int size(int x){
return -p[find(x)];
}
void println(String s){
System.out.println(s);
}
public static void main(String[] args){
new P109C().run();
}
}
| Java | ["4\n1 2 4\n3 1 2\n1 4 7", "4\n1 2 4\n1 3 47\n1 4 7447"] | 2 seconds | ["16", "24"] | NoteThe 16 triples of vertexes from the first sample are: (1, 2, 4), (1, 4, 2), (2, 1, 3), (2, 1, 4), (2, 3, 1), (2, 3, 4), (2, 4, 1), (2, 4, 3), (3, 2, 4), (3, 4, 2), (4, 1, 2), (4, 1, 3), (4, 2, 1), (4, 2, 3), (4, 3, 1), (4, 3, 2).In the second sample all the triples should be counted: 4·3·2 = 24. | Java 6 | standard input | [
"combinatorics",
"dfs and similar",
"trees"
] | 6992db71923a01211b5073ee0f8a193a | The first line contains the single integer n (1 ≤ n ≤ 105) — the number of tree vertexes. Next n - 1 lines contain three integers each: ui vi wi (1 ≤ ui, vi ≤ n, 1 ≤ wi ≤ 109) — the pair of vertexes connected by the edge and the edge's weight. | 1,900 | On the single line print the single number — the answer. Please do not use the %lld specificator to read or write 64-bit numbers in С++. It is recommended to use the cin, cout streams or the %I64d specificator. | standard output | |
PASSED | fe157d2e3d8865790bcf9b21affbf29a | train_003.jsonl | 1314633600 | Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.One day Petya encountered a tree with n vertexes. Besides, the tree was weighted, i. e. each edge of the tree has weight (a positive integer). An edge is lucky if its weight is a lucky number. Note that a tree with n vertexes is an undirected connected graph that has exactly n - 1 edges.Petya wondered how many vertex triples (i, j, k) exists that on the way from i to j, as well as on the way from i to k there must be at least one lucky edge (all three vertexes are pairwise distinct). The order of numbers in the triple matters, that is, the triple (1, 2, 3) is not equal to the triple (2, 1, 3) and is not equal to the triple (1, 3, 2). Find how many such triples of vertexes exist. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class E
{
public static StringTokenizer inp;
public static int n;
public static long ans;
public static ArrayList<Integer> tree[];
public static boolean visit[];
public static void main(String[] args) throws NumberFormatException, IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
tree = new ArrayList[n+1];
visit = new boolean[n+1];
for(int i = 1 ; i <= n ;i++)tree[i] = new ArrayList<Integer>();
for(int i = 0 ; i < n-1 ; i++)
{
inp = new StringTokenizer(br.readLine());
int u = nextInt(),v = nextInt();
if(isLucky(inp.nextToken().toCharArray()))continue;
tree[u].add(v);tree[v].add(u);
}
for(int i = 1 ; i <= n ; i++)if(!visit[i])bfs(i);
System.out.println(ans);
}
public static void bfs(int s)
{
Queue<Integer> q = new LinkedList<Integer>();
q.add(s);
long num = 0;
while(!q.isEmpty())
{
num++;
int curr = q.remove();
visit[curr] = true;
for(int i : tree[curr])
if(!visit[i]) q.add(i);
}
ans += num * (n-num) * (n-num-1);
}
public static boolean isLucky(char s[])
{
for(int i = 0 ; i < s.length ; i++)
if(s[i]!='4' && s[i]!='7')return false;
return true;
}
public static int nextInt()
{
return Integer.parseInt(inp.nextToken());
}
}
| Java | ["4\n1 2 4\n3 1 2\n1 4 7", "4\n1 2 4\n1 3 47\n1 4 7447"] | 2 seconds | ["16", "24"] | NoteThe 16 triples of vertexes from the first sample are: (1, 2, 4), (1, 4, 2), (2, 1, 3), (2, 1, 4), (2, 3, 1), (2, 3, 4), (2, 4, 1), (2, 4, 3), (3, 2, 4), (3, 4, 2), (4, 1, 2), (4, 1, 3), (4, 2, 1), (4, 2, 3), (4, 3, 1), (4, 3, 2).In the second sample all the triples should be counted: 4·3·2 = 24. | Java 6 | standard input | [
"combinatorics",
"dfs and similar",
"trees"
] | 6992db71923a01211b5073ee0f8a193a | The first line contains the single integer n (1 ≤ n ≤ 105) — the number of tree vertexes. Next n - 1 lines contain three integers each: ui vi wi (1 ≤ ui, vi ≤ n, 1 ≤ wi ≤ 109) — the pair of vertexes connected by the edge and the edge's weight. | 1,900 | On the single line print the single number — the answer. Please do not use the %lld specificator to read or write 64-bit numbers in С++. It is recommended to use the cin, cout streams or the %I64d specificator. | standard output | |
PASSED | d47be56e3e57cf0d6c9d7d797db3d6bd | train_003.jsonl | 1314633600 | Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.One day Petya encountered a tree with n vertexes. Besides, the tree was weighted, i. e. each edge of the tree has weight (a positive integer). An edge is lucky if its weight is a lucky number. Note that a tree with n vertexes is an undirected connected graph that has exactly n - 1 edges.Petya wondered how many vertex triples (i, j, k) exists that on the way from i to j, as well as on the way from i to k there must be at least one lucky edge (all three vertexes are pairwise distinct). The order of numbers in the triple matters, that is, the triple (1, 2, 3) is not equal to the triple (2, 1, 3) and is not equal to the triple (1, 3, 2). Find how many such triples of vertexes exist. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Stack;
public class E {
public static boolean isLucky(int x) {
while (x > 0) {
if (x % 10 != 4 && x % 10 != 7)
return false;
x /= 10;
}
return true;
}
public static void main(String[] args) throws NumberFormatException,
IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(in.readLine());
LinkedList<Integer>[] E = new LinkedList[n];
for (int i = 0; i < n; i++)
E[i] = new LinkedList<Integer>();
for (int i = 1; i < n; i++) {
String[] S = in.readLine().split(" ");
int u = Integer.parseInt(S[0]) - 1;
int v = Integer.parseInt(S[1]) - 1;
int w = Integer.parseInt(S[2]);
if (!isLucky(w)) {
E[u].add(v);
E[v].add(u);
}
}
boolean[] visited = new boolean[n];
long ans = 0;
for (int i = 0; i < n; i++) {
Stack<Integer> S = new Stack<Integer>();
if (visited[i])
continue;
S.push(i);
long val = 0;
while (!S.isEmpty()) {
int temp = S.pop();
if (visited[temp])
continue;
visited[temp] = true;
val++;
for (int x : E[temp])
S.push(x);
}
ans += val * (n - val) * (n - val - 1);
}
System.out.println(ans);
}
}
| Java | ["4\n1 2 4\n3 1 2\n1 4 7", "4\n1 2 4\n1 3 47\n1 4 7447"] | 2 seconds | ["16", "24"] | NoteThe 16 triples of vertexes from the first sample are: (1, 2, 4), (1, 4, 2), (2, 1, 3), (2, 1, 4), (2, 3, 1), (2, 3, 4), (2, 4, 1), (2, 4, 3), (3, 2, 4), (3, 4, 2), (4, 1, 2), (4, 1, 3), (4, 2, 1), (4, 2, 3), (4, 3, 1), (4, 3, 2).In the second sample all the triples should be counted: 4·3·2 = 24. | Java 6 | standard input | [
"combinatorics",
"dfs and similar",
"trees"
] | 6992db71923a01211b5073ee0f8a193a | The first line contains the single integer n (1 ≤ n ≤ 105) — the number of tree vertexes. Next n - 1 lines contain three integers each: ui vi wi (1 ≤ ui, vi ≤ n, 1 ≤ wi ≤ 109) — the pair of vertexes connected by the edge and the edge's weight. | 1,900 | On the single line print the single number — the answer. Please do not use the %lld specificator to read or write 64-bit numbers in С++. It is recommended to use the cin, cout streams or the %I64d specificator. | standard output | |
PASSED | b1e399719dfb4dcd6e1302176b5d4055 | train_003.jsonl | 1314633600 | Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.One day Petya encountered a tree with n vertexes. Besides, the tree was weighted, i. e. each edge of the tree has weight (a positive integer). An edge is lucky if its weight is a lucky number. Note that a tree with n vertexes is an undirected connected graph that has exactly n - 1 edges.Petya wondered how many vertex triples (i, j, k) exists that on the way from i to j, as well as on the way from i to k there must be at least one lucky edge (all three vertexes are pairwise distinct). The order of numbers in the triple matters, that is, the triple (1, 2, 3) is not equal to the triple (2, 1, 3) and is not equal to the triple (1, 3, 2). Find how many such triples of vertexes exist. | 256 megabytes | //package tes7;
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 P84E {
InputStream is;
PrintWriter out;
String INPUT = "";
void solve()
{
int n = ni();
int[] from = new int[n-1];
int[] to = new int[n-1];
int[] w = new int[n-1];
for(int i = 0;i < n-1;i++){
from[i] = ni()-1;
to[i] = ni()-1;
w[i] = ni();
while(w[i] > 0){
if(w[i] % 10 == 4 || w[i] % 10 == 7){
w[i] /= 10;
}else{
w[i] = 1;
break;
}
}
}
int[][][] g = packWU(n, from, to, w);
int[][] pars = parents(g, 0);
int[] par = pars[0], ord = pars[1], pw = pars[4];
int[] below = new int[n];
int[] des = new int[n];
for(int i = n-1;i >= 0;i--){
int cur = ord[i];
des[cur] = i == 0 ? 0 : 1;
int lsum = 0;
for(int[] e : g[cur]){
if(par[cur] != e[0]){
des[cur] += des[e[0]];
if(pw[e[0]] == 1){
lsum += below[e[0]];
}else{
lsum += des[e[0]];
}
}
}
below[cur] = lsum;
}
int[] above = new int[n];
for(int i = 1;i < n;i++){
int cur = ord[i];
if(pw[cur] == 0){
above[cur] = n - des[cur];
}else{
above[cur] = below[par[cur]] - below[cur] + above[par[cur]];
}
}
long ret = 0;
for(int i = 0;i < n;i++){
long num = above[i] + below[i];
ret += num * (num-1);
}
out.println(ret);
}
public static int[][][] packWU(int n, int[] from, int[] to, int[] w) {
int[][][] g = new int[n][][];
int[] p = new int[n];
for(int f : from)
p[f]++;
for(int t : to)
p[t]++;
for(int i = 0;i < n;i++)
g[i] = new int[p[i]][2];
for(int i = 0;i < from.length;i++){
--p[from[i]];
g[from[i]][p[from[i]]][0] = to[i];
g[from[i]][p[from[i]]][1] = w[i];
--p[to[i]];
g[to[i]][p[to[i]]][0] = from[i];
g[to[i]][p[to[i]]][1] = w[i];
}
return g;
}
public static int[][] parents(int[][][] g, int root)
{
int n = g.length;
int[] par = new int[n];
Arrays.fill(par, -1);
int[] dw = new int[n];
int[] pw = new int[n];
int[] dep = new int[n];
int[] q = new int[n];
q[0] = root;
for(int p = 0, r = 1;p < r;p++) {
int cur = q[p];
for(int[] nex : g[cur]){
if(par[cur] != nex[0]){
q[r++] = nex[0];
par[nex[0]] = cur;
dep[nex[0]] = dep[cur] + 1;
dw[nex[0]] = dw[cur] + nex[1];
pw[nex[0]] = nex[1];
}
}
}
return new int[][] {par, q, dep, dw, pw};
}
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 P84E().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 | ["4\n1 2 4\n3 1 2\n1 4 7", "4\n1 2 4\n1 3 47\n1 4 7447"] | 2 seconds | ["16", "24"] | NoteThe 16 triples of vertexes from the first sample are: (1, 2, 4), (1, 4, 2), (2, 1, 3), (2, 1, 4), (2, 3, 1), (2, 3, 4), (2, 4, 1), (2, 4, 3), (3, 2, 4), (3, 4, 2), (4, 1, 2), (4, 1, 3), (4, 2, 1), (4, 2, 3), (4, 3, 1), (4, 3, 2).In the second sample all the triples should be counted: 4·3·2 = 24. | Java 6 | standard input | [
"combinatorics",
"dfs and similar",
"trees"
] | 6992db71923a01211b5073ee0f8a193a | The first line contains the single integer n (1 ≤ n ≤ 105) — the number of tree vertexes. Next n - 1 lines contain three integers each: ui vi wi (1 ≤ ui, vi ≤ n, 1 ≤ wi ≤ 109) — the pair of vertexes connected by the edge and the edge's weight. | 1,900 | On the single line print the single number — the answer. Please do not use the %lld specificator to read or write 64-bit numbers in С++. It is recommended to use the cin, cout streams or the %I64d specificator. | standard output | |
PASSED | 7eb128f091d71cf59361020d6e004d67 | train_003.jsonl | 1314633600 | Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.One day Petya encountered a tree with n vertexes. Besides, the tree was weighted, i. e. each edge of the tree has weight (a positive integer). An edge is lucky if its weight is a lucky number. Note that a tree with n vertexes is an undirected connected graph that has exactly n - 1 edges.Petya wondered how many vertex triples (i, j, k) exists that on the way from i to j, as well as on the way from i to k there must be at least one lucky edge (all three vertexes are pairwise distinct). The order of numbers in the triple matters, that is, the triple (1, 2, 3) is not equal to the triple (2, 1, 3) and is not equal to the triple (1, 3, 2). Find how many such triples of vertexes exist. | 256 megabytes | /**
* Created by IntelliJ IDEA.
* User: piyushd
* Date: 3/26/11
* Time: 10:53 PM
* To change this template use File | Settings | File Templates.
*/
public class TaskC {
int[] par;
int[] size;
int getParent(int v) {
int parent = par[v];
if(parent == v) return v;
return par[v] = getParent(parent);
}
void join(int a, int b) {
int pa = getParent(a);
int pb = getParent(b);
if(pa == pb) return;
if(size[pa] >= size[pb]) {
par[pb] = pa;
size[pa] += size[pb];
}
else {
par[pa]= pb;
size[pb] += size[pa];
}
}
boolean isLucky(int n) {
while(n > 0) {
int x = n % 10;
if(x != 4 && x != 7) return false;
n /= 10;
}
return true;
}
void run(){
int n = nextInt();
this.par = new int[n];
this.size = new int[n];
for(int i = 0; i < n; i++) {
par[i] = i;
size[i] = 1;
}
for(int i = 0; i < n - 1; i++) {
int u = nextInt() - 1;
int v = nextInt() - 1;
int w = nextInt();
if(!isLucky(w)) {
join(u, v);
}
}
long ans = 0;
for(int i = 0; i < n; i++) {
int left = n - size[getParent(i)];
ans += (left) * (long)(left - 1);
}
System.out.println(ans);
}
int nextInt(){
try{
int c = System.in.read();
if(c == -1) return c;
while(c != '-' && (c < '0' || '9' < c)){
c = System.in.read();
if(c == -1) return c;
}
if(c == '-') return -nextInt();
int res = 0;
do{
res *= 10;
res += c - '0';
c = System.in.read();
}while('0' <= c && c <= '9');
return res;
}catch(Exception e){
return -1;
}
}
long nextLong(){
try{
int c = System.in.read();
if(c == -1) return -1;
while(c != '-' && (c < '0' || '9' < c)){
c = System.in.read();
if(c == -1) return -1;
}
if(c == '-') return -nextLong();
long res = 0;
do{
res *= 10;
res += c-'0';
c = System.in.read();
}while('0' <= c && c <= '9');
return res;
}catch(Exception e){
return -1;
}
}
double nextDouble(){
return Double.parseDouble(next());
}
String next(){
try{
StringBuilder res = new StringBuilder("");
int c = System.in.read();
while(Character.isWhitespace(c))
c = System.in.read();
do{
res.append((char)c);
}while(!Character.isWhitespace(c=System.in.read()));
return res.toString();
}catch(Exception e){
return null;
}
}
String nextLine(){
try{
StringBuilder res = new StringBuilder("");
int c = System.in.read();
while(c == '\r' || c == '\n')
c = System.in.read();
do{
res.append((char)c);
c = System.in.read();
}while(c != '\r' && c != '\n');
return res.toString();
}catch(Exception e){
return null;
}
}
public static void main(String[] args){
new TaskC().run();
}
}
| Java | ["4\n1 2 4\n3 1 2\n1 4 7", "4\n1 2 4\n1 3 47\n1 4 7447"] | 2 seconds | ["16", "24"] | NoteThe 16 triples of vertexes from the first sample are: (1, 2, 4), (1, 4, 2), (2, 1, 3), (2, 1, 4), (2, 3, 1), (2, 3, 4), (2, 4, 1), (2, 4, 3), (3, 2, 4), (3, 4, 2), (4, 1, 2), (4, 1, 3), (4, 2, 1), (4, 2, 3), (4, 3, 1), (4, 3, 2).In the second sample all the triples should be counted: 4·3·2 = 24. | Java 6 | standard input | [
"combinatorics",
"dfs and similar",
"trees"
] | 6992db71923a01211b5073ee0f8a193a | The first line contains the single integer n (1 ≤ n ≤ 105) — the number of tree vertexes. Next n - 1 lines contain three integers each: ui vi wi (1 ≤ ui, vi ≤ n, 1 ≤ wi ≤ 109) — the pair of vertexes connected by the edge and the edge's weight. | 1,900 | On the single line print the single number — the answer. Please do not use the %lld specificator to read or write 64-bit numbers in С++. It is recommended to use the cin, cout streams or the %I64d specificator. | standard output | |
PASSED | cc24c6508ade20617903f75c15baf10e | train_003.jsonl | 1401627600 | Of course our child likes walking in a zoo. The zoo has n areas, that are numbered from 1 to n. The i-th area contains ai animals in it. Also there are m roads in the zoo, and each road connects two distinct areas. Naturally the zoo is connected, so you can reach any area of the zoo from any other area using the roads.Our child is very smart. Imagine the child want to go from area p to area q. Firstly he considers all the simple routes from p to q. For each route the child writes down the number, that is equal to the minimum number of animals among the route areas. Let's denote the largest of the written numbers as f(p, q). Finally, the child chooses one of the routes for which he writes down the value f(p, q).After the child has visited the zoo, he thinks about the question: what is the average value of f(p, q) for all pairs p, q (p ≠ q)? Can you answer his question? | 256 megabytes | import java.io.*;
import java.util.*;
public class B {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
boolean eof;
int[] p, size;
int get(int x) {
return p[x] == x ? x : (p[x] = get(p[x]));
}
Random rng = new Random();
void union(int v, int u) {
if (rng.nextBoolean()) {
p[v] = u;
size[u] += size[v];
} else {
p[u] = v;
size[v] += size[u];
}
}
void solve() throws IOException {
int n = nextInt();
int m = nextInt();
List<Integer>[] g = new List[n];
for (int i = 0; i < n; i++) {
g[i] = new ArrayList<>();
}
final int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
for (int i = 0; i < m; i++) {
int v1 = nextInt() - 1;
int v2 = nextInt() - 1;
g[v1].add(v2);
g[v2].add(v1);
}
Integer[] order = new Integer[n];
for (int i = 0; i < n; i++) {
order[i] = i;
}
Arrays.sort(order, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return -Integer.compare(a[o1], a[o2]);
}
});
boolean[] built = new boolean[n];
long sum = 0;
p = new int[n];
size = new int[n];
for (int v : order) {
built[v] = true;
p[v] = v;
size[v] = 1;
for (int i = 0; i < g[v].size(); i++) {
int u = g[v].get(i);
if (!built[u]) {
continue;
}
// System.err.println(v + " " + u);
u = get(u);
int vv = get(v);
if (u == vv) {
continue;
}
sum += (long) size[vv] * size[u] * a[v];
// System.err.println(size[vv] + " " + size[u]);
union(u, vv);
}
}
// System.err.println(sum);
double ans = 2.0 * sum / n / (n - 1);
out.println(ans);
}
B() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
}
public static void main(String[] args) throws IOException {
new B();
}
String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
eof = true;
return null;
}
}
return st.nextToken();
}
String nextString() {
try {
return br.readLine();
} catch (IOException e) {
eof = true;
return null;
}
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
} | Java | ["4 3\n10 20 30 40\n1 3\n2 3\n4 3", "3 3\n10 20 30\n1 2\n2 3\n3 1", "7 8\n40 20 10 30 20 50 40\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n1 4\n5 7"] | 2 seconds | ["16.666667", "13.333333", "18.571429"] | NoteConsider the first sample. There are 12 possible situations: p = 1, q = 3, f(p, q) = 10. p = 2, q = 3, f(p, q) = 20. p = 4, q = 3, f(p, q) = 30. p = 1, q = 2, f(p, q) = 10. p = 2, q = 4, f(p, q) = 20. p = 4, q = 1, f(p, q) = 10. Another 6 cases are symmetrical to the above. The average is .Consider the second sample. There are 6 possible situations: p = 1, q = 2, f(p, q) = 10. p = 2, q = 3, f(p, q) = 20. p = 1, q = 3, f(p, q) = 10. Another 3 cases are symmetrical to the above. The average is . | Java 8 | standard input | [
"dp",
"dsu",
"sortings"
] | 6931beaa1c40e03ee52bcb0cfb9bff51 | The first line contains two integers n and m (2 ≤ n ≤ 105; 0 ≤ m ≤ 105). The second line contains n integers: a1, a2, ..., an (0 ≤ ai ≤ 105). Then follow m lines, each line contains two integers xi and yi (1 ≤ xi, yi ≤ n; xi ≠ yi), denoting the road between areas xi and yi. All roads are bidirectional, each pair of areas is connected by at most one road. | 1,900 | Output a real number — the value of . The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4. | standard output | |
PASSED | e38f32ccc01c0b4daeb9a022e0f40acf | train_003.jsonl | 1401627600 | Of course our child likes walking in a zoo. The zoo has n areas, that are numbered from 1 to n. The i-th area contains ai animals in it. Also there are m roads in the zoo, and each road connects two distinct areas. Naturally the zoo is connected, so you can reach any area of the zoo from any other area using the roads.Our child is very smart. Imagine the child want to go from area p to area q. Firstly he considers all the simple routes from p to q. For each route the child writes down the number, that is equal to the minimum number of animals among the route areas. Let's denote the largest of the written numbers as f(p, q). Finally, the child chooses one of the routes for which he writes down the value f(p, q).After the child has visited the zoo, he thinks about the question: what is the average value of f(p, q) for all pairs p, q (p ≠ q)? Can you answer his question? | 256 megabytes | import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
import java.util.Vector;
public class B {
public static final boolean DEBUG = false;
Scanner sc;
public void debug(Object o) {
if (DEBUG) {
int ln = Thread.currentThread().getStackTrace()[2].getLineNumber();
String fn = Thread.currentThread().getStackTrace()[2].getFileName();
System.out.println("(" + fn + ":" + ln+ "): " + o);
}
}
public void pln(Object o) {
System.out.println(o);
}
class Node {
long w;
boolean processed = false;
Vector<Node> conn = new Vector<Node>();
long count = 1;
Node parent = null;
public Node find() {
if (parent == null) return this;
return parent = parent.find();
}
public void union(Node n2) {
Node p1 = find();
Node p2 = n2.find();
if (p1 != p2) {
Node small = p1;
Node large = p2;
if (p1.count > p2.count) {
small = p2;
large = p1;
}
small.parent = large;
large.count = small.count + large.count;
}
}
Node(int w) {
this.w = w;
}
}
public void run() {
sc = new Scanner(System.in);
long n = sc.nextInt();
long m = sc.nextInt();
Vector<Node> nodes = new Vector<Node>();
for (int i=0; i<n; i++) {
nodes.add(new Node(sc.nextInt()));
}
for (int j=0; j<m; j++) {
int a = sc.nextInt() - 1;
int b = sc.nextInt() - 1;
nodes.get(a).conn.add(nodes.get(b));
nodes.get(b).conn.add(nodes.get(a));
}
Collections.sort(nodes, new Comparator<Node>() {
public int compare(Node o1, Node o2) {
return - (int)(o1.w - o2.w);
}
});
long total = 0;
for (Node n1: nodes) {
for (Node n2: n1.conn) {
if (n2.processed) {
if (n1.find() != n2.find()) {
total += ((long)n1.find().count) * n2.find().count * n1.w;
n1.union(n2);
}
}
}
n1.processed = true;
}
pln(((double)total) * 2 / (n * (n-1)));
return;
}
public static void main(String[] args) {
B t = new B();
t.run();
}
} | Java | ["4 3\n10 20 30 40\n1 3\n2 3\n4 3", "3 3\n10 20 30\n1 2\n2 3\n3 1", "7 8\n40 20 10 30 20 50 40\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n1 4\n5 7"] | 2 seconds | ["16.666667", "13.333333", "18.571429"] | NoteConsider the first sample. There are 12 possible situations: p = 1, q = 3, f(p, q) = 10. p = 2, q = 3, f(p, q) = 20. p = 4, q = 3, f(p, q) = 30. p = 1, q = 2, f(p, q) = 10. p = 2, q = 4, f(p, q) = 20. p = 4, q = 1, f(p, q) = 10. Another 6 cases are symmetrical to the above. The average is .Consider the second sample. There are 6 possible situations: p = 1, q = 2, f(p, q) = 10. p = 2, q = 3, f(p, q) = 20. p = 1, q = 3, f(p, q) = 10. Another 3 cases are symmetrical to the above. The average is . | Java 6 | standard input | [
"dp",
"dsu",
"sortings"
] | 6931beaa1c40e03ee52bcb0cfb9bff51 | The first line contains two integers n and m (2 ≤ n ≤ 105; 0 ≤ m ≤ 105). The second line contains n integers: a1, a2, ..., an (0 ≤ ai ≤ 105). Then follow m lines, each line contains two integers xi and yi (1 ≤ xi, yi ≤ n; xi ≠ yi), denoting the road between areas xi and yi. All roads are bidirectional, each pair of areas is connected by at most one road. | 1,900 | Output a real number — the value of . The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4. | standard output | |
PASSED | 30b9e7bc09f74387c27c6be974ba357e | train_003.jsonl | 1401627600 | Of course our child likes walking in a zoo. The zoo has n areas, that are numbered from 1 to n. The i-th area contains ai animals in it. Also there are m roads in the zoo, and each road connects two distinct areas. Naturally the zoo is connected, so you can reach any area of the zoo from any other area using the roads.Our child is very smart. Imagine the child want to go from area p to area q. Firstly he considers all the simple routes from p to q. For each route the child writes down the number, that is equal to the minimum number of animals among the route areas. Let's denote the largest of the written numbers as f(p, q). Finally, the child chooses one of the routes for which he writes down the value f(p, q).After the child has visited the zoo, he thinks about the question: what is the average value of f(p, q) for all pairs p, q (p ≠ q)? Can you answer his question? | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
/**
* Created by fangxue.zhang on 2014/6/1.
*/
public class CF_250_div2 {
public static List<Integer> nodes = new ArrayList<Integer>(1100);
public static List<Integer> valList = new ArrayList<Integer>();
public static Map<Integer, Integer> parent = new HashMap<Integer, Integer>();
public static Map<Integer, Integer> count = new HashMap<Integer, Integer>();
public static void main(String[] args) throws IOException {
input.init(System.in);
// List<String> list = new LinkedList<String>();
//
// for(int i = 0; i < 4; i++){
// String str = input.next();
// list.add(str);
// }
//
// int count = 0;
// int idx = -1;
// for(int i = 0; i < 4; i++){
// int len = list.get(i).length() - 2;
// boolean bingo = true;
// boolean bingo1 = true;
// for(int j = 0; j < 4; j++){
// if(i == j) continue;
// int len1 = list.get(j).length() - 2;
// if(len < len1 * 2) bingo = false;
// if(len * 2 > len1) bingo1 = false;
// }
// if(bingo == true || bingo1 == true) {
// count += 1;
// idx = i;
// }
// }
// if(count == 0 || count >= 2){
// System.out.println("C");
// return;
// }
// System.out.println(list.get(idx).substring(0, 1));
// class Pair{
// public int a, b;
//
//
// }
//
// int sum = input.nextInt();
// int limit = input.nextInt();
//
// List<Integer> list= new LinkedList<Integer>();
//
// for(int i = limit; i >= 1; i--){
//
// System.out.println(getLowBit(i));
//
// Pair pair = new Pair();
//
//
//
//
// }
// int n = input.nextInt();
// int m = input.nextInt();
//
//
// List<Integer> order = new ArrayList<Integer>(1100);
// List<List<Integer>> mat = new ArrayList<List<Integer>>(1100);
//
//
// for(int i = 0; i < n; i++){
// int x = input.nextInt();
// nodes.add(x);
// order.add(i);
// mat.add(new LinkedList<Integer>());
// }
//
//
//
// for(int i = 0; i < m; i++){
// int a = input.nextInt() - 1;
// int b = input.nextInt() - 1;
// mat.get(a).add(b);
// mat.get(b).add(a);
// }
//
//// System.out.println(mat);
//
// ComparatorUser comparator=new ComparatorUser();
//
// Collections.sort(order, comparator);
//
//// System.out.println(order);
// Integer res = 0;
//
// for(int i = n - 1; i >= 0; i--){
// int x = order.get(i);
//// System.out.println(res);
// for(Integer idx : mat.get(x)){
// res += nodes.get(idx);
// }
//// nodes.add(x, 0);
// nodes.set(x, 0);
//// System.out.println(nodes);
// }
//
//// System.out.println("==========");
//
// System.out.println(res);
//BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
// int sum = input.nextInt(), limit = input.nextInt();
//
// List<Integer> list = new ArrayList<Integer>();
//
//
// for(int i = 0; i <= limit; i++){
// list.add(i);
// valList.add(getLowBit(i));
// }
//
// Collections.sort(list, new Comp());
//
// List<Integer> res = new LinkedList<Integer>();
//
// for(int i = limit; i >= 0; i--){
// int low = valList.get(list.get(i));
//
//
// if(sum >= low && low > 0) {
//// System.out.println(i + " " + list.get(i));
// sum -= low;
// res.add(list.get(i));
// }
// }
//
// if(sum == 0){
// System.out.println(res.size());
// for(Integer x : res){
// System.out.print(x + " ");
// }
// }
// else {
// System.out.println(-1);
// }
//DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
int n = input.nextInt(), m = input.nextInt();
List<Edge> list = new ArrayList<Edge>();
for(int i = 0; i < n; i++){
int x = input.nextInt();
parent.put(i, i);
count.put(i, 1);
nodes.add(x);
}
for(int i = 0; i < m; i++){
int a = input.nextInt() - 1;
int b = input.nextInt() - 1;
Edge edge = new Edge();
edge.x = a;
edge.y = b;
edge.c = Math.min(nodes.get(a), nodes.get(b));
list.add(edge);
}
Collections.sort(list, new CompD());
// System.out.println(list);
double res = 0;
for(int i = m - 1; i >= 0; i--){
Edge edge = list.get(i);
int x = find(edge.x);
int y = find(edge.y);
if(x == y) continue;
res += (long)count.get(x) * (long)count.get(y) * (long)edge.c ;
// System.out.println(" " + count.get(x) + " " + count.get(y) + " " + edge.c);
parent.put(y, x);
count.put(x, count.get(x) + count.get(y));
}
res *= 2;
res /= n;
res /= n - 1;
System.out.println(res);
}
public static int find(int x){
int p = parent.get(x);
if(p == x) return p;
parent.put(x, find(p));
return parent.get(x);
}
public static class CompD implements Comparator{
public int compare(Object arg0, Object arg1) {
Edge a=(Edge)arg0;
Edge b=(Edge)arg1;
return a.c.compareTo(b.c);
}
}
public static class Comp implements Comparator{
public int compare(Object arg0, Object arg1) {
Integer a=(Integer)arg0;
Integer b=(Integer)arg1;
return valList.get(a).compareTo(valList.get(b));
}
}
public static class ComparatorUser implements Comparator {
public int compare(Object arg0, Object arg1) {
Integer a=(Integer)arg0;
Integer b=(Integer)arg1;
return nodes.get(a).compareTo(nodes.get(b));
}
}
public static Integer getLowBit(Integer x){
if(x.equals(0)) return 0;
Integer res = 1;
while(x % 2 == 0){
res *= 2;
x /= 2;
}
return res;
}
public static class Edge{
public Integer x, y, c;
@Override
public String toString() {
return "Edge{" +
"x=" + x +
", y=" + y +
", c=" + c +
'}';
}
}
public static class input {
static BufferedReader reader;
static StringTokenizer tokenizer;
/** call this method to initialize reader for InputStream */
static void init(InputStream input) {
reader = new BufferedReader(
new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
/** get next word */
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt( next() );
}
static double nextDouble() throws IOException {
return Double.parseDouble( next() );
}
static long nextLong() throws IOException {
return Long.parseLong( next() );
}
}
}
| Java | ["4 3\n10 20 30 40\n1 3\n2 3\n4 3", "3 3\n10 20 30\n1 2\n2 3\n3 1", "7 8\n40 20 10 30 20 50 40\n1 2\n2 3\n3 4\n4 5\n5 6\n6 7\n1 4\n5 7"] | 2 seconds | ["16.666667", "13.333333", "18.571429"] | NoteConsider the first sample. There are 12 possible situations: p = 1, q = 3, f(p, q) = 10. p = 2, q = 3, f(p, q) = 20. p = 4, q = 3, f(p, q) = 30. p = 1, q = 2, f(p, q) = 10. p = 2, q = 4, f(p, q) = 20. p = 4, q = 1, f(p, q) = 10. Another 6 cases are symmetrical to the above. The average is .Consider the second sample. There are 6 possible situations: p = 1, q = 2, f(p, q) = 10. p = 2, q = 3, f(p, q) = 20. p = 1, q = 3, f(p, q) = 10. Another 3 cases are symmetrical to the above. The average is . | Java 6 | standard input | [
"dp",
"dsu",
"sortings"
] | 6931beaa1c40e03ee52bcb0cfb9bff51 | The first line contains two integers n and m (2 ≤ n ≤ 105; 0 ≤ m ≤ 105). The second line contains n integers: a1, a2, ..., an (0 ≤ ai ≤ 105). Then follow m lines, each line contains two integers xi and yi (1 ≤ xi, yi ≤ n; xi ≠ yi), denoting the road between areas xi and yi. All roads are bidirectional, each pair of areas is connected by at most one road. | 1,900 | Output a real number — the value of . The answer will be considered correct if its relative or absolute error doesn't exceed 10 - 4. | standard output | |
PASSED | db69385cd809fd62a2ad8ef9ea0fb0e1 | train_003.jsonl | 1565706900 | You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
public class EqualRectangles {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int wh = sc.nextInt();
while(wh > 0) {
int[] arr = new int[sc.nextInt() * 4];
int lung = arr.length;
for(int i = 0; i < lung; i++) {
arr[i] = sc.nextInt();
}
Arrays.sort(arr);
/*
if(arr[0] <= 0) {
System.out.println("NO");
wh--;
continue;
}
*/
int area = 0;
if(arr[0] == arr[1] && arr[lung - 1] == arr[lung - 2]) {
area = arr[0] * arr[lung - 1];
}
boolean check = true;
for(int i = 0; i < lung / 2; i = i + 2) {
if(arr[i] != arr[i + 1] || arr[lung - i - 1] != arr[lung - i - 2] || arr[i] * arr[lung - i - 1] != area) {
check = false;
}
}
if(check) System.out.println("YES");
else System.out.println("NO");
wh--;
}
}
}
| Java | ["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES"] | null | Java 8 | standard input | [
"greedy",
"math"
] | 08783e3dff3f3b7eb586931f9d0cd457 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick. | 1,200 | For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". | standard output | |
PASSED | a9a3fe0ba31e12a844d61ce6c85e75a2 | train_003.jsonl | 1565706900 | You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class Main {
public static void main(String[] args)throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(in.readLine());
for(int i=0;i<t;i++) {
int n = Integer.parseInt(in.readLine());
String[] str = in.readLine().split("\\s+");
int[] input = new int[4*n];
for (int j = 0; j < 4*n; j++) {
input[j] = Integer.parseInt(str[j]);
}
Arrays.sort(input);
boolean ctr = true;
int x = -1;
for(int j=0,k=4*n-1;j<4*n&&k>=0&&j<k;j+=2,k-=2){
if(input[j]!=input[j+1] || input[k]!=input[k-1])
{
ctr =false;
break;
}
if(j!=0){
if(input[j]*input[k]!=x) {
ctr = false;
break;
}
}
x = input[j]*input[k];
}
if(ctr)
System.out.println("YES");
else
System.out.println("NO");
}
}
}
| Java | ["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES"] | null | Java 8 | standard input | [
"greedy",
"math"
] | 08783e3dff3f3b7eb586931f9d0cd457 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick. | 1,200 | For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". | standard output | |
PASSED | 5fecc7294b2f7b151c2b871560f26da4 | train_003.jsonl | 1565706900 | You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries. | 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.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Jenish
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
ScanReader in = new ScanReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
BEqualRectangles solver = new BEqualRectangles();
solver.solve(1, in, out);
out.close();
}
static class BEqualRectangles {
public void solve(int testNumber, ScanReader in, PrintWriter out) {
int q = in.scanInt();
while (q-- > 0) {
int n = in.scanInt();
int arr[] = new int[4 * n];
in.scanInt(arr);
int count[] = new int[100000];
CodeX.sort(arr);
for (int k : arr) count[k]++;
boolean f = false;
long area = arr[0] * arr[4 * n - 1];
int c = 0;
for (long a = 1; a * a <= area; a++) {
if (area % a == 0) {
if (a * a != area) {
int b = (int) (area / a);
if (a < 100000 && b < 100000)
c += Math.min(count[(int) a] / 2, count[b] / 2);
} else {
if (a < 100000)
c += count[(int) a] / 4;
}
}
}
if (c == n) {
out.println("YES");
} else {
out.println("NO");
}
}
}
}
static class ScanReader {
private byte[] buf = new byte[4 * 1024];
private int INDEX;
private BufferedInputStream in;
private int TOTAL;
public ScanReader(InputStream inputStream) {
in = new BufferedInputStream(inputStream);
}
private int scan() {
if (INDEX >= TOTAL) {
INDEX = 0;
try {
TOTAL = in.read(buf);
} catch (Exception e) {
e.printStackTrace();
}
if (TOTAL <= 0) return -1;
}
return buf[INDEX++];
}
public int scanInt() {
int I = 0;
int n = scan();
while (isWhiteSpace(n)) n = scan();
int neg = 1;
if (n == '-') {
neg = -1;
n = scan();
}
while (!isWhiteSpace(n)) {
if (n >= '0' && n <= '9') {
I *= 10;
I += n - '0';
n = scan();
}
}
return neg * I;
}
private boolean isWhiteSpace(int n) {
if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
else return false;
}
public void scanInt(int[] A) {
for (int i = 0; i < A.length; i++) A[i] = scanInt();
}
}
static class CodeX {
public static void sort(int arr[]) {
merge_sort(arr, 0, arr.length - 1);
}
private static void merge_sort(int A[], int start, int end) {
if (start < end) {
int mid = (start + end) / 2;
merge_sort(A, start, mid);
merge_sort(A, mid + 1, end);
merge(A, start, mid, end);
}
}
private static void merge(int A[], int start, int mid, int end) {
int p = start, q = mid + 1;
int Arr[] = new int[end - start + 1];
int k = 0;
for (int i = start; i <= end; i++) {
if (p > mid)
Arr[k++] = A[q++];
else if (q > end)
Arr[k++] = A[p++];
else if (A[p] < A[q])
Arr[k++] = A[p++];
else
Arr[k++] = A[q++];
}
for (int i = 0; i < k; i++) {
A[start++] = Arr[i];
}
}
}
}
| Java | ["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES"] | null | Java 8 | standard input | [
"greedy",
"math"
] | 08783e3dff3f3b7eb586931f9d0cd457 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick. | 1,200 | For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". | standard output | |
PASSED | 4614733bf17aee7450c11f2647b4cf41 | train_003.jsonl | 1565706900 | You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
public class Exam {
public static long mod = (long) Math.pow(10, 9)+7 ;
public static InputReader sc = new InputReader(System.in);
public static PrintWriter pw = new PrintWriter(System.out);
public static int check(String or,String s[]){
for(int i=0;i<s.length;i++){
if(!(s[i].equals(or.substring(0,s[i].length()))||s[i].equals(or.substring(or.length()-s[i].length())))){
return 0;
}
}
return 1;
}
public static void main(String[] args) {
// Code starts..
int t=sc.nextInt();
int flag=0;
while(t-->0){
int n=sc.nextInt();
int a[]=scanArray(4*n);
Arrays.sort(a);
flag=0;
int ar=a[0]*a[4*n-1];
int b[]=new int[100000];
for(int i=0;i<4*n;i++){
b[a[i]]++;
}
for(int i=0;i<4*n;i++){
if(b[a[i]]%2!=0)
flag=1;
}
for(int i=1;i<2*n;i++){
if(a[i]*a[4*n-i-1]!=ar)
flag=1;
}
if(flag==0)
pw.println("YES");
else
pw.println("NO");
}
// Code ends...
pw.flush();
pw.close();
}
public static String reverseString(String s){
StringBuilder input1 = new StringBuilder();
input1.append(s);
input1 = input1.reverse();
return input1.toString();
}
public static int[] scanArray(int n){
int a[]=new int [n];
for(int i=0;i<n;i++)
a[i]=sc.nextInt();
return a;
}
public static long[] scanLongArray(int n){
long a[]=new long [n];
for(int i=0;i<n;i++)
a[i]=sc.nextLong();
return a;
}
public static String [] scanStrings(int n){
String a[]=new String [n];
for(int i=0;i<n;i++)
a[i]=sc.nextLine();
return a;
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES"] | null | Java 8 | standard input | [
"greedy",
"math"
] | 08783e3dff3f3b7eb586931f9d0cd457 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick. | 1,200 | For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". | standard output | |
PASSED | 7aed2e308c516f3bf4397ec7595b226d | train_003.jsonl | 1565706900 | You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries. | 256 megabytes |
import java.io.*;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws IOException {
Reader reader = new Reader();
int q = reader.nextInt();
loop:
while(q-- > 0){
int n = reader.nextInt();
int[] a = new int[4 * n];
for(int i = 0; i < 4 * n; ++i){
a[i] = reader.nextInt();
}
Arrays.sort(a);
int area = -1;
for(int i = 0; i < 2 * n; ++i){
int p = a[i] * a[4 * n - i - 1];
if(area == -1){
area = p;
}else{
if(area != p){
System.out.println("NO");
continue loop;
}
}
}
for(int i = 0; i < 4 * n; i += 2){
if(a[i] != a[i + 1]){
System.out.println("NO");
continue loop;
}
}
System.out.println("YES");
}
}
}
class Reader{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() throws IOException{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
} | Java | ["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES"] | null | Java 8 | standard input | [
"greedy",
"math"
] | 08783e3dff3f3b7eb586931f9d0cd457 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick. | 1,200 | For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". | standard output | |
PASSED | 3b1b9a15b8dd8cdf955ba34ffa89b5d4 | train_003.jsonl | 1565706900 | You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries. | 256 megabytes |
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
public static final int MAX = 10000 + 5;
public static void main(String[] args) throws IOException {
Reader reader = new Reader();
int q = reader.nextInt();
loop:
while(q-- > 0){
int n = reader.nextInt();
int[] a = new int[4 * n];
int[] v = new int[MAX];
for(int i = 0; i < 4 * n; ++i){
a[i] = reader.nextInt();
v[a[i]]++;
}
List<Integer> list = new ArrayList<>();
for(int i = 0; i < MAX; ++i){
if(v[i] % 2 == 1){
System.out.println("NO");
continue loop;
}
for(int k = 0; k < v[i] / 2; ++k){
list.add(i);
}
}
Collections.sort(list);
int area = -1;
for(int i = 0; i < 2 * n; ++i){
if(area == -1){
area = list.get(i) * list.get(2 * n - 1 - i);
}else{
if(list.get(i) * list.get(2 * n - 1 - i) != area){
System.out.println("NO");
continue loop;
}
}
}
System.out.println("YES");
}
}
}
class Reader{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() throws IOException{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
} | Java | ["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES"] | null | Java 8 | standard input | [
"greedy",
"math"
] | 08783e3dff3f3b7eb586931f9d0cd457 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick. | 1,200 | For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". | standard output | |
PASSED | 86b0e8f8fd33b55d2d42619b83498679 | train_003.jsonl | 1565706900 | You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
public class EqualRectagles {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while (t>0){
t--;
int n=sc.nextInt();
int arr[]=new int[4*n];
Map<Integer,Integer> map=new TreeMap<>();
for(int i=0;i<4*n;i++){
arr[i]=sc.nextInt();
if(!map.containsKey(arr[i])){
map.put(arr[i],1);
}else{
int count=map.get(arr[i]);
map.replace(arr[i],count+1);
}
}
boolean flag=true;
ArrayList<Integer> list= new ArrayList<>(map.keySet());
int left=0;
int right=list.size()-1;
int area=list.get(left)*list.get(right);
while(left<(list.size()/2)){
int start=list.get(left);
int end=list.get(right);
if( !valid(map.get(start),map.get(end)) || !valid2(start,end,area) ){
System.out.println("NO");
flag=false;
break;
}
left++;
right--;
}
if(flag){
if(list.size()%2!=0){
int midKey=list.get(left);
int start=list.get(0);
int last=list.get(list.size()-1);
if(midKey*midKey!=start*last){
System.out.println("NO");
flag=false;
}
}
}
if(flag)
System.out.println("YES");
}
}
private static boolean valid2(int start, int end, int area) {
if(start*end==area)
return true;
else
return false;
}
private static boolean valid(int x, int y) {
if((x%2==0 && y%2==0) && (x==y))
return true;
else
return false;
}
}
| Java | ["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES"] | null | Java 8 | standard input | [
"greedy",
"math"
] | 08783e3dff3f3b7eb586931f9d0cd457 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick. | 1,200 | For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". | standard output | |
PASSED | 788f85c00ddce2f85c3dbc3a2639a5ed | train_003.jsonl | 1565706900 | You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.*;
import java.math.*;
import java.util.*;
public class icpc
{
public static void main(String[] args) throws IOException
{
Reader in = new Reader();
// BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int q = in.nextInt();
for (int i=0;i<q;i++)
{
int n = in.nextInt();
int[] count = new int[10001];
int max = Integer.MIN_VALUE;
for (int j=0;j<4 * n;j++)
{
int a = in.nextInt();
max = Math.max(max, a);
count[a]++;
}
boolean flag = true;
if (max == 1)
{
System.out.println("YES");
}
else
{
ArrayList<Integer> A = new ArrayList<>();
for (int j=0;j<count.length;j++)
{
if (count[j] > 0)
{
for (int k=0;k<count[j];k++)
A.add(j);
}
}
boolean flag1 = true;
int m = A.size();
long prod = 1L * A.get(0) * A.get(m - 1) * A.get(1) * A.get(m - 2);
for (int j=0;j<m;j+=2)
{
if ((int)A.get(j) == (int)A.get(j + 1) && (int)A.get(m - 1 - j) == (int)A.get(m - 2 - j) && 1L * A.get(j) * A.get(m - 1 - j) * A.get(j + 1) * A.get(m - 2 - j) == prod)
{
continue;
}
else
{
flag1 = false;
break;
}
}
if (flag1)
System.out.println("YES");
else
System.out.println("NO");
}
}
}
}
class NumberTheory
{
public boolean isPrime(long n)
{
if(n < 2)
return false;
for(long x = 2;x * x <= n;x++)
{
if(n % x == 0)
return false;
}
return true;
}
public ArrayList<Long> primeFactorisation(long n)
{
ArrayList<Long> f = new ArrayList<>();
for(long x=2;x * x <= n;x++)
{
while(n % x == 0)
{
f.add(x);
n /= x;
}
}
if(n > 1)
f.add(n);
return f;
}
public int[] sieveOfEratosthenes(int n)
{
int[] sieve = new int[n + 1];
for(int x=2;x<=n;x++)
{
if(sieve[x] != 0)
continue;
sieve[x] = x;
for(int u=2*x;u<=n;u+=x)
if(sieve[u] == 0)
sieve[u] = x;
}
return sieve;
}
public long gcd(long a, long b)
{
if(b == 0)
return a;
return gcd(b, a % b);
}
public long phi(long n)
{
double result = n;
for(long p=2;p*p<=n;p++)
{
if(n % p == 0)
{
while (n % p == 0)
n /= p;
result *= (1.0 - (1.0 / (double)p));
}
}
if(n > 1)
result *= (1.0 - (1.0 / (double)n));
return (long)result;
}
public Name extendedEuclid(long a, long b)
{
if(b == 0)
return new Name(a, 1, 0);
Name n1 = extendedEuclid(b, a % b);
Name n2 = new Name(n1.d, n1.y, n1.x - (long)Math.floor((double)a / b) * n1.y);
return n2;
}
public long modularExponentiation(long a, long b, long n)
{
long d = 1L;
String bString = Long.toBinaryString(b);
for(int i=0;i<bString.length();i++)
{
d = (d * d) % n;
if(bString.charAt(i) == '1')
d = (d * a) % n;
}
return d;
}
}
class Name
{
long d;
long x;
long y;
public Name(long d, long x, long y)
{
this.d = d;
this.x = x;
this.y = y;
}
}
class SuffixArray
{
int ALPHABET_SZ = 256, N;
int[] T, lcp, sa, sa2, rank, tmp, c;
public SuffixArray(String str)
{
this(toIntArray(str));
}
private static int[] toIntArray(String s)
{
int[] text = new int[s.length()];
for (int i = 0; i < s.length(); i++) text[i] = s.charAt(i);
return text;
}
public SuffixArray(int[] text)
{
T = text;
N = text.length;
sa = new int[N];
sa2 = new int[N];
rank = new int[N];
c = new int[Math.max(ALPHABET_SZ, N)];
construct();
kasai();
}
private void construct()
{
int i, p, r;
for (i = 0; i < N; ++i) c[rank[i] = T[i]]++;
for (i = 1; i < ALPHABET_SZ; ++i) c[i] += c[i - 1];
for (i = N - 1; i >= 0; --i) sa[--c[T[i]]] = i;
for (p = 1; p < N; p <<= 1)
{
for (r = 0, i = N - p; i < N; ++i) sa2[r++] = i;
for (i = 0; i < N; ++i) if (sa[i] >= p) sa2[r++] = sa[i] - p;
Arrays.fill(c, 0, ALPHABET_SZ, 0);
for (i = 0; i < N; ++i) c[rank[i]]++;
for (i = 1; i < ALPHABET_SZ; ++i) c[i] += c[i - 1];
for (i = N - 1; i >= 0; --i) sa[--c[rank[sa2[i]]]] = sa2[i];
for (sa2[sa[0]] = r = 0, i = 1; i < N; ++i)
{
if (!(rank[sa[i - 1]] == rank[sa[i]]
&& sa[i - 1] + p < N
&& sa[i] + p < N
&& rank[sa[i - 1] + p] == rank[sa[i] + p])) r++;
sa2[sa[i]] = r;
}
tmp = rank;
rank = sa2;
sa2 = tmp;
if (r == N - 1) break;
ALPHABET_SZ = r + 1;
}
}
private void kasai()
{
lcp = new int[N];
int[] inv = new int[N];
for (int i = 0; i < N; i++) inv[sa[i]] = i;
for (int i = 0, len = 0; i < N; i++)
{
if (inv[i] > 0)
{
int k = sa[inv[i] - 1];
while ((i + len < N) && (k + len < N) && T[i + len] == T[k + len]) len++;
lcp[inv[i] - 1] = len;
if (len > 0) len--;
}
}
}
}
class ZAlgorithm
{
public int[] calculateZ(char input[])
{
int Z[] = new int[input.length];
int left = 0;
int right = 0;
for(int k = 1; k < input.length; k++) {
if(k > right) {
left = right = k;
while(right < input.length && input[right] == input[right - left]) {
right++;
}
Z[k] = right - left;
right--;
} else {
//we are operating inside box
int k1 = k - left;
//if value does not stretches till right bound then just copy it.
if(Z[k1] < right - k + 1) {
Z[k] = Z[k1];
} else { //otherwise try to see if there are more matches.
left = k;
while(right < input.length && input[right] == input[right - left]) {
right++;
}
Z[k] = right - left;
right--;
}
}
}
return Z;
}
public ArrayList<Integer> matchPattern(char text[], char pattern[])
{
char newString[] = new char[text.length + pattern.length + 1];
int i = 0;
for(char ch : pattern) {
newString[i] = ch;
i++;
}
newString[i] = '$';
i++;
for(char ch : text) {
newString[i] = ch;
i++;
}
ArrayList<Integer> result = new ArrayList<>();
int Z[] = calculateZ(newString);
for(i = 0; i < Z.length ; i++) {
if(Z[i] == pattern.length) {
result.add(i - pattern.length - 1);
}
}
return result;
}
}
class KMPAlgorithm
{
public int[] computeTemporalArray(char[] pattern)
{
int[] lps = new int[pattern.length];
int index = 0;
for(int i=1;i<pattern.length;)
{
if(pattern[i] == pattern[index])
{
lps[i] = index + 1;
index++;
i++;
}
else
{
if(index != 0)
{
index = lps[index - 1];
}
else
{
lps[i] = 0;
i++;
}
}
}
return lps;
}
public ArrayList<Integer> KMPMatcher(char[] text, char[] pattern)
{
int[] lps = computeTemporalArray(pattern);
int j = 0;
int i = 0;
int n = text.length;
int m = pattern.length;
ArrayList<Integer> indices = new ArrayList<>();
while(i < n)
{
if(pattern[j] == text[i])
{
i++;
j++;
}
if(j == m)
{
indices.add(i - j);
j = lps[j - 1];
}
else if(i < n && pattern[j] != text[i])
{
if(j != 0)
j = lps[j - 1];
else
i = i + 1;
}
}
return indices;
}
}
class Hashing
{
public long[] computePowers(long p, int n, long m)
{
long[] powers = new long[n];
powers[0] = 1;
for(int i=1;i<n;i++)
{
powers[i] = (powers[i - 1] * p) % m;
}
return powers;
}
public long computeHash(String s)
{
long p = 31;
long m = 1_000_000_009;
long hashValue = 0L;
long[] powers = computePowers(p, s.length(), m);
for(int i=0;i<s.length();i++)
{
char ch = s.charAt(i);
hashValue = (hashValue + (ch - 'a' + 1) * powers[i]) % m;
}
return hashValue;
}
}
class BasicFunctions
{
public long min(long[] A)
{
long min = Long.MAX_VALUE;
for(int i=0;i<A.length;i++)
{
min = Math.min(min, A[i]);
}
return min;
}
public long max(long[] A)
{
long max = Long.MAX_VALUE;
for(int i=0;i<A.length;i++)
{
max = Math.max(max, A[i]);
}
return max;
}
}
class Matrix
{
long a;
long b;
long c;
long d;
public Matrix(long a, long b, long c, long d)
{
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
}
class MergeSortInt
{
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r) {
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
int L[] = new int[n1];
int R[] = new int[n2];
/*Copy data to temp arrays*/
for (int i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
void sort(int arr[], int l, int r) {
if (l < r) {
// Find the middle point
int m = (l + r) / 2;
// Sort first and second halves
sort(arr, l, m);
sort(arr, m + 1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
}
class MergeSortLong
{
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(long arr[], int l, int m, int r) {
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
long L[] = new long[n1];
long R[] = new long[n2];
/*Copy data to temp arrays*/
for (int i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (int j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
// Main function that sorts arr[l..r] using
// merge()
void sort(long arr[], int l, int r) {
if (l < r) {
// Find the middle point
int m = (l + r) / 2;
// Sort first and second halves
sort(arr, l, m);
sort(arr, m + 1, r);
// Merge the sorted halves
merge(arr, l, m, r);
}
}
}
class Node
{
int sum;
int len;
Node(int a, int b)
{
this.sum = a;
this.len = b;
}
@Override
public boolean equals(Object ob)
{
if(ob == null)
return false;
if(!(ob instanceof Node))
return false;
if(ob == this)
return true;
Node obj = (Node)ob;
if(this.sum == obj.sum && this.len == obj.len)
return true;
return false;
}
@Override
public int hashCode()
{
return (int)this.len;
}
}
class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException
{
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1)
{
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException
{
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do
{
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
class FenwickTree
{
public void update(long[] fenwickTree,long delta,int index)
{
index += 1;
while(index < fenwickTree.length)
{
fenwickTree[index] += delta;
index = index + (index & (-index));
}
}
public long prefixSum(long[] fenwickTree,int index)
{
long sum = 0L;
index += 1;
while(index > 0)
{
sum += fenwickTree[index];
index -= (index & (-index));
}
return sum;
}
}
class SegmentTree
{
public int nextPowerOfTwo(int num)
{
if(num == 0)
return 1;
if(num > 0 && (num & (num - 1)) == 0)
return num;
while((num &(num - 1)) > 0)
{
num = num & (num - 1);
}
return num << 1;
}
public int[] createSegmentTree(int[] input)
{
int np2 = nextPowerOfTwo(input.length);
int[] segmentTree = new int[np2 * 2 - 1];
for(int i=0;i<segmentTree.length;i++)
segmentTree[i] = Integer.MIN_VALUE;
constructSegmentTree(segmentTree,input,0,input.length-1,0);
return segmentTree;
}
private void constructSegmentTree(int[] segmentTree,int[] input,int low,int high,int pos)
{
if(low == high)
{
segmentTree[pos] = input[low];
return;
}
int mid = (low + high)/ 2;
constructSegmentTree(segmentTree,input,low,mid,2*pos + 1);
constructSegmentTree(segmentTree,input,mid+1,high,2*pos + 2);
segmentTree[pos] = Math.max(segmentTree[2*pos + 1],segmentTree[2*pos + 2]);
}
public int rangeMinimumQuery(int []segmentTree,int qlow,int qhigh,int len)
{
return rangeMinimumQuery(segmentTree,0,len-1,qlow,qhigh,0);
}
private int rangeMinimumQuery(int segmentTree[],int low,int high,int qlow,int qhigh,int pos)
{
if(qlow <= low && qhigh >= high){
return segmentTree[pos];
}
if(qlow > high || qhigh < low){
return Integer.MIN_VALUE;
}
int mid = (low+high)/2;
return Math.max(rangeMinimumQuery(segmentTree, low, mid, qlow, qhigh, 2 * pos + 1),
rangeMinimumQuery(segmentTree, mid + 1, high, qlow, qhigh, 2 * pos + 2));
}
} | Java | ["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES"] | null | Java 8 | standard input | [
"greedy",
"math"
] | 08783e3dff3f3b7eb586931f9d0cd457 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick. | 1,200 | For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". | standard output | |
PASSED | a4f04f239d8798fa669b963ab7d82fff | train_003.jsonl | 1565706900 | You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Codechef{
PrintWriter out;
StringTokenizer st;
BufferedReader br;
class Pair
{
int f;
int s;
public Pair(int t, int r) {
f = t;
s = r;
}
}
String ns() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
String nextLine() throws Exception {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
throw new Exception(e.toString());
}
return str;
}
int nextInt() {
return Integer.parseInt(ns());
}
long nextLong() {
return Long.parseLong(ns());
}
double nextDouble() {
return Double.parseDouble(ns());
}
public static void main(String args[]) throws IOException {
new Codechef().run();
}
void run() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
long s = System.currentTimeMillis();
solve();
out.flush();
out.close();
}
long power(long x,long y)
{
long ans=1;
while(y!=0)
{
if(y%2==1)
ans*=x;
x=x*x;
y/=2;
}
return ans;
}
void solve(){
int q=nextInt();
while(q-->0)
{
int n=nextInt();
int arr[]=new int[4*n];
for(int i=0;i<4*n;i++)
arr[i]=nextInt();
Arrays.sort(arr,0,4*n);
int a=arr[0]*arr[4*n-1];
int l=0,r=4*n-1,flag=0;
while(l<=r)
{
if(arr[l]*arr[r]==a&&arr[l]==arr[l+1]&&arr[r]==arr[r-1])
{
l+=2;r-=2;
continue;
}
else
{
flag=1;
break;
}
}
if(flag==0)
out.println("YES");
else
out.println("NO");
}
}
} | Java | ["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES"] | null | Java 8 | standard input | [
"greedy",
"math"
] | 08783e3dff3f3b7eb586931f9d0cd457 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick. | 1,200 | For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". | standard output | |
PASSED | e44829bcc81720c69de89a69301b91c1 | train_003.jsonl | 1565706900 | You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Scanner;
public class scratch_10 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PrintWriter pw = new PrintWriter(System.out);
int T = sc.nextInt();
for (int t = 0; t < T; t++) {
int n = sc.nextInt();
int sticks[] = new int[4*n];
for (int nn = 0; nn < 4 * n; nn++) {
sticks[nn] = sc.nextInt();
}
pw.println(solve(n, sticks));
}
pw.flush();
pw.close();
}
private static String solve(int n, int[] st) {
Arrays.sort(st);
if (n == 1 && st[0] == st[1] && st[2] == st[3]) return "YES";
int[] ss = new int[st.length / 2];
int i = 0;
for (int j = 0; j < st.length; j = j + 2) {
if (st[j] != st[j + 1]) return "NO";
ss[i++] = st[j];
}
long prod = ss[0] * ss[ss.length - 1];
for (int k = 1; k < ss.length / 2; k ++) {
if (prod != ss[k] * ss[ss.length - 1 - k]) return "NO";
}
return "YES";
}
} | Java | ["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES"] | null | Java 8 | standard input | [
"greedy",
"math"
] | 08783e3dff3f3b7eb586931f9d0cd457 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick. | 1,200 | For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". | standard output | |
PASSED | 3abe5228904657b365ff91d645fa508f | train_003.jsonl | 1565706900 | You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries. | 256 megabytes |
import java.math.*;
import java.text.*;
import java.util.*;
import javafx.util.*;
public class CompleteSearch {
public static Scanner in =new Scanner(System.in);
public static void main(String[] args){
int q=in.nextInt();
for(int t=0;t<q;t++){
int n=in.nextInt();
int[]z=new int[n*4];
for(int i =0;i<n*4;i++)
z[i]=in.nextInt();
Arrays.sort(z);
int area=z[(4*n)-1]*z[0];
boolean ans=true;
int l=0,r=(4*n)-1;
for(int i=0;i<n;i++){
if(z[l]==z[l+1]&&z[r]==z[r-1]){
int cur=z[l]*z[r];
if(cur!=area){
ans=false;
break;
}
l+=2;
r-=2;
}
else{
ans=false;
break;
}
}
if(ans)
System.out.println("YES");
else
System.out.println("NO");
}
}
} | Java | ["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES"] | null | Java 8 | standard input | [
"greedy",
"math"
] | 08783e3dff3f3b7eb586931f9d0cd457 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick. | 1,200 | For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". | standard output | |
PASSED | e22a1ec58e7550b65baa6e0ed7915a1d | train_003.jsonl | 1565706900 | You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class Solution {
public static String Array(int[] Arr)
{
int n=Arr[0];
for(int i=1;i<Arr.length;i++)
{
n=n^Arr[i];
}
if(n==0)
{
Arrays.sort(Arr);
int m=0;
int O=Arr.length-1;
int ans=Arr[m]*Arr[O];
//System.out.println(ans);
while(m<=O)
{
if(ans==Arr[m]*Arr[O])
{
m=m+2;
O=O-2;
}
else
{
break;
}
}
if(m>O)
{
return "YES";
}
else
return "NO";
}
else
return "NO";
}
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner(System.in);
int t=0;
if(sc.hasNextInt())
t=sc.nextInt();
for(int i=0;i<t;i++)
{
int n=0;
if(sc.hasNextInt())
n=sc.nextInt();
int[] Arr=new int[4*n];
for(int j=0;j<4*n;j++)
{
Arr[j]=sc.nextInt();
}
System.out.println(Array(Arr));
}
}
}
| Java | ["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES"] | null | Java 8 | standard input | [
"greedy",
"math"
] | 08783e3dff3f3b7eb586931f9d0cd457 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick. | 1,200 | For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". | standard output | |
PASSED | 67c0beec88f548ade958aab032779f52 | train_003.jsonl | 1565706900 | You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
public class Main {
static int mod=1000000007;
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
StringBuilder st=new StringBuilder();
int t=sc.nextInt();
while(t-->0) {
int n=sc.nextInt();
int a[]=new int [4*n];
for(int i=0;i<a.length;i++)
{
a[i]=sc.nextInt();
}
boolean f=true;
Arrays.sort(a);
String ans="YES";
int area=a[0]*a[a.length-1];
int left=0;
int right=a.length-1;
while(left<right)
{
if(!(a[left]*a[right]==area &&
a[left]==a[left+1]
&& a[right]==a[right-1]))
{
ans="NO";
break;
}
left+=2;
right-=2;
}
st.append(ans+"\n");
}
System.out.println(st);
}
public static long gcd(long a, long b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
} | Java | ["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES"] | null | Java 8 | standard input | [
"greedy",
"math"
] | 08783e3dff3f3b7eb586931f9d0cd457 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick. | 1,200 | For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". | standard output | |
PASSED | 8a274142bdeb54a12629cbfc932b3ba0 | train_003.jsonl | 1565706900 | You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries. | 256 megabytes |
import java.io.*;
import java.util.*;
public class Hey2018 {
public static void main(String[] args) throws IOException {
BufferedReader jk = new BufferedReader(new InputStreamReader(System.in)) ;
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)) ;
StringTokenizer ana = new StringTokenizer(jk.readLine()) ;
int q= Integer.parseInt(ana.nextToken()) ;
for(int j=0 ; j<q ;j++)
{
ana = new StringTokenizer(jk.readLine()) ;
int n= Integer.parseInt(ana.nextToken()) ;
ana = new StringTokenizer(jk.readLine()) ;
int t[]= new int[4*n] ;
for(int i=0 ; i< 4*n ;i++)
{
t[i] = Integer.parseInt(ana.nextToken()) ;
}
Arrays.sort(t);
int area = t[0]*t[4*n-1] ;
int u = 4*n-1 ;
boolean te = true ;
for(int i=0 ; i<2*n ;i+=2)
{
int a = t[i]*t[u-i] ;
if(a!=area)
{
te =false ;
}
if((t[i]!=t[i+1]) || (t[u-i]!=t[u-i-1]))
{
te =false ;
}
}
if(te) out.println("YES");
else out.println("NO");
}
out.flush();
}
}
| Java | ["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES"] | null | Java 8 | standard input | [
"greedy",
"math"
] | 08783e3dff3f3b7eb586931f9d0cd457 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick. | 1,200 | For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". | standard output | |
PASSED | 9ed78e197cddf7e0ecd9a2b5c96c3f9a | train_003.jsonl | 1565706900 | You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
import java.io.*;
//267630EY
public class Main1203BA2
{
static PrintWriter out=new PrintWriter(System.out);
public static void main(String[] args) throws IOException
{
Scanner sc=new Scanner(System.in);
int q=sc.nextInt();
while(q-->0)
{
int n=sc.nextInt();
long[] a=sc.nextLongArray(4*n);
Arrays.sort(a);
long area=a[0]*a[4*n-1];
boolean flag=true;
for(int i=0;i<n;i++)
{
if(!(a[2*i]==a[2*i+1]&&a[4*n-2*i-1]==a[4*n-2*i-2]&&a[2*i]*a[4*n-2*i-1]==area))
{
flag=false;
break;
}
}
if(!flag)
out.println("NO");
else
out.println("YES");
out.flush();
}
}
static class Scanner
{
BufferedReader br;
StringTokenizer tk=new StringTokenizer("");
public Scanner(InputStream is)
{
br=new BufferedReader(new InputStreamReader(is));
}
public boolean hasNext()
{
boolean result=false;
try
{
result = br.ready();
}
catch (IOException e)
{
System.err.println(e);
}
return result;
}
public int nextInt() throws IOException
{
if(tk.hasMoreTokens())
return Integer.parseInt(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextInt();
}
public long nextLong() throws IOException
{
if(tk.hasMoreTokens())
return Long.parseLong(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextLong();
}
public String next() throws IOException
{
if(tk.hasMoreTokens())
return (tk.nextToken());
tk=new StringTokenizer(br.readLine());
return next();
}
public String nextLine() throws IOException
{
tk=new StringTokenizer("");
return br.readLine();
}
public double nextDouble() throws IOException
{
if(tk.hasMoreTokens())
return Double.parseDouble(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextDouble();
}
public char nextChar() throws IOException
{
if(tk.hasMoreTokens())
return (tk.nextToken().charAt(0));
tk=new StringTokenizer(br.readLine());
return nextChar();
}
public int[] nextIntArray(int n) throws IOException
{
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=nextInt();
return a;
}
public long[] nextLongArray(int n) throws IOException
{
long a[]=new long[n];
for(int i=0;i<n;i++)
a[i]=nextLong();
return a;
}
public int[] nextIntArrayOneBased(int n) throws IOException
{
int a[]=new int[n+1];
for(int i=1;i<=n;i++)
a[i]=nextInt();
return a;
}
public long[] nextLongArrayOneBased(int n) throws IOException
{
long a[]=new long[n+1];
for(int i=1;i<=n;i++)
a[i]=nextLong();
return a;
}
}
}
| Java | ["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES"] | null | Java 8 | standard input | [
"greedy",
"math"
] | 08783e3dff3f3b7eb586931f9d0cd457 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick. | 1,200 | For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". | standard output | |
PASSED | 7004a359910312ac5ff812b881b8587b | train_003.jsonl | 1565706900 | You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
import java.io.*;
//267630EY
public class Main1203B
{
static PrintWriter out=new PrintWriter(System.out);
public static void main(String[] args) throws IOException
{
Scanner sc=new Scanner(System.in);
int q=sc.nextInt();
while(q-->0)
{
int n=sc.nextInt();
int[] a=sc.nextIntArray(4*n);
Arrays.sort(a);
Vector<Integer> v=new Vector<Integer>();
for(int i=0;i<a.length;i++)
{
if(!v.contains(a[i]))
v.add(a[i]);
}
int area=a[0]*a[a.length-1];
int[] count=new int[10001];
for(int i=0;i<4*n;i++)
{
count[a[i]]++;
}
int i=0;
int j=v.size()-1;
boolean flag=true;
while(i<=j)
{
if(count[v.elementAt(i)]!=count[v.elementAt(j)]||count[v.elementAt(i)]%2!=0||count[v.elementAt(j)]%2!=0||v.elementAt(i)*v.elementAt(j)!=area)
{
flag=false;
break;
}
if(i==j)
{
if(count[v.elementAt(i)]%4!=0||area!=v.elementAt(i)*v.elementAt(i))
flag=false;
}
i++;
j--;
}
if(!flag)
out.println("NO");
else
out.println("YES");
}
out.flush();
}
static class Scanner
{
BufferedReader br;
StringTokenizer tk=new StringTokenizer("");
public Scanner(InputStream is)
{
br=new BufferedReader(new InputStreamReader(is));
}
public int nextInt() throws IOException
{
if(tk.hasMoreTokens())
return Integer.parseInt(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextInt();
}
public long nextLong() throws IOException
{
if(tk.hasMoreTokens())
return Long.parseLong(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextLong();
}
public String next() throws IOException
{
if(tk.hasMoreTokens())
return (tk.nextToken());
tk=new StringTokenizer(br.readLine());
return next();
}
public String nextLine() throws IOException
{
tk=new StringTokenizer("");
return br.readLine();
}
public double nextDouble() throws IOException
{
if(tk.hasMoreTokens())
return Double.parseDouble(tk.nextToken());
tk=new StringTokenizer(br.readLine());
return nextDouble();
}
public char nextChar() throws IOException
{
if(tk.hasMoreTokens())
return (tk.nextToken().charAt(0));
tk=new StringTokenizer(br.readLine());
return nextChar();
}
public int[] nextIntArray(int n) throws IOException
{
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=nextInt();
return a;
}
public long[] nextLongArray(int n) throws IOException
{
long a[]=new long[n];
for(int i=0;i<n;i++)
a[i]=nextLong();
return a;
}
public int[] nextIntArrayOneBased(int n) throws IOException
{
int a[]=new int[n+1];
for(int i=1;i<=n;i++)
a[i]=nextInt();
return a;
}
public long[] nextLongArrayOneBased(int n) throws IOException
{
long a[]=new long[n+1];
for(int i=1;i<=n;i++)
a[i]=nextLong();
return a;
}
}
}
| Java | ["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES"] | null | Java 8 | standard input | [
"greedy",
"math"
] | 08783e3dff3f3b7eb586931f9d0cd457 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick. | 1,200 | For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". | standard output | |
PASSED | c695afed653573a21653a3762af04535 | train_003.jsonl | 1565706900 | You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
public class div3B {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int q = sc.nextInt();
while(q-->0){
boolean ans = true;
int n = sc.nextInt();
int arr[] = new int[4*n];
int len = arr.length;
for ( int i =0;i < len;i++){
arr[i] = sc.nextInt();
}
Arrays.sort(arr);
int area = arr[0]*arr[len-1];
for ( int i = 0,j = len-1;i < j ; i+=2,j-=2){
if(arr[i]!=arr[i+1] || arr[j]!=arr[j-1] || arr[i]*arr[j]!=area) {
ans = false;
break;
}
}
if(ans){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
}
private static class Scanner{
public BufferedReader reader;
public StringTokenizer st;
public Scanner(InputStream stream){
reader = new BufferedReader(new InputStreamReader(stream));
st = null;
}
public String next(){
while(st == null || !st.hasMoreTokens()){
try{
String line = reader.readLine();
if(line == null) return null;
st = new StringTokenizer(line);
}catch (Exception e){
throw (new RuntimeException());
}
}
return st.nextToken();
}
public int nextInt(){
return Integer.parseInt(next());
}
public long nextLong(){
return Long.parseLong(next());
}
public double nextDouble(){
return Double.parseDouble(next());
}
}
}
| Java | ["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES"] | null | Java 8 | standard input | [
"greedy",
"math"
] | 08783e3dff3f3b7eb586931f9d0cd457 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick. | 1,200 | For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". | standard output | |
PASSED | 1ba37923793159c1af456397451bf31e | train_003.jsonl | 1565706900 | You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries. | 256 megabytes | /*Author: Satyajeet Singh, Delhi Technological University*/
import java.io.*;
import java.util.*;
import java.text.*;
import java.lang.*;
import java.math.*;
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<Pair> graph[];
static boolean oj = System.getProperty("ONLINE_JUDGE") != null;
/****************************************Solutions Begins***************************************/
public static void main (String[] args) throws Exception {
String st[]=nl();
int t=pi(st[0]);
while(t-->0){
st=nl();
int n=pi(st[0]);
boolean flag=true;
HashMap<Integer,Integer> map=new HashMap<>();
st=nl();
for(int i=0;i<4*n;i++){
int a=pi(st[i]);
map.put(a,map.getOrDefault(a,0)+1);
}
ArrayList<Pair> list=new ArrayList<>();
for(int u:map.keySet()){
list.add(new Pair(u,map.get(u)));
}
Collections.sort(list,new PairComp());
int i=0,j=list.size()-1;
HashSet<Integer> set=new HashSet<>();
while(i<j){
if(list.get(i).v%2==0&&list.get(i).v==list.get(j).v){
set.add(list.get(i).u*list.get(j).u);
}
else{
flag=false;
break;
}
i++;
j--;
}
//debug(list);
if(list.size()%2==1){
set.add(list.get(list.size()/2).u*list.get(list.size()/2).u);
}
//debug(set);
if(set.size()>1){
flag=false;
}
if(flag)out.println("YES");
else out.println("NO");
}
/****************************************Solutions Ends**************************************************/
out.flush();
out.close();
}
/****************************************Template Begins************************************************/
static String[] nl() throws Exception{
return br.readLine().split(" ");
}
static String[] nls() throws Exception{
return br.readLine().split("");
}
static int pi(String str) {
return Integer.parseInt(str);
}
static long pl(String str){
return Long.parseLong(str);
}
static double pd(String str){
return Double.parseDouble(str);
}
/***************************************Precision Printing**********************************************/
static void printPrecision(double d){
DecimalFormat ft = new DecimalFormat("0.00000000000000000");
out.println(ft.format(d));
}
/**************************************Bit Manipulation**************************************************/
static void printMask(int mask){
System.out.println(Integer.toBinaryString(mask));
}
/******************************************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,int c){
graph[a].add(new Pair(b,c));
}
/*********************************************PAIR********************************************************/
static class PairComp implements Comparator<Pair>{
public int compare(Pair p1,Pair p2){
if(p1.u!=p2.u){
return p1.u-p2.u;
}
else{
return p1.u-p2.u;
}
}
}
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){
long aa=p2.v-p1.v;
if(aa<0){
return -1;
}
else if(aa>0){
return 1;
}
else{
return 0;
}
}
}
static class Pairl implements Comparable<Pairl> {
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(Pairl 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) {
if(!oj)
System.out.println(Arrays.deepToString(o));
}
/************************************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);
}
}
}
/********************************************End***********************************************************/
} | Java | ["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES"] | null | Java 8 | standard input | [
"greedy",
"math"
] | 08783e3dff3f3b7eb586931f9d0cd457 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick. | 1,200 | For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". | standard output | |
PASSED | 3a671f50b1b098296d19d65b5a8c2c74 | train_003.jsonl | 1565706900 | You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.Scanner;
import java.util.ArrayList;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main
{
public static void main(String[] args)
{
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskB solver = new TaskB();
solver.solve(1, in, out);
out.close();
}
static class TaskB
{
public void solve(int testNumber, Scanner in, PrintWriter out)
{
int q = in.nextInt();
for (int i = 0; i < q; i++)
{
int n = in.nextInt();
int[] sticks = new int[4 * n];
//read sticks
for (int ii = 0; ii < 4 * n; ii++)
{
sticks[ii] = in.nextInt();
}
int max = max(sticks);
int min = min(sticks);
int halfArea = min * max;
List<Integer> sticksList = new ArrayList<>();
for (int ii = 0; ii < sticks.length; ii++)
{
sticksList.add(sticks[ii]);
}
boolean good = true;
while (!sticksList.isEmpty() && good)
{
//remove pair
int current = sticksList.remove(0);
Integer currentInt = current;
if (!sticksList.remove(currentInt))
{
good = false;
continue;
}
//remove pair
if (halfArea % current == 0)
{
Integer toRemove = halfArea / current;
boolean good1 = sticksList.remove(toRemove);
boolean good2 = good = sticksList.remove(toRemove);
good = good1 && good2;
} else
good = false;
}
if (sticksList.isEmpty() && good)
out.println("YES");
else
out.println("NO");
}
}
private int max(int sticks[])
{
int max = Integer.MIN_VALUE;
for (int ii = 0; ii < sticks.length; ii++)
{
if (max < sticks[ii]) max = sticks[ii];
}
return max;
}
private int min(int sticks[])
{
int min = Integer.MAX_VALUE;
for (int ii = 0; ii < sticks.length; ii++)
{
if (min > sticks[ii]) min = sticks[ii];
}
return min;
}
}
}
| Java | ["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES"] | null | Java 8 | standard input | [
"greedy",
"math"
] | 08783e3dff3f3b7eb586931f9d0cd457 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick. | 1,200 | For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". | standard output | |
PASSED | fcf5cd1891574f6c9ef4eab58d70cbc0 | train_003.jsonl | 1565706900 | You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main {
static Scanner sc = new Scanner(System.in);
static PrintWriter out = new PrintWriter(System.out);
static void solve() throws Exception{
int n = sc.nextInt();
HashMap<Integer,Integer> mp = new HashMap<>();
for(int i = 0; i < n * 4; i++) {
int k = sc.nextInt();
int val = mp.getOrDefault(k, 0);
mp.put(k, val + 1);
}
Pair arr[] = new Pair[mp.size()];
int idx = 0;
for(Map.Entry<Integer,Integer> e : mp.entrySet()) {
arr[idx++] = new Pair(e.getKey(),e.getValue());
}
if(arr.length > 100) {
out.println("NO");
return;
}
HashMap<Integer,Integer> ans = new HashMap<>();
for(int i = 0; i < arr.length; i++) {
for(int j = i; j < arr.length; j++) {
int k = arr[i].k * arr[j].k;
int v = ans.getOrDefault(k,0);
if(i == j) {
v += arr[i].v / 2;
}else {
v += Math.min(arr[i].v, arr[j].v);
}
ans.put(k,v);
}
}
boolean flag = ans.containsValue(n);
out.println(flag ? "YES" : "NO");
}
public static void main(String[] args) throws Exception {
int q = sc.nextInt();
while(q-- > 0) {
solve();
}
out.close();
}
static class Pair{
int k, v;
public Pair(int k, int v) {
this.k = k;
this.v = v/2;
}
}
}
class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
}
| Java | ["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES"] | null | Java 8 | standard input | [
"greedy",
"math"
] | 08783e3dff3f3b7eb586931f9d0cd457 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick. | 1,200 | For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". | standard output | |
PASSED | 85494bee084894b10d04469cac927414 | train_003.jsonl | 1565706900 | You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
import java.io.*;
public class B
{
public static void main(String[] args) throws NumberFormatException, IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int q = Integer.parseInt(br.readLine());
loop : for(int d=0;d<q;d++)
{
int n = Integer.parseInt(br.readLine());
Integer[] arr = new Integer[4*n];
String[] inp = br.readLine().split(" ");
for(int i=0;i<4*n;i++)
{
arr[i]= Integer.parseInt(inp[i]);
}
Arrays.sort(arr);
int i=0,j=4*n-1,area=arr[i]*arr[j];
while(i<j)
{
int temp = arr[i]*arr[j];
if(temp!=area || arr[j]>arr[j-1] || arr[i] < arr[i+1])
{
System.out.println("NO");
continue loop;
}
i+=2;j-=2;
}
System.out.println("YES");
}
}
}
| Java | ["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES"] | null | Java 8 | standard input | [
"greedy",
"math"
] | 08783e3dff3f3b7eb586931f9d0cd457 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick. | 1,200 | For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". | standard output | |
PASSED | 4c28943229ad746103b9bfed8136de8d | train_003.jsonl | 1565706900 | You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries. | 256 megabytes | /*
If you want to aim high, aim high
Don't let that studying and grades consume you
Just live life young
******************************
If I'm the sun, you're the moon
Because when I go up, you go down
*******************************
I'm working for the day I will surpass you
https://www.a2oj.com/Ladder16.html
*/
import java.util.*;
import java.io.*;
import java.math.*;
public class B
{
public static void main(String omkar[]) throws Exception
{
BufferedReader infile = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(infile.readLine());
int Q = Integer.parseInt(st.nextToken());
while(Q-->0)
{
int N = Integer.parseInt(infile.readLine());
int[] arr = readArr(4*N, infile, st);
sort(arr);
N *= 4;
int x = 0;
int y = N-1;
long area = -1;
boolean temp = true;
while(x < y)
{
if(area == -1)
area = (long)arr[x]*(long)arr[y];
else
{
long boof = (long)arr[x]*(long)arr[y];
if(boof != area)
temp = false;
if(arr[x] != arr[x+1] || arr[y] != arr[y-1])
temp = false;
}
if(arr[x] != arr[x+1] || arr[y] != arr[y-1])
temp = false;
x+=2;
y-=2;
}
if(temp)
System.out.println("YES");
else
System.out.println("NO");
}
}
public static void sort(int[] arr)
{
//stable heap sort
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
for(int a: arr)
pq.add(a);
for(int i=0; i < arr.length; i++)
arr[i] = pq.poll();
}
public static int[] readArr(int N, BufferedReader infile, StringTokenizer st) throws Exception
{
int[] arr = new int[N];
st = new StringTokenizer(infile.readLine());
for(int i=0; i < N; i++)
arr[i] = Integer.parseInt(st.nextToken());
return arr;
}
} | Java | ["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES"] | null | Java 8 | standard input | [
"greedy",
"math"
] | 08783e3dff3f3b7eb586931f9d0cd457 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick. | 1,200 | For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". | standard output | |
PASSED | dc8fd7fdd377b9746c5a6995a3d30930 | train_003.jsonl | 1565706900 | You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.BigInteger;
public class Solution{
public static void main(String[] args) throws Exception{
FastReader ip=new FastReader();
int q=ip.nextInt();
while(q-->0) {
int n=ip.nextInt();
int arr[]=new int[4*n];
for(int i=0;i<4*n;i++) {
arr[i]=ip.nextInt();
}
Arrays.sort(arr);
int product=-1;
if(arr[0]==arr[1] && arr[4*n-1]==arr[4*n-2]) {
product=arr[0]*arr[4*n-1];
int i=0;
int j=4*n-1;
int m=0;
int ans=0;
while(i<j) {
if(arr[i]==arr[i+1] && arr[j]==arr[j-1]) {
if(arr[i]*arr[j]==product) {
m++;
i=i+2;
j=j-2;
}else {
ans=1;
break;
}
}else {
ans=1;
break;
}
}
if(ans==1) {
System.out.println("NO");
}else {
System.out.println("YES");
}
}else {
System.out.println("NO");
}
}
}
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
}
| Java | ["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES"] | null | Java 8 | standard input | [
"greedy",
"math"
] | 08783e3dff3f3b7eb586931f9d0cd457 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick. | 1,200 | For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". | standard output | |
PASSED | 3788e349b62fbcfdc280228bb7d792e8 | train_003.jsonl | 1565706900 | You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
public class Main1 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t-- > 0) {
int n = sc.nextInt();
int[] arr = new int[4*n];
for (int i = 0; i < 4*n; i++)
arr[i] = sc.nextInt();
int res = 1;
int l = 0, r = 4*n - 1;
Arrays.sort(arr);
int area = -1;
while (l < r) {
if (area == -1)
{
if(arr[l]==arr[l+1] && arr[r]==arr[r-1])
area = arr[l] * arr[r];
else{
res=0;break;
}
}
else if (area != arr[l] * arr[r] || arr[l]!=arr[l+1] || arr[r]!=arr[r-1]) {
res = 0;
break;
}
l+=2;
r-=2;
}
if (res == 0)
System.out.println("NO");
else
System.out.println("YES");
}
}
} | Java | ["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES"] | null | Java 8 | standard input | [
"greedy",
"math"
] | 08783e3dff3f3b7eb586931f9d0cd457 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick. | 1,200 | For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". | standard output | |
PASSED | be3c0032cb92ebd5dded64c5138ec4b4 | train_003.jsonl | 1565706900 | You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.*;
import java.io.BufferedReader;
public class Main{
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int q = sc.nextInt();
for (int i = 0; i < q; i++) {
int n = sc.nextInt();
int[] a = new int[4*n];
int cur = 0;
HashMap<Integer,Integer> h = new HashMap<>();
int[] num = new int[100001];
int count = 4*n;
for (int j = 0; j < 4*n; j++) {
a[j] = sc.nextInt();
num[a[j]]++;
}
for (int j = 0; j < 4*n; j++) {
if (num[a[j]]%2 == 1) num[a[j]] = 0;
}
Arrays.sort(a);
cur = a[0]*a[4*n-1];
for (int j = 0; j < 4*n && count != 0; j++) {
if (cur%a[j] == 0){
if (cur/a[j] > num.length-1) break;
if (num[a[j]] != num[cur/a[j]]) break;
if (num[a[j]] == 0) continue;
if (num[a[j]] > 0 && num[cur/a[j]] > 0 ){
count-=2;
num[a[j]]--;num[cur/a[j]]--;
}
else break;
}
else break;
}
if (count == 0) out.println("YES");
else out.println("NO");
}
out.flush();
}
}
class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
| Java | ["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES"] | null | Java 8 | standard input | [
"greedy",
"math"
] | 08783e3dff3f3b7eb586931f9d0cd457 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick. | 1,200 | For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". | standard output | |
PASSED | 18218a9330965168876ec5220adf9c79 | train_003.jsonl | 1565706900 | You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.Arrays;
public class Main {
static StreamTokenizer st=new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
public static void main(String[] args) {
int q=nextInt();
while(q-->0){
int n=nextInt();
int a[]=new int[4*n+1];
for(int i=1;i<=4*n;i++){
a[i]=nextInt();
}
boolean flag=true;
Arrays.sort(a,1,4*n+1);
if(n==1){
if(a[1]!=a[2]||a[3]!=a[4]){
flag=false;
}
if(a[1]*a[4]!=a[2]*a[3]){
flag=false;
}
}else{
for(int i=1;i<=2*n;i+=2){
if(a[i]!=a[i+1]||a[4*n-i+1]!=a[4*n-i]){
flag=false;
break;
}
if(a[i]*a[4*n-i+1]!=a[i+2]*a[4*n-i-1]){
flag=false;
break;
}
}
}
if(flag){
System.out.println("YES");
}else{
System.out.println("NO");
}
}
}
static int nextInt(){
try {
st.nextToken();
} catch (IOException e) {
e.printStackTrace();
}
return (int)st.nval;
}
}
| Java | ["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES"] | null | Java 8 | standard input | [
"greedy",
"math"
] | 08783e3dff3f3b7eb586931f9d0cd457 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick. | 1,200 | For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". | standard output | |
PASSED | 238afb4b218d687970e78d0a89a4086f | train_003.jsonl | 1565706900 | You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
public class Main {
static Scanner scn = new Scanner(System.in);
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int t = scn.nextInt();
while (t != 0) {
int n = scn.nextInt();
int a=0,b=4*n-1;
int[]arr=new int[4*n];
for(int i=0;i<4*n;i++)
{
arr[i]=scn.nextInt();
}
Arrays.parallelSort(arr);
boolean bh=true;
long area=arr[a]*arr[b];
while(a<=b)
{
if(arr[a]*arr[b]!=area)
{
bh=false;
break;
}
if(arr[a+1]!=arr[a]||arr[b-1]!=arr[b])
{
bh=false;
break;
}
else
{
a+=2;
b-=2;
}
}
if(bh) System.out.println("YES");
else System.out.println("NO");
t--;
}
}
} | Java | ["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES"] | null | Java 8 | standard input | [
"greedy",
"math"
] | 08783e3dff3f3b7eb586931f9d0cd457 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick. | 1,200 | For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". | standard output | |
PASSED | 6927a1e9c456647a0443693b5cc1d3f7 | train_003.jsonl | 1565706900 | You are given $$$4n$$$ sticks, the length of the $$$i$$$-th stick is $$$a_i$$$.You have to create $$$n$$$ rectangles, each rectangle will consist of exactly $$$4$$$ sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only one rectangle. Each stick should be used as a side, you cannot break the stick or use it not to the full length.You want to all rectangles to have equal area. The area of the rectangle with sides $$$a$$$ and $$$b$$$ is $$$a \cdot b$$$.Your task is to say if it is possible to create exactly $$$n$$$ rectangles of equal area or not.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
public class Mohammad {
public static void Mohammad_AboHasan(){
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0){
int n = sc.nextInt();
int[] a = new int[n*4];
int[] b = new int[n];
boolean m = true;
for (int i = 0; i < a.length; i++)
a[i] = sc.nextInt();
Arrays.sort(a);
int c = 0;
//System.out.println(Arrays.toString(a));
for (int i = 0; i < n*2; i+=2) {
if(a[i] == a[i+1] && a[a.length-i-1] == a[a.length-i-2]){
b[c++] = (a[i]*a[a.length-i-1]) + (a[i+1]*a[a.length-i-2]);
//System.out.println(a[i] +" "+ a[i+1] + " f "+ a[a.length-i-1] +" "+ a[a.length-i-2]);
}
else {
m = false;
break;
}
}
//System.out.println(Arrays.toString(b));
if(!m){
System.out.println("NO");
continue;
}
for (int i = 0; i < n-1; i++)
if(b[i] != b[i+1]){
m = false;
break;
}
System.out.println(m ? "YES" : "NO");
}
}
public static void main(String[] args){
Mohammad_AboHasan();
}
} | Java | ["5\n1\n1 1 10 10\n2\n10 5 2 10 1 1 2 5\n2\n10 5 1 10 5 1 1 1\n2\n1 1 1 1 1 1 1 1\n1\n10000 10000 10000 10000"] | 2 seconds | ["YES\nYES\nNO\nYES\nYES"] | null | Java 8 | standard input | [
"greedy",
"math"
] | 08783e3dff3f3b7eb586931f9d0cd457 | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Then $$$q$$$ queries follow. The first line of the query contains one integer $$$n$$$ ($$$1 \le n \le 100$$$) — the number of rectangles. The second line of the query contains $$$4n$$$ integers $$$a_1, a_2, \dots, a_{4n}$$$ ($$$1 \le a_i \le 10^4$$$), where $$$a_i$$$ is the length of the $$$i$$$-th stick. | 1,200 | For each query print the answer to it. If it is impossible to create exactly $$$n$$$ rectangles of equal area using given sticks, print "NO". Otherwise print "YES". | standard output | |
PASSED | e9cec338d64c1be7f145a77f1925df71 | train_003.jsonl | 1596810900 | This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format: $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$ $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides. | 256 megabytes | import org.omg.CORBA.INTERNAL;
import java.io. *;
import java.util.*;
import static java.lang.Math.*;
public class Main {
static final FastReader sc = new FastReader(System.in);
static final PrintWriter pw = new PrintWriter(System.out);
static int visited[];
static ArrayList<ArrayList<Integer>> adjlist;
static class edge implements Comparator<edge>{
int dest;
int cost;
public edge(int dest, int cost) {
this.dest = dest;
this.cost = cost;
}
@Override
public int compare(edge o1, edge o2) {
return o1.cost-o2.cost;
}
}
static int dist[];
static int nodesinSubtree[];
static int color[];
static ArrayList<Integer> leaves;
static ArrayList<PriorityQueue<Integer>> apq;
static class Graph {
int V;
ArrayList<ArrayList<edge>> adj;
PriorityQueue<edge> pq;
boolean visited[];
public Graph(int V) {
this.V = V;
adj = new ArrayList<>(V);
pq = new PriorityQueue<>(V, new edge(-1, -1));
dist = new int[V];
visited = new boolean[V];
for (int i = 0; i < V; i++) {
dist[i] = Integer.MAX_VALUE;
adj.add(i, new ArrayList<>());
}
}
void addedge(int u, int v, int w) {
adj.get(u).add(new edge(v, w));
adj.get(v).add(new edge(u, w));
}
void rDfs(int src, int e) {
if(adj.get(src).size()==0){
leaves.add(src);
}
for (int i = 0; i < adj.get(src).size(); i++) {
if (adj.get(src).get(i).dest == e) {
continue;
}
rDfs(adj.get(src).get(i).dest, src);
}
}
PriorityQueue<Integer> Dfs(int src, int e, PriorityQueue<Integer> pq) {
if(adj.get(src).size()==0){
if(src!=0 && !pq.isEmpty()){
pq.remove(adj.get(src).get(e).cost);
}
}
for (int i = 0; i < adj.get(src).size(); i++) {
if (adj.get(src).get(i).dest == e) {
continue;
}
if (adj.get(src).get(i).dest == 1) {
pq.add(adj.get(src).get(i).cost);
return pq;
}
pq.add(adj.get(src).get(i).cost);
Dfs(adj.get(src).get(i).dest, src, pq);
}
return pq;
}
/*
void dijkstra(int src){
for(int i=0; i<V; i++){
dist[i] = Integer.MAX_VALUE;
}
dist[src] = 0;
pq.add(new edge(src,0));
while (!pq.isEmpty()){
int u = pq.poll().dest;
for(int i=0; i<adj.get(u).size(); i++){
int v = adj.get(u).get(i).dest;
int w = adj.get(u).get(i).cost;
if(dist[u]+w<=dist[v]){
dist[v] = dist[u] + w;
pq.add(new edge(v,dist[v]));
}
}
}
}
}
*/
}
static int I[];
static int L[];
static void LIS(int n, int arr[]){
I = new int[n+1];
L = new int[n];
I[0] = Integer.MIN_VALUE;
for(int i=1;i<=n; i++){
I[i] = Integer.MAX_VALUE;
}
int lisLength = 1;
for(int i=n-1; i>=0; i--) {
int low = 1;
int high = lisLength;
int mid = 0;
while (low < high) {
mid = (low + high) >> 1;
if (I[mid] <= arr[i]) {
high = mid;
} else {
low = mid + 1;
}
}
I[high] = arr[i];
L[i] = high;
if(lisLength<=high){
lisLength++;
}
}
}
public static long gcd(long a, long b)
{
if (a == 0)
return b;
return gcd(b%a, a);
}
public static long lcm(long a, long b)
{
return (a*b)/gcd(a, b);
}
static long nCr(long n, long r)
{
return fact(n) / (fact(r) * fact(n - r));
}
// Returns factorial of n
static long fact(long n)
{
long res = 1;
for (int i = 2; i <= n; i++)
res = (res * i)%MOD;
return res;
}
static int MOD = 1000000007;
static int power(int x, int y, int p)
{
// Initialize result
int res = 1;
// Update x if it is more than or
// equal to p
x = x % p;
while (y > 0)
{
// If y is odd, multiply x
// with result
if (y % 2 == 1)
res = (res * x) % p;
// y must be even now
y = y >> 1; // y = y/2
x = (x * x) % p;
}
return res;
}
// Returns n^(-1) mod p
static int modInverse(int n, int p)
{
return power(n, p-2, p);
}
static int nCrModPFermat(int n, int r,
int p)
{
if (r == 0)
return 1;
int[] fac = new int[n+1];
fac[0] = 1;
for (int i = 1 ;i <= n; i++)
fac[i] = fac[i-1] * i % p;
return (fac[n]* modInverse(fac[r], p)
% p * modInverse(fac[n-r], p)
% p) % p;
}
static int[] phi;
static void generatePhi(int n){
phi = new int[n+1];
for(int i = 0; i<=n; i++){
phi[i] = i;
}
for(int i=2; i<=n; i++){
if(phi[i]==i){
for(int j= i; j<=n; j+=i){
phi[j] -= (phi[j]/i);
}
}
}
}
static int gcdCount(int n, int d){
return phi[n/d];
}
static boolean prime[];
static int smallestFactor[];
static void sieveOfEratosthenes(int n)
{
prime = new boolean[n+1];
smallestFactor = new int[n+1];
smallestFactor[1] = 1;
for(int i=2;i<n;i++) {
prime[i] = true;
smallestFactor[i] = i;
}
for(int p = 2; p*p <=n; p++)
{
if(prime[p])
{
smallestFactor[p] = p;
for(int i = p*p; i <= n; i += p) {
prime[i] = false;
smallestFactor[i] = min(p,smallestFactor[i]);
}
}
}
}
static double Logx(double n, int x){
return log(n)/log(x);
}
static boolean isPrime(long n){
if(n<2){
return false;
}
for(int i = 2; i*i<=n; i++){
if(n%i==0){
return false;
}
}
return true;
}
static int sumOfDigits(int n){
int digitSum = 0;
while (n>0){
digitSum+=n%10;
n/=10;
}
return digitSum;
}
static boolean checkSum(PriorityQueue<Integer> pq, long s){
long sum = 0;
while (!pq.isEmpty()){
sum+= pq.poll();
}
if(sum>s){
return false;
}
return true;
}
public static void main(String[] args) {
int n = sc.nextInt();
int a[] = new int[n];
int numbers [] =new int[(int)1e5+10];
for(int i = 0; i<n; i++){
a[i] = sc.nextInt();
numbers[a[i]]++;
}
int fours = 0;
int twos = 0;
for(int i =0; i<1e5+10; i++){
if(numbers[i]>=4){
fours += (numbers[i]/4);
}
}
for(int i =0; i<1e5+10; i++){
if(numbers[i]!=0){
twos+= (numbers[i]%4)/2;
}
}
int q = sc.nextInt();
int b[] = new int[q];
for(int i =0; i<q; i++){
char sign = sc.nextChar();
int k = sc.nextInt();
if(sign=='+'){
b[i] = k;
}else{
b[i] = -k;
}
}
for(int i = 0; i<q; i++){
if(b[i]<0){
b[i] = abs(b[i]);
if(numbers[b[i]]%4==0 && numbers[b[i]]!=0){
numbers[b[i]]--;
fours--;
twos++;
}else if(numbers[b[i]]%2==0 && numbers[b[i]]!=0){
numbers[b[i]]--;
twos--;
}else{
numbers[b[i]]--;
}
}else{
b[i] = abs(b[i]);
if ((numbers[b[i]] + 1) % 4 == 0) {
numbers[b[i]]++;
fours++;
twos--;
} else if ((numbers[b[i]]+1) % 2 == 0) {
numbers[b[i]]++;
twos++;
} else {
numbers[b[i]]++;
}
}
if(fours>=1 && ((fours-1)>=1 || twos>=2)){
pw.println("YES");
}else{
pw.println("NO");
}
}
pw.flush();
}
static void debug(Object...obj) {
System.err.println(Arrays.deepToString(obj));
}
static class FastReader {
InputStream is;
private byte[] inbuf = new byte[1024];
private int lenbuf = 0, ptrbuf = 0;
public FastReader(InputStream is) {
this.is = is;
}
public 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++];
}
public boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
public int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b)) ;
return b;
}
public String next(){
int b = skip();
StringBuilder sb = new StringBuilder();
while(!(isSpaceChar(b))) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public String nextLine(){
int b = readByte();
StringBuilder sb = new StringBuilder();
while(b != '\n' || b != '\r'){
sb.appendCodePoint(b);
}
return sb.toString();
}
public int nextInt() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = (num << 3) + (num << 1) + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public long nextLong() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-')) ;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = (num << 3) + (num << 1) + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
public double nextDouble() {
return Double.parseDouble(next());
}
public char[] next(int n){
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
public char nextChar () {
return (char) skip();
}
}
} | Java | ["6\n1 1 1 2 1 1\n6\n+ 2\n+ 1\n- 1\n+ 2\n- 1\n+ 2"] | 2 seconds | ["NO\nYES\nNO\nNO\nNO\nYES"] | NoteAfter the second event Applejack can build a rectangular storage using planks with lengths $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.After the sixth event Applejack can build a rectangular storage using planks with lengths $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$. | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"greedy"
] | d14bad9abf2a27ba57c80851405a360b | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$): the initial amount of planks at the company's storehouse, the second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$): the lengths of the planks. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$): the number of events in the company. Each of the next $$$q$$$ lines contains a description of the events in a given format: the type of the event (a symbol $$$+$$$ or $$$-$$$) is given first, then goes the integer $$$x$$$ ($$$1 \le x \le 10^5$$$). | 1,400 | After every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower). | standard output | |
PASSED | dac6e467a14b250d6a6645909e810b13 | train_003.jsonl | 1596810900 | This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format: $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$ $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides. | 256 megabytes | //package compete;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.security.acl.LastOwnerException;
import java.util.*;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class Main {
public static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String[] nextSArray() {
String sr[] = null;
try {
sr = br.readLine().trim().split(" ");
} catch (IOException e) {
e.printStackTrace();
}
return sr;
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
//static ArrayList<Integer>al=new ArrayList<>()
//
static class Pair{
char ch;
int count;
Pair(char ch,int count){
this.ch=ch;
this.count=count;
}
Pair(){}
}
static int max=100001;
static int MAX=Integer.MAX_VALUE,MIN=Integer.MIN_VALUE;
public static void main(String[] args) throws Exception{
FastReader sc=new FastReader();
int n=sc.nextInt();
int arr[]=new int[max];
int cnt2=0,cnt4=0;
while(n-->0){
int x=sc.nextInt();
cnt2-=arr[x]/2;
cnt4-=arr[x]/4;
arr[x]++;
cnt2+=arr[x]/2;
cnt4+=arr[x]/4;
}
n=sc.nextInt();
while(n-->0){
String s=sc.nextLine();
char ch=s.charAt(0);
int x=Integer.parseInt(s.substring(2,s.length()));
cnt2-=arr[x]/2;
cnt4-=arr[x]/4;
if(ch=='+') arr[x]++;
else arr[x]--;
cnt2+=arr[x]/2;
cnt4+=arr[x]/4;
if(cnt2>=4 && cnt4>=1) out.println("YES");
else out.println("NO");
}
out.close();
}
} | Java | ["6\n1 1 1 2 1 1\n6\n+ 2\n+ 1\n- 1\n+ 2\n- 1\n+ 2"] | 2 seconds | ["NO\nYES\nNO\nNO\nNO\nYES"] | NoteAfter the second event Applejack can build a rectangular storage using planks with lengths $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.After the sixth event Applejack can build a rectangular storage using planks with lengths $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$. | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"greedy"
] | d14bad9abf2a27ba57c80851405a360b | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$): the initial amount of planks at the company's storehouse, the second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$): the lengths of the planks. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$): the number of events in the company. Each of the next $$$q$$$ lines contains a description of the events in a given format: the type of the event (a symbol $$$+$$$ or $$$-$$$) is given first, then goes the integer $$$x$$$ ($$$1 \le x \le 10^5$$$). | 1,400 | After every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower). | standard output | |
PASSED | 49e9e1f122eb4df0c603dd81f82a8d1b | train_003.jsonl | 1596810900 | This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format: $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$ $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main{
public static void main(String[] args)throws IOException{
Scanner sc = new Scanner(System.in);
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
int a,b,c,d,e,f,g,i,j,k,l;
int h;
c = sc.nextInt();
int x[] = new int[100010];
//int y[] = new int[100010];
//ArrayList<Integer> y = new ArrayList<Integer>();
//ArrayList<Integer> z = new ArrayList<Integer>();
//ArrayList<Integer> w = new ArrayList<Integer>();
//ArrayList<Integer> u = new ArrayList<Integer>();
//HashMap<Integer,Integer> m = new HashMap<Integer,Integer>();
g = 0;
h = 0;
l = 0;
k = 0;
for(d = 0;d < c;d++){
e = sc.nextInt();
x[e]++;
if(x[e] == 2){
h++;
}
if(x[e] == 4){
g++;
h--;
}
if(x[e] == 6){
l++;
}
if(x[e] == 8){
k++;
}
}
d = sc.nextInt();
//System.out.println(z.get(0)+" "+y.get(0)+" "+x[1]+" "+x[2]);
for(e = 0;e < d;e++){
String A = sc.next();
f = sc.nextInt();
if(A.equals("-")){
if(x[f] == 4){
g--;
h++;
}
else if(x[f] == 2){
h--;
}
else if(x[f] == 6){
l--;
}
else if(x[f] == 8){
k--;
}
x[f]--;
}
else{
if(x[f] == 3){
g++;
h--;
}
else if(x[f] == 1){
h++;
}
else if(x[f] == 5){
l++;
}
else if(x[f] == 7){
k++;
}
x[f]++;
}
if(g >= 2){
System.out.println("YES");
}
else if(g == 1){
if(h >= 2){
System.out.println("YES");
}
else {
if(h == 1){
if(l >= 1){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
else{
if(k >= 1){
System.out.println("YES");
}
else{
System.out.println("NO");
}
}
}
}
else{
if(k >= 1){
System.out.println("YES");
}
else{
System.out.println("NO");
}}
//System.out.println(g+" "+h);
}
}
}
| Java | ["6\n1 1 1 2 1 1\n6\n+ 2\n+ 1\n- 1\n+ 2\n- 1\n+ 2"] | 2 seconds | ["NO\nYES\nNO\nNO\nNO\nYES"] | NoteAfter the second event Applejack can build a rectangular storage using planks with lengths $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.After the sixth event Applejack can build a rectangular storage using planks with lengths $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$. | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"greedy"
] | d14bad9abf2a27ba57c80851405a360b | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$): the initial amount of planks at the company's storehouse, the second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$): the lengths of the planks. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$): the number of events in the company. Each of the next $$$q$$$ lines contains a description of the events in a given format: the type of the event (a symbol $$$+$$$ or $$$-$$$) is given first, then goes the integer $$$x$$$ ($$$1 \le x \le 10^5$$$). | 1,400 | After every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower). | standard output | |
PASSED | 104bcdd592be0ceabc59b4f42116d1c1 | train_003.jsonl | 1596810900 | This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format: $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$ $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static int MAXN = 100005;
static int[]a,qu;
static int n,q;
static int sqr,rec;
public static void main(String[]args) throws IOException{
a = new int[MAXN];
String[]data;
try (BufferedReader f = new BufferedReader(new InputStreamReader(System.in))) {
n = Integer.valueOf(f.readLine());
data = f.readLine().split(" ");
for(int i = 0 ; i < n ; ++i){
int u = Integer.valueOf(data[i]);
a[u-1]++;
count(a[u-1]);
}
q = Integer.valueOf(f.readLine());
qu = new int[q];
for(int i = 0 ; i < q ; ++i){
qu[i] = Integer.parseInt(f.readLine().replace(" ", ""));
}
}
for(int i = 0 ; i < q ; ++i){
if(qu[i]>0){
a[qu[i]-1]++;
count(a[qu[i]-1]);
}else{
a[(-1*qu[i])-1]--;
discount(a[(-1*qu[i])-1]);
}
System.out.println(isPossible() ? "YES" : "NO");
}
}
private static boolean isPossible() {
if(sqr>1)
return true;
else if(sqr==1 && rec>=2){
return true;
}
return false;
}
private static void count(int a) {
if(a%4 == 0){
++sqr;
--rec;
}else if(a%2 == 0)
++rec;
}
private static void discount(int a) {
if(a%4 == 3){
--sqr;
++rec;
}else if(a%2 == 1)
--rec;
}
} | Java | ["6\n1 1 1 2 1 1\n6\n+ 2\n+ 1\n- 1\n+ 2\n- 1\n+ 2"] | 2 seconds | ["NO\nYES\nNO\nNO\nNO\nYES"] | NoteAfter the second event Applejack can build a rectangular storage using planks with lengths $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.After the sixth event Applejack can build a rectangular storage using planks with lengths $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$. | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"greedy"
] | d14bad9abf2a27ba57c80851405a360b | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$): the initial amount of planks at the company's storehouse, the second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$): the lengths of the planks. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$): the number of events in the company. Each of the next $$$q$$$ lines contains a description of the events in a given format: the type of the event (a symbol $$$+$$$ or $$$-$$$) is given first, then goes the integer $$$x$$$ ($$$1 \le x \le 10^5$$$). | 1,400 | After every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower). | standard output | |
PASSED | 2bc3bc3ce11aba2a083c5c8e499ff9dc | train_003.jsonl | 1596810900 | This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well).Applejack will build the storages using planks, she is going to spend exactly one plank on each side of the storage. She can get planks from her friend's company. Initially, the company storehouse has $$$n$$$ planks, Applejack knows their lengths. The company keeps working so it receives orders and orders the planks itself. Applejack's friend can provide her with information about each operation. For convenience, he will give her information according to the following format: $$$+$$$ $$$x$$$: the storehouse received a plank with length $$$x$$$ $$$-$$$ $$$x$$$: one plank with length $$$x$$$ was removed from the storehouse (it is guaranteed that the storehouse had some planks with length $$$x$$$). Applejack is still unsure about when she is going to order the planks so she wants to know if she can order the planks to build rectangular and square storages out of them after every event at the storehouse. Applejack is busy collecting apples and she has completely no time to do the calculations so she asked you for help!We remind you that all four sides of a square are equal, and a rectangle has two pairs of equal sides. | 256 megabytes |
import java.io.InputStream;
import java.util.*;
public class B662 {
static int n;
static int q;
// static List<Integer> lenghts;
static Map<Integer, Integer> len;
public static void main(String[] args) {
readInput(System.in);
}
private static void readInput(InputStream s) {
Scanner in = new Scanner(s);
n = in.nextInt();
len = new HashMap<>();
for (int i = 0; i < n; i++) {
int newValue = in.nextInt();
if (len.keySet().contains(newValue)) {
len.replace(newValue, len.get(newValue) + 1);
} else {
len.put(newValue, 1);
}
}
q = in.nextInt();
int[] four_and_two = new int[5];
for (Map.Entry<Integer, Integer> v : len.entrySet()) {
four_and_two[4] += v.getValue() / 4;
four_and_two[2] += v.getValue() / 2;
}
for (int i = 0; i < q; i++) {
String znak = in.next();
int number = in.nextInt();
if ("+".equals(znak)) {
if (len.keySet().contains(number)) {
len.put(number, len.get(number) + 1);
} else {
len.put(number, 1);
}
if (len.get(number) % 4 == 0) {
four_and_two[4] += 1;
four_and_two[2] += 1;
} else if (len.get(number) % 2 == 0) {
four_and_two[2] += 1;
}
} else {
len.put(number, len.get(number) - 1);
if ((len.get(number) + 1) % 4 == 0) {
four_and_two[4] -= 1;
four_and_two[2] -= 1;
} else if ((len.get(number) + 1) % 2 == 0) {
four_and_two[2] -= 1;
}
}
boolean b = true;
if (four_and_two[4] >= 1 && four_and_two[2] >= 4 || four_and_two[4] >= 2) {
System.out.println("YES");
} else {
System.out.println("NO");
}
}
}
} | Java | ["6\n1 1 1 2 1 1\n6\n+ 2\n+ 1\n- 1\n+ 2\n- 1\n+ 2"] | 2 seconds | ["NO\nYES\nNO\nNO\nNO\nYES"] | NoteAfter the second event Applejack can build a rectangular storage using planks with lengths $$$1$$$, $$$2$$$, $$$1$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$.After the sixth event Applejack can build a rectangular storage using planks with lengths $$$2$$$, $$$2$$$, $$$2$$$, $$$2$$$ and a square storage using planks with lengths $$$1$$$, $$$1$$$, $$$1$$$, $$$1$$$. | Java 8 | standard input | [
"data structures",
"constructive algorithms",
"implementation",
"greedy"
] | d14bad9abf2a27ba57c80851405a360b | The first line contains a single integer $$$n$$$ ($$$1 \le n \le 10^5$$$): the initial amount of planks at the company's storehouse, the second line contains $$$n$$$ integers $$$a_1, a_2, \ldots, a_n$$$ ($$$1 \le a_i \le 10^5$$$): the lengths of the planks. The third line contains a single integer $$$q$$$ ($$$1 \le q \le 10^5$$$): the number of events in the company. Each of the next $$$q$$$ lines contains a description of the events in a given format: the type of the event (a symbol $$$+$$$ or $$$-$$$) is given first, then goes the integer $$$x$$$ ($$$1 \le x \le 10^5$$$). | 1,400 | After every event in the company, print "YES" if two storages of the required shape can be built from the planks of that company's set, and print "NO" otherwise. You can print each letter in any case (upper or lower). | standard output | |
PASSED | 3b118535515938af2010c30daafca902 | train_003.jsonl | 1457870400 | Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
HashSet<String> hs = new HashSet<String>();
String[] a = new String[n];
for(int i = 0;i<n;i++){
a[i]=br.readLine();
}
for(int i = n-1 ; i >= 0 ; i--)
if(!hs.contains(a[i])){
System.out.println(a[i]);
hs.add(a[i]);
}
}
}
| Java | ["4\nalex\nivan\nroman\nivan", "8\nalina\nmaria\nekaterina\ndarya\ndarya\nekaterina\nmaria\nalina"] | 3 seconds | ["ivan\nroman\nalex", "alina\nmaria\nekaterina\ndarya"] | NoteIn the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows: alex Then Polycarpus writes to friend by name "ivan" and the list looks as follows: ivan alex Polycarpus writes the third message to friend by name "roman" and the list looks as follows: roman ivan alex Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows: ivan roman alex | Java 8 | standard input | [
"constructive algorithms",
"*special",
"sortings",
"data structures",
"binary search"
] | 18f4d9262150294b63d99803250ed49c | The first line contains integer n (1 ≤ n ≤ 200 000) — the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10. | 1,200 | Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom. | standard output | |
PASSED | 0ba615524982456ed6408e9eed5ec608 | train_003.jsonl | 1457870400 | Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.LinkedHashSet;
import java.util.Stack;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int n = Integer.parseInt(br.readLine());
Stack<String> easy = new Stack<String>();
LinkedHashSet<String> question = new LinkedHashSet<String>();
for (int i = 0; i < n; i++)
easy.push(br.readLine());
for (int i = 0; i < n; i++)
question.add(easy.pop());
for(String x:question)
out.println(x);
out.flush();
out.close();
}
} | Java | ["4\nalex\nivan\nroman\nivan", "8\nalina\nmaria\nekaterina\ndarya\ndarya\nekaterina\nmaria\nalina"] | 3 seconds | ["ivan\nroman\nalex", "alina\nmaria\nekaterina\ndarya"] | NoteIn the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows: alex Then Polycarpus writes to friend by name "ivan" and the list looks as follows: ivan alex Polycarpus writes the third message to friend by name "roman" and the list looks as follows: roman ivan alex Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows: ivan roman alex | Java 8 | standard input | [
"constructive algorithms",
"*special",
"sortings",
"data structures",
"binary search"
] | 18f4d9262150294b63d99803250ed49c | The first line contains integer n (1 ≤ n ≤ 200 000) — the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10. | 1,200 | Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom. | standard output | |
PASSED | 1c801a6175492dd916ed23be07627682 | train_003.jsonl | 1457870400 | Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Stack;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
int n= Integer.parseInt(br.readLine());
Stack<String> s= new Stack<String>();
LinkedHashSet<String> h= new LinkedHashSet<String>();
LinkedList<String> l= new LinkedList<String>();
for(int i=0;i<n;i++)
s.push(br.readLine());
while(!s.empty())
h.add(s.pop());
for(String x:h)
out.println(x);
out.flush();
out.close();
}
} | Java | ["4\nalex\nivan\nroman\nivan", "8\nalina\nmaria\nekaterina\ndarya\ndarya\nekaterina\nmaria\nalina"] | 3 seconds | ["ivan\nroman\nalex", "alina\nmaria\nekaterina\ndarya"] | NoteIn the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows: alex Then Polycarpus writes to friend by name "ivan" and the list looks as follows: ivan alex Polycarpus writes the third message to friend by name "roman" and the list looks as follows: roman ivan alex Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows: ivan roman alex | Java 8 | standard input | [
"constructive algorithms",
"*special",
"sortings",
"data structures",
"binary search"
] | 18f4d9262150294b63d99803250ed49c | The first line contains integer n (1 ≤ n ≤ 200 000) — the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10. | 1,200 | Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom. | standard output | |
PASSED | e6026b5a03700f8b0d5c463a8ac9e7ee | train_003.jsonl | 1457870400 | Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus. | 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.*;
import java.io.InputStream;
public class B {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
Task solver = new Task();
solver.solve(in, out);
out.close();
}
}
class Task {
public void solve(InputReader in, PrintWriter out) {
int n = in.nextInt();
String[] s = new String[n];
for (int i = n - 1; i >= 0; i--) {
s[i] = in.next();
}
Set<String> set = new LinkedHashSet<>(Arrays.asList(s));
String[] ans = set.toArray(new String[set.size()]);
for (String no : ans) out.println(no + " ");
}
}
class InputReader {
public BufferedReader reader;
public StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
} | Java | ["4\nalex\nivan\nroman\nivan", "8\nalina\nmaria\nekaterina\ndarya\ndarya\nekaterina\nmaria\nalina"] | 3 seconds | ["ivan\nroman\nalex", "alina\nmaria\nekaterina\ndarya"] | NoteIn the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows: alex Then Polycarpus writes to friend by name "ivan" and the list looks as follows: ivan alex Polycarpus writes the third message to friend by name "roman" and the list looks as follows: roman ivan alex Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows: ivan roman alex | Java 8 | standard input | [
"constructive algorithms",
"*special",
"sortings",
"data structures",
"binary search"
] | 18f4d9262150294b63d99803250ed49c | The first line contains integer n (1 ≤ n ≤ 200 000) — the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10. | 1,200 | Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom. | standard output | |
PASSED | 53c9753ba80c1dbe7178ccf8379d39f9 | train_003.jsonl | 1457870400 | Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus. | 256 megabytes |
import java.util.*;
import java.lang.*;
import java.lang.reflect.Array;
import java.io.*;
import java.math.*;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Collections;
public class Prac{
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int ni() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nl() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nia(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = ni();
}
return a;
}
public String rs() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
static PrintWriter w = new PrintWriter(System.out);
public static class Pair {
int value;
int index;
public Pair(Integer value,Integer index)
{
this.value = value;
this.index =index;
}
}
public static void main(String[] args) throws IOException {
InputReader sc=new InputReader(System.in);
int n=sc.ni();
String arr[]=new String[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextLine();
}
Set<String> set=new LinkedHashSet<String>();
for(int i=n-1;i>=0;i--){
if(!set.contains(arr[i]))
set.add(arr[i]);
}
Iterator itr=set.iterator();
while(itr.hasNext()){
System.out.println((String)itr.next());
}
w.close();
}
}
| Java | ["4\nalex\nivan\nroman\nivan", "8\nalina\nmaria\nekaterina\ndarya\ndarya\nekaterina\nmaria\nalina"] | 3 seconds | ["ivan\nroman\nalex", "alina\nmaria\nekaterina\ndarya"] | NoteIn the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows: alex Then Polycarpus writes to friend by name "ivan" and the list looks as follows: ivan alex Polycarpus writes the third message to friend by name "roman" and the list looks as follows: roman ivan alex Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows: ivan roman alex | Java 8 | standard input | [
"constructive algorithms",
"*special",
"sortings",
"data structures",
"binary search"
] | 18f4d9262150294b63d99803250ed49c | The first line contains integer n (1 ≤ n ≤ 200 000) — the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10. | 1,200 | Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom. | standard output | |
PASSED | 7290e92d8d60359d2ad73c111a47cc61 | train_003.jsonl | 1457870400 | Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus. | 256 megabytes | import java.io.*;
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String args[])throws IOException
{
BufferedReader obj=new BufferedReader(new InputStreamReader(System.in));
int N=Integer.parseInt(obj.readLine());
String temp="|";
String arr[]=new String[N];
int bit[]=new int[10000];
String ans[]=new String[N];
for(int i=0;i<N;i++)
{
String str=obj.readLine();
arr[i]=str;
}
int k=0;
Set<String> s = new HashSet<String>();
for(int i=N-1;i>=0;i--)
{
if(s.contains(arr[i]))
continue;
s.add(arr[i]);
System.out.println(arr[i]);
}
/* for(int i=N-1;i>=0;i--)
{
int flag=0;
for(int j=i+1;j<N;j++)
{
if(arr[i].equals(arr[j]))
{
flag=1;
break;
}
}
if(flag==0)
{
{
ans[k]=arr[i];
k++;
}
}
}
for(int i=0;i<N;i++)
{
if(ans[i]==null)
{
break;
}
System.out.println(ans[i]);
}
*/
}
}
| Java | ["4\nalex\nivan\nroman\nivan", "8\nalina\nmaria\nekaterina\ndarya\ndarya\nekaterina\nmaria\nalina"] | 3 seconds | ["ivan\nroman\nalex", "alina\nmaria\nekaterina\ndarya"] | NoteIn the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows: alex Then Polycarpus writes to friend by name "ivan" and the list looks as follows: ivan alex Polycarpus writes the third message to friend by name "roman" and the list looks as follows: roman ivan alex Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows: ivan roman alex | Java 8 | standard input | [
"constructive algorithms",
"*special",
"sortings",
"data structures",
"binary search"
] | 18f4d9262150294b63d99803250ed49c | The first line contains integer n (1 ≤ n ≤ 200 000) — the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10. | 1,200 | Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom. | standard output | |
PASSED | a7cc075cc3f63c3d8f91587972b5c116 | train_003.jsonl | 1457870400 | Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Stack;
//import java.util.*;
//import java.io.Reader;
//import java.math.BigDecimal;
//import java.util.ArrayList;
//import java.util.Arrays;
//ArrayList<Integer> list = new ArrayList<Integer>();
//import java.util.Collections;
//import java.io.IOException;
//import java.io.InputStream;
//import java.io.InputStreamReader;
//s=s.replaceAll("[^a-z]"," ");
import java.util.StringTokenizer;
public class Main{
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
//Queue<String> q=new LinkedList<String>();
HashSet<String> map=new HashSet<>();
int n=sc.nextInt();
String a[]=new String[n];
for(int i=0 ; i<n ; i++) {
a[i]=sc.nextLine();
}
int l=a.length-1;
for(int i=l ; i>=0 ; i--) {
if(!map.contains(a[i])) {
map.add(a[i]);
out.println(a[i]);
}
}
out.flush();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public int[] nextIntArr(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
public long[] nextLongArr(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nextLong();
return arr;
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
| Java | ["4\nalex\nivan\nroman\nivan", "8\nalina\nmaria\nekaterina\ndarya\ndarya\nekaterina\nmaria\nalina"] | 3 seconds | ["ivan\nroman\nalex", "alina\nmaria\nekaterina\ndarya"] | NoteIn the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows: alex Then Polycarpus writes to friend by name "ivan" and the list looks as follows: ivan alex Polycarpus writes the third message to friend by name "roman" and the list looks as follows: roman ivan alex Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows: ivan roman alex | Java 8 | standard input | [
"constructive algorithms",
"*special",
"sortings",
"data structures",
"binary search"
] | 18f4d9262150294b63d99803250ed49c | The first line contains integer n (1 ≤ n ≤ 200 000) — the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10. | 1,200 | Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom. | standard output | |
PASSED | d706a9eb362a719a347fa2c8ebde8a66 | train_003.jsonl | 1457870400 | Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Stack;
//import java.util.*;
//import java.io.Reader;
//import java.math.BigDecimal;
//import java.util.ArrayList;
//import java.util.Arrays;
//ArrayList<Integer> list = new ArrayList<Integer>();
//import java.util.Collections;
//import java.io.IOException;
//import java.io.InputStream;
//import java.io.InputStreamReader;
//s=s.replaceAll("[^a-z]"," ");
import java.util.StringTokenizer;
public class Main{
public static void main(String[] args) throws IOException {
Scanner sc=new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
//Queue<String> q=new LinkedList<String>();
HashSet<String> map=new HashSet<>();
int n=sc.nextInt();
String a[]=new String[n];
for(int i=0 ; i<n ; i++) {
a[i]=sc.nextLine();
}
int l=a.length-1;
for(int i=l ; i>=0 ; i--) {
if(!map.contains(a[i])) {
map.add(a[i]);
out.println(a[i]);
}
}
out.flush();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream s) {
br = new BufferedReader(new InputStreamReader(s));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public int[] nextIntArr(int n) throws IOException {
int[] arr = new int[n];
for (int i = 0; i < n; i++)
arr[i] = nextInt();
return arr;
}
public long[] nextLongArr(int n) throws IOException {
long[] arr = new long[n];
for (int i = 0; i < n; i++)
arr[i] = nextLong();
return arr;
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public boolean ready() throws IOException {
return br.ready();
}
}
}
| Java | ["4\nalex\nivan\nroman\nivan", "8\nalina\nmaria\nekaterina\ndarya\ndarya\nekaterina\nmaria\nalina"] | 3 seconds | ["ivan\nroman\nalex", "alina\nmaria\nekaterina\ndarya"] | NoteIn the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows: alex Then Polycarpus writes to friend by name "ivan" and the list looks as follows: ivan alex Polycarpus writes the third message to friend by name "roman" and the list looks as follows: roman ivan alex Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows: ivan roman alex | Java 8 | standard input | [
"constructive algorithms",
"*special",
"sortings",
"data structures",
"binary search"
] | 18f4d9262150294b63d99803250ed49c | The first line contains integer n (1 ≤ n ≤ 200 000) — the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10. | 1,200 | Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom. | standard output | |
PASSED | 555f336d83a8c9c7ffb5d960d476322b | train_003.jsonl | 1457870400 | Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus. | 256 megabytes | import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
public class ChatOrder {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int n = input.nextInt();
String[] s = new String[n];
HashSet<String> set = new HashSet<String>();
PrintWriter out = new PrintWriter(System.out);
for(int i=0; i<n;i++){
s[i] = input.next();
set.add(s[i]);
}
int i=n-1;
while(!set.isEmpty()){
if(set.contains(s[i])){
out.println(s[i]);
set.remove(s[i]);
}
i--;
}
out.flush();
out.close();
}
}
| Java | ["4\nalex\nivan\nroman\nivan", "8\nalina\nmaria\nekaterina\ndarya\ndarya\nekaterina\nmaria\nalina"] | 3 seconds | ["ivan\nroman\nalex", "alina\nmaria\nekaterina\ndarya"] | NoteIn the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows: alex Then Polycarpus writes to friend by name "ivan" and the list looks as follows: ivan alex Polycarpus writes the third message to friend by name "roman" and the list looks as follows: roman ivan alex Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows: ivan roman alex | Java 8 | standard input | [
"constructive algorithms",
"*special",
"sortings",
"data structures",
"binary search"
] | 18f4d9262150294b63d99803250ed49c | The first line contains integer n (1 ≤ n ≤ 200 000) — the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10. | 1,200 | Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom. | standard output | |
PASSED | d716e5594dc54b04919df09b05aff0fb | train_003.jsonl | 1457870400 | Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus. | 256 megabytes |
import java.util.*;
import java.io.*;
public class p765c {
public static void main(String[] args)throws Exception{
Scanner sc=new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
int n=sc.nextInt();
Stack<String> s1=new Stack<String>();
for(int i=0;i<n;i++) {
s1.push(sc.next());
}
TreeSet<String> s2=new TreeSet<String>();
while(!s1.isEmpty()) {
String e=s1.pop();
if (!s2.contains(e)) {
s2.add(e);
out.println(e);
}
}
out.flush();
}
static class Scanner
{
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {br = new BufferedReader(new InputStreamReader(system));}
public Scanner(String file) throws Exception {br = new BufferedReader(new FileReader(file));}
public String next() throws IOException
{
while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine()throws IOException{return br.readLine();}
public int nextInt() throws IOException {return Integer.parseInt(next());}
public double nextDouble() throws IOException {return Double.parseDouble(next());}
public char nextChar()throws IOException{return next().charAt(0);}
public Long nextLong()throws IOException{return Long.parseLong(next());}
public boolean ready() throws IOException{return br.ready();}
public void waitForInput() throws InterruptedException {Thread.sleep(3000);}
}
}
| Java | ["4\nalex\nivan\nroman\nivan", "8\nalina\nmaria\nekaterina\ndarya\ndarya\nekaterina\nmaria\nalina"] | 3 seconds | ["ivan\nroman\nalex", "alina\nmaria\nekaterina\ndarya"] | NoteIn the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows: alex Then Polycarpus writes to friend by name "ivan" and the list looks as follows: ivan alex Polycarpus writes the third message to friend by name "roman" and the list looks as follows: roman ivan alex Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows: ivan roman alex | Java 8 | standard input | [
"constructive algorithms",
"*special",
"sortings",
"data structures",
"binary search"
] | 18f4d9262150294b63d99803250ed49c | The first line contains integer n (1 ≤ n ≤ 200 000) — the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10. | 1,200 | Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom. | standard output | |
PASSED | 87722cf84299bcd8c9d92cd4855f683f | train_003.jsonl | 1457870400 | Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus. | 256 megabytes | import java.util.*;
public class Chat {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Stack<String> stack = new Stack<String>();
TreeSet<String> tree = new TreeSet<String>();
int n = sc.nextInt();
for (int i = 0; i < n; i++)
stack.push(sc.next());
while(!stack.isEmpty()){
if(!tree.contains(stack.peek()))
{
tree.add(stack.peek());
System.out.println(stack.pop());
}else
stack.pop();
}
}
}
| Java | ["4\nalex\nivan\nroman\nivan", "8\nalina\nmaria\nekaterina\ndarya\ndarya\nekaterina\nmaria\nalina"] | 3 seconds | ["ivan\nroman\nalex", "alina\nmaria\nekaterina\ndarya"] | NoteIn the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows: alex Then Polycarpus writes to friend by name "ivan" and the list looks as follows: ivan alex Polycarpus writes the third message to friend by name "roman" and the list looks as follows: roman ivan alex Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows: ivan roman alex | Java 8 | standard input | [
"constructive algorithms",
"*special",
"sortings",
"data structures",
"binary search"
] | 18f4d9262150294b63d99803250ed49c | The first line contains integer n (1 ≤ n ≤ 200 000) — the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10. | 1,200 | Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom. | standard output | |
PASSED | e102ca9772934f36ad63a895b60ed3a7 | train_003.jsonl | 1457870400 | Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus. | 256 megabytes | import java.util.*;
import java.io.*;
import java.math.*;
public class cf
{
static int n;
static int m;
static Integer arr[];
static Integer brr[];
public static void main(String[] args)throws IOException
{
PrintWriter out= new PrintWriter(System.out);
BufferedReader sc=new BufferedReader(new InputStreamReader(System.in));
n=Integer.parseInt(sc.readLine());
String arr[]=new String[n];
for(int i = 0 ;i<n;i++)
arr[i]=sc.readLine();
HashMap<String,Boolean> hm=new HashMap<String,Boolean>();
String ans[]=new String[n+1];
int counter=0;
for(int i= n-1;i>=0;i--)
{
if(hm.get(arr[i])!=null)
continue;
else
{
hm.put(arr[i],true);
ans[counter++]=arr[i];
}
}
for(int i = 0 ;i<counter;i++)
out.println(ans[i]);
out.flush();
}
} | Java | ["4\nalex\nivan\nroman\nivan", "8\nalina\nmaria\nekaterina\ndarya\ndarya\nekaterina\nmaria\nalina"] | 3 seconds | ["ivan\nroman\nalex", "alina\nmaria\nekaterina\ndarya"] | NoteIn the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows: alex Then Polycarpus writes to friend by name "ivan" and the list looks as follows: ivan alex Polycarpus writes the third message to friend by name "roman" and the list looks as follows: roman ivan alex Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows: ivan roman alex | Java 8 | standard input | [
"constructive algorithms",
"*special",
"sortings",
"data structures",
"binary search"
] | 18f4d9262150294b63d99803250ed49c | The first line contains integer n (1 ≤ n ≤ 200 000) — the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10. | 1,200 | Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom. | standard output | |
PASSED | f0bdc78b4da59ca28ee2b7cd6547e3b1 | train_003.jsonl | 1457870400 | Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus. | 256 megabytes | // AC as of 3/9/2018
// Solution: Trivial, store chat list in String array, then read from the back
// Use HashMap to keep track of names already seen
import java.util.HashMap;
import java.util.Scanner;
public class CF637B {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int nChats = sc.nextInt();
String[] chats = new String[nChats];
for(int i=0; i<nChats; i++) chats[i] = sc.next();
HashMap<String, Integer> map = new HashMap<>();
for(int i=nChats-1; i>=0; i--){
if(!map.containsKey(chats[i])) {
map.put(chats[i], 0);
System.out.println(chats[i]);
}
}
}
}
| Java | ["4\nalex\nivan\nroman\nivan", "8\nalina\nmaria\nekaterina\ndarya\ndarya\nekaterina\nmaria\nalina"] | 3 seconds | ["ivan\nroman\nalex", "alina\nmaria\nekaterina\ndarya"] | NoteIn the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows: alex Then Polycarpus writes to friend by name "ivan" and the list looks as follows: ivan alex Polycarpus writes the third message to friend by name "roman" and the list looks as follows: roman ivan alex Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows: ivan roman alex | Java 8 | standard input | [
"constructive algorithms",
"*special",
"sortings",
"data structures",
"binary search"
] | 18f4d9262150294b63d99803250ed49c | The first line contains integer n (1 ≤ n ≤ 200 000) — the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10. | 1,200 | Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom. | standard output | |
PASSED | 0aa8f6af1246cf2d00b8682cd19c058b | train_003.jsonl | 1457870400 | Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus. | 256 megabytes | import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Scanner;
public class CF637B {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int nChats = sc.nextInt();
ArrayList<String> chats = new ArrayList<>();
while(nChats-->0) chats.add(sc.next());
HashMap<String, Integer> map = new HashMap<>();
for(int i=chats.size()-1; i>=0; i--){
if(!map.containsKey(chats.get(i))) {
map.put(chats.get(i), 0);
System.out.println(chats.get(i));
}
}
}
}
| Java | ["4\nalex\nivan\nroman\nivan", "8\nalina\nmaria\nekaterina\ndarya\ndarya\nekaterina\nmaria\nalina"] | 3 seconds | ["ivan\nroman\nalex", "alina\nmaria\nekaterina\ndarya"] | NoteIn the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows: alex Then Polycarpus writes to friend by name "ivan" and the list looks as follows: ivan alex Polycarpus writes the third message to friend by name "roman" and the list looks as follows: roman ivan alex Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows: ivan roman alex | Java 8 | standard input | [
"constructive algorithms",
"*special",
"sortings",
"data structures",
"binary search"
] | 18f4d9262150294b63d99803250ed49c | The first line contains integer n (1 ≤ n ≤ 200 000) — the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10. | 1,200 | Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom. | standard output | |
PASSED | a145e8bc69dda068dee7af7cb9f9b628 | train_003.jsonl | 1457870400 | Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main
{
static BufferedReader br;
static StringTokenizer st;
static PrintWriter pr = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
public static class AL<T> extends ArrayList<T> {};
public static class HM<T,Integer> extends HashMap<T,T> {};
public static class HS<T> extends HashSet<T> {};
public static void main(String[] args) throws IOException
{
br=new BufferedReader(new InputStreamReader(System.in));
st=new StringTokenizer(br.readLine());
int n=nxtInt();
LinkedHashSet<String> set=new LinkedHashSet<String>();
for(int i=0;i<n;i++)
{
String s=nxtLn();
if(set.contains(s))
{
set.remove(s);
set.add(s);
}
else set.add(s);
}
AL<String> a=new AL<>();
for(String s: set) a.add(s);
for(int i=a.size()-1;i>=0;i--) pr.println(a.get(i));
pr.flush();
pr.close();
}
static int nxtInt(){
return Integer.parseInt(nxt());
}
static long nxtLong(){
return Long.parseLong(nxt());
}
static double nxtDoub(){
return Double.parseDouble(nxt());
}
static String nxt(){
return st.nextToken();
}
static String nxtLn() throws IOException{
return br.readLine();
}
} | Java | ["4\nalex\nivan\nroman\nivan", "8\nalina\nmaria\nekaterina\ndarya\ndarya\nekaterina\nmaria\nalina"] | 3 seconds | ["ivan\nroman\nalex", "alina\nmaria\nekaterina\ndarya"] | NoteIn the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows: alex Then Polycarpus writes to friend by name "ivan" and the list looks as follows: ivan alex Polycarpus writes the third message to friend by name "roman" and the list looks as follows: roman ivan alex Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows: ivan roman alex | Java 8 | standard input | [
"constructive algorithms",
"*special",
"sortings",
"data structures",
"binary search"
] | 18f4d9262150294b63d99803250ed49c | The first line contains integer n (1 ≤ n ≤ 200 000) — the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10. | 1,200 | Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom. | standard output | |
PASSED | 8b322c10bdfc71c146aa50470107c5fe | train_003.jsonl | 1457870400 | Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus. | 256 megabytes | import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.TreeSet;
//import java.util.*;
/**
* Created by Андрей on 13.03.2016.
*/
public class A {
public static PrintWriter pw;
public static void main(String[] args) throws FileNotFoundException {
// Scanner in = new Scanner(new File("input.txt"));
// pw = new PrintWriter(new File("output.txt"));
Scanner in = new Scanner(System.in);
pw = new PrintWriter(System.out);
int N=in.nextInt();
//ArrayDeque<String> tr=new ArrayDeque<>();
ArrayList<String> ar=new ArrayList<>();
// ArrayList<String> ar0=new ArrayList<>();
TreeSet<String> tr=new TreeSet<>();
//String s[]=new String[N];
for(int i=0;i<N;i++){
String s=in.next();
ar.add(s);
tr.add(s);
// int t=ar0.indexOf(s);
/* if(!ar0.contains(s)){
ar.add(s);
ar0.add(s);
}*/
}
for(int i=ar.size()-1;i>=0;i--) {
String t=ar.get(i);
/*if(!ar0.contains(t)){
ar0.add(t);
pw.println(t);
}*/
if(tr.contains(t)){
tr.remove(t);
pw.println(t);
}
if(tr.size()==0)break;
// pw.println(ar.get(i));
}
pw.close();
}
}
| Java | ["4\nalex\nivan\nroman\nivan", "8\nalina\nmaria\nekaterina\ndarya\ndarya\nekaterina\nmaria\nalina"] | 3 seconds | ["ivan\nroman\nalex", "alina\nmaria\nekaterina\ndarya"] | NoteIn the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows: alex Then Polycarpus writes to friend by name "ivan" and the list looks as follows: ivan alex Polycarpus writes the third message to friend by name "roman" and the list looks as follows: roman ivan alex Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows: ivan roman alex | Java 8 | standard input | [
"constructive algorithms",
"*special",
"sortings",
"data structures",
"binary search"
] | 18f4d9262150294b63d99803250ed49c | The first line contains integer n (1 ≤ n ≤ 200 000) — the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10. | 1,200 | Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom. | standard output | |
PASSED | 5e57e99be4e43cbb79ba1b596313cc92 | train_003.jsonl | 1457870400 | Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class ChatOrder {
public static void main(String[]args) throws Exception {
Scanner sc=new Scanner(System.in);
PrintWriter out=new PrintWriter(System.out);
TreeMap<Integer,String> tm=new TreeMap<>((a,b) -> b-a);
TreeSet<String>ts=new TreeSet<>();
Stack<String> st=new Stack<>();
int n=sc.nextInt();
for(int i=1;i<=n;i++) //O(nlogn)
{
String s=sc.next();
tm.put(i,s);
ts.add(s);
}
for(Map.Entry<Integer,String> entry:tm.entrySet())//O(nlogn)
if(ts.contains(entry.getValue()))
{
out.println(entry.getValue());
ts.remove(entry.getValue());
}
out.flush();
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br=new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while(st==null||!st.hasMoreTokens())
st=new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException{
return Integer.parseInt(this.next());
}
public double nextDouble() throws IOException{
return Double.parseDouble(this.next());
}
public char nextChar() throws IOException{
return this.next().charAt(0);
}
public long nextLong() throws IOException{
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException{
Thread.sleep(5000);
}
}
}
| Java | ["4\nalex\nivan\nroman\nivan", "8\nalina\nmaria\nekaterina\ndarya\ndarya\nekaterina\nmaria\nalina"] | 3 seconds | ["ivan\nroman\nalex", "alina\nmaria\nekaterina\ndarya"] | NoteIn the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows: alex Then Polycarpus writes to friend by name "ivan" and the list looks as follows: ivan alex Polycarpus writes the third message to friend by name "roman" and the list looks as follows: roman ivan alex Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows: ivan roman alex | Java 8 | standard input | [
"constructive algorithms",
"*special",
"sortings",
"data structures",
"binary search"
] | 18f4d9262150294b63d99803250ed49c | The first line contains integer n (1 ≤ n ≤ 200 000) — the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10. | 1,200 | Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom. | standard output | |
PASSED | dc3dcc19a4380e56b79fd7c2c2531b79 | train_003.jsonl | 1457870400 | Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus. | 256 megabytes | import java.util.*;
import java.io.*;
public class ChatOrder {
public static void main (String args [] ) throws IOException , InterruptedException {
Scanner sc = new Scanner (System.in) ;
PrintWriter p = new PrintWriter(System.out) ;
// Thread.sleep(1500);
int n = sc.nextInt() ;
String x [] = new String [n] ;
HashSet <String> t = new HashSet<String>() ;
for (int i = 0 ; i < n ; i ++ ) {
x[i] = sc.nextLine() ;
t.add(x[i]) ;
}
int j = n-1 ;
Stack<String> q = new Stack<String>() ;
while (t.size()>0) {
if(t.contains(x[j])) {
q.add(x[j]) ;
t.remove(x[j]) ;
}
j-- ;
}
for(String s : q) {
p.println(s) ;
}
p.close();
}
static class Scanner {
StringTokenizer st;
BufferedReader br;
public Scanner(InputStream system) {
br = new BufferedReader(new InputStreamReader(system));
}
public Scanner(String file) throws Exception {
br = new BufferedReader(new FileReader(file));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return br.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public char nextChar() throws IOException {
return next().charAt(0);
}
public Long nextLong() throws IOException {
return Long.parseLong(next());
}
public boolean ready() throws IOException {
return br.ready();
}
public void waitForInput() throws InterruptedException {
Thread.sleep(3000);
}
}
}
| Java | ["4\nalex\nivan\nroman\nivan", "8\nalina\nmaria\nekaterina\ndarya\ndarya\nekaterina\nmaria\nalina"] | 3 seconds | ["ivan\nroman\nalex", "alina\nmaria\nekaterina\ndarya"] | NoteIn the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows: alex Then Polycarpus writes to friend by name "ivan" and the list looks as follows: ivan alex Polycarpus writes the third message to friend by name "roman" and the list looks as follows: roman ivan alex Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows: ivan roman alex | Java 8 | standard input | [
"constructive algorithms",
"*special",
"sortings",
"data structures",
"binary search"
] | 18f4d9262150294b63d99803250ed49c | The first line contains integer n (1 ≤ n ≤ 200 000) — the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10. | 1,200 | Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom. | standard output | |
PASSED | 50a4b65e43c28fe422fca0836e44f74a | train_003.jsonl | 1457870400 | Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw=new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
StringTokenizer s=new StringTokenizer(br.readLine());
int n=Integer.parseInt(s.nextToken());
HashMap<String,Node>hm=new HashMap<>();
for(int i=0;i<n;i++) {
s=new StringTokenizer(br.readLine());
String st=s.nextToken();
if(!hm.containsKey(st)) {
hm.put(st, new Node(st,i));
}else {
hm.put(st, new Node(st,i));
}
}
Node ar[]=new Node[hm.size()];
int i=0;
for(String str:hm.keySet()) {
ar[i]=hm.get(str);
i++;
}
Arrays.sort(ar,(a,b) -> b.lastI-a.lastI);
for(int j=0;j<ar.length;j++) {
pw.println(ar[j].st);
}
pw.close();
}
}
class Node{
String st;
int lastI;
Node(String st,int lastI){
this.st=st;
this.lastI=lastI;
}
} | Java | ["4\nalex\nivan\nroman\nivan", "8\nalina\nmaria\nekaterina\ndarya\ndarya\nekaterina\nmaria\nalina"] | 3 seconds | ["ivan\nroman\nalex", "alina\nmaria\nekaterina\ndarya"] | NoteIn the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows: alex Then Polycarpus writes to friend by name "ivan" and the list looks as follows: ivan alex Polycarpus writes the third message to friend by name "roman" and the list looks as follows: roman ivan alex Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows: ivan roman alex | Java 8 | standard input | [
"constructive algorithms",
"*special",
"sortings",
"data structures",
"binary search"
] | 18f4d9262150294b63d99803250ed49c | The first line contains integer n (1 ≤ n ≤ 200 000) — the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10. | 1,200 | Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom. | standard output | |
PASSED | 5f781899c2472bc9460f9e970d0ca53c | train_003.jsonl | 1457870400 | Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus. | 256 megabytes | import java.util.*;
/**
* Created by mooks on 13.03.2016.
*/
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
Map<String, Integer> chats = new HashMap();
int size = 0;
in.nextLine();
for (int i = 0; i < n; i++) {
String chat = in.nextLine();
chats.put(chat, size++);
}
Set<Map.Entry<String, Integer>> entries = chats.entrySet();
List<Map.Entry<String, Integer>> list = new LinkedList();
for (Map.Entry<String, Integer> tmp : entries) {
list.add(tmp);
}
Collections.sort(list, (o1, o2) -> o2.getValue() - o1.getValue());
for (Map.Entry<String, Integer> tmp : list) {
System.out.println(tmp.getKey());
}
}
}
| Java | ["4\nalex\nivan\nroman\nivan", "8\nalina\nmaria\nekaterina\ndarya\ndarya\nekaterina\nmaria\nalina"] | 3 seconds | ["ivan\nroman\nalex", "alina\nmaria\nekaterina\ndarya"] | NoteIn the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows: alex Then Polycarpus writes to friend by name "ivan" and the list looks as follows: ivan alex Polycarpus writes the third message to friend by name "roman" and the list looks as follows: roman ivan alex Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows: ivan roman alex | Java 8 | standard input | [
"constructive algorithms",
"*special",
"sortings",
"data structures",
"binary search"
] | 18f4d9262150294b63d99803250ed49c | The first line contains integer n (1 ≤ n ≤ 200 000) — the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10. | 1,200 | Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom. | standard output | |
PASSED | cf77cd24b19980fd023c513b04830889 | train_003.jsonl | 1457870400 | Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus. | 256 megabytes | import java.io.*;
import java.util.*;
public class ChatOrder {
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter pr=new PrintWriter(System.out);
int n=scan.nextInt();
HashSet<String> set=new HashSet<>();
String[] s=new String[n];
for(int i=0;i<n;i++){
s[i]=scan.next();
}
for(int i=n-1;i>=0;i--){
if(!set.contains(s[i])){
set.add(s[i]);
pr.println(s[i]);
}
}
pr.close();
}
} | Java | ["4\nalex\nivan\nroman\nivan", "8\nalina\nmaria\nekaterina\ndarya\ndarya\nekaterina\nmaria\nalina"] | 3 seconds | ["ivan\nroman\nalex", "alina\nmaria\nekaterina\ndarya"] | NoteIn the first test case Polycarpus first writes to friend by name "alex", and the list looks as follows: alex Then Polycarpus writes to friend by name "ivan" and the list looks as follows: ivan alex Polycarpus writes the third message to friend by name "roman" and the list looks as follows: roman ivan alex Polycarpus writes the fourth message to friend by name "ivan", to who he has already sent a message, so the list of chats changes as follows: ivan roman alex | Java 8 | standard input | [
"constructive algorithms",
"*special",
"sortings",
"data structures",
"binary search"
] | 18f4d9262150294b63d99803250ed49c | The first line contains integer n (1 ≤ n ≤ 200 000) — the number of Polycarpus' messages. Next n lines enlist the message recipients in the order in which the messages were sent. The name of each participant is a non-empty sequence of lowercase English letters of length at most 10. | 1,200 | Print all the recipients to who Polycarp talked to in the order of chats with them, from top to bottom. | standard output | |
PASSED | 784310f984cc2b11786fe6faea394981 | train_003.jsonl | 1364025600 | A double tourist path, located at a park in Ultima Thule, is working by the following principle: We introduce the Cartesian coordinate system. At some points of time there are two tourists going (for a walk) from points ( - 1, 0) and (1, 0) simultaneously. The first one is walking from ( - 1, 0), the second one is walking from (1, 0). Both tourists in a pair move at the same speed 1 (distance unit per second), the first one moves along line x = - 1, the second one moves along line x = 1, both of them are moving in the positive direction of the Oy axis. At some points of time walls appear. Wall (li, ri) is a segment between points (0, li) and (0, ri). Each wall appears immediately. The Ultima Thule government wants to learn this for each pair of tourists that walk simultaneously: for how long (in seconds) will they not see each other? Two tourists don't see each other if the segment that connects their positions on the plane intersects at least one wall. Two segments intersect if they share at least one point. We assume that the segments' ends belong to the segments.Help the government count the required time. Note that the walls can intersect (in any way) or coincide. | 256 megabytes | import java.util.NavigableSet;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.util.Comparator;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Random;
import java.io.Writer;
import java.util.Map;
import java.util.List;
import java.io.IOException;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.AbstractSet;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;
import java.util.AbstractMap;
import java.util.NoSuchElementException;
import java.util.TreeSet;
import java.math.BigInteger;
import java.util.Collections;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Egor Kulikov (egor@egork.net)
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
OutputWriter out = new OutputWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
public void solve(int testNumber, InputReader in, OutputWriter out) {
int count = in.readInt();
int blockCount = in.readInt();
int[] from = new int[blockCount];
int[] to = new int[blockCount];
int[] appear = new int[blockCount];
IOUtils.readIntArrays(in, from, to, appear);
int[] start = IOUtils.readIntArray(in, count);
List<Event> events = new ArrayList<Event>();
// for (int i = 0; i < blockCount; i++) {
// events[2 * i] = new Event(Event.Type.ADD, i, appear[i] - to[i]);
// events[2 * i + 1] = new Event(Event.Type.FIX, i, appear[i] - from[i]);
// }
for (int i = 0; i < count; i++)
events.add(new Event(Event.Type.TOURIST, i, start[i]));
int[] order = ArrayUtils.order(appear);
NavigableSet<Pair<Integer, Integer>> occupied = new TreeSet<Pair<Integer, Integer>>();
for (int i : order) {
Pair<Integer, Integer> key = Pair.makePair(from[i], to[i]);
Pair<Integer, Integer> last = occupied.floor(key);
int left = from[i];
int current = from[i];
if (last != null && last.second >= from[i]) {
left = last.first;
current = last.second;
occupied.remove(last);
}
NavigableSet<Pair<Integer, Integer>> subSet = occupied.subSet(key, false, Pair.makePair(to[i], Integer.MAX_VALUE), false);
Iterator<Pair<Integer, Integer>> iterator = subSet.iterator();
while (iterator.hasNext()) {
Pair<Integer, Integer> next = iterator.next();
if (next.first > current) {
events.add(new Event(Event.Type.ADD, i, appear[i] - next.first));
events.add(new Event(Event.Type.FIX, i, appear[i] - current));
}
current = Math.max(current, next.second);
iterator.remove();
}
if (current < to[i]) {
events.add(new Event(Event.Type.ADD, i, appear[i] - to[i]));
events.add(new Event(Event.Type.FIX, i, appear[i] - current));
current = to[i];
}
occupied.add(Pair.makePair(left, current));
}
Collections.sort(events);
long[] answer = new long[count];
long current = 0;
long delta = 0;
int last = Integer.MIN_VALUE;
for (Event event : events) {
current += delta * (event.value - last);
last = event.value;
if (event.type == Event.Type.ADD)
delta++;
else if (event.type == Event.Type.FIX)
delta--;
else
answer[event.index] = current;
}
for (long i : answer)
out.printLine(i);
}
static class Event implements Comparable<Event> {
public int compareTo(Event o) {
if (value == o.value)
return 0;
else if (value < o.value)
return -1;
else
return 1;
}
enum Type {
ADD, FIX, TOURIST
}
final Type type;
final int index;
final int value;
Event(Type type, int index, int value) {
this.type = type;
this.index = index;
this.value = value;
}
}
}
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 read() {
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars) {
curChar = 0;
try {
numChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return isWhitespace(c);
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
class OutputWriter {
private final PrintWriter writer;
public OutputWriter(OutputStream outputStream) {
writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
}
public OutputWriter(Writer writer) {
this.writer = new PrintWriter(writer);
}
public void print(Object...objects) {
for (int i = 0; i < objects.length; i++) {
if (i != 0)
writer.print(' ');
writer.print(objects[i]);
}
}
public void printLine(Object...objects) {
print(objects);
writer.println();
}
public void close() {
writer.close();
}
}
class IOUtils {
public static int[] readIntArray(InputReader in, int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = in.readInt();
return array;
}
public static void readIntArrays(InputReader in, int[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++)
arrays[j][i] = in.readInt();
}
}
}
class ArrayUtils {
private static int[] tempInt = new int[0];
public static int[] createOrder(int size) {
int[] order = new int[size];
for (int i = 0; i < size; i++)
order[i] = i;
return order;
}
public static int[] sort(int[] array, IntComparator comparator) {
return sort(array, 0, array.length, comparator);
}
public static int[] sort(int[] array, int from, int to, IntComparator comparator) {
ensureCapacityInt(to - from);
System.arraycopy(array, from, tempInt, 0, to - from);
sortImpl(array, from, to, tempInt, 0, to - from, comparator);
return array;
}
private static void ensureCapacityInt(int size) {
if (tempInt.length >= size)
return;
size = Math.max(size, tempInt.length << 1);
tempInt = new int[size];
}
private static void sortImpl(int[] array, int from, int to, int[] temp, int fromTemp, int toTemp, IntComparator comparator) {
if (to - from <= 1)
return;
int middle = (to - from) >> 1;
int tempMiddle = fromTemp + middle;
sortImpl(temp, fromTemp, tempMiddle, array, from, from + middle, comparator);
sortImpl(temp, tempMiddle, toTemp, array, from + middle, to, comparator);
int index = from;
int index1 = fromTemp;
int index2 = tempMiddle;
while (index1 < tempMiddle && index2 < toTemp) {
if (comparator.compare(temp[index1], temp[index2]) <= 0)
array[index++] = temp[index1++];
else
array[index++] = temp[index2++];
}
if (index1 != tempMiddle)
System.arraycopy(temp, index1, array, index, tempMiddle - index1);
if (index2 != toTemp)
System.arraycopy(temp, index2, array, index, toTemp - index2);
}
public static int[] order(final int[] array) {
return sort(createOrder(array.length), new IntComparator() {
public int compare(int first, int second) {
if (array[first] < array[second])
return -1;
if (array[first] > array[second])
return 1;
return 0;
}
});
}
}
class Pair<U, V> implements Comparable<Pair<U, V>> {
public final U first;
public final V second;
public static<U, V> Pair<U, V> makePair(U first, V second) {
return new Pair<U, V>(first, second);
}
private Pair(U first, V second) {
this.first = first;
this.second = second;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Pair pair = (Pair) o;
return !(first != null ? !first.equals(pair.first) : pair.first != null) && !(second != null ? !second.equals(pair.second) : pair.second != null);
}
public int hashCode() {
int result = first != null ? first.hashCode() : 0;
result = 31 * result + (second != null ? second.hashCode() : 0);
return result;
}
public String toString() {
return "(" + first + "," + second + ")";
}
public int compareTo(Pair<U, V> o) {
int value = ((Comparable<U>)first).compareTo(o.first);
if (value != 0)
return value;
return ((Comparable<V>)second).compareTo(o.second);
}
}
interface IntComparator {
public int compare(int first, int second);
}
| Java | ["2 2\n1 4 3\n3 6 5\n0 1", "3 3\n0 3 4\n0 1 2\n2 4 0\n1 3 4"] | 1 second | ["2\n4", "2\n4\n4"] | null | Java 7 | standard input | [
"data structures",
"sortings"
] | 8cbc9e2127c21746dc5341ab07bfee86 | The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 105) — the number of pairs of tourists and the number of built walls. The next m lines contain three space-separated integers li, ri and ti each (0 ≤ li < ri ≤ 109, 0 ≤ ti ≤ 109) — the wall ends and the time it appeared. The last line contains n distinct space-separated strictly increasing integers q1, q2, ..., qn (0 ≤ qi ≤ 109) — the points of time when pairs of tourists walk. All points of time are given in seconds. | 2,600 | For each pair of tourists print on a single line a single integer — the time in seconds when the two tourists from the corresponding pair won't see each other. Print the numbers in the order in which the they go in the input. | standard output | |
PASSED | e0e73ee47d879c8aace504dad10f8958 | train_003.jsonl | 1364025600 | A double tourist path, located at a park in Ultima Thule, is working by the following principle: We introduce the Cartesian coordinate system. At some points of time there are two tourists going (for a walk) from points ( - 1, 0) and (1, 0) simultaneously. The first one is walking from ( - 1, 0), the second one is walking from (1, 0). Both tourists in a pair move at the same speed 1 (distance unit per second), the first one moves along line x = - 1, the second one moves along line x = 1, both of them are moving in the positive direction of the Oy axis. At some points of time walls appear. Wall (li, ri) is a segment between points (0, li) and (0, ri). Each wall appears immediately. The Ultima Thule government wants to learn this for each pair of tourists that walk simultaneously: for how long (in seconds) will they not see each other? Two tourists don't see each other if the segment that connects their positions on the plane intersects at least one wall. Two segments intersect if they share at least one point. We assume that the segments' ends belong to the segments.Help the government count the required time. Note that the walls can intersect (in any way) or coincide. | 256 megabytes | import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.TreeMap;
import java.util.ArrayList;
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
* @author sheep
*/
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
class Event implements Comparable<Event> {
int at, t;
Event(int at, int t) {
this.at = at;
this.t = t;
}
public int compareTo(Event event) {
if (at != event.at) return at - event.at;
return event.t - t;
}
}
class Query implements Comparable<Query> {
int at, t;
Query(int at, int t) {
this.at = at;
this.t = t;
}
public int compareTo(Query query) {
return t - query.t;
}
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
TreeMap<Integer, Integer> set = new TreeMap<Integer, Integer>();
int m = in.nextInt();
int n = in.nextInt();
int l[] = new int[n],
r[] = new int[n],
t[] = new int[n];
for (int i = 0; i < n; ++i) {
l[i] = in.nextInt();
r[i] = in.nextInt();
t[i] = in.nextInt() + 1;
}
Query q[] = new Query[m];
for (int i = 0; i < m; ++i) {
q[i] = new Query(i, in.nextInt() + 1);
}
Event events[] = new Event[2 * n];
for (int i = 0; i < n; ++i) {
events[2 * i] = new Event(l[i], t[i]);
events[2 * i + 1] = new Event(r[i], -t[i]);
}
Arrays.sort(events);
ArrayList<Integer> left, right, time;
left = new ArrayList<Integer>();
right = new ArrayList<Integer>();
time = new ArrayList<Integer>();
for (int i = 0; i < events.length; ) {
if (i != 0 && events[i - 1].at != events[i].at && set.size() > 0) {
left.add(events[i - 1].at);
right.add(events[i].at);
time.add(set.firstKey());
}
int j = i;
while (j < events.length && events[i].at == events[j].at && Long.signum(events[i].t) == Long.signum(events[j].t)) {
int val = events[j].t, key = Math.abs(val);
int lastTime = 0;
if (set.containsKey(key)) {
lastTime = set.get(key);
set.remove(key);
}
if (val < 0) {
--lastTime;
} else {
++lastTime;
}
if (lastTime != 0) {
set.put(key, lastTime);
}
++j;
}
i = j;
}
Arrays.sort(q);
events = new Event[left.size() * 2];
for (int i = 0; i < left.size(); ++i) {
events[i * 2] = new Event(time.get(i) - left.get(i), -(i + 1));
events[i * 2 + 1] = new Event(time.get(i) - right.get(i), i + 1);
}
int numSegments = 0;
long work = 0, fixed = 0;
Arrays.sort(events);
int ptrEvents = 0;
long ans[] = new long[m];
for (int i = 0; i < q.length; ++i) {
while (ptrEvents < events.length && events[ptrEvents].at <= q[i].t) {
int index = Math.abs(events[ptrEvents].t) - 1;
work += (right.get(index) - time.get(index)) * Long.signum(events[ptrEvents].t);
numSegments += Long.signum(events[ptrEvents].t);
if (events[ptrEvents].t < 0) {
fixed += right.get(index) - left.get(index);
}
++ptrEvents;
}
ans[q[i].at] = work + q[i].t * (long)numSegments + fixed;
}
for (int i = 0; i < m; ++i) {
out.println(ans[i]);
}
}
}
class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e) {
throw new UnknownError();
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
} | Java | ["2 2\n1 4 3\n3 6 5\n0 1", "3 3\n0 3 4\n0 1 2\n2 4 0\n1 3 4"] | 1 second | ["2\n4", "2\n4\n4"] | null | Java 7 | standard input | [
"data structures",
"sortings"
] | 8cbc9e2127c21746dc5341ab07bfee86 | The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 105) — the number of pairs of tourists and the number of built walls. The next m lines contain three space-separated integers li, ri and ti each (0 ≤ li < ri ≤ 109, 0 ≤ ti ≤ 109) — the wall ends and the time it appeared. The last line contains n distinct space-separated strictly increasing integers q1, q2, ..., qn (0 ≤ qi ≤ 109) — the points of time when pairs of tourists walk. All points of time are given in seconds. | 2,600 | For each pair of tourists print on a single line a single integer — the time in seconds when the two tourists from the corresponding pair won't see each other. Print the numbers in the order in which the they go in the input. | standard output | |
PASSED | 34ff865d7b62780d4e03272a2d3317dd | train_003.jsonl | 1364025600 | A double tourist path, located at a park in Ultima Thule, is working by the following principle: We introduce the Cartesian coordinate system. At some points of time there are two tourists going (for a walk) from points ( - 1, 0) and (1, 0) simultaneously. The first one is walking from ( - 1, 0), the second one is walking from (1, 0). Both tourists in a pair move at the same speed 1 (distance unit per second), the first one moves along line x = - 1, the second one moves along line x = 1, both of them are moving in the positive direction of the Oy axis. At some points of time walls appear. Wall (li, ri) is a segment between points (0, li) and (0, ri). Each wall appears immediately. The Ultima Thule government wants to learn this for each pair of tourists that walk simultaneously: for how long (in seconds) will they not see each other? Two tourists don't see each other if the segment that connects their positions on the plane intersects at least one wall. Two segments intersect if they share at least one point. We assume that the segments' ends belong to the segments.Help the government count the required time. Note that the walls can intersect (in any way) or coincide. | 256 megabytes | import java.util.Map;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.TreeMap;
import java.util.Comparator;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.util.NavigableMap;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.SortedMap;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
* @author Niyaz Nigmatullin
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
FastScanner in = new FastScanner(inputStream);
FastPrinter out = new FastPrinter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
public void solve(int testNumber, FastScanner in, FastPrinter out) {
int n = in.nextInt();
int m = in.nextInt();
Event[] events = new Event[2 * m];
for (int i = 0; i < m; i++) {
int l = in.nextInt();
int r = in.nextInt();
int t = in.nextInt();
events[2 * i] = new Event(l, true, t);
events[2 * i + 1] = new Event(r, false, t);
}
NavigableMap<Integer, Integer> map = new TreeMap<>();
Arrays.sort(events, new Comparator<Event>() {
@Override
public int compare(Event o1, Event o2) {
return o1.x - o2.x;
}
});
int[] q = in.readIntArray(n);
int last = 0;
FenwickRev f1 = new FenwickRev(n);
FenwickRev f2 = new FenwickRev(n);
for (Event e : events) {
if (!map.isEmpty() && last < e.x) {
int time = map.firstKey();
int left = last;
int right = e.x;
int firstQ;
int lastQ;
{
int l = -1;
int r = n;
while (l < r - 1) {
int mid = l + r >> 1;
if (q[mid] >= time - right) {
r = mid;
} else {
l = mid;
}
}
firstQ = r;
}
{
int l = -1;
int r = n;
while (l < r - 1) {
int mid = l + r >> 1;
if (q[mid] > time - left) {
r = mid;
} else {
l = mid;
}
}
lastQ = r;
}
f1.add(firstQ, lastQ, 1);
f2.add(firstQ, lastQ, -(time - right));
f2.add(lastQ, n, right - left);
}
if (e.start) {
add(map, e.time);
} else {
remove(map, e.time);
}
last = e.x;
}
for (int i = 0; i < n; i++) {
int ans = f1.getElement(i) * q[i] + f2.getElement(i);
out.println(ans);
}
}
static void add(Map<Integer, Integer> map, int x) {
Integer z = map.get(x);
if (z == null) {
z = 0;
}
map.put(x, z + 1);
}
static void remove(Map<Integer, Integer> map, int x) {
Integer z = map.get(x);
if (z == 1) {
map.remove(x);
} else {
map.put(x, z - 1);
}
}
static class Event {
int x;
boolean start;
int time;
Event(int x, boolean start, int time) {
this.x = x;
this.start = start;
this.time = time;
}
}
}
class FastScanner extends BufferedReader {
boolean isEOF;
public FastScanner(InputStream is) {
super(new InputStreamReader(is));
}
public int read() {
try {
int ret = super.read();
if (isEOF && ret < 0) {
throw new InputMismatchException();
}
isEOF = ret == -1;
return ret;
} catch (IOException e) {
throw new InputMismatchException();
}
}
static boolean isWhiteSpace(int c) {
return c >= 0 && c <= 32;
}
public int nextInt() {
int c = read();
while (isWhiteSpace(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int ret = 0;
while (c >= 0 && !isWhiteSpace(c)) {
if (c < '0' || c > '9') {
throw new NumberFormatException("digit expected " + (char) c
+ " found");
}
ret = ret * 10 + c - '0';
c = read();
}
return ret * sgn;
}
public int[] readIntArray(int n) {
int[] ret = new int[n];
for (int i = 0; i < n; i++) {
ret[i] = nextInt();
}
return ret;
}
}
class FastPrinter extends PrintWriter {
public FastPrinter(OutputStream out) {
super(out);
}
public FastPrinter(Writer out) {
super(out);
}
}
class FenwickRev {
int[] a;
public FenwickRev(int n) {
a = new int[n];
}
public void add(int x, int y) {
for (int i = x; i >= 0; i = (i & (i + 1)) - 1) {
a[i] += y;
}
}
public int getElement(int x) {
int ret = 0;
for (int i = x; i < a.length; i |= i + 1) {
ret += a[i];
}
return ret;
}
public void add(int left, int right, int y) {
add(left - 1, -y);
add(right - 1, y);
}
}
| Java | ["2 2\n1 4 3\n3 6 5\n0 1", "3 3\n0 3 4\n0 1 2\n2 4 0\n1 3 4"] | 1 second | ["2\n4", "2\n4\n4"] | null | Java 7 | standard input | [
"data structures",
"sortings"
] | 8cbc9e2127c21746dc5341ab07bfee86 | The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 105) — the number of pairs of tourists and the number of built walls. The next m lines contain three space-separated integers li, ri and ti each (0 ≤ li < ri ≤ 109, 0 ≤ ti ≤ 109) — the wall ends and the time it appeared. The last line contains n distinct space-separated strictly increasing integers q1, q2, ..., qn (0 ≤ qi ≤ 109) — the points of time when pairs of tourists walk. All points of time are given in seconds. | 2,600 | For each pair of tourists print on a single line a single integer — the time in seconds when the two tourists from the corresponding pair won't see each other. Print the numbers in the order in which the they go in the input. | standard output | |
PASSED | ab61bf89318d82ef87dc447ad4e38f13 | train_003.jsonl | 1364025600 | A double tourist path, located at a park in Ultima Thule, is working by the following principle: We introduce the Cartesian coordinate system. At some points of time there are two tourists going (for a walk) from points ( - 1, 0) and (1, 0) simultaneously. The first one is walking from ( - 1, 0), the second one is walking from (1, 0). Both tourists in a pair move at the same speed 1 (distance unit per second), the first one moves along line x = - 1, the second one moves along line x = 1, both of them are moving in the positive direction of the Oy axis. At some points of time walls appear. Wall (li, ri) is a segment between points (0, li) and (0, ri). Each wall appears immediately. The Ultima Thule government wants to learn this for each pair of tourists that walk simultaneously: for how long (in seconds) will they not see each other? Two tourists don't see each other if the segment that connects their positions on the plane intersects at least one wall. Two segments intersect if they share at least one point. We assume that the segments' ends belong to the segments.Help the government count the required time. Note that the walls can intersect (in any way) or coincide. | 256 megabytes | import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.TreeMap;
import java.util.ArrayList;
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
* @author sheep
*/
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);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
}
class TaskD {
class Event implements Comparable<Event> {
int at, t;
Event(int at, int t) {
this.at = at;
this.t = t;
}
public int compareTo(Event event) {
if (at != event.at) return at - event.at;
return event.t - t;
}
}
class Query implements Comparable<Query> {
int at, t;
Query(int at, int t) {
this.at = at;
this.t = t;
}
public int compareTo(Query query) {
return t - query.t;
}
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
TreeMap<Integer, Integer> set = new TreeMap<Integer, Integer>();
int m = in.nextInt();
int n = in.nextInt();
int l[] = new int[n],
r[] = new int[n],
t[] = new int[n];
for (int i = 0; i < n; ++i) {
l[i] = in.nextInt();
r[i] = in.nextInt();
t[i] = in.nextInt() + 1;
}
Query q[] = new Query[m];
for (int i = 0; i < m; ++i) {
q[i] = new Query(i, in.nextInt() + 1);
}
Event events[] = new Event[2 * n];
for (int i = 0; i < n; ++i) {
events[2 * i] = new Event(l[i], t[i]);
events[2 * i + 1] = new Event(r[i], -t[i]);
}
Arrays.sort(events);
ArrayList<Integer> left, right, time;
left = new ArrayList<Integer>();
right = new ArrayList<Integer>();
time = new ArrayList<Integer>();
for (int i = 0; i < events.length; ) {
if (i != 0 && events[i - 1].at != events[i].at && set.size() > 0) {
left.add(events[i - 1].at);
right.add(events[i].at);
time.add(set.firstKey());
}
int j = i;
while (j < events.length && events[i].at == events[j].at && Long.signum(events[i].t) == Long.signum(events[j].t)) {
int val = events[j].t, key = Math.abs(val);
int lastTime = 0;
if (set.containsKey(key)) {
lastTime = set.get(key);
set.remove(key);
}
if (val < 0) {
--lastTime;
} else {
++lastTime;
}
if (lastTime != 0) {
set.put(key, lastTime);
}
++j;
}
i = j;
}
Arrays.sort(q);
events = new Event[left.size() * 2];
for (int i = 0; i < left.size(); ++i) {
events[i * 2] = new Event(time.get(i) - left.get(i), -(i + 1));
events[i * 2 + 1] = new Event(time.get(i) - right.get(i), i + 1);
}
int numSegments = 0;
long work = 0, fixed = 0;
Arrays.sort(events);
int ptrEvents = 0;
long ans[] = new long[m];
for (int i = 0; i < q.length; ++i) {
while (ptrEvents < events.length && events[ptrEvents].at <= q[i].t) {
int index = Math.abs(events[ptrEvents].t) - 1;
work += (right.get(index) - time.get(index)) * Long.signum(events[ptrEvents].t);
numSegments += Long.signum(events[ptrEvents].t);
if (events[ptrEvents].t < 0) {
fixed += right.get(index) - left.get(index);
}
++ptrEvents;
}
ans[q[i].at] = work + q[i].t * (long)numSegments + fixed;
}
for (int i = 0; i < m; ++i) {
out.println(ans[i]);
}
}
}
class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream));
tokenizer = null;
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (Exception e) {
throw new UnknownError();
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
| Java | ["2 2\n1 4 3\n3 6 5\n0 1", "3 3\n0 3 4\n0 1 2\n2 4 0\n1 3 4"] | 1 second | ["2\n4", "2\n4\n4"] | null | Java 7 | standard input | [
"data structures",
"sortings"
] | 8cbc9e2127c21746dc5341ab07bfee86 | The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 105) — the number of pairs of tourists and the number of built walls. The next m lines contain three space-separated integers li, ri and ti each (0 ≤ li < ri ≤ 109, 0 ≤ ti ≤ 109) — the wall ends and the time it appeared. The last line contains n distinct space-separated strictly increasing integers q1, q2, ..., qn (0 ≤ qi ≤ 109) — the points of time when pairs of tourists walk. All points of time are given in seconds. | 2,600 | For each pair of tourists print on a single line a single integer — the time in seconds when the two tourists from the corresponding pair won't see each other. Print the numbers in the order in which the they go in the input. | standard output | |
PASSED | e86379a1e7320ac19341c865f2135624 | train_003.jsonl | 1364025600 | A double tourist path, located at a park in Ultima Thule, is working by the following principle: We introduce the Cartesian coordinate system. At some points of time there are two tourists going (for a walk) from points ( - 1, 0) and (1, 0) simultaneously. The first one is walking from ( - 1, 0), the second one is walking from (1, 0). Both tourists in a pair move at the same speed 1 (distance unit per second), the first one moves along line x = - 1, the second one moves along line x = 1, both of them are moving in the positive direction of the Oy axis. At some points of time walls appear. Wall (li, ri) is a segment between points (0, li) and (0, ri). Each wall appears immediately. The Ultima Thule government wants to learn this for each pair of tourists that walk simultaneously: for how long (in seconds) will they not see each other? Two tourists don't see each other if the segment that connects their positions on the plane intersects at least one wall. Two segments intersect if they share at least one point. We assume that the segments' ends belong to the segments.Help the government count the required time. Note that the walls can intersect (in any way) or coincide. | 256 megabytes | import java.io.*;
import java.util.*;
public class D {
public static void main(String[] args) {
new D().run();
}
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 class Event implements Comparable<Event> {
int x, t;
boolean type;
public Event(int x, int t, boolean type) {
this.x = x;
this.t = t;
this.type = type;
}
public int compareTo(Event e) {
return x - e.x;
}
}
public void add(int[] fenv, int l, int r, int add) {
if (fenv.length > l && l >= 0)
fenv[l] += add;
if (fenv.length > r && r >= 0)
fenv[r] -= add;
}
public void solve() throws IOException {
int n = nextInt();
int m = nextInt();
int[] f1 = new int[n];
int[] f2 = new int[n];
Event[] events = new Event[2 * m];
for (int i = 0; i < m; i++) {
int l = nextInt();
int r = nextInt();
int t = nextInt();
events[2 * i] = new Event(l, t, false);
events[2 * i + 1] = new Event(r, t, true);
}
Arrays.sort(events);
int[] q = new int[n];
for (int i = 0; i < n; i++) {
q[i] = nextInt();
}
TreeMap<Integer, Integer> times = new TreeMap<Integer, Integer>();
int s = 0;
int f = 0;
for (Event e : events) {
if (s < e.x && times.size() != 0) {
f = e.x;
int time = times.firstKey();
int l = -1;
int r = n;
while (l < r - 1) {
int mi = (l + r) / 2;
if (time - q[mi] < s) {
r = mi;
} else {
l = mi;
}
}
int right = r;
l = -1;
r = n;
while (l < r - 1) {
int mi = (l + r) / 2;
if (time - q[mi] <= f) {
r = mi;
} else {
l = mi;
}
}
int left = r;
add(f1, left, right, f - time);
add(f1, right, n, f - s);
add(f2, left, right, 1);
}
if (e.type) {
int z = times.get(e.t);
if (z == 1) {
times.remove(e.t);
} else {
times.put(e.t, z - 1);
}
} else {
int z = 1;
if (times.containsKey(e.t)) {
z = times.get(e.t) + 1;
}
times.put(e.t, z);
}
s = e.x;
}
int g1 = 0;
int g2 = 0;
for (int i = 0; i < q.length; i++) {
g1 += f1[i];
g2 += f2[i];
out.println(g1 + g2 * q[i]);
}
}
public void run() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| Java | ["2 2\n1 4 3\n3 6 5\n0 1", "3 3\n0 3 4\n0 1 2\n2 4 0\n1 3 4"] | 1 second | ["2\n4", "2\n4\n4"] | null | Java 7 | standard input | [
"data structures",
"sortings"
] | 8cbc9e2127c21746dc5341ab07bfee86 | The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 105) — the number of pairs of tourists and the number of built walls. The next m lines contain three space-separated integers li, ri and ti each (0 ≤ li < ri ≤ 109, 0 ≤ ti ≤ 109) — the wall ends and the time it appeared. The last line contains n distinct space-separated strictly increasing integers q1, q2, ..., qn (0 ≤ qi ≤ 109) — the points of time when pairs of tourists walk. All points of time are given in seconds. | 2,600 | For each pair of tourists print on a single line a single integer — the time in seconds when the two tourists from the corresponding pair won't see each other. Print the numbers in the order in which the they go in the input. | standard output | |
PASSED | 172272dd6fa9e5fd2ce4b8289aee6f2b | train_003.jsonl | 1364025600 | A double tourist path, located at a park in Ultima Thule, is working by the following principle: We introduce the Cartesian coordinate system. At some points of time there are two tourists going (for a walk) from points ( - 1, 0) and (1, 0) simultaneously. The first one is walking from ( - 1, 0), the second one is walking from (1, 0). Both tourists in a pair move at the same speed 1 (distance unit per second), the first one moves along line x = - 1, the second one moves along line x = 1, both of them are moving in the positive direction of the Oy axis. At some points of time walls appear. Wall (li, ri) is a segment between points (0, li) and (0, ri). Each wall appears immediately. The Ultima Thule government wants to learn this for each pair of tourists that walk simultaneously: for how long (in seconds) will they not see each other? Two tourists don't see each other if the segment that connects their positions on the plane intersects at least one wall. Two segments intersect if they share at least one point. We assume that the segments' ends belong to the segments.Help the government count the required time. Note that the walls can intersect (in any way) or coincide. | 256 megabytes | // 10 monthes remaining for red =D
import java.io.*;
import java.util.*;
public class D {
public static void main(String[] args) {
new D().run();
}
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 class Event implements Comparable<Event> {
int x, t;
boolean type;
public Event(int x, int t, boolean type) {
this.x = x;
this.t = t;
this.type = type;
}
public int compareTo(Event e) {
return x - e.x;
}
}
public void add(int[] fenv, int l, int r, int add) {
if (fenv.length > l && l >= 0)
fenv[l] += add;
if (fenv.length > r && r >= 0)
fenv[r] -= add;
}
public void solve() throws IOException {
int n = nextInt();
int m = nextInt();
int[] f1 = new int[n];
int[] f2 = new int[n];
Event[] events = new Event[2 * m];
for (int i = 0; i < m; i++) {
int l = nextInt();
int r = nextInt();
int t = nextInt();
events[2 * i] = new Event(l, t, false);
events[2 * i + 1] = new Event(r, t, true);
}
Arrays.sort(events);
int[] q = new int[n];
for (int i = 0; i < n; i++) {
q[i] = nextInt();
}
TreeMap<Integer, Integer> times = new TreeMap<Integer, Integer>();
int s = 0;
int f = 0;
for (Event e : events) {
if (s < e.x && times.size() != 0) {
f = e.x;
int time = times.firstKey();
int l = -1;
int r = n;
while (l < r - 1) {
int mi = (l + r) / 2;
if (time - q[mi] < s) {
r = mi;
} else {
l = mi;
}
}
int right = r;
l = -1;
r = n;
while (l < r - 1) {
int mi = (l + r) / 2;
if (time - q[mi] <= f) {
r = mi;
} else {
l = mi;
}
}
int left = r;
add(f1, left, right, f - time);
add(f1, right, n, f - s);
add(f2, left, right, 1);
}
if (e.type) {
int z = times.get(e.t);
if (z == 1) {
times.remove(e.t);
} else {
times.put(e.t, z - 1);
}
} else {
int z = 1;
if (times.containsKey(e.t)) {
z = times.get(e.t) + 1;
}
times.put(e.t, z);
}
s = e.x;
}
int g1 = 0;
int g2 = 0;
for (int i = 0; i < q.length; i++) {
g1 += f1[i];
g2 += f2[i];
out.println(g1 + g2 * q[i]);
}
}
public void run() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| Java | ["2 2\n1 4 3\n3 6 5\n0 1", "3 3\n0 3 4\n0 1 2\n2 4 0\n1 3 4"] | 1 second | ["2\n4", "2\n4\n4"] | null | Java 7 | standard input | [
"data structures",
"sortings"
] | 8cbc9e2127c21746dc5341ab07bfee86 | The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 105) — the number of pairs of tourists and the number of built walls. The next m lines contain three space-separated integers li, ri and ti each (0 ≤ li < ri ≤ 109, 0 ≤ ti ≤ 109) — the wall ends and the time it appeared. The last line contains n distinct space-separated strictly increasing integers q1, q2, ..., qn (0 ≤ qi ≤ 109) — the points of time when pairs of tourists walk. All points of time are given in seconds. | 2,600 | For each pair of tourists print on a single line a single integer — the time in seconds when the two tourists from the corresponding pair won't see each other. Print the numbers in the order in which the they go in the input. | standard output | |
PASSED | b342fa6dc58e743cd41afa48232fff43 | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes | import java.io.*;
import java.lang.Math;
import java.util.Scanner;
public class main
{
public static Scanner in;
public static PrintStream out;
public static double t0;
public static boolean check_line(double x1, double y1, double z1, double x2, double y2, double z2, double xp, double yp, double zp, double vs, double vp)
{
double r = Math.sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1) + (z2-z1)*(z2-z1) ) ;
double tx = (x2-x1) / r;
double ty = (y2-y1) / r;
double tz = (z2-z1) / r;
double a = (1/(vp*vp) - 1/(vs*vs));
double b = (2*tx*(x1-xp)+2*ty*(y1-yp)+2*tz*(z1-zp))/(vp*vp) - 2*t0/vs;
double c = ((x1-xp)*(x1-xp)+(y1-yp)*(y1-yp)+(z1-zp)*(z1-zp))/(vp*vp)-t0*t0;
if (c<=0)
{
out.println("YES");
out.println(t0);
out.print(x1);out.print(' ');out.print(y1);out.print(' ');out.println(z1);
return true;
}
/*
out.print(a);out.print(' ');
out.print(b);out.print(' ');
out.print(c);out.print(' ');
out.println("\n===========");
*/
double d,p;
if (a>-0.0000001)
{
p = - c / b;
}
else
{
d = (b*b - 4*a*c);
p = (-b - Math.sqrt(d)) / 2 / a;
}
/*
out.println(p);
out.print(x1+p*tx);out.print(' ');
out.print(y1+p*ty);out.print(' ');
out.print(z1+p*tz);out.print(' ');
out.println("\n===========");
*/
if ((p>=0)&&(p <= r))
{
out.println("YES");
out.println(t0 + p/vs);
out.print(x1+tx*p);out.print(' ');out.print(y1+ty*p);out.print(' ');out.println(z1+tz*p);
return true;
}
t0 += r / vs;
return false;
}
public static void test()
{
int n = in.nextInt();
int[] x,y,z;
x = new int[n+1];
y = new int[n+1];
z = new int[n+1];
int i;
for (i=0; i<=n; i++)
{
x[i] = in.nextInt();
y[i] = in.nextInt();
z[i] = in.nextInt();
}
int vs,vp;
vp = in.nextInt();
vs = in.nextInt();
int xp,yp,zp;
xp = in.nextInt();
yp = in.nextInt();
zp = in.nextInt();
t0 = 0;
for (i=0; i<n; i++)
{
if (check_line(x[i],y[i],z[i],x[i+1],y[i+1],z[i+1],xp,yp,zp,vs,vp))
{
return;
}
}
out.println("NO");
}
public static void main(String args[])
{
try
{
in = new Scanner(System.in);
//in = new Scanner(new File("in.txt"));
//out = new PrintStream(new File("out.txt"));
out = System.out;
}
catch (Exception e)
{
return;
}
test();
}
}
| Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output | |
PASSED | f752777a85e5142704394732f0306090 | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes | import java.util.*;
public class c60c
{
private final Scanner sc;
private static final boolean debug = true;
static void debug(Object ... objects)
{
if(debug)
System.err.println(Arrays.toString(objects));
}
c60c()
{
sc = new Scanner(System.in);
}
public static void main(String [] args)
{
(new c60c()).solve();
}
double dist(double [] p1, double [] p2)
{
double d = 0.0;
for(int i=0;i<p1.length;i++)
d+=(p1[i]-p2[i])*(p1[i]-p2[i]);
return Math.sqrt(d);
}
void solve()
{
int n = sc.nextInt()+1;
double coords[][] = new double[n][3];
double P[] = new double[3];
for(int i=0;i<n;i++)
for(int j=0;j<3;j++)
coords[i][j] = sc.nextInt();
final int vp = sc.nextInt();
final int vs = sc.nextInt();
for(int j=0;j<3;j++)
P[j] = sc.nextInt();
double prevT = 0;
double ans = -1;
double [] ansCoord = new double[3];
final double eps = 10e-9;
for(int i=0;i<n-1;i++)
{
double dis = dist(coords[i],coords[i+1]);
double maxT = dis/vs;
double pT = dist(coords[i+1],P)/vp;
debug(maxT + " " + (maxT + prevT +eps)+ " " + pT);
if(pT <= maxT + prevT + eps)
{
double minT = 0, mid =0;
double vx[] = new double[3];
double nc[] = new double[3];
for(int j=0;j<3;j++)
vx[j] = vs * (coords[i+1][j]-coords[i][j])/dis;
for(int iter=0;iter<100;iter++)
{
mid = (minT+maxT)/2.0;
for(int j=0;j<3;j++)
nc[j] = coords[i][j] + vx[j]*mid;
debug(mid + " " + dist(nc,P) + " " + ((mid+prevT) * vs + eps));
if(dist(nc,P) > (mid+prevT) * vp - eps)
minT = mid;
else
maxT = mid;
}
System.out.println("YES");
System.out.printf("%.10f\n",mid + prevT);
System.out.printf("%.10f %.10f %.10f\n",nc[0],nc[1],nc[2]);
return;
}
prevT+=maxT;
}
System.out.println("NO");
}
}
| Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output | |
PASSED | a23a71ff8378edab6d7ced033d915f5d | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes | import java.io.PrintWriter;
import java.util.Scanner;
public class C {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int[] x = new int[n + 1];
int[] y = new int[n + 1];
int[] z = new int[n + 1];
for (int i = 0; i <= n; ++i) {
x[i] = in.nextInt();
y[i] = in.nextInt();
z[i] = in.nextInt();
}
int vp = in.nextInt();
int vs = in.nextInt();
int px = in.nextInt();
int py = in.nextInt();
int pz = in.nextInt();
double[] time = new double[n + 1];
time[0] = 0.;
for (int i = 1; i <= n; ++i) {
double dist = 1. * (x[i] - x[i - 1]) * (x[i] - x[i - 1]) + 1. * (y[i] - y[i - 1]) * (y[i] - y[i - 1]) + 1. * (z[i] - z[i - 1]) * (z[i] - z[i - 1]);
dist = Math.sqrt(dist);
time[i] = time[i - 1] + dist / vs;
}
int ans = -1;
for (int i = 0; i <= n; ++i) {
double dist = 1. * (x[i] - px) * (x[i] - px) + 1. * (y[i] - py) * (y[i] - py) + 1. * (z[i] - pz) * (z[i] - pz);
dist = Math.sqrt(dist);
double curTime = dist / vp;
if (curTime - 1e-7 <= time[i]) {
ans = i;
break;
}
}
if (ans == -1) {
out.println("NO");
} else {
out.println("YES");
if (ans == 0) {
out.println(0);
out.print(px);
out.print(" ");
out.print(py);
out.print(" ");
out.println(pz);
} else {
double lox = x[ans - 1], loy = y[ans - 1], loz = z[ans - 1];
double hix = x[ans], hiy = y[ans], hiz = z[ans];
for (int i = 0; i < 100; ++i) {
double midx = (lox + hix) / 2, midy = (loy + hiy) / 2, midz = (loz + hiz) / 2;
double dist = 1. * (midx - px) * (midx - px) + 1. * (midy - py) * (midy - py) + 1. * (midz - pz) * (midz - pz);
dist = Math.sqrt(dist);
double curTime = dist / vp;
double lomTime = time[ans - 1] + (time[ans] - time[ans - 1]) * (midx - x[ans - 1] + midy - y[ans - 1] + midz - z[ans - 1]) / (x[ans] - x[ans - 1] + y[ans] - y[ans - 1] + z[ans] - z[ans - 1]);
if (curTime <= lomTime) {
hix = midx;
hiy = midy;
hiz = midz;
} else {
lox = midx;
loy = midy;
loz = midz;
}
}
double curTime = time[ans - 1] + (time[ans] - time[ans - 1]) * (lox - x[ans - 1] + loy - y[ans - 1] + loz - z[ans - 1]) / (x[ans] - x[ans - 1] + y[ans] - y[ans - 1] + z[ans] - z[ans - 1]);
out.println(curTime);
out.print(lox);
out.print(" ");
out.print(loy);
out.print(" ");
out.println(loz);
}
}
in.close();
out.close();
}
}
| Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output | |
PASSED | 3d3abedb2c2c95ff98e4bfc840368e80 | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Locale;
import java.util.StringTokenizer;
public class TaskC {
BufferedReader br;
PrintWriter out;
StringTokenizer st;
public static void main(String[] args) throws IOException {
new TaskC().run();
}
void run() throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
st = null;
out = new PrintWriter(System.out);
solve();
br.close();
out.close();
}
int x[];
int y[];
int z[];
int vs;
int vp;
void solve() throws IOException {
int n = nextInt() + 1;
x = new int[n];
y = new int[n];
z = new int[n];
for (int i = 0; i < n; ++i) {
x[i] = nextInt();
y[i] = nextInt();
z[i] = nextInt();
}
vp = nextInt();
vs = nextInt();
int sx = nextInt();
int sy = nextInt();
int sz = nextInt();
double t[] = new double[n];
for (int i = 1; i < n; ++i) {
t[i] = t[i - 1] + (dist(i, i - 1) / (double) vs) ;
}
double ans = 2000000000000.0;
boolean ok = false;
double resx = 0, resy = 0, resz = 0;
for (int i = 1; i < n; ++i) {
double lx = x[i - 1];
double ly = y[i - 1];
double lz = z[i - 1];
double rx = x[i];
double ry = y [i];
double rz = z[i];
double d1 = 0, d2 = 0;
double m1x = 0, m1y = 0, m1z = 0, m2x = 0, m2y = 0, m2z = 0;
for (int iter = 0; iter < 120; ++iter) {
m1x = lx + (rx - lx) / 3.0;
m1y = ly + (ry - ly) / 3.0;
m1z = lz + (rz - lz) / 3.0;
m2x = rx - (rx - lx) / 3.0;
m2y = ry - (ry - ly) / 3.0;
m2z = rz - (rz - lz) / 3.0;
d1 = calc(m1x, m1y, m1z, sx, sy, sz, t[i - 1], i - 1, vp, vs);
d2 = calc(m2x, m2y, m2z, sx, sy, sz, t[i - 1], i - 1, vp, vs);
if (d1 < d2) {
rx = m2x;
ry = m2y;
rz = m2z;
} else {
lx = m1x;
ly = m1y;
lz = m1z;
}
}
if (Math.abs(d1) < 1e-10) {
ok = true;
double d = dist(i - 1, m1x , m1y, m1z ) / vs + t[i - 1];
if (ans > d + 1e-10) {
ans = d;
resx = m1x;
resy = m1y;
resz = m1z;
}
}
}
if (!ok) out.print("NO");
else {
out.print("YES" + "\n");
out.printf(Locale.US, "%.10f", ans);
out.print("\n");
out.printf(Locale.US, "%.10f", resx);
out.print(" ");
out.printf(Locale.US, "%.10f", resy);
out.print(" ");
out.printf(Locale.US, "%.10f", resz);
}
}
private double calc(double mx, double my, double mz, double sx, double sy, double sz, double tm, int i, double vp, double vs) {
double t = tm + (dist(i, mx, my, mz)) / vs;
double tp = dist(mx, my, mz, sx, sy, sz) / vp;
return sqr(tp - t);
}
double sqr(double a) {
return a * a;
}
double dist(double x, double y, double z, double X, double Y, double Z) {
return Math.sqrt( sqr(x - X) + sqr(y - Y) + sqr(z - Z));
}
double dist(int i, double X, double Y, double Z) {
return Math.sqrt( sqr(x[i] - X) + sqr(y[i] - Y) + sqr(z[i] - Z));
}
double dist(int i, int j) {
return Math.sqrt( sqr(x[i] - x[j]) + sqr(y[i] - y[j]) + sqr(z[i] - z[j]));
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
} | Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output | |
PASSED | 60888cf239c6a5c507c36d7e3226f193 | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes |
import java.util.*;
import java.math.*;
import static java.lang.Character.isDigit;
import static java.lang.Character.isLowerCase;
import static java.lang.Character.isUpperCase;
import static java.lang.Math.*;
import static java.math.BigInteger.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
import static java.lang.Character.isDigit;
public class Main{
static void debug(Object...os){
System.err.println(deepToString(os));
}
void run(){
n=nextInt();
ps=new P[n+1];
for(int i=0;i<n+1;i++)ps[i]=new P(nextDouble(),nextDouble(),nextDouble());
vp=nextDouble();vs=nextDouble();
potter=new P(nextDouble(),nextDouble(),nextDouble());
double res=solve();
if(res==-1) {
System.out.println("NO");
}else {
System.out.println("YES");
System.out.println(res);
System.out.println(resP.x+" "+resP.y+" "+resP.z);
}
}
class P{
double x,y,z;
P(double x,double y,double z){
this.x=x;this.y=y;this.z=z;
}
double norm() {
return sqrt(x*x+y*y+z*z);
}
double dist(P p) {
return sub(p).norm();
}
P sub(P p) {
return new P(x-p.x,y-p.y,z-p.z);
}
P mul(double d){
return new P(x*d,y*d,z*d);
}
P add(P p){
return new P(x+p.x,y+p.y,z+p.z);
}
}
int n;
P[] ps;
double vs,vp;
P potter;
P resP;
double EPS = 1e-9;
double solve() {
if(vs==0) {
resP=ps[0];
return potter.dist(ps[0])/vp;
}
double[] ts=new double[n+1];
for(int i=0;i<n+1;i++)ts[i] = i==0 ? 0 : ts[i-1] + ps[i-1].dist(ps[i])/vs;
for(int i=1;i<=n;i++) {
double ptTime = potter.dist(ps[i]) / vp;
double D = ts[i]-ts[i-1];
if(ts[i] + EPS > ptTime) {
double left=0,right=D;
double tmpTime = Double.NaN;
for(int o=0;o<100;o++) {
double mid = (left+right)/2;
resP = ps[i-1].add(ps[i].sub(ps[i-1]).mul(mid/D));
double tmpPtTime = potter.dist(resP)/vp;
tmpTime = ts[i-1] + mid;
if(tmpTime < tmpPtTime) {
left = mid;
}
else {
right = mid;
}
}
return tmpTime;
}
}
return -1;
}
int nextInt(){
try{
int c=System.in.read();
if(c==-1) return c;
while(c!='-'&&(c<'0'||'9'<c)){
c=System.in.read();
if(c==-1) return c;
}
if(c=='-') return -nextInt();
int res=0;
do{
res*=10;
res+=c-'0';
c=System.in.read();
}while('0'<=c&&c<='9');
return res;
}catch(Exception e){
return -1;
}
}
long nextLong(){
try{
int c=System.in.read();
if(c==-1) return -1;
while(c!='-'&&(c<'0'||'9'<c)){
c=System.in.read();
if(c==-1) return -1;
}
if(c=='-') return -nextLong();
long res=0;
do{
res*=10;
res+=c-'0';
c=System.in.read();
}while('0'<=c&&c<='9');
return res;
}catch(Exception e){
return -1;
}
}
double nextDouble(){
return Double.parseDouble(next());
}
String next(){
try{
StringBuilder res=new StringBuilder("");
int c=System.in.read();
while(Character.isWhitespace(c))
c=System.in.read();
do{
res.append((char)c);
}while(!Character.isWhitespace(c=System.in.read()));
return res.toString();
}catch(Exception e){
return null;
}
}
String nextLine(){
try{
StringBuilder res=new StringBuilder("");
int c=System.in.read();
while(c=='\r'||c=='\n')
c=System.in.read();
do{
res.append((char)c);
c=System.in.read();
}while(c!='\r'&&c!='\n');
return res.toString();
}catch(Exception e){
return null;
}
}
public static void main(String[] args){
new Main().run();
}
}
| Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output | |
PASSED | 575daf30256bb3fe8c3514a28cc5f753 | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes | import java.io.*;
import java.util.*;
public class C65 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
State[] list = new State[n+1];
for(int i = 0; i <= n; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
list[i] = new State(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()));
}
StringTokenizer st = new StringTokenizer(br.readLine());
int vLarge = Integer.parseInt(st.nextToken());
int vSmall = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
int z = Integer.parseInt(st.nextToken());
State start = new State(x,y,z);
double timeSpent = 0;
for(int i = 1; i <= n; i++) {
double time = dist(list[i-1], list[i]) / vSmall;
double require = dist(start, list[i]);
if(require / vLarge > (timeSpent+time)) {
timeSpent += time;
continue;
}
double min = 0;
double max = time;
for(int q = 0; q < 50; q++) {
double mid = (min+max)/2;
double xx = list[i-1].x + (list[i].x - list[i-1].x) * mid / time;
double yy = list[i-1].y + (list[i].y - list[i-1].y) * mid / time;
double zz = list[i-1].z + (list[i].z - list[i-1].z) * mid / time;
State now = new State(xx,yy,zz);
require = dist(start, now);
if(require / vLarge > (timeSpent + mid))
min = mid;
else
max = mid;
}
System.out.println("YES");
System.out.println(min + timeSpent);
double xx = list[i-1].x + (list[i].x - list[i-1].x) * min / time;
double yy = list[i-1].y + (list[i].y - list[i-1].y) * min / time;
double zz = list[i-1].z + (list[i].z - list[i-1].z) * min / time;
System.out.println(xx + " " + yy + " " + zz);
return;
}
System.out.println("NO");
}
public static double dist(State a, State b) {
double x = a.x-b.x;
double y = a.y-b.y;
double z = a.z-b.z;
return Math.sqrt(x*x+y*y+z*z);
}
static class State {
public double x,y,z;
public State(double a, double b, double c) {
x=a;
y=b;
z=c;
}
}
}
| Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output | |
PASSED | 3d90d1f5138c412ad5b2db2f01a255cc | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes | import java.util.Scanner;
public class C {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[]x = new int[n+1],y = new int[n+1], z = new int[n+1];
for (int i = 0; i <= n; i++) {
x[i] = sc.nextInt();
y[i] = sc.nextInt();
z[i] = sc.nextInt();
}
int vp = sc.nextInt();
int vs = sc.nextInt();
int px = sc.nextInt();
int py = sc.nextInt();
int pz = sc.nextInt();
double path_legnth = 0;
for (int i = 1; i <= n; i++) {
path_legnth += dis(x[i], y[i], z[i], x[i-1], y[i-1], z[i-1]);
}
double dis = dis(px, py, pz, x[n], y[n], z[n]);
if (dis/vp > path_legnth/vs+1e-8) {
System.out.println("NO");
return;
}
double ans = 1e12, x0 = 0, y0 = 0, z0 = 0;
path_legnth = 0;
for (int i = 1; i <= n; i++) {
double xl = x[i-1], yl = y[i-1], zl = z[i-1];
double xr = x[i], yr = y[i], zr = z[i];
for (int step = 1; step <= 80; step++) {
double xm = (xl+xr)/2, ym = (yl+yr)/2, zm = (zl+zr)/2;
if (dis(px, py, pz, xm, ym, zm)/vp < (path_legnth+dis(x[i-1], y[i-1], z[i-1], xm, ym, zm))/vs) {
xr = xm;
yr = ym;
zr = zm;
}
else {
xl = xm;
yl = ym;
zl = zm;
}
}
double t = dis(px, py, pz, xl, yl, zl)/vp;
if (t < (path_legnth+dis(x[i-1], y[i-1], z[i-1], xl, yl, zl))/vs+1e-8 && (path_legnth+dis(x[i-1], y[i-1], z[i-1], xl, yl, zl))/vs < ans) {
ans = (path_legnth+dis(x[i-1], y[i-1], z[i-1], xl, yl, zl))/vs;
x0 = xl;
y0 = yl;
z0 = zl;
}
path_legnth += dis(x[i], y[i], z[i], x[i-1], y[i-1], z[i-1]);
}
System.out.println("YES");
System.out.println(ans);
System.out.println(x0+" "+y0+" "+z0);
}
private static double dis(double x1, double y1, double z1, double x2, double y2, double z2) {
return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)+(z1-z2)*(z1-z2));
}
}
| Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output | |
PASSED | 609b77d43c6f66782f3b4a81a213bd1a | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
public class C65 {
static StreamTokenizer sc;
public static void main(String[] args) throws IOException{
sc = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
int n = nextInt();
int[]x = new int[n+1],y = new int[n+1],z = new int[n+1];
for (int i = 0; i <= n; i++) {
x[i] = nextInt();
y[i] = nextInt();
z[i] = nextInt();
}
int vp = nextInt();
int vs = nextInt();
int x0 = nextInt();
int y0 = nextInt();
int z0 = nextInt();
double min = Integer.MAX_VALUE;
double x1 = 0,y1 = 0,z1 = 0;
double[]d = new double[n+1];
for (int i = 1; i <= n; i++) {
d[i] = d[i-1]+distens(x[i], y[i], z[i], x[i-1], y[i-1], z[i-1]);
}
double xl,xr,yl,yr,zl,zr,xm,ym,zm,t0,tp,ts,eps = 1e-10, eps2 = 1e-12;
for (int i = 0; i < n; i++) {
t0 = d[i] / vs;
xl = x[i];
xr = x[i+1];
yl = y[i];
yr = y[i+1];
zl = z[i];
zr = z[i+1];
while (Math.abs(xr-xl) >= eps2 || Math.abs(yr-yl) >= eps2 || Math.abs(zr-zl) >= eps2) {
xm = (xr+xl) / 2;
ym = (yr+yl) / 2;
zm = (zr+zl) / 2;
tp = distens(x0, y0, z0, xm, ym, zm) / vp;
ts = t0+distens(x[i], y[i], z[i], xm, ym, zm) / vs;
if (Math.abs(tp-ts) < eps) {
if (tp < min) {
min = tp;
x1 = xm;
y1 = ym;
z1 = zm;
}
break;
}
if (tp < ts) {
xr = xm;
yr = ym;
zr = zm;
}
else {
xl = xm;
yl = ym;
zl = zm;
}
}
}
if (min==Integer.MAX_VALUE)
System.out.println("NO");
else {
System.out.println("YES");
System.out.println(min);
System.out.println(x1+" "+y1+" "+z1);
}
}
private static double distens(double x1, double y1, double z1, double x2, double y2, double z2) {
return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)+(z2-z1)*(z2-z1));
}
private static int nextInt() throws IOException{
sc.nextToken();
return (int) sc.nval;
}
}
| Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output | |
PASSED | dbfa60b782a14d6a6f594c0fa436bfb2 | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes | import static java.lang.Math.*;
import static java.util.Arrays.*;
import static java.util.Collections.*;
import java.io.*;
import java.math.*;
import java.util.*;
@SuppressWarnings("unused")
public class HarryPotterandtheGoldenSnitch {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
point[] list = new point[n + 1];
for (int i = 0; i <= n; i++)
list[i] = new point(in.nextInt(), in.nextInt(), in.nextInt());
int vp = in.nextInt();
int vs = in.nextInt();
point p = new point(in.nextInt(), in.nextInt(), in.nextInt());
go(list, vp, vs, p);
}
static void go(point[] list, int vp, int vs, point p) {
double time = 0;
for (int i = 1; i < list.length; i++)
time += list[i - 1].distance(list[i]) / vs;
if (p.distance(list[list.length - 1]) / vp > time) {
System.out.println("NO");
return;
}
double begin = 0;
double end = time;
double mid = 0;
point s = null;
for (int i = 0; i < 100; i++) {
mid = (begin + end) / 2;
s = f(list, mid, vs);
if (p.distance(s) / vp > mid)
begin = mid;
else
end = mid;
}
System.out.println("YES");
System.out.println(mid);
System.out.println(s.x + " " + s.y + " " + s.z);
}
static point f(point[] list, double mid, int vs) {
double time = 0;
for (int i = 1; i < list.length; i++) {
double t = list[i - 1].distance(list[i]) / vs;
time += t;
if (time > mid) {
point a = list[i - 1];
point b = list[i];
point v = a.add(b.multiply(-1));
return b.add(v.multiply((time - mid) / t));
}
}
return list[list.length - 1];
}
static class point {
double x, y, z;
point(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
double distance(point p) {
double dx = x - p.x, dy = y - p.y, dz = z - p.z;
return sqrt(dx * dx + dy * dy + dz * dz);
}
point add(point p) {
return new point(x + p.x, y + p.y, z + p.z);
}
point multiply(double d) {
return new point(x * d, y * d, z * d);
}
}
}
| Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output | |
PASSED | ea41a93093e27ab489b343c29d3f8cc1 | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes |
import java.awt.*;
import java.io.*;
import java.util.*;
import java.awt.geom.*;
public class C {
class Point
{
public double x,y,z;
public Point(double x,double y,double z)
{
this.x=x;
this.y=y;
this.z=z;
}
}
double eps=1e-10;
void solve() throws Exception {
int n=nextInt()+1;
Point[]a=new Point[n];
for(int i=0;i<n;i++)
a[i]=new Point(nextDouble(),nextDouble(),nextDouble());
double vp=nextDouble();
double vs=nextDouble();
Point h=new Point(nextDouble(),nextDouble(),nextDouble());
double have=0;
double minTime=-1;
Point res=new Point(0,0,0);
for(int i=0;i<n-1;i++)
{
double low=0;
double high=Long.MAX_VALUE;
double d=dist(a[i], a[i + 1]);
Point speed=new Point((a[i+1].x-a[i].x)/d*vs,(a[i+1].y-a[i].y)/d*vs,(a[i+1].z-a[i].z)/d*vs);
boolean can=false;
for(int step=0;step<100;step++)
{
double mid=(low+high)/2;
Point other=new Point(a[i].x+speed.x*mid,a[i].y+speed.y*mid,a[i].z+speed.z*mid);
if(dist(other,a[i])>d+eps)
{
high=mid;
}
else
{
double r=vp*(have+mid);
if(contains(h,r,other))
{
high=mid;
can=true;
}
else
{
low=mid;
}
}
}
if(can)
{
minTime=low+have;
res=new Point(a[i].x+speed.x*low,a[i].y+speed.y*low,a[i].z+speed.z*low);
break;
}
have+=d/vs;
}
if(minTime==-1)
{
System.out.println("NO");
}
else
{
System.out.println("YES");
System.out.println(minTime);
System.out.println(res.x+" "+res.y+" "+res.z);
}
}
private boolean contains(Point h,double r,Point a ) {
{
double d1=dist(h,a);
return d1<r+eps;
}
}
double dist(Point a,Point b)
{
return Math.sqrt(Math.pow(a.x-b.x,2)+Math.pow(a.y-b.y,2)+Math.pow(a.z-b.z,2));
}
BufferedReader reader;
PrintWriter writer;
StringTokenizer stk;
void run() throws Exception {
reader = new BufferedReader(new InputStreamReader(System.in));
stk = null;
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
}
int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
String nextString() throws Exception {
return nextToken();
}
String nextLine() throws Exception {
return reader.readLine();
}
String nextToken() throws Exception {
if (stk == null || !stk.hasMoreTokens()) {
stk = new StringTokenizer(nextLine());
return nextToken();
}
return stk.nextToken();
}
public static void main(String[] a) throws Exception {
new C().run();
}
}
| Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output | |
PASSED | f21ad3a931c529baf61aee6c740ad960 | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes |
import java.awt.*;
import java.io.*;
import java.util.*;
import java.awt.geom.*;
public class C {
double eps=1e-14;
void solve() throws Exception {
int n=nextInt()+1;
double[][]p=new double[n][3];
for(int i=0;i<n;i++)
for(int j=0;j<3;j++)
p[i][j]=nextDouble();
double vp=nextDouble();
double vs=nextDouble();
double[]harry=new double[3];
for(int i=0;i<3;i++)
harry[i]=nextDouble();
double minTime=-1;
double[]res=new double[3];
double have=0;
for(int i=1;i<n;i++)
{
double d=dist(p[i],p[i-1]);
double low=0;
double high=d/vs;
double[]v=new double[3];
for(int j=0;j<3;j++)
v[j]=(p[i][j]-p[i-1][j])/d*vs;
for(int step=0;step<100;step++)
{
double mid=(low+high)/2;
double[]cur=new double[3];
for(int j=0;j<3;j++)
cur[j]=p[i-1][j]+v[j]*mid;
double curDist=dist(cur,harry);
double r=(have+mid)*vp;
if(curDist<=r+eps)
{
high=mid;
minTime=mid+have;
res=cur;
}
else
low=mid;
}
if(minTime!=-1)
{
break;
}
have+=d/vs;
}
if(minTime==-1)
System.out.println("NO");
else
{
System.out.println("YES");
System.out.println(minTime);
for(int i=0;i<3;i++)
System.out.print(res[i]+" ");
}
}
private double dist(double[] a, double[] b)
{
double res=0;
for(int i=0;i<3;i++)
res+=Math.pow(a[i]-b[i],2);
return Math.sqrt(res);
}
BufferedReader reader;
PrintWriter writer;
StringTokenizer stk;
void run() throws Exception {
reader = new BufferedReader(new InputStreamReader(System.in));
stk = null;
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
}
int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
String nextString() throws Exception {
return nextToken();
}
String nextLine() throws Exception {
return reader.readLine();
}
String nextToken() throws Exception {
if (stk == null || !stk.hasMoreTokens()) {
stk = new StringTokenizer(nextLine());
return nextToken();
}
return stk.nextToken();
}
public static void main(String[] a) throws Exception {
new C().run();
}
}
| Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output | |
PASSED | 942f0a7cb0e7d7f4eaa99d8c25836c4c | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes |
import java.awt.*;
import java.io.*;
import java.util.*;
import java.awt.geom.*;
public class C {
double eps=1e-8;
void solve() throws Exception {
int n=nextInt()+1;
double[][]p=new double[n][3];
for(int i=0;i<n;i++)
for(int j=0;j<3;j++)
p[i][j]=nextDouble();
double vp=nextDouble();
double vs=nextDouble();
double[]harry=new double[3];
for(int i=0;i<3;i++)
harry[i]=nextDouble();
double minTime=-1;
double[]res=new double[3];
double have=0;
for(int i=1;i<n;i++)
{
double d=dist(p[i],p[i-1]);
double low=0;
double high=d/vs;
double[]v=new double[3];
for(int j=0;j<3;j++)
v[j]=(p[i][j]-p[i-1][j])/d*vs;
for(int step=0;step<100;step++)
{
double mid=(low+high)/2;
double[]cur=new double[3];
for(int j=0;j<3;j++)
cur[j]=p[i-1][j]+v[j]*mid;
double curDist=dist(cur,harry);
double r=(have+mid)*vp;
if(curDist<=r+eps)
{
high=mid;
minTime=mid+have;
res=cur;
}
else
low=mid;
}
if(minTime!=-1)
{
break;
}
have+=d/vs;
}
if(minTime==-1)
System.out.println("NO");
else
{
System.out.println("YES");
System.out.println(minTime);
for(int i=0;i<3;i++)
System.out.print(res[i]+" ");
}
}
private double dist(double[] a, double[] b)
{
double res=0;
for(int i=0;i<3;i++)
res+=Math.pow(a[i]-b[i],2);
return Math.sqrt(res);
}
BufferedReader reader;
PrintWriter writer;
StringTokenizer stk;
void run() throws Exception {
reader = new BufferedReader(new InputStreamReader(System.in));
stk = null;
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
}
int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
String nextString() throws Exception {
return nextToken();
}
String nextLine() throws Exception {
return reader.readLine();
}
String nextToken() throws Exception {
if (stk == null || !stk.hasMoreTokens()) {
stk = new StringTokenizer(nextLine());
return nextToken();
}
return stk.nextToken();
}
public static void main(String[] a) throws Exception {
new C().run();
}
}
| Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output | |
PASSED | cf01c6d0a313f62faf963dfb00b21b51 | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
public class Main
{
static double eps=1e-10;
static BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer stk=new StringTokenizer("");
static int nextInt()throws Exception
{
if(!stk.hasMoreElements())
stk=new StringTokenizer(reader.readLine());
return Integer.parseInt(stk.nextToken()) ;
}
public static void main(String[] arqs)throws Exception
{
//Scanner scan = ne Scanner(System.in);
int n = nextInt();
int[][] points = new int[n+1][3];
double S = 0;
for(int i = 0;i <= n;i++)
{
points[i][0] = nextInt();
points[i][1] = nextInt();
points[i][2] = nextInt();
if(i != 0)
{
S += Math.sqrt((points[i][0]-points[i-1][0])*(points[i][0]-points[i-1][0]) + (points[i][1]-points[i-1][1])*(points[i][1]-points[i-1][1]) + (points[i][2]-points[i-1][2])*(points[i][2]-points[i-1][2]));
}
}
int hisS =nextInt();
int ballS =nextInt();
S /= ballS;
int x = nextInt();
int y = nextInt();
int z = nextInt();
double right = S;
double left = 0.0;
int it=0;
while(it++<100)
{
double mid = (right+left)/2;
if(reaches(mid, points, ballS, hisS, x, y, z))
{
right = mid;
}
else
{
left = mid;
}
}
double res = (right+left)/2;
if(reaches(right, points, ballS, hisS, x, y, z) || reaches(left, points, ballS, hisS, x, y, z))
{
System.out.println("YES");
System.out.println(res);
double[] pS = find(res, points, ballS);
System.out.println(pS[0] + " " + pS[1] + " " + pS[2]);
}
else
{
System.out.println("NO");
}
}
static boolean reaches(double time, int[][] points, int vS, int vP, int x, int y, int z)
{
double[] pos = find(time, points, vS);
return Math.sqrt((x-pos[0])*(x-pos[0]) + (y-pos[1])*(y-pos[1]) + (z-pos[2])*(z-pos[2])) <= time*vP+eps;
}
static double[] find(double time, int[][] points, int vS)
{
double nT = 0;
double x = points[0][0];
double y = points[0][1];
double z = points[0][2];
for(int i = 1;i < points.length;i++)
{
double dis = Math.sqrt((x-points[i][0])*(x-points[i][0]) + (y-points[i][1])*(y-points[i][1]) + (z-points[i][2])*(z-points[i][2]));
if(dis/vS <= time+eps)
{
time -= dis/vS;
x = points[i][0];
y = points[i][1];
z = points[i][2];
}
else
{
double req = dis/vS;
x += (points[i][0] - x)*time/req;
y += (points[i][1] - y)*time/req;
z += (points[i][2] - z)*time/req;
break;
}
}
double[] res = new double[3];
res[0] = x;
res[1] = y;
res[2] = z;
return res;
}
} | Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output | |
PASSED | aa074c134f7887f1bff6f3370926b67f | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
public class Main
{
static double eps=1e-10;
static BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer stk=new StringTokenizer("");
static int nextInt()throws Exception
{
if(!stk.hasMoreElements())
stk=new StringTokenizer(reader.readLine());
return Integer.parseInt(stk.nextToken()) ;
}
public static void main(String[] arqs)throws Exception
{
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[][] points = new int[n+1][3];
double S = 0;
for(int i = 0;i <= n;i++)
{
points[i][0] =scan.nextInt();
points[i][1] =scan.nextInt();
points[i][2] =scan.nextInt();
if(i != 0)
{
S += Math.sqrt((points[i][0]-points[i-1][0])*(points[i][0]-points[i-1][0]) + (points[i][1]-points[i-1][1])*(points[i][1]-points[i-1][1]) + (points[i][2]-points[i-1][2])*(points[i][2]-points[i-1][2]));
}
}
int hisS =scan.nextInt();
int ballS =scan.nextInt();
S /= ballS;
int x = scan.nextInt();
int y = scan.nextInt();
int z = scan.nextInt();
double right = S;
double left = 0.0;
int it=0;
while(it++<100)
{
double mid = (right+left)/2;
if(reaches(mid, points, ballS, hisS, x, y, z))
{
right = mid;
}
else
{
left = mid;
}
}
double res = (right+left)/2;
if(reaches(right, points, ballS, hisS, x, y, z) || reaches(left, points, ballS, hisS, x, y, z))
{
System.out.println("YES");
System.out.println(res);
double[] pS = find(res, points, ballS);
System.out.println(pS[0] + " " + pS[1] + " " + pS[2]);
}
else
{
System.out.println("NO");
}
}
static boolean reaches(double time, int[][] points, int vS, int vP, int x, int y, int z)
{
double[] pos = find(time, points, vS);
return Math.sqrt((x-pos[0])*(x-pos[0]) + (y-pos[1])*(y-pos[1]) + (z-pos[2])*(z-pos[2])) <= time*vP+eps;
}
static double[] find(double time, int[][] points, int vS)
{
double nT = 0;
double x = points[0][0];
double y = points[0][1];
double z = points[0][2];
for(int i = 1;i < points.length;i++)
{
double dis = Math.sqrt((x-points[i][0])*(x-points[i][0]) + (y-points[i][1])*(y-points[i][1]) + (z-points[i][2])*(z-points[i][2]));
if(dis/vS <= time+eps)
{
time -= dis/vS;
x = points[i][0];
y = points[i][1];
z = points[i][2];
}
else
{
double req = dis/vS;
x += (points[i][0] - x)*time/req;
y += (points[i][1] - y)*time/req;
z += (points[i][2] - z)*time/req;
break;
}
}
double[] res = new double[3];
res[0] = x;
res[1] = y;
res[2] = z;
return res;
}
} | Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output | |
PASSED | bdfbdeada01a81df03933866f01f1cb0 | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes |
import java.awt.*;
import java.io.*;
import java.util.*;
import java.awt.geom.*;
public class C {
double eps=1e-10;
void solve() throws Exception {
int n=nextInt()+1;
double[][]p=new double[n][3];
for(int i=0;i<n;i++)
for(int j=0;j<3;j++)
p[i][j]=nextDouble();
double vp=nextDouble();
double vs=nextDouble();
double[]harry=new double[3];
for(int i=0;i<3;i++)
harry[i]=nextDouble();
double minTime=-1;
double[]res=new double[3];
double have=0;
for(int i=1;i<n;i++)
{
double d=dist(p[i],p[i-1]);
double low=0;
double high=d/vs;
double[]v=new double[3];
for(int j=0;j<3;j++)
v[j]=(p[i][j]-p[i-1][j])/d*vs;
for(int step=0;step<100;step++)
{
double mid=(low+high)/2;
double[]cur=new double[3];
for(int j=0;j<3;j++)
cur[j]=p[i-1][j]+v[j]*mid;
double curDist=dist(cur,harry);
double r=(have+mid)*vp;
if(curDist<r+eps)
{
high=mid;
minTime=mid+have;
res=cur;
}
else
low=mid;
}
if(minTime!=-1)
{
break;
}
have+=d/vs;
}
if(minTime==-1)
System.out.println("NO");
else
{
System.out.println("YES");
System.out.println(minTime);
for(int i=0;i<3;i++)
System.out.print(res[i]+" ");
}
}
private double dist(double[] a, double[] b)
{
double res=0;
for(int i=0;i<3;i++)
res+=Math.pow(a[i]-b[i],2);
return Math.sqrt(res);
}
BufferedReader reader;
PrintWriter writer;
StringTokenizer stk;
void run() throws Exception {
reader = new BufferedReader(new InputStreamReader(System.in));
stk = null;
writer = new PrintWriter(System.out);
solve();
reader.close();
writer.close();
}
int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
String nextString() throws Exception {
return nextToken();
}
String nextLine() throws Exception {
return reader.readLine();
}
String nextToken() throws Exception {
if (stk == null || !stk.hasMoreTokens()) {
stk = new StringTokenizer(nextLine());
return nextToken();
}
return stk.nextToken();
}
public static void main(String[] a) throws Exception {
new C().run();
}
}
| Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output | |
PASSED | 9e2b7c27c0b847396591a6b17e5ad5fd | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes | import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
// 15.01.2012 17:56:37
// C65 by Resurgent
public class C65 {
class Point {
double x, y, z;
Point(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
void show() {
printf(x);
print(" ");
printf(y);
print(" ");
printf(z);
println("");
}
}
final double EPS = 10e-12;
private void Solution() throws IOException {
int n = nextInt();
Point[] path = new Point[n + 1];
for (int i = 0; i < n + 1; i++) {
double x = nextDouble(), y = nextDouble(), z = nextDouble();
path[i] = new Point(x, y, z);
}
int vpotter = nextInt(), vball = nextInt();
Point potter = new Point(nextDouble(), nextDouble(), nextDouble());
double time = 0;
for (int i = 0; i < n; i++) {
Point begin = path[i];
Point left = path[i], right = path[i + 1];
int iter = 0;
double piece = length(left, right);
while (iter < 200) {
Point m = new Point((left.x + right.x) / 2,
(left.y + right.y) / 2, (left.z + right.z) / 2);
double l = length(potter, m);
double step = length(begin, m);
double t = l / vpotter, add = step / vball;
if (Math.abs(time + add - t) < EPS) {
println("YES");
printf(t);
println("");
m.show();
return;
} else if (time + add > t) {
right = m;
} else {
left = m;
}
iter++;
}
time += piece / vball;
}
println("NO");
}
double length(Point p1, Point p2) {
return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y)
* (p1.y - p2.y) + (p1.z - p2.z) * (p1.z - p2.z));
}
public static void main(String[] args) {
new C65().run();
}
BufferedReader in;
PrintWriter out;
StringTokenizer tokenizer;
public void run() {
try {
String file = "";
file = "system";
if (file.equals("system")) {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
} else if (file.equals("")) {
in = new BufferedReader(new FileReader(new File("input.txt")));
out = new PrintWriter(new File("output.txt"));
} else {
in = new BufferedReader(new FileReader(new File(file + ".in")));
out = new PrintWriter(new File(file + ".out"));
}
tokenizer = null;
Solution();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
void printf(double n) {
out.printf("%.10f", n);
}
void print(Object... o) {
for (int i = 0; i < o.length; i++) {
if (i != 0)
out.print(" ");
out.print(o[i]);
}
}
void println(Object... o) {
for (int i = 0; i < o.length; i++) {
if (i != 0)
out.print(" ");
out.print(o[i]);
}
out.println();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws NumberFormatException, IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws NumberFormatException, IOException {
return Double.parseDouble(nextToken());
}
String nextToken() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens())
tokenizer = new StringTokenizer(in.readLine());
return tokenizer.nextToken();
}
}
| Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output | |
PASSED | 51c5c6beecc7052b5cc44e1256745170 | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes | import java.lang.*;
import java.math.BigInteger;
import java.io.*;
import java.util.*;
public class Solution implements Runnable{
public static BufferedReader br;
public static PrintWriter out;
public static StringTokenizer stk;
public static boolean isStream = true;
public static void main(String[] args) throws IOException {
if (isStream) {
br = new BufferedReader(new InputStreamReader(System.in));
} else {
br = new BufferedReader(new FileReader("in.txt"));
}
out = new PrintWriter(System.out);
new Thread(new Solution()).start();
}
public void loadLine() {
try {
stk = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
public String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
public String nextWord() {
while (stk==null||!stk.hasMoreTokens()) loadLine();
return stk.nextToken();
}
public Integer nextInt() {
while (stk==null||!stk.hasMoreTokens()) loadLine();
return Integer.valueOf(stk.nextToken());
}
public Long nextLong() {
while (stk==null||!stk.hasMoreTokens()) loadLine();
return Long.valueOf(stk.nextToken());
}
public Double nextDouble() {
while (stk==null||!stk.hasMoreTokens()) loadLine();
return Double.valueOf(stk.nextToken());
}
public Float nextFloat() {
while (stk==null||!stk.hasMoreTokens()) loadLine();
return Float.valueOf(stk.nextToken());
}
double getDist(double x1, double y1, double z1, double x2, double y2, double z2) {
return Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)+(z1-z2)*(z1-z2));
}
double EPS = 1e-12;
public void run() {
int n = nextInt()+1;
double[] xx = new double[n];
double[] yy = new double[n];
double[] zz = new double[n];
for (int i = 0; i < n; i++) {
xx[i] = nextDouble();
yy[i] = nextDouble();
zz[i] = nextDouble();
}
double vh = nextDouble();
double vs = nextDouble();
double px = nextDouble();
double py = nextDouble();
double pz = nextDouble();
double time = 0.0;
double atime = -1.0;
double ax = 0;
double ay = 0;
double az = 0;
boolean f = false;
for (int i = 0; i < n-1; i++) {
double dist = getDist(xx[i], yy[i], zz[i], xx[i+1], yy[i+1], zz[i+1]);
double dist2 = getDist(px, py, pz, xx[i+1], yy[i+1], zz[i+1]);
double ntime = dist/vs;
if (dist2 / vh <= time+ntime+EPS) {
double l = 0.0;
double r = 1.0;
for (int iter = 0; iter < 50; iter++) {
double m = (l+r)/2.0;
double mtime = dist * m / vs;
double nx = xx[i] + (xx[i+1]-xx[i])*m;
double ny = yy[i] + (yy[i+1]-yy[i])*m;
double nz = zz[i] + (zz[i+1]-zz[i])*m;
double mdist = getDist(px, py, pz, nx, ny, nz);
if (mdist / vh <= time+mtime+EPS) {
r = m;
} else {
l = m;
}
}
ax = xx[i] + (xx[i+1]-xx[i])*l;
ay = yy[i] + (yy[i+1]-yy[i])*l;
az = zz[i] + (zz[i+1]-zz[i])*l;
atime = time + dist * l / vs;
f = true;
break;
} else {
time += ntime;
}
}
if (!f) {
out.println("NO");
} else {
out.println("YES");
out.println(atime);
out.print(ax);
out.print(' ');
out.print(ay);
out.print(' ');
out.println(az);
}
out.flush();
}
}
| Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output | |
PASSED | a0fdc6c5698672e392002b8b9e2d265e | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Locale;
import java.util.Queue;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class Solution implements Runnable {
public static void main(String[] args) {
(new Thread(new Solution())).start();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st;
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String r = in.readLine();
if (r == null) return null;
st = new StringTokenizer(r);
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
class Point {
double x, y, z;
Point(double q, double w, double e) {
x = q; y = w; z = e;
}
Point sub(Point b) {
return new Point(x - b.x, y - b.y, z - b.z);
}
Point mul(double a) {
return new Point(x * a, y * a, z * a);
}
double len() {
return Math.sqrt(x * x + y * y + z * z);
}
boolean equals(Point b) {
return x == b.x && y == b.y && z == b.z;
}
}
double vp, vs;
Point zero;
double eps = 1e-10;
boolean ff(Point a, Point b, double time) {
double tmin = 0;
double tmax = b.sub(a).len() / vs;
Point v = b.sub(a).mul(vs / b.sub(a).len());
while (tmax - tmin > eps) {
double t1 = (tmax + 2 * tmin) / 3;
double t2 = (2 * tmax + tmin) / 3;
double f1 = a.sub(zero).sub(v.mul(-t1)).len() - vp * (time + t1);
double f2 = a.sub(zero).sub(v.mul(-t2)).len() - vp * (time + t2);
if (f1 > f2) tmin = t1; else tmax = t2;
}
if (a.sub(zero).sub(v.mul(-tmax)).len() - vp * (time + tmax) > eps) {
return false;
}
tmin = 0;
while (tmax - tmin > eps) {
double t = (tmax + tmin) / 2;
double f = a.sub(zero).sub(v.mul(-t)).len() - vp * (time + t);
if (f < 0) tmax = t; else tmin = t;
}
out.println("YES");
out.printf("%.8f\n", time + tmax);
Point ans = a.sub(v.mul(-tmax));
out.printf("%.8f %.8f %.8f", ans.x, ans.y, ans.z);
return true;
}
void solve() throws Exception {
int n = nextInt();
Point[] a = new Point[n + 1];
a[0] = new Point(nextInt(), nextInt(), nextInt());
for (int i = 1; i <= n; i++) {
a[i] = new Point(nextInt(), nextInt(), nextInt());
}
vp = nextDouble();
vs = nextDouble();
zero = new Point(nextInt(), nextInt(), nextInt());
if (zero.equals(a[0])) {
out.println("YES");
out.println("0");
out.println(zero.x + " " + zero.y + " " + zero.z);
} else {
double time = 0;
for (int i = 0; i < n; i++) {
if (ff(a[i], a[i + 1], time)) return;
time += a[i + 1].sub(a[i]).len() / vs;
}
out.println("NO");
}
}
public void run() {
Locale.setDefault(Locale.UK);
try {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
} finally {
out.flush();
}
}
} | Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output | |
PASSED | d8290ce114a93269f1dfefef940c4481 | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes | import java.io.*;
import java.util.*;
/**
* Codeforces #65C "Harry Potter and the Golden Snitch"
* @link http://codeforces.ru/problemset/problem/65/C
* @author Caesar
*/
public class Solution65C implements Runnable {
private static final int EXIT_CODE = -1;
private StringTokenizer tok;
private BufferedReader in;
private PrintWriter out;
public static void main(String[] args) {
new Thread(new Solution65C()).start();
}
public void run() {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
long start = System.currentTimeMillis();
try {
solve();
} catch (Throwable ex) {
ex.printStackTrace();
System.exit(EXIT_CODE);
} finally {
out.flush();
}
System.err.println("Time used: " + (System.currentTimeMillis() - start));
}
private String readString() throws IOException {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
return tok.nextToken();
}
private int readInt() throws IOException {
return Integer.parseInt(readString());
}
private double distSqr(double x1, double y1, double z1, double x2, double y2, double z2) {
return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) + (z1 - z2) * (z1 - z2);
}
private double dist(double x1, double y1, double z1, double x2, double y2, double z2) {
return Math.sqrt(distSqr(x1, y1, z1, x2, y2, z2));
}
public void solve() throws IOException{
final double eps = 1.0E-9;
int n = readInt() + 1;
double[] x = new double[n];
double[] y = new double[n];
double[] z = new double[n];
for (int i = 0; i < n; ++i) {
x[i] = readInt();
y[i] = readInt();
z[i] = readInt();
}
double vp = readInt();
double vs = readInt();
double xp = readInt();
double yp = readInt();
double zp = readInt();
double t0 = 0.0;
double vp2 = vp * vp;
double vs2 = vs * vs;
double vpvs2 = vp2 - vs2;
for (int i = 1; i < n; ++i) {
double xa = x[i - 1];
double ya = y[i - 1];
double za = z[i - 1];
double xb = x[i];
double yb = y[i];
double zb = z[i];
double rab2 = distSqr(xa, ya, za, xb, yb, zb);
double rap2 = distSqr(xa, ya, za, xp, yp, zp);
double rab = Math.sqrt(rab2);
double rap = Math.sqrt(rap2);
if (rap <= t0 * vp) {
out.println("YES");
out.println(t0);
out.print(xa);
out.print(' ');
out.print(ya);
out.print(' ');
out.println(za);
return;
}
double a = rab2 * vpvs2;
double b = 2.0 * vs * (t0 * rab * vp2 + vs *
((xp - xa) * (xb - xa) + (yp - ya) * (yb - ya) + (zp - za) * (zb - za)));
double c = vs2 * (t0 * t0 * vp2 - rap2);
if (Math.abs(a) < eps) {
double s = -c / b;
if (s >= 0 && s <= 1) {
double xq = xa + s * (xb - xa);
double yq = ya + s * (yb - ya);
double zq = za + s * (zb - za);
out.println("YES");
out.println(dist(xp, yp, zp, xq, yq, zq) / vp);
out.print(xq);
out.print(' ');
out.print(yq);
out.print(' ');
out.println(zq);
return;
}
} else {
double d = b * b - 4.0 * a * c;
if (d >= 0) {
double s1 = (-b - Math.sqrt(d)) / (2.0 * a);
double s2 = (-b + Math.sqrt(d)) / (2.0 * a);
if (s1 > s2) {
double temp = s1;
s1 = s2;
s2 = temp;
}
if (s1 >= 0 && s1 <= 1) {
double xq = xa + s1 * (xb - xa);
double yq = ya + s1 * (yb - ya);
double zq = za + s1 * (zb - za);
out.println("YES");
out.println(dist(xp, yp, zp, xq, yq, zq) / vp);
out.print(xq);
out.print(' ');
out.print(yq);
out.print(' ');
out.println(zq);
return;
}
if (s2 >= 0 && s2 <= 1) {
double xq = xa + s2 * (xb - xa);
double yq = ya + s2 * (yb - ya);
double zq = za + s2 * (zb - za);
out.println("YES");
out.println(dist(xp, yp, zp, xq, yq, zq) / vp);
out.print(xq);
out.print(' ');
out.print(yq);
out.print(' ');
out.println(zq);
return;
}
}
}
t0 += rab / vs;
}
out.println("NO");
}
}
| Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output | |
PASSED | f2bad129de0c64f851f9c2b35d98ef33 | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes | import static java.lang.Math.*;
import static java.lang.System.currentTimeMillis;
import static java.lang.System.exit;
import static java.lang.System.arraycopy;
import static java.util.Arrays.sort;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.fill;
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
try {
if (new File("input.txt").exists())
System.setIn(new FileInputStream("input.txt"));
} catch (SecurityException e) {
}
new Thread(null, new Runnable() {
public void run() {
try {
new Main().run();
} catch (Throwable e) {
e.printStackTrace();
exit(999);
}
}
}, "1", 1 << 23).start();
}
BufferedReader in;
PrintWriter out;
StringTokenizer st = new StringTokenizer("");
double func(P pp){
double rez = (pp.len(left) + len) / vS - pp.len(px,py,pz)/vP;
// out.println("!!!" + pp);
// out.println((pp.len(left) + len) / vS );
// out.println(pp.len(px,py,pz)/vP);
// out.println("rez = "+ abs(rez));
// out.println("-------");
return abs(rez);
}
int px,py,pz;
int vP,vS;
double len = 0;
P left = null;
private void run() throws IOException {
in = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
int n = nextInt();
P p[] = new P[10001];
for (int i = 0; i <= n; i++)
p[i] = new P(nextInt(), nextInt(), nextInt());
vP = nextInt();
vS = nextInt();
px = nextInt();
py = nextInt();
pz = nextInt();
len = 0;
boolean f = false;
int i = 0;
for (; i < n; i++) {
len += p[i].len(p[i + 1]);
if (1e-15 + len * vP >= p[i + 1].len(px, py, pz) * vS) {
f = true;
break;
}
}
if(f) len -= p[i].len(p[i + 1]);
P el = null;
P er = null;
left = p[i];
double eps = 1e-3;
if (px != p[0].x || py != p[0].y || pz != p[0].z)
if (f) {
P r = p[i + 1];
P l = p[i];
while (r.len(l) > 1e-9) {
el = new P((r.x + l.x) / 2 - eps * (r.x-l.x), (r.y + l.y) / 2 - eps * (r.y-l.y), (r.z + l.z) / 2 - eps * (r.z-l.z));
er = new P((r.x + l.x) / 2 + eps * (r.x-l.x), (r.y + l.y) / 2 + eps * (r.y-l.y), (r.z + l.z) / 2 + eps * (r.z-l.z));
if ( func(el) > func(er) ){
l = el;
}
else
r = er;
// out.println(l + " l " + func(l));
// out.println(r + " r " + func(r));
}
out.println("YES");
out.println(((el.len(left) + len) / vS) );
out.println(el.x + " " + el.y + " " + el.z);
} else
out.println("NO");
else {
out.println("YES");
out.println("0");
out.println(px + " " + py + " " + pz);
}
in.close();
out.close();
}
class P {
double x;
double y;
double z;
P(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
double len(double a, double b, double c) {
return sqrt((x - a) * (x - a) + (y - b) * (y - b) + (z - c) * (z - c));
}
double len(P a) {
return sqrt((x - a.x) * (x - a.x) + (y - a.y) * (y - a.y) + (z - a.z) * (z - a.z));
}
public String toString() {
return x + " " + y + " " + z;
}
}
void chk(boolean b) {
if (b)
return;
System.out.println(new Error().getStackTrace()[1]);
exit(999);
}
void deb(String fmt, Object... args) {
System.out.printf(Locale.US, fmt + "%n", args);
}
String nextToken() throws IOException {
while (!st.hasMoreTokens())
st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
long nextLong() throws IOException {
return Long.parseLong(nextToken());
}
double nextDouble() throws IOException {
return Double.parseDouble(nextToken());
}
String nextLine() throws IOException {
st = new StringTokenizer("");
return in.readLine();
}
boolean EOF() throws IOException {
while (!st.hasMoreTokens()) {
String s = in.readLine();
if (s == null)
return true;
st = new StringTokenizer(s);
}
return false;
}
}
| Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output | |
PASSED | 5ceb752dd4b1153f2237a79893ad92a7 | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes | import java.io.*;
import java.lang.*;
import java.util.*;
import java.math.*;
public class Main implements Runnable{
StringTokenizer str;
BufferedReader in;
int nextInt() throws IOException
{
while(!str.hasMoreElements()) str = new StringTokenizer(in.readLine());
return Integer.parseInt(str.nextToken());
}
public void run(){
try{
//BufferedReader in=new BufferedReader(new FileReader(new File("a.in")));
//PrintWriter out = new PrintWriter(new File("a.out"));
Locale.setDefault(Locale.US);
in=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
str = new StringTokenizer(in.readLine());
int n = nextInt();
int[] x=new int[n+1];
int[] y=new int[n+1];
int[] z=new int[n+1];
int x0,y0,z0; int vs,vp;
for(int i=0;i<=n;i++)
{
x[i]=nextInt();
y[i]=nextInt();
z[i]=nextInt();
}
vp=nextInt();
vs=nextInt();
x0=nextInt();
y0=nextInt();
z0=nextInt();
double tmax=0,tmin=0;
double eps=1e-8;
if(x0==x[0] && y0==y[0] && z0==z[0])
{
out.println("YES");
out.println(0);
out.println(x0+" "+y0+" "+z0);
out.close();
System.exit(0);
}
for(int i=0;i<n;i++)
{
double rx=x[i]-x0;
double ry=y[i]-y0;
double rz=z[i]-z0;
double vx=x[i+1]-x[i];
double vy=y[i+1]-y[i];
double vz=z[i+1]-z[i];
double c=rx*vx+ry*vy+rz*vz;
double v=Math.sqrt(vx*vx+vy*vy+vz*vz);
tmin=tmax;
tmax+=v/vs;
c/=v*v;
double nx=rx-vx*c;
double ny=ry-vy*c;
double nz=rz-vz*c;
c*=v;
c-=tmin*vs;
double l=Math.sqrt(nx*nx+ny*ny+nz*nz);
if(vs==vp)
{
double t=-(l*l+c*c)/(2*vs*c);
if(t+eps>0 && t-eps<tmax)
{
out.println("YES");
out.format("%.6f\n",t);
t-=tmin;
out.format("%.6f %.6f %.6f",(x[i]+vx*t*vs/v),(y[i]+vy*t*vs/v),(z[i]+vz*t*vs/v));
out.close();
System.exit(0);
}
}
else
{
double t= ( c*vs+Math.sqrt( c*c*vs*vs+(c*c+l*l)*(vp*vp-vs*vs) ) ) / (vp*vp-vs*vs);
if(t-eps<tmax)
{
out.println("YES");
out.format("%.6f\n",t);
t-=tmin;
out.format("%.6f %.6f %.6f\n", (x[i]+vx*t*vs/v),(y[i]+vy*t*vs/v),(z[i]+vz*t*vs/v));
out.close();
System.exit(0);
}
}
}
out.println("NO");
out.close();
}
catch (IOException e) {}
}
public static void main(String args[]) throws Exception
{
new Thread(new Main()).start();
}
} | Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output | |
PASSED | 5b71eba0382f8749e91a27326bc0f63d | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.InputMismatchException;
import java.util.List;
/**
* @author Egor Kulikov (egor@egork.net)
*/
public class TaskC {
@SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"})
private final InputReader in;
private final PrintWriter out;
private final boolean testMode;
private static final double EPS = 1e-11;
private void solve() {
int pointCount = in.readInt();
int[] x = new int[pointCount + 1];
int[] y = new int[pointCount + 1];
int[] z = new int[pointCount + 1];
in.readIntArrays(x, y, z);
int potterSpeed = in.readInt();
int snitchSpeed = in.readInt();
int potterX = in.readInt();
int potterY = in.readInt();
int potterZ = in.readInt();
double snitchDistance = 0;
for (int i = 1; i <= pointCount; i++) {
double oldSnitchDistance = snitchDistance;
final double edgeLength = Math.hypot(x[i] - x[i - 1], Math.hypot(y[i] - y[i - 1], z[i] - z[i - 1]));
snitchDistance += edgeLength;
double potterDistance = Math.hypot(potterX - x[i], Math.hypot(potterY - y[i], potterZ - z[i]));
if (snitchDistance / snitchSpeed > potterDistance / potterSpeed - EPS) {
out.println("YES");
double addTime = oldSnitchDistance / snitchSpeed;
double leftTime = 0;
double edgeTime = edgeLength / snitchSpeed;
double rightTime = edgeTime;
while (leftTime + EPS < rightTime) {
double currentTime = (leftTime + rightTime) / 2;
double snitchX = x[i - 1] + currentTime / edgeTime * (x[i] - x[i - 1]);
double snitchY = y[i - 1] + currentTime / edgeTime * (y[i] - y[i - 1]);
double snitchZ = z[i - 1] + currentTime / edgeTime * (z[i] - z[i - 1]);
double distance = Math.hypot(potterX - snitchX, Math.hypot(potterY - snitchY, potterZ - snitchZ));
if (currentTime + addTime > distance / potterSpeed - EPS)
rightTime = currentTime;
else
leftTime = currentTime;
}
double currentTime = (leftTime + rightTime) / 2;
out.printf("%.10f\n", currentTime + addTime);
double snitchX = x[i - 1] + currentTime / edgeTime * (x[i] - x[i - 1]);
double snitchY = y[i - 1] + currentTime / edgeTime * (y[i] - y[i - 1]);
double snitchZ = z[i - 1] + currentTime / edgeTime * (z[i] - z[i - 1]);
out.printf("%.10f %.10f %.10f\n", snitchX, snitchY, snitchZ);
return;
}
}
out.println("NO");
}
private static List<Test> createTests() {
List<Test> tests = new ArrayList<Test>();
tests.add(new Test("4\n" +
"0 0 0\n" +
"0 10 0\n" +
"10 10 0\n" +
"10 0 0\n" +
"0 0 0\n" +
"1 1\n" +
"5 5 25", "YES\n" +
"25.5000000000\n" +
"10.0000000000 4.5000000000 0.0000000000"));
tests.add(new Test("4\n" +
"0 0 0\n" +
"0 10 0\n" +
"10 10 0\n" +
"10 0 0\n" +
"0 0 0\n" +
"1 1\n" +
"5 5 50", "NO"));
tests.add(new Test("1\n" +
"1 2 3\n" +
"4 5 6\n" +
"20 10\n" +
"1 2 3", "YES\n" +
"0.0000000000\n" +
"1.0000000000 2.0000000000 3.0000000000"));
// tests.add(new Test("", ""));
// tests.add(new Test("", ""));
// tests.add(new Test("", ""));
// tests.add(new Test("", ""));
// tests.add(new Test("", ""));
// tests.add(new Test("", ""));
// tests.add(new Test("", ""));
return tests;
}
private void run() {
//noinspection InfiniteLoopStatement
// while (true)
// int testCount = in.readInt();
// for (int i = 0; i < testCount; i++)
solve();
exit();
}
private TaskC() {
@SuppressWarnings({"UnusedDeclaration"})
String id = getClass().getName().toLowerCase();
//noinspection EmptyTryBlock
try {
// System.setIn(new FileInputStream(id + ".in"));
// System.setOut(new PrintStream(new FileOutputStream(id + ".out")));
// System.setIn(new FileInputStream("input.txt"));
// System.setOut(new PrintStream(new FileOutputStream("output.txt")));
} catch (Exception e) {
throw new RuntimeException(e);
}
in = new StreamInputReader(System.in);
out = new PrintWriter(System.out);
testMode = false;
}
@SuppressWarnings({"UnusedParameters"})
private static String check(String input, String result, String output) {
return strictCheck(result, output);
// return tokenCheck(result, output);
}
public static void main(String[] args) {
if (args.length != 0 && args[0].equals("42"))
test();
else
new TaskC().run();
}
private static void test() {
List<Test> tests = createTests();
int testCase = 0;
for (Test test : tests) {
System.out.print("Test #" + testCase + ": ");
InputReader in = new StringInputReader(test.getInput());
StringWriter out = new StringWriter(test.getOutput().length());
long time = System.currentTimeMillis();
try {
new TaskC(in, new PrintWriter(out)).run();
} catch (TestException e) {
time = System.currentTimeMillis() - time;
String checkResult = check(test.getInput(), out.getBuffer().toString(), test.getOutput());
if (checkResult == null)
System.out.print("OK");
else
System.out.print("WA (" + checkResult + ")");
System.out.printf(" in %.3f s.\n", time / 1000.);
} catch (Throwable e) {
System.out.println("Exception thrown:");
e.printStackTrace(System.out);
}
testCase++;
}
}
private static String tokenCheck(String result, String output) {
StringInputReader resultStream = new StringInputReader(result);
StringInputReader outputStream = new StringInputReader(output);
int index = 0;
boolean readingResult = false;
try {
while (true) {
readingResult = true;
String resultToken = resultStream.readString();
readingResult = false;
String outputToken = outputStream.readString();
if (!resultToken.equals(outputToken))
return "'" + outputToken + "' expected at " + index + " but '" + resultToken + "' received";
index++;
}
} catch (InputMismatchException e) {
if (readingResult) {
try {
outputStream.readString();
return "only " + index + " tokens received";
} catch (InputMismatchException e1) {
return null;
}
} else
return "only " + index + " tokens expected";
}
}
@SuppressWarnings({"UnusedDeclaration"})
private static String strictCheck(String result, String output) {
if (result.equals(output))
return null;
return "'" + output + "' expected but '" + result + "' received";
}
@SuppressWarnings({"UnusedDeclaration"})
private static boolean isDoubleEquals(double expected, double result, double certainty) {
return Math.abs(expected - result) < certainty || Math.abs(expected - result) < certainty * expected;
}
private TaskC(InputReader in, PrintWriter out) {
this.in = in;
this.out = out;
testMode = true;
}
@SuppressWarnings({"UnusedDeclaration"})
private void exit() {
out.close();
if (testMode)
throw new TestException();
System.exit(0);
}
private static class Test {
private final String input;
private final String output;
private Test(String input, String output) {
this.input = input;
this.output = output;
}
public String getInput() {
return input;
}
public String getOutput() {
return output;
}
}
@SuppressWarnings({"UnusedDeclaration"})
private abstract static class InputReader {
public abstract int read();
public int readInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String readString() {
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;
}
private String readLine0() {
StringBuffer buf = new StringBuffer();
int c = read();
while (c != '\n' && c != -1) {
if (c != '\r')
buf.appendCodePoint(c);
c = read();
}
return buf.toString();
}
public String readLine() {
String s = readLine0();
while (s.trim().length() == 0)
s = readLine0();
return s;
}
public String readLine(boolean ignoreEmptyLines) {
if (ignoreEmptyLines)
return readLine();
else
return readLine0();
}
public BigInteger readBigInteger() {
try {
return new BigInteger(readString());
} catch (NumberFormatException e) {
throw new InputMismatchException();
}
}
public char readCharacter() {
int c = read();
while (isSpaceChar(c))
c = read();
return (char) c;
}
public double readDouble() {
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, readInt());
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, readInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public int[] readIntArray(int size) {
int[] array = new int[size];
for (int i = 0; i < size; i++)
array[i] = readInt();
return array;
}
public long[] readLongArray(int size) {
long[] array = new long[size];
for (int i = 0; i < size; i++)
array[i] = readLong();
return array;
}
public double[] readDoubleArray(int size) {
double[] array = new double[size];
for (int i = 0; i < size; i++)
array[i] = readDouble();
return array;
}
public String[] readStringArray(int size) {
String[] array = new String[size];
for (int i = 0; i < size; i++)
array[i] = readString();
return array;
}
public char[][] readTable(int rowCount, int columnCount) {
char[][] table = new char[rowCount][columnCount];
for (int i = 0; i < rowCount; i++) {
for (int j = 0; j < columnCount; j++)
table[i][j] = readCharacter();
}
return table;
}
public void readIntArrays(int[]... arrays) {
for (int i = 0; i < arrays[0].length; i++) {
for (int j = 0; j < arrays.length; j++)
arrays[j][i] = readInt();
}
}
}
private static class StreamInputReader extends InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar, numChars;
public StreamInputReader(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++];
}
}
private static class StringInputReader extends InputReader {
private Reader stream;
private char[] buf = new char[1024];
private int curChar, numChars;
public StringInputReader(String stream) {
this.stream = new StringReader(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++];
}
}
private static class TestException extends RuntimeException {}
}
| Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output | |
PASSED | 504497c760cbd0afacb8dd22bbaafc9f | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes | /*
* Hello! You are trying to hack my solution, are you? =)
* Don't be afraid of the size, it's just a dump of useful methods like gcd, or n-th Fib number.
* And I'm just too lazy to create a new .java for every task.
* And if you were successful to hack my solution, please, send me this test as a message or to Abrackadabraa@gmail.com.
* It can help me improve my skills and i'd be very grateful for that.
* Sorry for time you spent reading this message. =)
* Good luck, unknown rival. =)
* */
import java.io.*;
import java.math.*;
import java.util.*;
public class Abra {
// double d = 2.2250738585072012e-308;
double d(double[] a, double[] b) {
return Math.sqrt((a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]) + (a[2] - b[2]) * (a[2] - b[2]));
}
void solve() throws IOException {
int n = nextInt() + 1;
double[][] a = new double[n][3];
for (int i = 0; i < n; i++) {
a[i][0] = nextInt() * 1.0;
a[i][1] = nextInt() * 1.0;
a[i][2] = nextInt() * 1.0;
}
double vp = nextInt() * 1.0, vs = nextInt() * 1.0;
double[] p = new double[3];
p[0] = nextInt() * 1.0;
p[1] = nextInt() * 1.0;
p[2] = nextInt() * 1.0;
double tp = 0.0;
for (int i = 1; i < n; i++) {
double dis = d(a[i - 1], a[i]);
double ttp = dis / vs;
double vx = (a[i][0] - a[i - 1][0]) / ttp;
double vy = (a[i][1] - a[i - 1][1]) / ttp;
double vz = (a[i][2] - a[i - 1][2]) / ttp;
double dx = p[0] - a[i - 1][0];
double dy = p[1] - a[i - 1][1];
double dz = p[2] - a[i - 1][2];
double c1 = (vx * vx + vy * vy + vz * vz) * (1 / vs / vs - 1 / vp / vp);
double c2 = 2 * tp * Math.sqrt(vx * vx + vy * vy + vz * vz) / vs + (dx * vx + dy * vy + dz * vz) * 2 / vp / vp;
double c3 = tp * tp - (dx * dx + dy * dy + dz * dz) / vp / vp;
double D = c2 * c2 - 4 * c1 * c3;
double t0 = -1, t1 = -1;
if (c1 == 0) {
t0 = - c3 / c2;
} else
if (D >= 0) {
t0 = (- c2 + Math.sqrt(D)) / 2 / c1;
t1 = (- c2 - Math.sqrt(D)) / 2 / c1;
}
if (t0 < 0) t0 = 1e100;
if (t1 < 0) t1 = 1e100;
t0 = Math.min(t0, t1);
if (t0 <= ttp) {
out.println("YES");
out.println(t0 + tp);
out.println((t0 * vx + a[i - 1][0]) + " " + (t0 * vy + a[i - 1][1]) + " " + (t0 * vz + a[i - 1][2]));
return;
}
tp += ttp;
}
out.println("NO");
}
public static void main(String[] args) throws IOException {
new Abra().run();
}
StreamTokenizer in;
PrintWriter out;
boolean oj;
BufferedReader br;
void init() throws IOException {
oj = System.getProperty("ONLINE_JUDGE") != null;
Reader reader = oj ? new InputStreamReader(System.in) : new FileReader("input.txt");
Writer writer = oj ? new OutputStreamWriter(System.out) : new FileWriter("output.txt");
br = new BufferedReader(reader);
in = new StreamTokenizer(br);
out = new PrintWriter(writer);
}
long beginTime;
void run() throws IOException {
beginTime = System.currentTimeMillis();
long beginMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
init();
solve();
long endMem = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
long endTime = System.currentTimeMillis();
if (!oj) {
System.out.println("Memory used = " + (endMem - beginMem));
System.out.println("Total memory = " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()));
System.out.println("Running time = " + (endTime - beginTime));
}
out.flush();
}
int nextInt() throws IOException {
in.nextToken();
return (int) in.nval;
}
long nextLong() throws IOException {
in.nextToken();
return (long) in.nval;
}
String nextString() throws IOException {
in.nextToken();
return in.sval;
}
double nextDouble() throws IOException {
in.nextToken();
return in.nval;
}
myLib lib = new myLib();
void time() {
System.out.print("It's ");
System.out.println(System.currentTimeMillis() - beginTime);
}
static class myLib {
long fact(long x) {
long a = 1;
for (long i = 2; i <= x; i++) {
a *= i;
}
return a;
}
long digitSum(String x) {
long a = 0;
for (int i = 0; i < x.length(); i++) {
a += x.charAt(i) - '0';
}
return a;
}
long digitSum(long x) {
long a = 0;
while (x > 0) {
a += x % 10;
x /= 10;
}
return a;
}
long digitMul(long x) {
long a = 1;
while (x > 0) {
a *= x % 10;
x /= 10;
}
return a;
}
int digitCubesSum(int x) {
int a = 0;
while (x > 0) {
a += (x % 10) * (x % 10) * (x % 10);
x /= 10;
}
return a;
}
double pif(double ax, double ay, double bx, double by) {
return Math.sqrt((ax - bx) * (ax - bx) + (ay - by) * (ay - by));
}
double pif3D(double ax, double ay, double az, double bx, double by, double bz) {
return Math.sqrt((ax - bx) * (ax - bx) + (ay - by) * (ay - by) + (az - bz) * (az - bz));
}
double pif3D(double[] a, double[] b) {
return Math.sqrt((a[0] - b[0]) * (a[0] - b[0]) + (a[1] - b[1]) * (a[1] - b[1]) + (a[2] - b[2]) * (a[2] - b[2]));
}
long gcd(long a, long b) {
if (a == 0 || b == 0) return 1;
if (a < b) {
long c = b;
b = a;
a = c;
}
while (a % b != 0) {
a = a % b;
if (a < b) {
long c = b;
b = a;
a = c;
}
}
return b;
}
int gcd(int a, int b) {
if (a == 0 || b == 0) return 1;
if (a < b) {
int c = b;
b = a;
a = c;
}
while (a % b != 0) {
a = a % b;
if (a < b) {
int c = b;
b = a;
a = c;
}
}
return b;
}
long lcm(long a, long b) {
return a * b / gcd(a, b);
}
int lcm(int a, int b) {
return a * b / gcd(a, b);
}
int countOccurences(String x, String y) {
int a = 0, i = 0;
while (true) {
i = y.indexOf(x);
if (i == -1) break;
a++;
y = y.substring(i + 1);
}
return a;
}
int[] findPrimes(int x) {
boolean[] forErato = new boolean[x - 1];
List<Integer> t = new Vector<Integer>();
int l = 0, j = 0;
for (int i = 2; i < x; i++) {
if (forErato[i - 2]) continue;
t.add(i);
l++;
j = i * 2;
while (j < x) {
forErato[j - 2] = true;
j += i;
}
}
int[] primes = new int[l];
Iterator<Integer> iterator = t.iterator();
for (int i = 0; iterator.hasNext(); i++) {
primes[i] = iterator.next().intValue();
}
return primes;
}
int rev(int x) {
int a = 0;
while (x > 0) {
a = a * 10 + x % 10;
x /= 10;
}
return a;
}
class myDate {
int d, m, y;
int[] ml = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
public myDate(int da, int ma, int ya) {
d = da;
m = ma;
y = ya;
if ((ma > 12 || ma < 1 || da > ml[ma - 1] || da < 1) && !(d == 29 && m == 2 && y % 4 == 0)) {
d = 1;
m = 1;
y = 9999999;
}
}
void incYear(int x) {
for (int i = 0; i < x; i++) {
y++;
if (m == 2 && d == 29) {
m = 3;
d = 1;
return;
}
if (m == 3 && d == 1) {
if (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)) {
m = 2;
d = 29;
}
return;
}
}
}
boolean less(myDate x) {
if (y < x.y) return true;
if (y > x.y) return false;
if (m < x.m) return true;
if (m > x.m) return false;
if (d < x.d) return true;
if (d > x.d) return false;
return true;
}
void inc() {
if ((d == 31) && (m == 12)) {
y++;
d = 1;
m = 1;
} else {
if (((y % 4 == 0) && (y % 100 != 0)) || (y % 400 == 0)) {
ml[1] = 29;
}
if (d == ml[m - 1]) {
m++;
d = 1;
} else
d++;
}
}
}
int partition(int n, int l, int m) {// n - sum, l - length, m - every
// part
// <= m
if (n < l) return 0;
if (n < l + 2) return 1;
if (l == 1) return 1;
int c = 0;
for (int i = Math.min(n - l + 1, m); i >= (n + l - 1) / l; i--) {
c += partition(n - i, l - 1, i);
}
return c;
}
int rifmQuality(String a, String b) {
if (a.length() > b.length()) {
String c = a;
a = b;
b = c;
}
int c = 0, d = b.length() - a.length();
for (int i = a.length() - 1; i >= 0; i--) {
if (a.charAt(i) == b.charAt(i + d)) c++;
else
break;
}
return c;
}
String numSym = "0123456789ABCDEF";
String ZFromXToYNotation(int x, int y, String z) {
if (z.equals("0")) return "0";
String a = "";
// long q = 0, t = 1;
BigInteger q = BigInteger.ZERO, t = BigInteger.ONE;
for (int i = z.length() - 1; i >= 0; i--) {
q = q.add(t.multiply(BigInteger.valueOf(z.charAt(i) - 48)));
t = t.multiply(BigInteger.valueOf(x));
}
while (q.compareTo(BigInteger.ZERO) == 1) {
a = numSym.charAt((int) (q.mod(BigInteger.valueOf(y)).intValue())) + a;
q = q.divide(BigInteger.valueOf(y));
}
return a;
}
double angleFromXY(int x, int y) {
if ((x == 0) && (y > 0)) return Math.PI / 2;
if ((x == 0) && (y < 0)) return -Math.PI / 2;
if ((y == 0) && (x > 0)) return 0;
if ((y == 0) && (x < 0)) return Math.PI;
if (x > 0) return Math.atan((double) y / x);
else {
if (y > 0) return Math.atan((double) y / x) + Math.PI;
else
return Math.atan((double) y / x) - Math.PI;
}
}
static boolean isNumber(String x) {
try {
Integer.parseInt(x);
} catch (NumberFormatException ex) {
return false;
}
return true;
}
static boolean stringContainsOf(String x, String c) {
for (int i = 0; i < x.length(); i++) {
if (c.indexOf(x.charAt(i)) == -1) return false;
}
return true;
}
long pow(long a, long n) { // b > 0
if (n == 0) return 1;
long k = n, b = 1, c = a;
while (k != 0) {
if (k % 2 == 0) {
k /= 2;
c *= c;
} else {
k--;
b *= c;
}
}
return b;
}
int pow(int a, int n) { // b > 0
if (n == 0) return 1;
int k = n, b = 1, c = a;
while (k != 0) {
if (k % 2 == 0) {
k /= 2;
c *= c;
} else {
k--;
b *= c;
}
}
return b;
}
double pow(double a, int n) { // b > 0
if (n == 0) return 1;
double k = n, b = 1, c = a;
while (k != 0) {
if (k % 2 == 0) {
k /= 2;
c *= c;
} else {
k--;
b *= c;
}
}
return b;
}
double log2(double x) {
return Math.log(x) / Math.log(2);
}
int lpd(int[] primes, int x) {// least prime divisor
int i;
for (i = 0; primes[i] <= x / 2; i++) {
if (x % primes[i] == 0) {
return primes[i];
}
}
;
return x;
}
int np(int[] primes, int x) {// number of prime number
for (int i = 0; true; i++) {
if (primes[i] == x) return i;
}
}
int[] dijkstra(int[][] map, int n, int s) {
int[] p = new int[n];
boolean[] b = new boolean[n];
Arrays.fill(p, Integer.MAX_VALUE);
p[s] = 0;
b[s] = true;
for (int i = 0; i < n; i++) {
if (i != s) p[i] = map[s][i];
}
while (true) {
int m = Integer.MAX_VALUE, mi = -1;
for (int i = 0; i < n; i++) {
if (!b[i] && (p[i] < m)) {
mi = i;
m = p[i];
}
}
if (mi == -1) break;
b[mi] = true;
for (int i = 0; i < n; i++)
if (p[mi] + map[mi][i] < p[i]) p[i] = p[mi] + map[mi][i];
}
return p;
}
boolean isLatinChar(char x) {
if (((x >= 'a') && (x <= 'z')) || ((x >= 'A') && (x <= 'Z'))) return true;
else
return false;
}
boolean isBigLatinChar(char x) {
if (x >= 'A' && x <= 'Z') return true;
else
return false;
}
boolean isSmallLatinChar(char x) {
if (x >= 'a' && x <= 'z') return true;
else
return false;
}
boolean isDigitChar(char x) {
if (x >= '0' && x <= '9') return true;
else
return false;
}
class NotANumberException extends Exception {
private static final long serialVersionUID = 1L;
String mistake;
NotANumberException() {
mistake = "Unknown.";
}
NotANumberException(String message) {
mistake = message;
}
}
class Real {
String num = "0";
long exp = 0;
boolean pos = true;
long length() {
return num.length();
}
void check(String x) throws NotANumberException {
if (!stringContainsOf(x, "0123456789+-.eE")) throw new NotANumberException("Illegal character.");
long j = 0;
for (long i = 0; i < x.length(); i++) {
if ((x.charAt((int) i) == '-') || (x.charAt((int) i) == '+')) {
if (j == 0) j = 1;
else
if (j == 5) j = 6;
else
throw new NotANumberException("Unexpected sign.");
} else
if ("0123456789".indexOf(x.charAt((int) i)) != -1) {
if (j == 0) j = 2;
else
if (j == 1) j = 2;
else
if (j == 2)
;
else
if (j == 3) j = 4;
else
if (j == 4)
;
else
if (j == 5) j = 6;
else
if (j == 6)
;
else
throw new NotANumberException("Unexpected digit.");
} else
if (x.charAt((int) i) == '.') {
if (j == 0) j = 3;
else
if (j == 1) j = 3;
else
if (j == 2) j = 3;
else
throw new NotANumberException("Unexpected dot.");
} else
if ((x.charAt((int) i) == 'e') || (x.charAt((int) i) == 'E')) {
if (j == 2) j = 5;
else
if (j == 4) j = 5;
else
throw new NotANumberException("Unexpected exponent.");
} else
throw new NotANumberException("O_o.");
}
if ((j == 0) || (j == 1) || (j == 3) || (j == 5)) throw new NotANumberException("Unexpected end.");
}
public Real(String x) throws NotANumberException {
check(x);
if (x.charAt(0) == '-') pos = false;
long j = 0;
String e = "";
boolean epos = true;
for (long i = 0; i < x.length(); i++) {
if ("0123456789".indexOf(x.charAt((int) i)) != -1) {
if (j == 0) num += x.charAt((int) i);
if (j == 1) {
num += x.charAt((int) i);
exp--;
}
if (j == 2) e += x.charAt((int) i);
}
if (x.charAt((int) i) == '.') {
if (j == 0) j = 1;
}
if ((x.charAt((int) i) == 'e') || (x.charAt((int) i) == 'E')) {
j = 2;
if (x.charAt((int) (i + 1)) == '-') epos = false;
}
}
while ((num.length() > 1) && (num.charAt(0) == '0'))
num = num.substring(1);
while ((num.length() > 1) && (num.charAt(num.length() - 1) == '0')) {
num = num.substring(0, num.length() - 1);
exp++;
}
if (num.equals("0")) {
exp = 0;
pos = true;
return;
}
while ((e.length() > 1) && (e.charAt(0) == '0'))
e = e.substring(1);
try {
if (e != "") if (epos) exp += Long.parseLong(e);
else
exp -= Long.parseLong(e);
} catch (NumberFormatException exc) {
if (!epos) {
num = "0";
exp = 0;
pos = true;
} else {
throw new NotANumberException("Too long exponent");
}
}
}
public Real() {
}
String toString(long mantissa) {
String a = "", b = "";
if (exp >= 0) {
a = num;
if (!pos) a = '-' + a;
for (long i = 0; i < exp; i++)
a += '0';
for (long i = 0; i < mantissa; i++)
b += '0';
if (mantissa == 0) return a;
else
return a + "." + b;
} else {
if (exp + length() <= 0) {
a = "0";
if (mantissa == 0) {
return a;
}
if (mantissa < -(exp + length() - 1)) {
for (long i = 0; i < mantissa; i++)
b += '0';
return a + "." + b;
} else {
if (!pos) a = '-' + a;
for (long i = 0; i < mantissa; i++)
if (i < -(exp + length())) b += '0';
else
if (i + exp >= 0) b += '0';
else
b += num.charAt((int) (i + exp + length()));
return a + "." + b;
}
} else {
if (!pos) a = "-";
for (long i = 0; i < exp + length(); i++)
a += num.charAt((int) i);
if (mantissa == 0) return a;
for (long i = exp + length(); i < exp + length() + mantissa; i++)
if (i < length()) b += num.charAt((int) i);
else
b += '0';
return a + "." + b;
}
}
}
}
boolean containsRepeats(int... num) {
Set<Integer> s = new TreeSet<Integer>();
for (int d : num)
if (!s.contains(d)) s.add(d);
else
return true;
return false;
}
int[] rotateDice(int[] a, int n) {
int[] c = new int[6];
if (n == 0) {
c[0] = a[1];
c[1] = a[5];
c[2] = a[2];
c[3] = a[0];
c[4] = a[4];
c[5] = a[3];
}
if (n == 1) {
c[0] = a[2];
c[1] = a[1];
c[2] = a[5];
c[3] = a[3];
c[4] = a[0];
c[5] = a[4];
}
if (n == 2) {
c[0] = a[3];
c[1] = a[0];
c[2] = a[2];
c[3] = a[5];
c[4] = a[4];
c[5] = a[1];
}
if (n == 3) {
c[0] = a[4];
c[1] = a[1];
c[2] = a[0];
c[3] = a[3];
c[4] = a[5];
c[5] = a[2];
}
if (n == 4) {
c[0] = a[0];
c[1] = a[2];
c[2] = a[3];
c[3] = a[4];
c[4] = a[1];
c[5] = a[5];
}
if (n == 5) {
c[0] = a[0];
c[1] = a[4];
c[2] = a[1];
c[3] = a[2];
c[4] = a[3];
c[5] = a[5];
}
return c;
}
int min(int... a) {
int c = Integer.MAX_VALUE;
for (int d : a)
if (d < c) c = d;
return c;
}
int max(int... a) {
int c = Integer.MIN_VALUE;
for (int d : a)
if (d > c) c = d;
return c;
}
int pos(int x) {
if (x > 0) return x;
else
return 0;
}
long pos(long x) {
if (x > 0) return x;
else
return 0;
}
double maxD(double... a) {
double c = Double.MIN_VALUE;
for (double d : a)
if (d > c) c = d;
return c;
}
double minD(double... a) {
double c = Double.MAX_VALUE;
for (double d : a)
if (d < c) c = d;
return c;
}
int[] normalizeDice(int[] a) {
int[] c = a.clone();
if (c[0] != 0) if (c[1] == 0) c = rotateDice(c, 0);
else
if (c[2] == 0) c = rotateDice(c, 1);
else
if (c[3] == 0) c = rotateDice(c, 2);
else
if (c[4] == 0) c = rotateDice(c, 3);
else
if (c[5] == 0) c = rotateDice(rotateDice(c, 0), 0);
while (c[1] != min(c[1], c[2], c[3], c[4]))
c = rotateDice(c, 4);
return c;
}
boolean sameDice(int[] a, int[] b) {
for (int i = 0; i < 6; i++)
if (a[i] != b[i]) return false;
return true;
}
final double goldenRatio = (1 + Math.sqrt(5)) / 2;
final double aGoldenRatio = (1 - Math.sqrt(5)) / 2;
long Fib(int n) {
if (n < 0) if (n % 2 == 0) return -Math.round((pow(goldenRatio, -n) - pow(aGoldenRatio, -n)) / Math.sqrt(5));
else
return -Math.round((pow(goldenRatio, -n) - pow(aGoldenRatio, -n)) / Math.sqrt(5));
return Math.round((pow(goldenRatio, n) - pow(aGoldenRatio, n)) / Math.sqrt(5));
}
class japaneeseComparator implements Comparator<String> {
@Override
public int compare(String a, String b) {
int ai = 0, bi = 0;
boolean m = false, ns = false;
if (a.charAt(ai) <= '9' && a.charAt(ai) >= '0') {
if (b.charAt(bi) <= '9' && b.charAt(bi) >= '0') m = true;
else
return -1;
}
if (b.charAt(bi) <= '9' && b.charAt(bi) >= '0') {
if (a.charAt(ai) <= '9' && a.charAt(ai) >= '0') m = true;
else
return 1;
}
a += "!";
b += "!";
int na = 0, nb = 0;
while (true) {
if (a.charAt(ai) == '!') {
if (b.charAt(bi) == '!') break;
return -1;
}
if (b.charAt(bi) == '!') {
return 1;
}
if (m) {
int ab = -1, bb = -1;
while (a.charAt(ai) <= '9' && a.charAt(ai) >= '0') {
if (ab == -1) ab = ai;
ai++;
}
while (b.charAt(bi) <= '9' && b.charAt(bi) >= '0') {
if (bb == -1) bb = bi;
bi++;
}
m = !m;
if (ab == -1) {
if (bb == -1) continue;
else
return 1;
}
if (bb == -1) return -1;
while (a.charAt(ab) == '0' && ab + 1 != ai) {
ab++;
if (!ns) na++;
}
while (b.charAt(bb) == '0' && bb + 1 != bi) {
bb++;
if (!ns) nb++;
}
if (na != nb) ns = true;
if (ai - ab < bi - bb) return -1;
if (ai - ab > bi - bb) return 1;
for (int i = 0; i < ai - ab; i++) {
if (a.charAt(ab + i) < b.charAt(bb + i)) return -1;
if (a.charAt(ab + i) > b.charAt(bb + i)) return 1;
}
} else {
m = !m;
while (true) {
if (a.charAt(ai) <= 'z' && a.charAt(ai) >= 'a' && b.charAt(bi) <= 'z' && b.charAt(bi) >= 'a') {
if (a.charAt(ai) < b.charAt(bi)) return -1;
if (a.charAt(ai) > b.charAt(bi)) return 1;
ai++;
bi++;
} else
if (a.charAt(ai) <= 'z' && a.charAt(ai) >= 'a') return 1;
else
if (b.charAt(bi) <= 'z' && b.charAt(bi) >= 'a') return -1;
else
break;
}
}
}
if (na < nb) return 1;
if (na > nb) return -1;
return 0;
}
}
Random random = new Random();
}
void readIntArray(int[] a) throws IOException {
for (int i = 0; i < a.length; i++)
a[i] = nextInt();
}
String readChars(int l) throws IOException {
String r = "";
for (int i = 0; i < l; i++)
r += (char) br.read();
return r;
}
class myFraction {
long num = 0, den = 1;
void reduce() {
long d = lib.gcd(num, den);
num /= d;
den /= d;
}
myFraction(long ch, long zn) {
num = ch;
den = zn;
reduce();
}
myFraction add(myFraction t) {
long nd = lib.lcm(den, t.den);
myFraction r = new myFraction(nd / den * num + nd / t.den * t.num, nd);
r.reduce();
return r;
}
public String toString() {
return num + "/" + den;
}
}
class myPoint {
myPoint(int a, int b) {
x = a;
y = b;
}
int x, y;
boolean equals(myPoint a) {
if (x == a.x && y == a.y) return true;
else
return false;
}
public String toString() {
return x + ":" + y;
}
}
/*
* class cubeWithLetters { String consts = "ЧКТФЭЦ"; char[][] letters = { {
* 'А', 'Б', 'Г', 'В' }, { 'Д', 'Е', 'З', 'Ж' }, { 'И', 'Л', 'Н', 'М' }, {
* 'О', 'П', 'С', 'Р' }, { 'У', 'Х', 'Щ', 'Ш' }, { 'Ы', 'Ь', 'Я', 'Ю' } };
*
* char get(char x) { if (consts.indexOf(x) != -1) return x; for (int i = 0;
* i < 7; i++) { for (int j = 0; j < 4; j++) { if (letters[i][j] == x) { if
* (j == 0) return letters[i][3]; else return letters[i][j - 1]; } } }
* return '!'; }
*
* void subrotate(int x) { char t = letters[x][0]; letters[x][0] =
* letters[x][3]; letters[x][3] = letters[x][2]; letters[x][2] =
* letters[x][1]; letters[x][1] = t; }
*
* void rotate(int x) { subrotate(x); char t; if (x == 0) { t =
* letters[1][0]; letters[1][0] = letters[2][0]; letters[2][0] =
* letters[3][0]; letters[3][0] = letters[5][2]; letters[5][2] = t;
*
* t = letters[1][1]; letters[1][1] = letters[2][1]; letters[2][1] =
* letters[3][1]; letters[3][1] = letters[5][3]; letters[5][3] = t; } if (x
* == 1) { t = letters[2][0]; letters[2][0] = letters[0][0]; letters[0][0] =
* letters[5][0]; letters[5][0] = letters[4][0]; letters[4][0] = t;
*
* t = letters[2][3]; letters[2][3] = letters[0][3]; letters[0][3] =
* letters[5][3]; letters[5][3] = letters[4][3]; letters[4][3] = t; } if (x
* == 2) { t = letters[0][3]; letters[0][3] = letters[1][2]; letters[1][2] =
* letters[4][1]; letters[4][1] = letters[3][0]; letters[3][0] = t;
*
* t = letters[0][2]; letters[0][2] = letters[1][1]; letters[1][1] =
* letters[4][0]; letters[4][0] = letters[3][3]; letters[3][3] = t; } if (x
* == 3) { t = letters[2][1]; letters[2][1] = letters[4][1]; letters[4][1] =
* letters[5][1]; letters[5][1] = letters[0][1]; letters[0][1] = t;
*
* t = letters[2][2]; letters[2][2] = letters[4][2]; letters[4][2] =
* letters[5][2]; letters[5][2] = letters[0][2]; letters[0][2] = t; } if (x
* == 4) { t = letters[2][3]; letters[2][3] = letters[1][3]; letters[1][3] =
* letters[5][1]; letters[5][1] = letters[3][3]; letters[3][3] = t;
*
* t = letters[2][2]; letters[2][2] = letters[1][2]; letters[1][2] =
* letters[5][0]; letters[5][0] = letters[3][2]; letters[3][2] = t; } if (x
* == 5) { t = letters[4][3]; letters[4][3] = letters[1][0]; letters[1][0] =
* letters[0][1]; letters[0][1] = letters[3][2]; letters[3][2] = t;
*
* t = letters[4][2]; letters[4][2] = letters[1][3]; letters[1][3] =
* letters[0][0]; letters[0][0] = letters[3][1]; letters[3][1] = t; } }
*
* public String toString(){ return " " + letters[0][0] + letters[0][1] +
* "\n" + " " + letters[0][3] + letters[0][2] + "\n" + letters[1][0] +
* letters[1][1] + letters[2][0] + letters[2][1] + letters[3][0] +
* letters[3][1] + "\n" + letters[1][3] + letters[1][2] + letters[2][3] +
* letters[2][2] + letters[3][3] + letters[3][2] + "\n" + " " +
* letters[4][0] + letters[4][1] + "\n" + " " + letters[4][3] +
* letters[4][2] + "\n" + " " + letters[5][0] + letters[5][1] + "\n" + " "
* + letters[5][3] + letters[5][2] + "\n"; } }
*
*
* Vector<Integer>[] a; int n, mc, c1, c2; int[] col;
*
* void wave(int x, int p) { for (Iterator<Integer> i = a[x].iterator();
* i.hasNext(); ) { int t = i.next(); if (t == x || t == p) continue; if
* (col[t] == 0) { col[t] = mc; wave(t, x); } else { c1 = x; c2 = t; } } }
*
* void solve() throws IOException {
*
* String s = "ЕПОЕЬРИТСГХЖЗТЯПСТАПДСБИСТЧК"; //String s =
* "ЗЬУОЫТВЗТЯПУБОЫТЕАЫШХЯАТЧК"; cubeWithLetters cube = new
* cubeWithLetters(); for (int x = 0; x < 4; x++) { for (int y = x + 1; y <
* 5; y++) { for (int z = y + 1; z < 6; z++) { cube = new cubeWithLetters();
* out.println(cube.toString()); cube.rotate(x);
* out.println(cube.toString()); cube.rotate(y);
* out.println(cube.toString()); cube.rotate(z);
* out.println(cube.toString()); out.print(x + " " + y + " " + z + " = ");
* for (int i = 0; i < s.length(); i++) { out.print(cube.get(s.charAt(i)));
* } out.println(); } } }
*
* int a = nextInt(), b = nextInt(), x = nextInt(), y = nextInt();
* out.print((lib.min(a / (x / lib.gcd(x, y)), b / (y / lib.gcd(x, y))) * (x
* / lib.gcd(x, y))) + " " + (lib.min(a / (x / lib.gcd(x, y)), b / (y /
* lib.gcd(x, y))) * (y / lib.gcd(x, y)))); }
*/
} | Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output | |
PASSED | dab2e264091c313e820caa0d3d405ffd | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class Main implements Runnable {
final double eps = 1e-8;
double dist(double x1, double y1, double z1, double x2, double y2, double z2) {
return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)
+ (z1 - z2) * (z1 - z2));
}
private void solve() throws IOException {
int n = nextInt();
double prex, prey, prez;
double[] x = new double[n + 1];
double[] y = new double[n + 1];
double[] z = new double[n + 1];
x[0] = nextDouble();
y[0] = nextDouble();
z[0] = nextDouble();
for (int i = 1; i <= n; ++i) {
x[i] = nextDouble();
y[i] = nextDouble();
z[i] = nextDouble();
}
double vp = nextDouble();
double vs = nextDouble();
double px = nextDouble();
double py = nextDouble();
double pz = nextDouble();
double preTime = 0;
double curTime = 0;
int i;
for (i = 1; i <= n; ++i) {
curTime = preTime + dist(x[i], y[i], z[i], x[i - 1], y[i - 1], z[i - 1])
/ vs;
double pTime = dist(x[i], y[i], z[i], px, py, pz) / vp;
if (pTime < curTime + eps) {
break;
}
preTime = curTime;
}
if (i == n + 1) {
out.println("NO");
} else {
out.println("YES");
double l = 0;
double r = 1;
double vx = x[i] - x[i - 1];
double vy = y[i] - y[i - 1];
double vz = z[i] - z[i - 1];
double dt = curTime - preTime;
double ts = 0;
--i;
for (int iiii = 0; iiii < 3000; ++iiii) {
double m = (r + l) / 2;
double dp = dist(x[i] + vx * m, y[i] + vy * m, z[i] + vz *m, px, py, pz);
double tp = dp / vp;
ts = preTime + dt * m;
if (tp < ts) {
r = m;
} else {
l = m;
}
}
out.println(ts);
out.print((x[i] + vx * l) + " " + (y[i] + vy * l) + " " + (z[i] + vz * l));
}
}
/**
* @param args
*/
public static void main(String[] args) {
new Thread(new Main()).start();
}
private BufferedReader br;
private StringTokenizer st;
private PrintWriter out;
@Override
public void run() {
try {
Locale.setDefault(Locale.US);
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer("");
out = new PrintWriter(System.out);
solve();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
String next() throws IOException {
while (!st.hasMoreTokens()) {
String temp = br.readLine();
if (temp == null) {
return null;
}
st = new StringTokenizer(temp);
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
}
| Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output | |
PASSED | d6db9276c0c016732e2f3a6914709fce | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
public class C
{
static double dist(double[] a, double[] b)
{
double sum = 0;
for (int j = 0; j < 3; ++j)
{
double dx = a[j] - b[j];
sum += dx*dx;
}
return Math.sqrt(sum);
}
public static void main(String[] args) throws Exception
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(in.readLine().trim());
double[][] ps = new double[N+1][3];
for (int i = 0; i < N+1; ++i)
{
String[] toks = in.readLine().trim().split("\\s+");
for (int j = 0; j < 3; ++j) ps[i][j] = Double.parseDouble(toks[j]);
}
String[] toks = in.readLine().trim().split("\\s+");
int vp = Integer.parseInt(toks[0]), vs = Integer.parseInt(toks[1]);
double[] harry = new double[3];
toks = in.readLine().trim().split("\\s+");
for (int i = 0; i < 3; ++i) harry[i] = Double.parseDouble(toks[i]);
double dist = 0;
for (int i = 1; i < N+1; ++i)
{
dist += dist(ps[i-1],ps[i]);
}
double R = dist/vs, L = 0;
if (dist(harry, ps[N])/vp > R + 1e-9)
{
System.out.println("NO");
return;
}
double[] midp = new double[3];
for (int X = 0; X < 200; ++X)
{
double M = (R+L)/2;
double far = M*vs;
int i = 1;
double sum = 0;
while (true)
{
if (i >= ps.length) break;
double d = dist(ps[i],ps[i-1]);
if (sum + d > far) break;
sum += d;
++i;
}
if (i >= ps.length)
{
R = M;
continue;
}
double frac = (far-sum)/dist(ps[i],ps[i-1]);
for (int j = 0; j < 3; ++j) midp[j] = ps[i-1][j] + frac*(ps[i][j] - ps[i-1][j]);
if (dist(midp,harry)/vp > M) L = M;
else R = M;
}
System.out.println("YES");
System.out.println(R);
for (int i = 0; i < 3; ++i)
{
if (i > 0) System.out.print(" ");
System.out.print(midp[i]);
}
System.out.println();
}
}
| Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output | |
PASSED | 5a1832b4c398d1cfcab7cddc2cebfcdb | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
import static java.lang.Math.*;
public class Main implements Runnable {
int[] x,y,z;
int vp, vs;
int px, py, pz;
double btw(double x1, double y1, double z1, double x2, double y2, double z2) {
double dx = x1 - x2;
double dy = y1 - y2;
double dz = z1 - z2;
double ret = Math.sqrt(dx * dx + dy * dy + dz * dz);
return ret;
}
public void solve() throws IOException {
int n = nextInt() + 1;
x = new int[n];
y = new int[n];
z = new int[n];
for(int i = 0; i < n; ++i) {
x[i] = nextInt(); y[i] = nextInt(); z[i] = nextInt();
}
vp = nextInt();
vs = nextInt();
px = nextInt(); py = nextInt(); pz = nextInt();
double sDist = 0;
for(int i = 0; i < n; ++i) {
double pDist = btw(px, py, pz, x[i], y[i], z[i]);
if (pDist * vs < sDist * vp + 1e-8) {
// from (i - 1) to i
int l = Math.max(i - 1, 0);
int r = i;
sDist -= btw(x[l], y[l], z[l], x[r], y[r], z[r]);
double ld = 0, rd = 1;
for(int j = 0; j < 100; ++j) {
double cd = (ld + rd) / 2;
double X = x[l] + (x[r] - x[l]) * cd;
double Y = y[l] + (y[r] - y[l]) * cd;
double Z = z[l] + (z[r] - z[l]) * cd;
double sDist2 = sDist + btw(x[l], y[l], z[l], X, Y, Z);
double pDist2 = btw(px, py, pz, X, Y, Z);
if (pDist2 * vs < sDist2 * vp) {
rd = cd;
} else {
ld = cd;
}
if (j + 1 == 100) {
pw.printf("YES\n%1.8f\n%1.8f %1.8f %1.8f\n", sDist2 / vs, X, Y, Z);
return;
}
}
}
if (i + 1 < n)
sDist += btw(x[i], y[i], z[i], x[i + 1], y[i + 1], z[i + 1]);
}
pw.println("NO");
}
static final String filename = "A";
static final boolean fromConsole = true;
public void run() {
try {
if (!fromConsole) {
in = new BufferedReader(new FileReader(filename + ".in"));
pw = new PrintWriter(filename + ".out");
} else {
in = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(System.out);
}
st = new StringTokenizer("");
long st = System.currentTimeMillis();
solve();
//pw.printf("\nWorking time: %d ms\n", System.currentTimeMillis() - st);
pw.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
private StringTokenizer st;
private BufferedReader in;
private PrintWriter pw;
boolean hasNext() throws IOException {
while (!st.hasMoreTokens()) {
String line = in.readLine();
if (line == null) {
return false;
}
st = new StringTokenizer(line);
}
return st.hasMoreTokens();
}
String next() throws IOException {
return hasNext() ? st.nextToken() : null;
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
BigInteger nextBigInteger() throws IOException {
return new BigInteger(next());
}
long nextLong() throws IOException {
return Long.parseLong(next());
}
double nextDouble() throws IOException {
return Double.parseDouble(next());
}
public static void main(String[] args) {
new Thread(new Main()).start();
}
} | Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output | |
PASSED | 6eba3688b86dc4bb35783a9689f960b8 | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class HarryPotterandtheGoldenSnitch {
static class Scanner{
BufferedReader br=null;
StringTokenizer tk=null;
public Scanner(){
br=new BufferedReader(new InputStreamReader(System.in));
}
public String next() throws IOException{
while(tk==null || !tk.hasMoreTokens())
tk=new StringTokenizer(br.readLine());
return tk.nextToken();
}
public int nextInt() throws NumberFormatException, IOException{
return Integer.valueOf(next());
}
public double nextDouble() throws NumberFormatException, IOException{
return Double.valueOf(next());
}
}
static class point{
double x,y,z;
double t;
public point(double xx,double yy,double zz){
x = xx;
y = yy;
z = zz;
t = 0;
}
double norm(){
return Math.sqrt(x*x + y*y + z*z);
}
point sub(point o){
return new point(x - o.x, y - o.y, z - o.z);
}
point add(point o){
return new point(x + o.x, y + o.y, z + o.z);
}
point multbyscalar(double a){
return new point(a*x,a*y,a*z);
}
point normalize(){
return this.multbyscalar(1.0 / this.norm());
}
}
static double inittime(){
double t = 0;
for(int i = 0; i < N; i++){
polyline[i].t = t;
t += polyline[i + 1].sub(polyline[i]).norm() / vs;
}
polyline[N].t = t;
return t;
}
static point[] polyline;
static double vp,vs;
static int N;
static point potter;
static boolean test(double t){
point p = getpos(t);
double alcanzado = potter.sub(p).norm() / vp;
return (alcanzado < t + eps);
}
static double eps = 1e-12;
static point getpos(double t){
int index = 0;
while(polyline[index + 1].t < t - eps)
index++;
t = t - polyline[index].t;
point vector = polyline[index + 1].sub(polyline[index]).normalize();
vector = vector.multbyscalar(vs);
return vector.multbyscalar(t).add(polyline[index]);
}
public static void main(String args[]) throws NumberFormatException, IOException{
Scanner sc = new Scanner();
N = sc.nextInt();
polyline = new point[N + 1];
for(int i = 0; i <= N; i++)
polyline[i] = new point(sc.nextDouble(),sc.nextDouble(),sc.nextDouble());
vp = sc.nextDouble();
vs = sc.nextDouble();
potter = new point(sc.nextDouble(),sc.nextDouble(),sc.nextDouble());
double last = inittime();
if (!test(last)){
System.out.println("NO");
return;
}
double low = 0.0;
double high = last ;
while(Math.abs(high - low) > 1e-10){
double mid = (low + high) / 2.0;
if (test(mid))
high = mid;
else
low = mid;
}
double time = (high + low)/2.0;
System.out.println("YES");
System.out.println(time);
point p = getpos(time);
System.out.println(p.x+" "+p.y+" "+p.z);
}
}
| Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output | |
PASSED | a05a884523af0602177a69e9c009fd9b | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class HarryPotterandtheGoldenSnitch {
static class Scanner{
BufferedReader br=null;
StringTokenizer tk=null;
public Scanner(){
br=new BufferedReader(new InputStreamReader(System.in));
}
public String next() throws IOException{
while(tk==null || !tk.hasMoreTokens())
tk=new StringTokenizer(br.readLine());
return tk.nextToken();
}
public int nextInt() throws NumberFormatException, IOException{
return Integer.valueOf(next());
}
public double nextDouble() throws NumberFormatException, IOException{
return Double.valueOf(next());
}
}
static class point{
double x,y,z;
double t;
public point(double xx,double yy,double zz){
x = xx;
y = yy;
z = zz;
t = 0;
}
double norm(){
return Math.sqrt(x*x + y*y + z*z);
}
point sub(point o){
return new point(x - o.x, y - o.y, z - o.z);
}
point add(point o){
return new point(x + o.x, y + o.y, z + o.z);
}
point multbyscalar(double a){
return new point(a*x,a*y,a*z);
}
point normalize(){
return this.multbyscalar(1.0 / this.norm());
}
}
static double inittime(){
double t = 0;
for(int i = 0; i < N; i++){
polyline[i].t = t;
t += polyline[i + 1].sub(polyline[i]).norm() / vs;
}
polyline[N].t = t;
return t;
}
static point[] polyline;
static double vp,vs;
static int N;
static point potter;
static boolean test(double t){
point p = getpos(t);
double alcanzado = potter.sub(p).norm() / vp;
return (alcanzado < t + eps);
}
static double eps = 1e-12;
static point getpos(double t){
int index = 0;
while(polyline[index + 1].t < t - eps)
index++;
t = t - polyline[index].t;
point vector = polyline[index + 1].sub(polyline[index]).normalize();
vector = vector.multbyscalar(vs);
return vector.multbyscalar(t).add(polyline[index]);
}
public static void main(String args[]) throws NumberFormatException, IOException{
Scanner sc = new Scanner();
N = sc.nextInt();
polyline = new point[N + 1];
for(int i = 0; i <= N; i++)
polyline[i] = new point(sc.nextDouble(),sc.nextDouble(),sc.nextDouble());
vp = sc.nextDouble();
vs = sc.nextDouble();
potter = new point(sc.nextDouble(),sc.nextDouble(),sc.nextDouble());
double last = inittime();
if (!test(last)){
System.out.println("NO");
return;
}
double low = 0.0;
double high = last ;
while(Math.abs(high - low) > 1e-12){
double mid = (low + high) / 2.0;
if (mid == low || mid == high)
break;
if (test(mid))
high = mid;
else
low = mid;
}
double time = (high + low)/2.0;
System.out.println("YES");
System.out.println(time);
point p = getpos(time);
System.out.println(p.x+" "+p.y+" "+p.z);
}
}
| Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output | |
PASSED | 7b1c4baa2d26cc99a2b53e523871cc81 | train_003.jsonl | 1299340800 | Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at the points (x0, y0, z0), (x1, y1, z1), ..., (xn, yn, zn). At the beginning of the game the snitch is positioned at the point (x0, y0, z0), and then moves along the polyline at the constant speed vs. The twins have not yet found out how the snitch behaves then. Nevertheless, they hope that the retrieved information will help Harry Potter and his team in the upcoming match against Slytherin. Harry Potter learned that at the beginning the game he will be at the point (Px, Py, Pz) and his super fast Nimbus 2011 broom allows him to move at the constant speed vp in any direction or remain idle. vp is not less than the speed of the snitch vs. Harry Potter, of course, wants to catch the snitch as soon as possible. Or, if catching the snitch while it is moving along the polyline is impossible, he wants to hurry the Weasley brothers with their experiments. Harry Potter catches the snitch at the time when they are at the same point. Help Harry. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.*;
public class C implements Runnable {
static class Point {
double x;
double y;
double z;
public Point(int x, int y, int z) {
super();
this.x = x;
this.y = y;
this.z = z;
}
public Point(double x, double y, double z) {
super();
this.x = x;
this.y = y;
this.z = z;
}
Point mul(double d) {
return new Point(x * d, y * d, z * d);
}
Point add(Point p) {
return new Point(x + p.x, y + p.y, z + p.z);
}
double dist(Point p) {
double dx = x - p.x;
double dy = y - p.y;
double dz = z - p.z;
return Math.sqrt(dx * dx + dy * dy + dz * dz);
}
Point subtract(Point p) {
return new Point(x - p.x, y - p.y, z - p.z);
}
double abs() {
return Math.sqrt(x * x + y * y + z * z);
}
Point setLength(double d) {
double e = abs() / d;
return new Point(x / e, y / e, z / e);
}
@Override
public String toString() {
return x + " " + y + " " + z;
}
}
void solve() {
int n = nextInt();
Point[] p = new Point[n + 1];
for (int i = 0; i < p.length; i++) {
p[i] = new Point(nextInt(), nextInt(), nextInt());
}
double vp = nextDouble();
double vs = nextDouble();
Point harry = new Point(nextDouble(), nextDouble(), nextDouble());
double sum = 0;
for (int i = 0; i < n; i++) {
sum += p[i].dist(p[i + 1]);
}
double l = 0;
double r = sum;
double m = (l + r) * .5;
while (l != m && r != m) {
Point q = getPoint(p, m);
double len = harry.dist(q);
if (len * vs <= m * vp) {
r = m;
} else {
l = m;
}
m = (l + r) * .5;
}
double len = harry.dist(getPoint(p, l));
if (compare(len * vs, m * vp) > 0) {
out.println("NO");
return;
}
out.println("YES");
out.println(l / vs);
out.println(getPoint(p, l));
}
static int compare(double a, double b) {
final double EPS = 1e-6;
return Math.abs(a - b) < EPS ? 0 : Double.compare(a, b);
}
static Point getPoint(Point[] p, double m) {
int n = p.length - 1;
double left = m;
Point q = null;
for (int i = 0; i < n; i++) {
if (left >= p[i].dist(p[i + 1])) {
left -= p[i].dist(p[i + 1]);
} else {
q = p[i].add(p[i + 1].subtract(p[i]).setLength(left));
break;
}
}
if (q == null) {
q = p[n + 1];
}
return q;
}
FastScanner sc;
PrintWriter out;
public void run() {
Locale.setDefault(Locale.US);
try {
sc = new FastScanner(System.in);
out = new PrintWriter(System.out);
solve();
sc.close();
out.close();
} catch (Throwable e) {
e.printStackTrace();
System.exit(1);
}
}
int nextInt() {
return sc.nextInt();
}
String nextToken() {
return sc.nextToken();
}
long nextLong() {
return sc.nextLong();
}
double nextDouble() {
return sc.nextDouble();
}
BigInteger nextBigInteger() {
return sc.nextBigInteger();
}
class FastScanner extends BufferedReader {
StringTokenizer st;
boolean eof;
String buf;
String curLine;
boolean createST;
public FastScanner(String fileName) throws FileNotFoundException {
this(fileName, true);
}
public FastScanner(String fileName, boolean createST)
throws FileNotFoundException {
super(new FileReader(fileName));
this.createST = createST;
nextToken();
}
public FastScanner(InputStream stream) {
this(stream, true);
}
public FastScanner(InputStream stream, boolean createST) {
super(new InputStreamReader(stream));
this.createST = createST;
nextToken();
}
String nextLine() {
String ret = curLine;
if (createST) {
st = null;
}
nextToken();
return ret;
}
String nextToken() {
if (!createST) {
try {
curLine = readLine();
} catch (Exception e) {
eof = true;
}
return null;
}
while (st == null || !st.hasMoreTokens()) {
try {
curLine = readLine();
st = new StringTokenizer(curLine);
} catch (Exception e) {
eof = true;
break;
}
}
String ret = buf;
buf = eof ? "-1" : st.nextToken();
return ret;
}
int nextInt() {
return Integer.parseInt(nextToken());
}
long nextLong() {
return Long.parseLong(nextToken());
}
double nextDouble() {
return Double.parseDouble(nextToken());
}
BigInteger nextBigInteger() {
return new BigInteger(nextToken());
}
public void close() {
try {
buf = null;
st = null;
curLine = null;
super.close();
} catch (Exception e) {
}
}
boolean isEOF() {
return eof;
}
}
public static void main(String[] args) {
new C().run();
}
} | Java | ["4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 25", "4\n0 0 0\n0 10 0\n10 10 0\n10 0 0\n0 0 0\n1 1\n5 5 50", "1\n1 2 3\n4 5 6\n20 10\n1 2 3"] | 2 seconds | ["YES\n25.5000000000\n10.0000000000 4.5000000000 0.0000000000", "NO", "YES\n0.0000000000\n1.0000000000 2.0000000000 3.0000000000"] | null | Java 6 | standard input | [
"binary search",
"geometry"
] | 6e2a8aa58ed8cd308cb482e4c24cbbbb | The first line contains a single integer n (1 ≤ n ≤ 10000). The following n + 1 lines contain the coordinates xi, yi, zi, separated by single spaces. The coordinates of any two consecutive points do not coincide. The next line contains the velocities vp and vs, the last line contains Px, Py, Pz, separated by single spaces. All the numbers in the input are integers, their absolute value does not exceed 104. The speeds are strictly positive. It is guaranteed that vs ≤ vp. | 2,100 | If Harry Potter can catch the snitch while it is moving along the polyline (including the end (xn, yn, zn)), print "YES" in the first line (without the quotes). Print in the second line t, which is the earliest moment of time, when Harry will be able to catch the snitch. On the third line print three numbers X, Y, Z, the coordinates of the point at which this happens. The absolute or relative error in the answer should not exceed 10 - 6. If Harry is not able to catch the snitch during its moving along the described polyline, print "NO". | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.