exec_outcome
stringclasses 1
value | code_uid
stringlengths 32
32
| file_name
stringclasses 111
values | prob_desc_created_at
stringlengths 10
10
| prob_desc_description
stringlengths 63
3.8k
| prob_desc_memory_limit
stringclasses 18
values | source_code
stringlengths 117
65.5k
| lang_cluster
stringclasses 1
value | prob_desc_sample_inputs
stringlengths 2
802
| prob_desc_time_limit
stringclasses 27
values | prob_desc_sample_outputs
stringlengths 2
796
| prob_desc_notes
stringlengths 4
3k
β | lang
stringclasses 5
values | prob_desc_input_from
stringclasses 3
values | tags
sequencelengths 0
11
| src_uid
stringlengths 32
32
| prob_desc_input_spec
stringlengths 28
2.37k
β | difficulty
int64 -1
3.5k
β | prob_desc_output_spec
stringlengths 17
1.47k
β | prob_desc_output_to
stringclasses 3
values | hidden_unit_tests
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PASSED | 6b9eb17ea034a898a7bb9163fbd50614 | train_000.jsonl | 1468514100 | Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2iβ+β1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). | 256 megabytes |
import java.util.*;
public class Nyc {
static Long swap(Long a, Long b) {
return a;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
HashMap<Long, Long> map = new HashMap<Long, Long>();
int q = sc.nextInt();
while (q-- > 0) {
int opt = sc.nextInt();
long u = sc.nextLong();
long v = sc.nextLong();
if (opt == 1) {
long w = sc.nextLong();
while (u != v) {
if (v > u) u = swap(v, v = u);
if (map.containsKey(u)) map.put(u, map.get(u) + w);
else map.put(u, w);
u /= 2;
}
} else {
long tcost = 0;
while (u != v) {
if (v > u) {
u = swap(v, v = u);
}
if (map.containsKey(u)) tcost += map.get(u);
u /= 2;
}
System.out.println(tcost);
}
}
}
} | Java | ["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"] | 1 second | ["94\n0\n32"] | NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32β+β32β+β30β=β94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). | Java 8 | standard input | [
"data structures",
"implementation",
"trees",
"brute force"
] | 12814033bec4956e7561767a6778d77e | The first line of input contains a single integer q (1ββ€βqββ€β1β000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1ββ€βv,βuββ€β1018,βvββ βu,β1ββ€βwββ€β109 states for every description line. | 1,500 | For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. | standard output | |
PASSED | fdd77debcfd64fb4c6249ec513bb638f | train_000.jsonl | 1468514100 | Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2iβ+β1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). | 256 megabytes |
import java.util.*;
public class Nyc {
static Long swap(Long a, Long b) {
return a;
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
HashMap<Long, Long> map = new HashMap<>();
int q = sc.nextInt();
while (q-- > 0) {
int opt = sc.nextInt();
long u = sc.nextLong();
long v = sc.nextLong();
if (opt == 1) {
long w = sc.nextLong();
while (u != v) {
if (v > u) u = swap(v, v = u);
if (map.containsKey(u)) map.compute(u, (key, val) -> val + w);
else map.put(u, w);
u /= 2;
}
} else {
long wayCost = 0;
while (u != v) {
if (v > u) u = swap(v, v = u);
if (map.containsKey(u)) wayCost += map.get(u);
u /= 2;
}
System.out.println(wayCost);
}
}
}
} | Java | ["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"] | 1 second | ["94\n0\n32"] | NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32β+β32β+β30β=β94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). | Java 8 | standard input | [
"data structures",
"implementation",
"trees",
"brute force"
] | 12814033bec4956e7561767a6778d77e | The first line of input contains a single integer q (1ββ€βqββ€β1β000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1ββ€βv,βuββ€β1018,βvββ βu,β1ββ€βwββ€β109 states for every description line. | 1,500 | For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. | standard output | |
PASSED | 7ab7d8119053db9c2cc4fd77b933661a | train_000.jsonl | 1468514100 | Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2iβ+β1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). | 256 megabytes | /**
* Created by Bakytzhan_Manaspayev on 8/2/2016.
*/
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.*;
public class Div2_697C {
//7
//1 3 4 30
//1 4 1 2
//1 3 6 8
//2 4 3
//1 6 1 40
//2 3 7
//2 2 4
//94
//0
//32
static Exception exception;
private static Scanner in;
private static Output out;
static boolean isFile = false;
public static void main(String[] args) throws Exception {
assert 1!=1;
Thread thread = new Thread(null, new Runnable() {
@Override
public void run() {
try {
initReaderWriter();
operate();
out.close();
} catch (Exception ex) {
exception = ex;
}
}
}, "", 1 << 26);
thread.start();
thread.join();
if (exception != null) {
throw exception;
}
}
static Long swap(long a, long b) {
return a;
}
private static void operate() throws IOException {
assert 5==6;
int n = in.nextInt();
HashMap<Long, Long> w = new HashMap();
for (int i = 0; i < n; i++) {
int type = in.nextInt();
long a = in.nextLong(), b = in.nextLong();
//add route data
if (type == 1) {
long c = in.nextLong();
while (a != b) {
a = swap(Math.max(a, b), b = Math.min(a, b));
w.compute(a, (key, val) -> val == null ? c : c + val);
a /= 2;
}
}
//print result
if (type == 2) {
long sum = 0;
while (a != b) {
a = swap(Math.max(a, b), b = Math.min(a, b));
sum += w.getOrDefault(a, 0L);
a /= 2;
}
out.println(sum);
}
}
}
private static void initReaderWriter() throws Exception {
if (isFile) {
in = new Scanner("input.txt");
out = new Output(new File("output.txt"));
} else {
in = new Scanner();
out = new Output(System.out);
}
}
private static boolean log = false;
public static void log(String msg) {
if (log) {
out.println(msg);
out.flush();
}
}
private static class Scanner {
StringTokenizer st = null;
BufferedReader bf;
public Scanner() {
bf = new BufferedReader(new InputStreamReader(System.in));
}
public Scanner(String fileName) throws FileNotFoundException {
bf = new BufferedReader(new FileReader(fileName));
}
public String next() throws IOException {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(bf.readLine());
return st.nextToken();
}
public String nextLine() throws IOException {
return bf.readLine();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public long nextLong() throws IOException {
return Long.parseLong(next());
}
public double nextDouble() throws IOException {
return Double.parseDouble(next());
}
}
private static class Output extends PrintStream {
public Output(OutputStream out) {
super(new BufferedOutputStream(out));
}
public Output(File file) throws FileNotFoundException {
super(new BufferedOutputStream(new FileOutputStream(file)));
}
}
private static void printMemory() {
Runtime runtime = Runtime.getRuntime();
long maxMemory = runtime.maxMemory();
long allocatedMemory = runtime.totalMemory();
long freeMemory = runtime.freeMemory();
long div = 1L * 1024 * 1024;
// long div = 1L ;
System.out.println("used memory[mgb]: " + (runtime.totalMemory() - runtime.freeMemory()) / div);
System.out.println();
}
static long appCurrentTime = System.currentTimeMillis();
static long appCurrentTimeNano = System.nanoTime();
private static void printCurrentTime() {
out.flush();
System.out.println("Time: " + (System.currentTimeMillis() - appCurrentTime));
System.out.println("Time Nano: " + (System.nanoTime() - appCurrentTimeNano));
}
} | Java | ["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"] | 1 second | ["94\n0\n32"] | NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32β+β32β+β30β=β94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). | Java 8 | standard input | [
"data structures",
"implementation",
"trees",
"brute force"
] | 12814033bec4956e7561767a6778d77e | The first line of input contains a single integer q (1ββ€βqββ€β1β000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1ββ€βv,βuββ€β1018,βvββ βu,β1ββ€βwββ€β109 states for every description line. | 1,500 | For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. | standard output | |
PASSED | 2824bf0627667aa4ccb22b00f3f2619a | train_000.jsonl | 1468514100 | Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2iβ+β1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). | 256 megabytes | import java.util.*;
public class C {
static HashMap<Long,Long> hm;
public static void main(String[] args) {
Scanner qwe = new Scanner(System.in);
hm = new HashMap<Long,Long>();
int q = qwe.nextInt();
while(q-->0){
int t = qwe.nextInt();
long v = qwe.nextLong();
long u = qwe.nextLong();
if(t == 1){
long w = qwe.nextInt();
while(v != u){
if(v > u) u = u^v^(v=u);
if(!hm.containsKey(u)){
hm.put(u, 0l);
}
hm.put(u, hm.get(u)+w);
u = u/2;
}
}
else{
long ans =0;
while(v != u){
if(v > u) u = u^v^(v=u);
if(!hm.containsKey(u)){
hm.put(u, 0l);
}
ans += hm.get(u);
u = u/2;
}
System.out.println(ans);
}
}
qwe.close();
}
}
| Java | ["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"] | 1 second | ["94\n0\n32"] | NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32β+β32β+β30β=β94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). | Java 8 | standard input | [
"data structures",
"implementation",
"trees",
"brute force"
] | 12814033bec4956e7561767a6778d77e | The first line of input contains a single integer q (1ββ€βqββ€β1β000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1ββ€βv,βuββ€β1018,βvββ βu,β1ββ€βwββ€β109 states for every description line. | 1,500 | For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. | standard output | |
PASSED | e6f41fbf8dd20348826e560b1707a66b | train_000.jsonl | 1468514100 | Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2iβ+β1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). | 256 megabytes | import javafx.util.Pair;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main
{
private String line;
private int index;
public long height(long x)
{
int nr = 0;
while (x > 0) { nr++; x = x / 2; }
return nr;
}
public Main() throws IOException
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
HashMap<Pair<Long, Long>, Long> cost = new HashMap<>();
for (int i = 0; i < n; i++) {
int type = in.nextInt();
if (type == 1) {
long v = in.nextLong();
long u = in.nextLong();
long w = in.nextLong();
while (v != u) {
if (height(v) >= height(u)) {
long parent = v / 2;
Pair<Long, Long> edge = new Pair<Long, Long>(parent, v);
Long currentValue = cost.get(edge);
if (currentValue != null) {
cost.put(edge, currentValue + w);
} else
cost.put(edge, w);
v = parent;
} else {
long parent = u / 2;
Pair<Long, Long> edge = new Pair<Long, Long>(parent, u);
Long currentValue = cost.get(edge);
if (currentValue != null) {
cost.put(edge, currentValue + w);
} else
cost.put(edge, w);
u = parent;
}
}
} else {
long v = in.nextLong();
long u = in.nextLong();
long answer = 0;
while (v != u) {
if (height(v) >= height(u)) {
long parent = v / 2;
Pair<Long, Long> edge = new Pair<Long, Long>(parent, v);
Long currentValue = cost.get(edge);
answer += currentValue == null ? 0 : currentValue;
v = parent;
} else {
long parent = u / 2;
Pair<Long, Long> edge = new Pair<Long, Long>(parent, u);
Long currentValue = cost.get(edge);
answer += currentValue == null ? 0 : currentValue;
u = parent;
}
}
System.out.println(answer);
}
}
}
private void readLine(BufferedReader reader) throws IOException
{
line = reader.readLine();
index = 0;
}
private char readChar()
{
index += 2;
return line.charAt(index - 2);
}
private int readInt()
{
int x = 0;
while (index < line.length() && line.charAt(index) >= '0' && line.charAt(index) <= '9') {
x = x * 10 + line.charAt(index) - 48;
index++;
}
index++;
return x;
}
public static void main(String[] args) throws IOException
{
new Main();
}
}
| Java | ["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"] | 1 second | ["94\n0\n32"] | NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32β+β32β+β30β=β94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). | Java 8 | standard input | [
"data structures",
"implementation",
"trees",
"brute force"
] | 12814033bec4956e7561767a6778d77e | The first line of input contains a single integer q (1ββ€βqββ€β1β000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1ββ€βv,βuββ€β1018,βvββ βu,β1ββ€βwββ€β109 states for every description line. | 1,500 | For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. | standard output | |
PASSED | ba81958951ab7f8daf2205d324d94d1f | train_000.jsonl | 1468514100 | Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2iβ+β1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). | 256 megabytes | import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.StringTokenizer;
public class C {
static class Edge {
long u, v;
public Edge(long u, long v) {
this.u = u;
this.v = v;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (u ^ (u >>> 32));
result = prime * result + (int) (v ^ (v >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Edge other = (Edge) obj;
if (u != other.u)
return false;
if (v != other.v)
return false;
return true;
}
@Override
public String toString() {
return "[u=" + u + ", v=" + v + "]";
}
}
static long depth(long n) {
long d = 0;
while (n >= 1) {
d++;
n /= 2;
}
return d;
}
public static void main(String[] args) throws IOException {
File inputFile = new File("entradaC");
if (inputFile.exists())
System.setIn(new FileInputStream(inputFile));
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringBuilder out = new StringBuilder();
String line = "";
while ((line = in.readLine()) != null) {
int q = Integer.parseInt(line);
HashMap<Edge, Long> edges = new HashMap<>();
for (int i = 0; i < q; i++) {
long[] d = readLongs(in.readLine());
long u = d[1], v = d[2], w = 0;
long depthu = depth(u);
long depthv = depth(v);
long depth = Math.min(depthu, depthv);
if (d[0] == 1L) {
w = d[3];
for (long j = depth; j < depthu; j++) {
long p = u / 2L;
Edge e = new Edge(p, u);
if (!edges.containsKey(e))
edges.put(e, w);
else
edges.put(e, edges.get(e) + w);
u = p;
}
for (long j = depth; j < depthv; j++) {
long p = v / 2L;
Edge e = new Edge(p, v);
if (!edges.containsKey(e))
edges.put(e, w);
else
edges.put(e, edges.get(e) + w);
v = p;
}
while (u != v) {
long pu = u / 2L;
Edge e = new Edge(pu, u);
if (!edges.containsKey(e))
edges.put(e, w);
else
edges.put(e, edges.get(e) + w);
u = pu;
long pv = v / 2L;
e = new Edge(pv, v);
if (!edges.containsKey(e))
edges.put(e, w);
else
edges.put(e, edges.get(e) + w);
v = pv;
}
} else {
long sum = 0;
for (long j = depth; j < depthu; j++) {
long p = u / 2L;
Edge e = new Edge(p, u);
if (edges.containsKey(e))
sum += edges.get(e);
u = p;
}
for (long j = depth; j < depthv; j++) {
long p = v / 2L;
Edge e = new Edge(p, v);
if (edges.containsKey(e))
sum += edges.get(e);
v = p;
}
while (u != v) {
long pu = u / 2L;
Edge e = new Edge(pu, u);
if (edges.containsKey(e))
sum += edges.get(e);
u = pu;
long pv = v / 2L;
e = new Edge(pv, v);
if (edges.containsKey(e))
sum += edges.get(e);
v = pv;
}
out.append(sum + "\n");
}
}
}
System.out.print(out);
}
static int[] readInts(String line) {
StringTokenizer st = new StringTokenizer(line.trim());
int a[] = new int[st.countTokens()], index = 0;
while (st.hasMoreTokens())
a[index++] = Integer.parseInt(st.nextToken());
return a;
}
static long[] readLongs(String line) {
StringTokenizer st = new StringTokenizer(line.trim());
long a[] = new long[st.countTokens()];
int index = 0;
while (st.hasMoreTokens())
a[index++] = Long.parseLong(st.nextToken());
return a;
}
static double[] readDoubles(String line) {
StringTokenizer st = new StringTokenizer(line.trim());
double a[] = new double[st.countTokens()];
int index = 0;
while (st.hasMoreTokens())
a[index++] = Double.parseDouble(st.nextToken());
return a;
}
}
| Java | ["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"] | 1 second | ["94\n0\n32"] | NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32β+β32β+β30β=β94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). | Java 8 | standard input | [
"data structures",
"implementation",
"trees",
"brute force"
] | 12814033bec4956e7561767a6778d77e | The first line of input contains a single integer q (1ββ€βqββ€β1β000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1ββ€βv,βuββ€β1018,βvββ βu,β1ββ€βwββ€β109 states for every description line. | 1,500 | For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. | standard output | |
PASSED | 1a919fbb0482e59f5ad76c02eb0cca09 | train_000.jsonl | 1468514100 | Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2iβ+β1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two intersections. Initially anyone can pass any road for free. But since SlapsGiving is ahead of us, there will q consecutive events happen soon. There are two types of events:1. Government makes a new rule. A rule can be denoted by integers v, u and w. As the result of this action, the passing fee of all roads on the shortest path from u to v increases by w dollars. 2. Barney starts moving from some intersection v and goes to intersection u where there's a girl he wants to cuddle (using his fake name Lorenzo Von Matterhorn). He always uses the shortest path (visiting minimum number of intersections or roads) between two intersections.Government needs your calculations. For each time Barney goes to cuddle a girl, you need to tell the government how much money he should pay (sum of passing fee of all roads he passes). | 256 megabytes | /*Author LAVLESH*/
import java.util.*;
import java.io.*;
public class solution{
static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st=new StringTokenizer("");
static public String next(){
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return st.nextToken();
}
public static void main(String[]args)throws IOException{
PrintWriter op =new PrintWriter(System.out);
int n=Integer.parseInt(next());
HashMap<Long,Long> hm=new HashMap<>();
while(n-->0){
int x=Integer.parseInt(next());
if(x==1){
long u=Long.parseLong(next());
long v=Long.parseLong(next());
long w=Long.parseLong(next());
while(v!=u){
if(v>u){
if(hm.containsKey(v))
hm.put(v,hm.get(v)+w);
else hm.put(v,w);
v/=2;
}
else{
if(hm.containsKey(u))
hm.put(u,hm.get(u)+w);
else hm.put(u,w);
u/=2;
}
}
}
else{
long u=Long.parseLong(next());
long v=Long.parseLong(next());
long sum=0;
while(v!=u){
if(v>u){
if(hm.containsKey(v))
sum+=hm.get(v);
v/=2;
}
else{
if(hm.containsKey(u))
sum+=hm.get(u);
u/=2;
}
}
op.println(sum);
}
}
op.close();
}
}
| Java | ["7\n1 3 4 30\n1 4 1 2\n1 3 6 8\n2 4 3\n1 6 1 40\n2 3 7\n2 2 4"] | 1 second | ["94\n0\n32"] | NoteIn the example testcase:Here are the intersections used: Intersections on the path are 3, 1, 2 and 4. Intersections on the path are 4, 2 and 1. Intersections on the path are only 3 and 6. Intersections on the path are 4, 2, 1 and 3. Passing fee of roads on the path are 32, 32 and 30 in order. So answer equals to 32β+β32β+β30β=β94. Intersections on the path are 6, 3 and 1. Intersections on the path are 3 and 7. Passing fee of the road between them is 0. Intersections on the path are 2 and 4. Passing fee of the road between them is 32 (increased by 30 in the first event and by 2 in the second). | Java 8 | standard input | [
"data structures",
"implementation",
"trees",
"brute force"
] | 12814033bec4956e7561767a6778d77e | The first line of input contains a single integer q (1ββ€βqββ€β1β000). The next q lines contain the information about the events in chronological order. Each event is described in form 1 v u w if it's an event when government makes a new rule about increasing the passing fee of all roads on the shortest path from u to v by w dollars, or in form 2 v u if it's an event when Barnie goes to cuddle from the intersection v to the intersection u. 1ββ€βv,βuββ€β1018,βvββ βu,β1ββ€βwββ€β109 states for every description line. | 1,500 | For each event of second type print the sum of passing fee of all roads Barney passes in this event, in one line. Print the answers in chronological order of corresponding events. | standard output | |
PASSED | ece377eaed27f67e192b7e66e0eb4b1d | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes | import java.util.Scanner;
import java.io.*;
import java.util.*;
import java.math.*;
import java.lang.*;
import static java.lang.Math.*;
public class Check2 implements Runnable
{
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars==-1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
}
catch (IOException e)
{
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public String nextLine()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
public int nextInt()
{
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if(c<'0'||c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
long res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
while (!isSpaceChar(c));
return res * sgn;
}
public double nextDouble()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.')
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.')
{
c = read();
double m = 1;
while (!isSpaceChar(c))
{
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public String readString()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
}
while (!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next()
{
return readString();
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
}
static class Pair implements Comparable<Pair>
{
int a;
int b;
public Pair(int a,int b)
{
this.a=a;
this.b=b;
}
public int compareTo(Pair pair)
{
if(Integer.compare(b,pair.b)==0)
return Integer.compare(a,pair.a);
return Integer.compare(b,pair.b);
}
}
static long gcd(long a,long b)
{
while(b!=0)
{
long temp=b;
b=a%b;
a=temp;
}
return a;
}
public static void main(String args[]) throws Exception
{
new Thread(null, new Check2(),"CHECK2",1<<26).start();
}
public void run()
{
InputReader sc=new InputReader(System.in);
PrintWriter w=new PrintWriter(System.out);
int n=sc.nextInt();
String ans[]=new String[n];
HashSet<String> taken=new HashSet<String>();
HashSet<String> taken1=new HashSet<String>();
HashSet<String> taken2=new HashSet<String>();
String ip[][]=new String[n][2];
for(int i=0;i<n;i++)
{
ip[i][0]=sc.next();
ip[i][1]=sc.next();
}
int flag=0;
for(int i=0;i<n;i++)
{
String temp=ip[i][0].substring(0,3);
String temp1=ip[i][0].substring(0,2)+ip[i][1].substring(0,1);
if(flag==1)
break;
if(!taken.contains(temp1) && !taken1.contains(temp1))
{
ans[i]=temp1;
taken1.add(temp1);
taken.add(temp1);
taken2.add(temp);
}
else if(!taken2.contains(temp) && !taken1.contains(temp1))
{
ans[i]=temp;
taken1.add(temp);
taken.add(temp);
}
else
flag=1;
}
if(flag==1)
{
taken.clear();
taken1.clear();
taken2.clear();
flag=0;
for(int i=0;i<n;i++)
{
String temp=ip[i][0].substring(0,3);
String temp1=ip[i][0].substring(0,2)+ip[i][1].substring(0,1);
if(flag==1)
break;
if(!taken.contains(temp) && !taken1.contains(temp))
{
ans[i]=temp;
taken1.add(temp);
taken.add(temp);
taken2.add(temp1);
}
else if(!taken2.contains(temp1) && !taken1.contains(temp))
{
ans[i]=temp1;
taken1.add(temp1);
taken.add(temp1);
}
else
flag=1;
}
if(flag==1)
w.println("NO");
else
{
w.println("YES");
for(int i=0;i<n;i++)
w.println(ans[i]);
}
}
else
{
w.println("YES");
for(int i=0;i<n;i++)
w.println(ans[i]);
}
w.close();
}
} | Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | 00c6229057b4d72f512203f4d2238256 | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes |
import java.util.*;
import java.io.*;
/**
*
* @author umang
*/
public class ProblemF {
public static int mod = 1000000007;
public static InputReader in;
public static PrintWriter out;
static String s1[];
static String s2[];
static int[] pick;
static void change(int id){
pick[id]=1;
for(int i=0;i<pick.length;i++){
if(s1[i].equals(s2[id]) && pick[i]==0){
change(i);
}
}
}
public static void main(String[] args) {
new Thread(null ,new Runnable(){
public void run(){
try{
solve();
} catch(Exception e){
e.printStackTrace();
}
}
},"1",1<<28).start();
}
public static void solve(){
in = new InputReader(System.in);
out = new PrintWriter(System.out);
int n=in.nextInt();
s1=new String[n];
s2=new String[n];
pick=new int[n];
for(int i=0;i<n;i++){
String x1=in.readString();
String x2=in.readString();
s1[i]=x1.substring(0,3);
s2[i]=x1.substring(0,2)+x2.substring(0,1);
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(i==j) continue;
if(s1[i].equals(s1[j]))
pick[i]=pick[j]=1;
}
}
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
String x,y;
x=pick[i]==0?s1[i]:s2[i];
y=pick[j]==0?s1[j]:s2[j];
if(x.equals(y)){
if(pick[i]==0) change(i);
if(pick[j]==0) change(j);
}
}
}
boolean f=true;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
String x,y;
x=pick[i]==0?s1[i]:s2[i];
y=pick[j]==0?s1[j]:s2[j];
//debug(x,y,i,j);
if(x.equals(y)){
f=false;
}
}
}
if(f){
out.println("YES");
for(int i=0;i<n;i++){
out.println(pick[i]==0?s1[i]:s2[i]);
}
}
else out.println("NO");
out.close();
}
public static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
static class Pair implements Comparable<Pair>{
char c;
int x;
int y;
Pair (int x,int y){
this.x=x;
this.y=y;
this.c='a';
}
public int compareTo(Pair o) {
return Long.compare(this.x,o.x);
}
public boolean equals(Object o) {
if (o instanceof Pair) {
Pair p = (Pair)o;
return (p.x == x && p.y == y && p.c==c);
}
return false;
}
@Override
public String toString() {
return "("+x + " " + y +")";
}
}
public static long add(long x, long y) {
return (x + y)%mod;
}
public static long mul(long x, long y) {
return (x*y)%mod;
}
public static boolean isPal(String s){
for(int i=0, j=s.length()-1;i<=j;i++,j--){
if(s.charAt(i)!=s.charAt(j)) return false;
}
return true;
}
public static String rev(String s){
StringBuilder sb=new StringBuilder(s);
sb.reverse();
return sb.toString();
}
public static long gcd(long x,long y){
if(x%y==0)
return y;
else
return gcd(y,x%y);
}
public static int gcd(int x,int y){
if(x%y==0)
return y;
else
return gcd(y,x%y);
}
public static long gcdExtended(long a,long b,long[] x){
if(a==0){
x[0]=0;
x[1]=1;
return b;
}
long[] y=new long[2];
long gcd=gcdExtended(b%a, a, y);
x[0]=y[1]-(b/a)*y[0];
x[1]=y[0];
return gcd;
}
public static int abs(int a,int b){
return (int)Math.abs(a-b);
}
public static long abs(long a,long b){
return (long)Math.abs(a-b);
}
public static int max(int a,int b){
if(a>b)
return a;
else
return b;
}
public static int min(int a,int b){
if(a>b)
return b;
else
return a;
}
public static long max(long a,long b){
if(a>b)
return a;
else
return b;
}
public static long min(long a,long b){
if(a>b)
return b;
else
return a;
}
public static long pow(long n,long p,long m){
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
if(result>=m)
result%=m;
p >>=1;
n*=n;
if(n>=m)
n%=m;
}
return result;
}
public static long pow(long n,long p){
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n) {
long a[] = new long[n];
for (int i = 0; i < n; i++) {
a[i] = 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 | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | 13a3156c4a5c2d6248b0a9c0759bcd45 | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes | import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(System.in);
HashMap<String, Boolean> ma, mma;
int N = sc.nextInt();
ma = new HashMap<String, Boolean>();
mma = new HashMap<String, Boolean>();
String[] Ans = new String[N];
String Answer="";
for(int i=0;i<N;i++){
String name1 = sc.next();
String name2 = sc.next();
String a = name1.substring(0, 3);
String b = name1.substring(0, 2)+name2.substring(0, 1);
if(!ma.containsKey(b) || !ma.get(b)){
ma.put(b, true);
Ans[i]=b;
mma.put(a, true);
}else{
if((ma.containsKey(a) && ma.get(a)) || (mma.containsKey(a) && mma.get(a))){
Answer="NO";
System.out.println(Answer);
break;
}else{
ma.put(a, true);
Ans[i]=a;
}
}
}
if(!Answer.equals("NO")){
System.out.println("YES");
for(int i=0;i<N;i++)
System.out.println(Ans[i]);
}
}
}
| Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | 43910cbd5514c76d6f8b5ad5bed30a71 | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
public class D2 {
public static void main(String[] args)throws Throwable {
MyScanner sc=new MyScanner();
PrintWriter pw=new PrintWriter(System.out);
int n=sc.nextInt();
boolean ok=true;
TreeSet<String> set=new TreeSet<String>();
String [][] a=new String [n][2];
for(int i=0;i<n;i++){
String x=sc.next().substring(0, 3);
String y=""+sc.next().charAt(0);
String s1=x,s2=x.substring(0, 2)+y;
a[i][0]=s1;
a[i][1]=s2;
if(set.contains(s1+" "+s2))
ok=false;
set.add(s1+" "+s2);
}
set=new TreeSet<String>();
String [] ans=new String [n];
for(int i=0;i<n;i++){
if(!set.contains(a[i][1])){
set.add(a[i][1]);
ans[i]=a[i][1];
}else
if(!set.contains(a[i][0])){
set.add(a[i][0]);
ans[i]=a[i][0];
}else
ok=false;
}
if(!ok)
pw.println("NO");
else{
pw.println("YES");
for(int i=0;i<n;i++)
pw.println(ans[i]);
}
pw.flush();
pw.close();
}
static class MyScanner {
BufferedReader br;
StringTokenizer st;
public MyScanner() {br = new BufferedReader(new InputStreamReader(System.in));}
String next() {while (st == null || !st.hasMoreElements()) {
try {st = new StringTokenizer(br.readLine());}
catch (IOException e) {e.printStackTrace();}}
return st.nextToken();}
int nextInt() {return Integer.parseInt(next());}
long nextLong() {return Long.parseLong(next());}
double nextDouble() {return Double.parseDouble(next());}
String nextLine(){String str = "";
try {str = br.readLine();}
catch (IOException e) {e.printStackTrace();}
return str;}
}
} | Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | 5268e30d8611fd5eeca47fc8425682b8 | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes | import java.util.*;
public class D {
public static void main(String[] args) {
Scanner qwe = new Scanner(System.in);
int n = qwe.nextInt();
String[][] names = new String[2][n];
HashMap<String,Integer> toid = new HashMap<String,Integer>();
int curid = n;
int[] count = new int[3*n+5];
String[] rev = new String[3*n+5];
for (int i = 0; i < n; i++) {
names[0][i] = qwe.next().substring(0,3);
names[1][i] = names[0][i].substring(0,2)+qwe.next().charAt(0);
for(int j =0; j < 2; j++)
if(!toid.containsKey(names[j][i])){
rev[curid] = names[j][i];
toid.put(names[j][i], curid++);
}
count[toid.get(names[0][i])]++;
}
int src = curid++;
int sink = curid++;
MaxFlowDinic din = new MaxFlowDinic(curid+1);
for(int i = n; i < src; i++){
din.addEdge(i, sink, 1);
}
for (int i = 0; i < n; i++) {
din.addEdge(src, i, 1);
int a = toid.get(names[0][i]);
int b = toid.get(names[1][i]);
din.addEdge(i, b, 1);
if(count[a] == 1 && a != b){
din.addEdge(i, a, 1);
}
}
int maxflow = din.maxFlow(src, sink);
if(maxflow != n) System.out.println("NO");
else{
System.out.println("YES");
for(int i =0; i < n; i++){
for(MaxFlowDinic.Edge e : din.graph[i]){
if(e != null && e.f == 1 && e.t != src && e.t >= 0 && e.t < rev.length){
System.out.println(rev[e.t]);
}
}
}
}
qwe.close();
}
static class MaxFlowDinic
{
ArrayList<Edge>[] graph;
class Edge {
int t, rev, cap, f;
public Edge(int t, int rev, int cap) {
this.t = t;
this.rev = rev;
this.cap = cap;
}
}
public MaxFlowDinic(int nodes)
{
graph = new ArrayList[nodes];
for (int i = 0; i < nodes; i++)
graph[i] = new ArrayList<Edge>();
}
public void addEdge(int s, int t, int cap) {
graph[s].add(new Edge(t, graph[t].size(), cap));
graph[t].add(new Edge(s, graph[s].size() - 1, 0));
}
boolean dinicBfs(int src, int dest, int[] dist) {
Arrays.fill(dist, -1);
dist[src] = 0;
int[] Q = new int[graph.length];
int sizeQ = 0;
Q[sizeQ++] = src;
for (int i = 0; i < sizeQ; i++) {
int u = Q[i];
for (Edge e : graph[u]) {
if (dist[e.t] < 0 && e.f < e.cap) {
dist[e.t] = dist[u] + 1;
Q[sizeQ++] = e.t;
}
}
}
return dist[dest] >= 0;
}
int dinicDfs(int[] ptr, int[] dist, int dest, int u, int f) {
if (u == dest)
return f;
for (; ptr[u] < graph[u].size(); ++ptr[u]) {
Edge e = graph[u].get(ptr[u]);
if (dist[e.t] == dist[u] + 1 && e.f < e.cap) {
int df = dinicDfs(ptr, dist, dest, e.t, Math.min(f, e.cap - e.f));
if (df > 0) {
e.f += df;
graph[e.t].get(e.rev).f -= df;
return df;
}
}
}
return 0;
}
public int maxFlow(int src, int dest) {
int flow = 0;
int[] dist = new int[graph.length];
while (dinicBfs(src, dest, dist)) {
int[] ptr = new int[graph.length];
while (true) {
int df = dinicDfs(ptr, dist, dest, src, Integer.MAX_VALUE);
if (df == 0)
break;
flow += df;
}
}
return flow;
}
}
}
| Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | 5d1b775cc99fa08d800e0faca8af06f8 | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 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.StringTokenizer;
import java.util.TreeSet;
public class Main {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = sc.nextInt();
String f [] = new String[n], s [] = new String[n];
TreeSet<String> first = new TreeSet<>(), second = new TreeSet<>();
boolean okF = true, okS = true;
for (int i = 0; i < n; i++) {
char a [] = sc.next().toCharArray(), b [] = sc.next().toCharArray();
f[i] = a[0] + "" + a[1] + "" + a[2];
s[i] = a[0] + "" + a[1] + "" + b[0];
if (first.contains(f[i])) {
okF = false;
}
if (second.contains(s[i])) {
okS = false;
}
first.add(f[i]);
second.add(s[i]);
}
if (okF) {
out.println("YES");
for (int i = 0; i < n; i++) {
out.println(f[i]);
}
}
else if (okS) {
out.println("YES");
for (int i = 0; i < n; i++) {
out.println(s[i]);
}
}
else {
out.println("NO");
}
out.flush();
out.close();
}
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 long nextLong() throws IOException {
return Long.parseLong(next());
}
public String nextLine() throws IOException {
return br.readLine();
}
public double nextDouble() throws IOException {
String x = next();
StringBuilder sb = new StringBuilder("0");
double res = 0, f = 1;
boolean dec = false, neg = false;
int start = 0;
if (x.charAt(0) == '-') {
neg = true;
start++;
}
for (int i = start; i < x.length(); i++)
if (x.charAt(i) == '.') {
res = Long.parseLong(sb.toString());
sb = new StringBuilder("0");
dec = true;
} else {
sb.append(x.charAt(i));
if (dec)
f *= 10;
}
res += Long.parseLong(sb.toString()) / f;
return res * (neg ? -1 : 1);
}
public boolean ready() throws IOException {
return br.ready();
}
public boolean nextEmpty() throws IOException {
String s = nextLine();
st = new StringTokenizer(s);
return s.isEmpty();
}
}
} | Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | 5cf38ca094914ce4b6bfff216d6140e6 | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.math.*;
import java.util.*;
import java.util.stream.*;
import java.util.regex.*;
import java.text.*;
public class Solution {
public static void main(String[] args) throws Exception {
MyReader reader = new MyReader(System.in);
MyWriter writer = new MyWriter(System.out);
int n = reader.nextInt();
String[][] s = new String[n][2];
for (int i = 0; i < n; i++) {
String s1 = reader.nextString();
String s2 = reader.nextString();
s[i][0] = s1.substring(0, 3);
s[i][1] = s1.substring(0, 2) + s2.charAt(0);
}
Set<String> s1 = new HashSet<>();
String[] a = new String[n];
Set<Integer> set = new HashSet<>();
l:
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i != j && s[i][0].equals(s[j][0])) {
a[i] = s[i][1];
s1.add(a[i]);
continue l;
}
}
set.add(i);
}
Set<Integer> set2 = set;
Set<String> s2 = s1;
do {
s1 = s2;
s2 = new HashSet<>();
set = set2;
set2 = new HashSet<>();
for (int i : set) {
boolean b1 = true;
boolean b2 = true;
for (String h : s1) {
b1 &= !h.equals(s[i][0]);
b2 &= !h.equals(s[i][1]);
}
if (!b1 && !b2) {
writer.print("NO");
writer.close();
return;
}
if (!b1) {
a[i] = s[i][1];
s2.add(a[i]);
} else if (!b2) {
a[i] = s[i][0];
s2.add(a[i]);
} else {
set2.add(i);
}
}
} while (s2.size() > 0);
for (int i = 0; i < n; i++) {
if (a[i] == null) {
a[i] = s[i][0];
}
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i].equals(a[j])) {
writer.print("NO");
writer.close();
return;
}
}
}
writer.print("YES\n");
for (int i = 0; i < n; i++) {
writer.print(a[i] + "\n");
}
writer.close();
}
static class MyReader {
final BufferedInputStream in;
final int bufSize = 1 << 16;
final byte buf[] = new byte[bufSize];
int i = bufSize;
int k = bufSize;
final StringBuilder str = new StringBuilder();
MyReader(InputStream in) {
this.in = new BufferedInputStream(in, bufSize);
}
int nextInt() throws IOException {
return (int) nextLong();
}
int[] nextIntArray(int n) throws IOException {
int[] m = new int[n];
for (int i = 0; i < n; i++) {
m[i] = nextInt();
}
return m;
}
int[][] nextIntMatrix(int n, int m) throws IOException {
int[][] a = new int[n][0];
for (int j = 0; j < n; j++) {
a[j] = nextIntArray(m);
}
return a;
}
long nextLong() throws IOException {
int c;
long x = 0;
boolean sign = true;
while ((c = nextChar()) <= 32) ;
if (c == '-') {
sign = false;
c = nextChar();
}
while (c >= '0') {
x = x * 10 + (c - '0');
c = nextChar();
}
return sign ? x : -x;
}
long[] nextLongArray(int n) throws IOException {
long[] m = new long[n];
for (int i = 0; i < n; i++) {
m[i] = nextLong();
}
return m;
}
String nextString() throws IOException {
int c;
str.setLength(0);
while ((c = nextChar()) <= 32 && c != -1) ;
if (c == -1) {
return null;
}
while (c > 32) {
str.append((char) c);
c = nextChar();
}
return str.toString();
}
String[] nextStringArray(int n) throws IOException {
String[] m = new String[n];
for (int i = 0; i < n; i++) {
m[i] = nextString();
}
return m;
}
int nextChar() throws IOException {
if (i == k) {
k = in.read(buf, 0, bufSize);
i = 0;
}
return i >= k ? -1 : buf[i++];
}
}
static class MyWriter {
final BufferedOutputStream out;
final int bufSize = 1 << 16;
final byte buf[] = new byte[bufSize];
int i = 0;
final byte c[] = new byte[30];
static final String newLine = System.getProperty("line.separator");
MyWriter(OutputStream out) {
this.out = new BufferedOutputStream(out, bufSize);
}
void print(long x) throws IOException {
int j = 0;
if (i + 30 >= bufSize) {
flush();
}
if (x < 0) {
buf[i++] = (byte) ('-');
x = -x;
}
while (j == 0 || x != 0) {
c[j++] = (byte) (x % 10 + '0');
x /= 10;
}
while (j-- > 0)
buf[i++] = c[j];
}
void print(int[] m) throws Exception {
for (int a : m) {
print(a);
print(' ');
}
}
void print(long[] m) throws Exception {
for (long a : m) {
print(a);
print(' ');
}
}
void print(String s) throws IOException {
for (int i = 0; i < s.length(); i++) {
print(s.charAt(i));
}
}
void print(char x) throws IOException {
if (i == bufSize) {
flush();
}
buf[i++] = (byte) x;
}
void print(char[] m) throws Exception {
for (char c : m) {
print(c);
}
}
void println(String s) throws IOException {
print(s);
println();
}
void println() throws IOException {
print(newLine);
}
void flush() throws IOException {
out.write(buf, 0, i);
i = 0;
}
void close() throws IOException {
flush();
out.close();
}
}
} | Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | 139e8e90ecf70c9f38149fcfc18abebb | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.math.*;
import java.util.*;
import java.util.stream.*;
import java.util.regex.*;
import java.text.*;
public class Solution {
public static void main(String[] args) throws Exception {
MyReader reader = new MyReader(System.in);
MyWriter writer = new MyWriter(System.out);
int n = reader.nextInt();
String[][] s = new String[n][2];
for (int i = 0; i < n; i++) {
String s1 = reader.nextString();
String s2 = reader.nextString();
s[i][0] = s1.substring(0, 3);
s[i][1] = s1.substring(0, 2) + s2.charAt(0);
}
String[] a = new String[n];
Set<Integer> set = new HashSet<>();
l:
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i != j && s[i][0].equals(s[j][0])) {
a[i] = s[i][1];
continue l;
}
}
set.add(i);
}
Set<Integer> set2 = set;
do {
set = set2;
set2 = new HashSet<>();
for (int i : set) {
boolean b1 = true;
boolean b2 = true;
for (int j = 0; j < n; j++) {
if (a[j] != null && i != j) {
b1 &= !a[j].equals(s[i][0]);
b2 &= !a[j].equals(s[i][1]);
}
}
if (!b1 && !b2) {
writer.print("NO");
writer.close();
return;
}
if (!b1) {
a[i] = s[i][1];
} else if (!b2) {
a[i] = s[i][0];
} else {
set2.add(i);
}
}
} while (set.size() != set2.size());
for (int i = 0; i < n; i++) {
if (a[i] == null) {
a[i] = s[i][0];
}
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i].equals(a[j])) {
writer.print("NO");
writer.close();
return;
}
}
}
writer.print("YES\n");
for (int i = 0; i < n; i++) {
writer.print(a[i] + "\n");
}
writer.close();
}
static class MyReader {
final BufferedInputStream in;
final int bufSize = 1 << 16;
final byte buf[] = new byte[bufSize];
int i = bufSize;
int k = bufSize;
final StringBuilder str = new StringBuilder();
MyReader(InputStream in) {
this.in = new BufferedInputStream(in, bufSize);
}
int nextInt() throws IOException {
return (int) nextLong();
}
int[] nextIntArray(int n) throws IOException {
int[] m = new int[n];
for (int i = 0; i < n; i++) {
m[i] = nextInt();
}
return m;
}
int[][] nextIntMatrix(int n, int m) throws IOException {
int[][] a = new int[n][0];
for (int j = 0; j < n; j++) {
a[j] = nextIntArray(m);
}
return a;
}
long nextLong() throws IOException {
int c;
long x = 0;
boolean sign = true;
while ((c = nextChar()) <= 32) ;
if (c == '-') {
sign = false;
c = nextChar();
}
while (c >= '0') {
x = x * 10 + (c - '0');
c = nextChar();
}
return sign ? x : -x;
}
long[] nextLongArray(int n) throws IOException {
long[] m = new long[n];
for (int i = 0; i < n; i++) {
m[i] = nextLong();
}
return m;
}
String nextString() throws IOException {
int c;
str.setLength(0);
while ((c = nextChar()) <= 32 && c != -1) ;
if (c == -1) {
return null;
}
while (c > 32) {
str.append((char) c);
c = nextChar();
}
return str.toString();
}
String[] nextStringArray(int n) throws IOException {
String[] m = new String[n];
for (int i = 0; i < n; i++) {
m[i] = nextString();
}
return m;
}
int nextChar() throws IOException {
if (i == k) {
k = in.read(buf, 0, bufSize);
i = 0;
}
return i >= k ? -1 : buf[i++];
}
}
static class MyWriter {
final BufferedOutputStream out;
final int bufSize = 1 << 16;
final byte buf[] = new byte[bufSize];
int i = 0;
final byte c[] = new byte[30];
static final String newLine = System.getProperty("line.separator");
MyWriter(OutputStream out) {
this.out = new BufferedOutputStream(out, bufSize);
}
void print(long x) throws IOException {
int j = 0;
if (i + 30 >= bufSize) {
flush();
}
if (x < 0) {
buf[i++] = (byte) ('-');
x = -x;
}
while (j == 0 || x != 0) {
c[j++] = (byte) (x % 10 + '0');
x /= 10;
}
while (j-- > 0)
buf[i++] = c[j];
}
void print(int[] m) throws Exception {
for (int a : m) {
print(a);
print(' ');
}
}
void print(long[] m) throws Exception {
for (long a : m) {
print(a);
print(' ');
}
}
void print(String s) throws IOException {
for (int i = 0; i < s.length(); i++) {
print(s.charAt(i));
}
}
void print(char x) throws IOException {
if (i == bufSize) {
flush();
}
buf[i++] = (byte) x;
}
void print(char[] m) throws Exception {
for (char c : m) {
print(c);
}
}
void println(String s) throws IOException {
print(s);
println();
}
void println() throws IOException {
print(newLine);
}
void flush() throws IOException {
out.write(buf, 0, i);
i = 0;
}
void close() throws IOException {
flush();
out.close();
}
}
} | Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | 9a1f7dae7c3daea12fd267fcb0506e93 | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes | import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class App {
private static boolean solve(Map<String, Integer> mp1, Map<String, Integer> mp2, String[] tm, String[] hm, int ind,
int flag) {
if (ind == tm.length) {
return true;
}
String tmp1 = tm[ind].substring(0, 3);
if (flag != -1) {
if (!mp1.containsKey(tmp1)) {
Set<String> st = mp1.keySet();
for (String s : st) {
if (mp1.get(s) == 2) {
int ti = mp2.get(s);
if (tmp1.equals(tm[ti].substring(0, 3))) {
boolean tmp = solve(mp1, mp2, tm, hm, ind, -1);
if (tmp == false) {
return false;
}
return solve(mp1, mp2, tm, hm, ind + 1, 0);
}
}
}
mp1.put(tmp1, 1);
mp2.put(tmp1, ind);
return solve(mp1, mp2, tm, hm, ind + 1, 0);
}
if (mp1.get(tmp1) == 2) {
boolean tmp = solve(mp1, mp2, tm, hm, ind, -1);
if (tmp == false) {
return false;
}
return solve(mp1, mp2, tm, hm, ind + 1, 0);
}
int t1 = mp2.get(tmp1);
mp1.remove(tmp1, 1);
mp2.remove(tmp1, t1);
boolean tmp = solve(mp1, mp2, tm, hm, t1, -1);
if (tmp == false) {
return false;
}
}
String tmp2 = tm[ind].substring(0, 2) + hm[ind].substring(0, 1);
// System.out.println(tm[ind] + " " + hm[ind]);
if (!mp1.containsKey(tmp2)) {
mp1.put(tmp2, 2);
mp2.put(tmp2, ind);
if (flag == -1)
return true;
} else if (mp1.get(tmp2) == 2) {
return false;
} else {
int t2 = mp2.get(tmp2);
mp1.remove(tmp2, 1);
mp2.remove(tmp2, t2);
boolean tmp = solve(mp1, mp2, tm, hm, t2, -1);
if (tmp == false) {
return false;
}
mp1.put(tmp2, 2);
mp2.put(tmp2, ind);
if (flag == -1)
return true;
}
return solve(mp1, mp2, tm, hm, ind + 1, 0);
}
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
int n = inp.nextInt();
inp.nextLine();
String[] tm = new String[n];
String[] hm = new String[n];
String tmp;
String[] ts;
for (int i = 0; i < n; i++) {
tmp = inp.nextLine();
ts = tmp.split("\\s");
tm[i] = ts[0];
hm[i] = ts[1];
}
Map<String, Integer> mp1 = new HashMap<>();
Map<String, Integer> mp2 = new HashMap<>();
boolean res = solve(mp1, mp2, tm, hm, 0, 0);
if (res) {
System.out.println("YES");
String[] ans = new String[n];
Set<String> st = mp2.keySet();
for (String s : st) {
ans[mp2.get(s)] = s;
}
for (int i = 0; i < n; i++) {
System.out.println(ans[i]);
}
} else {
System.out.println("NO");
}
inp.close();
}
}
| Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | 7aa12c8e601740acc705fd193b2fb4d4 | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes | import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;
public class D_403
{
public static final long[] POWER2 = generatePOWER2();
public static final IteratorBuffer ITERATOR_BUFFER_PRIME = new IteratorBuffer(streamPrime(1000000).iterator());
private static BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
private static StringTokenizer stringTokenizer = null;
private static PrintWriter out = new PrintWriter(new BufferedOutputStream(System.out));
interface BiFunctionResult<Type0, Type1, TypeResult>
{
TypeResult apply(Type0 x0, Type1 x1, TypeResult x2);
}
static class Array<Type> implements Iterable<Type>
{
private Object[] array;
public Array(int size)
{
this.array = new Object[size];
}
public Array(int size, Type element)
{
this(size);
Arrays.fill(this.array, element);
}
public Array(Array<Type> array, Type element)
{
this(array.size() + 1);
for (int index = 0; index < array.size(); index++)
{
set(index, array.get(index));
}
set(size() - 1, element);
}
public Array(List<Type> list)
{
this(list.size());
int index = 0;
for (Type element : list)
{
set(index, element);
index += 1;
}
}
public Type get(int index)
{
return (Type) this.array[index];
}
public Array set(int index, Type value)
{
this.array[index] = value;
return this;
}
public int size()
{
return this.array.length;
}
public List<Type> toList()
{
List<Type> result = new ArrayList<>();
for (Type element : this)
{
result.add(element);
}
return result;
}
@Override
public Iterator<Type> iterator()
{
return new Iterator<Type>()
{
int index = 0;
@Override
public boolean hasNext()
{
return this.index < size();
}
@Override
public Type next()
{
Type result = Array.this.get(index);
index += 1;
return result;
}
};
}
@Override
public String toString()
{
return "[" + D_403.toString(this, ", ") + "]";
}
}
static abstract class Edge<TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>>
{
public final TypeVertex vertex0;
public final TypeVertex vertex1;
public final boolean bidirectional;
public Edge(TypeVertex vertex0, TypeVertex vertex1, boolean bidirectional)
{
this.vertex0 = vertex0;
this.vertex1 = vertex1;
this.bidirectional = bidirectional;
this.vertex0.edges.add(getThis());
if (this.bidirectional)
{
this.vertex1.edges.add(getThis());
}
}
public TypeVertex other(Vertex<TypeVertex, TypeEdge> vertex)
{
TypeVertex result;
if (vertex0 == vertex)
{
result = vertex1;
}
else
{
result = vertex0;
}
return result;
}
public abstract TypeEdge getThis();
public void remove()
{
this.vertex0.edges.remove(getThis());
if (this.bidirectional)
{
this.vertex1.edges.remove(getThis());
}
}
@Override
public String toString()
{
return this.vertex0 + "->" + this.vertex1;
}
}
public static class EdgeDefault<TypeVertex extends Vertex<TypeVertex, EdgeDefault<TypeVertex>>> extends Edge<TypeVertex, EdgeDefault<TypeVertex>>
{
public EdgeDefault(TypeVertex vertex0, TypeVertex vertex1, boolean bidirectional)
{
super(vertex0, vertex1, bidirectional);
}
@Override
public EdgeDefault<TypeVertex> getThis()
{
return this;
}
}
public static class Vertex<TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>> implements Comparable<Vertex<? super TypeVertex, ? super TypeEdge>>
{
public static <TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>> void depthFirstSearch(
Array<TypeVertex> vertices,
int indexVertexStart,
BiConsumer<TypeVertex, TypeEdge> functionPreVisit,
BiConsumer<TypeVertex, TypeEdge> functionPostVisit
)
{
boolean[] isVisited = new boolean[vertices.size()];
boolean[] isOnStack = new boolean[vertices.size()];
Stack<TypeVertex> stackVertices = new Stack<>();
Stack<TypeEdge> stackEdges = new Stack<>();
TypeVertex vertexStart = vertices.get(indexVertexStart);
stackVertices.push(vertexStart);
stackEdges.push(null);
isOnStack[vertexStart.index] = true;
while (!stackVertices.isEmpty())
{
TypeVertex vertex = stackVertices.peek();
TypeEdge edge = stackEdges.peek();
if (isVisited[vertex.index])
{
functionPostVisit.accept(vertex, edge);
stackVertices.pop();
stackEdges.pop();
}
else
{
functionPreVisit.accept(vertex, edge);
isVisited[vertex.index] = true;
for (TypeEdge edgeTo : vertex.edges)
{
TypeVertex vertexTo = edgeTo.other(vertex);
if (!isOnStack[vertexTo.index])
{
stackVertices.push(vertexTo);
stackEdges.push(edgeTo);
isOnStack[vertexTo.index] = true;
}
}
}
}
}
public static <TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>> void depthFirstSearch(
Array<TypeVertex> vertices,
int indexVertexStart,
Consumer<TypeVertex> functionPreVisit,
Consumer<TypeVertex> functionPostVisit
)
{
depthFirstSearch(
vertices,
indexVertexStart,
(vertex, edge) -> functionPreVisit.accept(vertex),
(vertex, edge) -> functionPostVisit.accept(vertex)
);
}
public static <TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>, TypeResult> TypeResult breadthFirstSearch(
TypeVertex vertex,
TypeEdge edge,
BiFunctionResult<TypeVertex, TypeEdge, TypeResult> function,
Array<Boolean> visited,
FIFO<TypeVertex> verticesNext,
FIFO<TypeEdge> edgesNext,
TypeResult result
)
{
if (!visited.get(vertex.index))
{
visited.set(vertex.index, true);
result = function.apply(vertex, edge, result);
for (TypeEdge edgeNext : vertex.edges)
{
TypeVertex vertexNext = edgeNext.other(vertex);
if (!visited.get(vertexNext.index))
{
verticesNext.push(vertexNext);
edgesNext.push(edgeNext);
}
}
}
return result;
}
public static <TypeVertex extends Vertex<TypeVertex, TypeEdge>, TypeEdge extends Edge<TypeVertex, TypeEdge>, TypeResult> TypeResult breadthFirstSearch(
Array<TypeVertex> vertices,
int indexVertexStart,
BiFunctionResult<TypeVertex, TypeEdge, TypeResult> function,
TypeResult result
)
{
Array<Boolean> visited = new Array(vertices.size(), false);
FIFO<TypeVertex> verticesNext = new FIFO<>();
verticesNext.push(vertices.get(indexVertexStart));
FIFO<TypeEdge> edgesNext = new FIFO<>();
edgesNext.push(null);
while (!verticesNext.isEmpty())
{
result = breadthFirstSearch(verticesNext.pop(), edgesNext.pop(), function, visited, verticesNext, edgesNext, result);
}
return result;
}
public final int index;
public final List<TypeEdge> edges;
public Vertex(int index)
{
this.index = index;
this.edges = new ArrayList<>();
}
@Override
public int compareTo(Vertex<? super TypeVertex, ? super TypeEdge> that)
{
return Integer.compare(this.index, that.index);
}
@Override
public String toString()
{
return "" + this.index;
}
}
public static class VertexDefault<TypeEdge extends Edge<VertexDefault<TypeEdge>, TypeEdge>> extends Vertex<VertexDefault<TypeEdge>, TypeEdge>
{
public VertexDefault(int index)
{
super(index);
}
}
public static class VertexDefaultDefault extends Vertex<VertexDefaultDefault, EdgeDefaultDefault>
{
public static Array<VertexDefaultDefault> vertices(int n)
{
Array<VertexDefaultDefault> result = new Array<VertexDefaultDefault>(n);
for (int index = 0; index < n; index++)
{
result.set(index, new VertexDefaultDefault(index));
}
return result;
}
public VertexDefaultDefault(int index)
{
super(index);
}
}
public static class EdgeDefaultDefault extends Edge<VertexDefaultDefault, EdgeDefaultDefault>
{
public EdgeDefaultDefault(VertexDefaultDefault vertex0, VertexDefaultDefault vertex1, boolean bidirectional)
{
super(vertex0, vertex1, bidirectional);
}
@Override
public EdgeDefaultDefault getThis()
{
return this;
}
}
public static class Tuple2<Type0, Type1>
{
public final Type0 v0;
public final Type1 v1;
public Tuple2(Type0 v0, Type1 v1)
{
this.v0 = v0;
this.v1 = v1;
}
@Override
public String toString()
{
return "(" + this.v0 + ", " + this.v1 + ")";
}
}
static class Wrapper<Type>
{
public Type value;
public Wrapper(Type value)
{
this.value = value;
}
public Type get()
{
return this.value;
}
public void set(Type value)
{
this.value = value;
}
@Override
public String toString()
{
return this.value.toString();
}
}
public static class Tuple3<Type0, Type1, Type2>
{
public final Type0 v0;
public final Type1 v1;
public final Type2 v2;
public Tuple3(Type0 v0, Type1 v1, Type2 v2)
{
this.v0 = v0;
this.v1 = v1;
this.v2 = v2;
}
@Override
public String toString()
{
return "(" + this.v0 + ", " + this.v1 + ", " + this.v2 + ")";
}
}
public static class Tuple2Comparable<Type0 extends Comparable<? super Type0>, Type1 extends Comparable<? super Type1>> extends Tuple2<Type0, Type1> implements Comparable<Tuple2Comparable<Type0, Type1>>
{
public Tuple2Comparable(Type0 v0, Type1 v1)
{
super(v0, v1);
}
@Override
public int compareTo(Tuple2Comparable<Type0, Type1> that)
{
int result = this.v0.compareTo(that.v0);
if (result == 0)
{
result = this.v1.compareTo(that.v1);
}
return result;
}
}
public static class SingleLinkedList<Type>
{
public final Type element;
public SingleLinkedList<Type> next;
public SingleLinkedList(Type element, SingleLinkedList<Type> next)
{
this.element = element;
this.next = next;
}
public void toCollection(Collection<Type> collection)
{
if (this.next != null)
{
this.next.toCollection(collection);
}
collection.add(this.element);
}
}
public static class Node<Type>
{
public static <Type> Node<Type> balance(Node<Type> result)
{
while (result != null && 1 < Math.abs(height(result.left) - height(result.right)))
{
if (height(result.left) < height(result.right))
{
Node right = result.right;
if (height(right.right) < height(right.left))
{
result = new Node(result.value, result.left, right.rotateRight());
}
result = result.rotateLeft();
}
else
{
Node left = result.left;
if (height(left.left) < height(left.right))
{
result = new Node(result.value, left.rotateLeft(), result.right);
}
result = result.rotateRight();
}
}
return result;
}
public static <Type> Node<Type> clone(Node<Type> result)
{
if (result != null)
{
result = new Node(result.value, clone(result.left), clone(result.right));
}
return result;
}
public static <Type> Node<Type> delete(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = null;
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
if (node.left == null)
{
result = node.right;
}
else
{
if (node.right == null)
{
result = node.left;
}
else
{
Node<Type> first = first(node.right);
result = new Node(first.value, node.left, delete(node.right, first.value, comparator));
}
}
}
else
{
if (compare < 0)
{
result = new Node(node.value, delete(node.left, value, comparator), node.right);
}
else
{
result = new Node(node.value, node.left, delete(node.right, value, comparator));
}
}
result = balance(result);
}
return result;
}
public static <Type> Node<Type> first(Node<Type> result)
{
while (result.left != null)
{
result = result.left;
}
return result;
}
public static <Type> Node<Type> get(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = null;
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
result = node;
}
else
{
if (compare < 0)
{
result = get(node.left, value, comparator);
}
else
{
result = get(node.right, value, comparator);
}
}
}
return result;
}
public static <Type> Node<Type> head(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = null;
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
result = node.left;
}
else
{
if (compare < 0)
{
result = head(node.left, value, comparator);
}
else
{
result = new Node(node.value, node.left, head(node.right, value, comparator));
}
}
result = balance(result);
}
return result;
}
public static int height(Node node)
{
return node == null ? 0 : node.height;
}
public static <Type> Node<Type> insert(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = new Node(value, null, null);
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
result = new Node(value, node.left, node.right);
;
}
else
{
if (compare < 0)
{
result = new Node(node.value, insert(node.left, value, comparator), node.right);
}
else
{
result = new Node(node.value, node.left, insert(node.right, value, comparator));
}
}
result = balance(result);
}
return result;
}
public static <Type> Node<Type> last(Node<Type> result)
{
while (result.right != null)
{
result = result.right;
}
return result;
}
public static int size(Node node)
{
return node == null ? 0 : node.size;
}
public static <Type> Node<Type> tail(Node<Type> node, Type value, Comparator<? super Type> comparator)
{
Node<Type> result;
if (node == null)
{
result = null;
}
else
{
int compare = comparator.compare(value, node.value);
if (compare == 0)
{
result = new Node(node.value, null, node.right);
}
else
{
if (compare < 0)
{
result = new Node(node.value, tail(node.left, value, comparator), node.right);
}
else
{
result = tail(node.right, value, comparator);
}
}
result = balance(result);
}
return result;
}
public static <Type> void traverseOrderIn(Node<Type> node, Consumer<Type> consumer)
{
if (node != null)
{
traverseOrderIn(node.left, consumer);
consumer.accept(node.value);
traverseOrderIn(node.right, consumer);
}
}
public final Type value;
public final Node<Type> left;
public final Node<Type> right;
public final int size;
private final int height;
public Node(Type value, Node<Type> left, Node<Type> right)
{
this.value = value;
this.left = left;
this.right = right;
this.size = 1 + size(left) + size(right);
this.height = 1 + Math.max(height(left), height(right));
}
public Node<Type> rotateLeft()
{
Node<Type> left = new Node(this.value, this.left, this.right.left);
return new Node(this.right.value, left, this.right.right);
}
public Node<Type> rotateRight()
{
Node right = new Node(this.value, this.left.right, this.right);
return new Node(this.left.value, this.left.left, right);
}
}
public static class SortedSetAVL<Type> implements SortedSet<Type>
{
public Comparator<? super Type> comparator;
public Node<Type> root;
private SortedSetAVL(Comparator<? super Type> comparator, Node<Type> root)
{
this.comparator = comparator;
this.root = root;
}
public SortedSetAVL(Comparator<? super Type> comparator)
{
this(comparator, null);
}
public SortedSetAVL(Collection<? extends Type> collection, Comparator<? super Type> comparator)
{
this(comparator, null);
this.addAll(collection);
}
public SortedSetAVL(SortedSetAVL sortedSetAVL)
{
this(sortedSetAVL.comparator, Node.clone(sortedSetAVL.root));
}
@Override
public void clear()
{
this.root = null;
}
@Override
public Comparator<? super Type> comparator()
{
return this.comparator;
}
public Type get(Type value)
{
Node<Type> node = Node.get(this.root, value, this.comparator);
return node == null ? null : node.value;
}
@Override
public SortedSetAVL<Type> subSet(Type valueStart, Type valueEnd)
{
return tailSet(valueStart).headSet(valueEnd);
}
@Override
public SortedSetAVL<Type> headSet(Type valueEnd)
{
return new SortedSetAVL<>(this.comparator, Node.head(this.root, valueEnd, this.comparator));
}
@Override
public SortedSetAVL<Type> tailSet(Type valueStart)
{
return new SortedSetAVL<>(this.comparator, Node.tail(this.root, valueStart, this.comparator));
}
@Override
public Type first()
{
return Node.first(this.root).value;
}
@Override
public Type last()
{
return Node.last(this.root).value;
}
@Override
public int size()
{
return this.root == null ? 0 : this.root.size;
}
@Override
public boolean isEmpty()
{
return this.root == null;
}
@Override
public boolean contains(Object value)
{
return Node.get(this.root, (Type) value, this.comparator) != null;
}
@Override
public Iterator<Type> iterator()
{
Stack<Node<Type>> path = new Stack<>();
return new Iterator<Type>()
{
{
push(SortedSetAVL.this.root);
}
public void push(Node<Type> node)
{
while (node != null)
{
path.push(node);
node = node.left;
}
}
@Override
public boolean hasNext()
{
return !path.isEmpty();
}
@Override
public Type next()
{
if (path.isEmpty())
{
throw new NoSuchElementException();
}
else
{
Node<Type> node = path.peek();
Type result = node.value;
if (node.right != null)
{
push(node.right);
}
else
{
do
{
node = path.pop();
}
while (!path.isEmpty() && path.peek().right == node);
}
return result;
}
}
};
}
@Override
public Object[] toArray()
{
List<Object> list = new ArrayList<>();
Node.traverseOrderIn(this.root, list::add);
return list.toArray();
}
@Override
public <T> T[] toArray(T[] ts)
{
throw new UnsupportedOperationException();
}
@Override
public boolean add(Type value)
{
int sizeBefore = size();
this.root = Node.insert(this.root, value, this.comparator);
return sizeBefore != size();
}
@Override
public boolean remove(Object value)
{
int sizeBefore = size();
this.root = Node.delete(this.root, (Type) value, this.comparator);
return sizeBefore != size();
}
@Override
public boolean containsAll(Collection<?> collection)
{
return collection.stream()
.allMatch(this::contains);
}
@Override
public boolean addAll(Collection<? extends Type> collection)
{
return collection.stream()
.map(this::add)
.reduce(true, (x, y) -> x | y);
}
@Override
public boolean retainAll(Collection<?> collection)
{
SortedSetAVL<Type> set = new SortedSetAVL<>(this.comparator);
collection.stream()
.map(element -> (Type) element)
.filter(this::contains)
.forEach(set::add);
boolean result = size() != set.size();
this.root = set.root;
return result;
}
@Override
public boolean removeAll(Collection<?> collection)
{
return collection.stream()
.map(this::remove)
.reduce(true, (x, y) -> x | y);
}
@Override
public String toString()
{
return "{" + D_403.toString(this, ", ") + "}";
}
}
public static class SortedMapAVL<TypeKey, TypeValue> implements SortedMap<TypeKey, TypeValue>
{
public final Comparator<? super TypeKey> comparator;
public final SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet;
public SortedMapAVL(Comparator<? super TypeKey> comparator)
{
this(comparator, new SortedSetAVL<>((entry0, entry1) -> comparator.compare(entry0.getKey(), entry1.getKey())));
}
private SortedMapAVL(Comparator<? super TypeKey> comparator, SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet)
{
this.comparator = comparator;
this.entrySet = entrySet;
}
@Override
public Comparator<? super TypeKey> comparator()
{
return this.comparator;
}
@Override
public SortedMapAVL<TypeKey, TypeValue> subMap(TypeKey keyStart, TypeKey keyEnd)
{
return new SortedMapAVL<>(this.comparator, this.entrySet.subSet(new AbstractMap.SimpleEntry<>(keyStart, null), new AbstractMap.SimpleEntry<>(keyEnd, null)));
}
@Override
public SortedMapAVL<TypeKey, TypeValue> headMap(TypeKey keyEnd)
{
return new SortedMapAVL<>(this.comparator, this.entrySet.headSet(new AbstractMap.SimpleEntry<>(keyEnd, null)));
}
@Override
public SortedMapAVL<TypeKey, TypeValue> tailMap(TypeKey keyStart)
{
return new SortedMapAVL<>(this.comparator, this.entrySet.tailSet(new AbstractMap.SimpleEntry<>(keyStart, null)));
}
public Entry<TypeKey, TypeValue> firstEntry()
{
return this.entrySet.first();
}
@Override
public TypeKey firstKey()
{
return firstEntry().getKey();
}
public Entry<TypeKey, TypeValue> lastEntry()
{
return this.entrySet.last();
}
@Override
public TypeKey lastKey()
{
return lastEntry().getKey();
}
@Override
public int size()
{
return this.entrySet().size();
}
@Override
public boolean isEmpty()
{
return this.entrySet.isEmpty();
}
@Override
public boolean containsKey(Object key)
{
return this.entrySet().contains(key);
}
@Override
public boolean containsValue(Object value)
{
throw new UnsupportedOperationException();
}
@Override
public TypeValue get(Object key)
{
Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>((TypeKey) key, null);
entry = this.entrySet.get(entry);
return entry == null ? null : entry.getValue();
}
@Override
public TypeValue put(TypeKey key, TypeValue value)
{
TypeValue result = get(key);
Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>(key, value);
this.entrySet().add(entry);
return result;
}
@Override
public TypeValue remove(Object key)
{
TypeValue result = get(key);
Entry<TypeKey, TypeValue> entry = new AbstractMap.SimpleEntry<>((TypeKey) key, null);
this.entrySet.remove(entry);
return result;
}
@Override
public void putAll(Map<? extends TypeKey, ? extends TypeValue> map)
{
map.entrySet().stream()
.forEach(entry -> put(entry.getKey(), entry.getValue()));
}
@Override
public void clear()
{
this.entrySet.clear();
}
@Override
public Set<TypeKey> keySet()
{
throw new UnsupportedOperationException();
}
@Override
public Collection<TypeValue> values()
{
return new Collection<TypeValue>()
{
@Override
public int size()
{
return SortedMapAVL.this.entrySet.size();
}
@Override
public boolean isEmpty()
{
return SortedMapAVL.this.entrySet.isEmpty();
}
@Override
public boolean contains(Object value)
{
throw new UnsupportedOperationException();
}
@Override
public Iterator<TypeValue> iterator()
{
return new Iterator<TypeValue>()
{
Iterator<Entry<TypeKey, TypeValue>> iterator = SortedMapAVL.this.entrySet.iterator();
@Override
public boolean hasNext()
{
return this.iterator.hasNext();
}
@Override
public TypeValue next()
{
return this.iterator.next().getValue();
}
};
}
@Override
public Object[] toArray()
{
throw new UnsupportedOperationException();
}
@Override
public <T> T[] toArray(T[] ts)
{
throw new UnsupportedOperationException();
}
@Override
public boolean add(TypeValue typeValue)
{
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object o)
{
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(Collection<?> collection)
{
throw new UnsupportedOperationException();
}
@Override
public boolean addAll(Collection<? extends TypeValue> collection)
{
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> collection)
{
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> collection)
{
throw new UnsupportedOperationException();
}
@Override
public void clear()
{
throw new UnsupportedOperationException();
}
};
}
@Override
public SortedSetAVL<Entry<TypeKey, TypeValue>> entrySet()
{
return this.entrySet;
}
@Override
public String toString()
{
return this.entrySet().toString();
}
}
public static class FIFO<Type>
{
public SingleLinkedList<Type> start;
public SingleLinkedList<Type> end;
public FIFO()
{
this.start = null;
this.end = null;
}
public boolean isEmpty()
{
return this.start == null;
}
public Type peek()
{
return this.start.element;
}
public Type pop()
{
Type result = this.start.element;
this.start = this.start.next;
return result;
}
public void push(Type element)
{
SingleLinkedList<Type> list = new SingleLinkedList<>(element, null);
if (this.start == null)
{
this.start = list;
this.end = list;
}
else
{
this.end.next = list;
this.end = list;
}
}
}
public static class MapCount<Type> extends SortedMapAVL<Type, Long>
{
private int count;
public MapCount(Comparator<? super Type> comparator)
{
super(comparator);
this.count = 0;
}
public long add(Type key, Long delta)
{
long result;
if (delta > 0)
{
Long value = get(key);
if (value == null)
{
value = delta;
}
else
{
value += delta;
}
put(key, value);
result = delta;
}
else
{
result = 0;
}
this.count += result;
return result;
}
public int count()
{
return this.count;
}
public List<Type> flatten()
{
List<Type> result = new ArrayList<>();
for (Entry<Type, Long> entry : entrySet())
{
for (long index = 0; index < entry.getValue(); index++)
{
result.add(entry.getKey());
}
}
return result;
}
@Override
public void putAll(Map<? extends Type, ? extends Long> map)
{
throw new UnsupportedOperationException();
}
@Override
public Long remove(Object key)
{
Long result = super.remove(key);
this.count -= result;
return result;
}
public long remove(Type key, Long delta)
{
long result;
if (delta > 0)
{
Long value = get(key) - delta;
if (value <= 0)
{
result = delta + value;
remove(key);
}
else
{
result = delta;
put(key, value);
}
}
else
{
result = 0;
}
this.count -= result;
return result;
}
@Override
public SortedMapAVL<Type, Long> subMap(Type keyStart, Type keyEnd)
{
throw new UnsupportedOperationException();
}
@Override
public SortedMapAVL<Type, Long> headMap(Type keyEnd)
{
throw new UnsupportedOperationException();
}
@Override
public SortedMapAVL<Type, Long> tailMap(Type keyStart)
{
throw new UnsupportedOperationException();
}
}
public static class MapSet<TypeKey, TypeValue> extends SortedMapAVL<TypeKey, SortedSetAVL<TypeValue>> implements Iterable<TypeValue>
{
private Comparator<? super TypeValue> comparatorValue;
public MapSet(Comparator<? super TypeKey> comparatorKey, Comparator<? super TypeValue> comparatorValue)
{
super(comparatorKey);
this.comparatorValue = comparatorValue;
}
public MapSet(Comparator<? super TypeKey> comparatorKey, SortedSetAVL<Entry<TypeKey, SortedSetAVL<TypeValue>>> entrySet, Comparator<? super TypeValue> comparatorValue)
{
super(comparatorKey, entrySet);
this.comparatorValue = comparatorValue;
}
public TypeValue firstValue()
{
TypeValue result;
Entry<TypeKey, SortedSetAVL<TypeValue>> firstEntry = firstEntry();
if (firstEntry == null)
{
result = null;
}
else
{
result = firstEntry.getValue().first();
}
return result;
}
public Iterator<TypeValue> iterator()
{
return new Iterator<TypeValue>()
{
Iterator<SortedSetAVL<TypeValue>> iteratorValues = values().iterator();
Iterator<TypeValue> iteratorValue = null;
@Override
public boolean hasNext()
{
return iteratorValues.hasNext() || (iteratorValue != null && iteratorValue.hasNext());
}
@Override
public TypeValue next()
{
if (iteratorValue == null || !iteratorValue.hasNext())
{
iteratorValue = iteratorValues.next().iterator();
}
return iteratorValue.next();
}
};
}
public TypeValue lastValue()
{
TypeValue result;
Entry<TypeKey, SortedSetAVL<TypeValue>> lastEntry = lastEntry();
if (lastEntry == null)
{
result = null;
}
else
{
result = lastEntry.getValue().last();
}
return result;
}
public boolean add(TypeKey key, TypeValue value)
{
SortedSetAVL<TypeValue> set = get(key);
if (set == null)
{
set = new SortedSetAVL<>(comparatorValue);
put(key, set);
}
return set.add(value);
}
public boolean removeSet(TypeKey key, TypeValue value)
{
boolean result;
SortedSetAVL<TypeValue> set = get(key);
if (set == null)
{
result = false;
}
else
{
result = set.remove(value);
if (set.size() == 0)
{
remove(key);
}
}
return result;
}
@Override
public MapSet<TypeKey, TypeValue> headMap(TypeKey keyEnd)
{
return new MapSet(this.comparator, this.entrySet.headSet(new AbstractMap.SimpleEntry<>(keyEnd, null)), this.comparatorValue);
}
@Override
public MapSet<TypeKey, TypeValue> tailMap(TypeKey keyStart)
{
return new MapSet(this.comparator, this.entrySet.tailSet(new AbstractMap.SimpleEntry<>(keyStart, null)), this.comparatorValue);
}
}
static class IteratorBuffer<Type>
{
private Iterator<Type> iterator;
private List<Type> list;
public IteratorBuffer(Iterator<Type> iterator)
{
this.iterator = iterator;
this.list = new ArrayList<Type>();
}
public Iterator<Type> iterator()
{
return new Iterator<Type>()
{
int index = 0;
@Override
public boolean hasNext()
{
return this.index < list.size() || iterator().hasNext();
}
@Override
public Type next()
{
if (list.size() <= this.index)
{
list.add(iterator.next());
}
Type result = list.get(index);
index += 1;
return result;
}
};
}
}
public static <Type> List<List<Type>> permutations(List<Type> list)
{
List<List<Type>> result = new ArrayList<>();
result.add(new ArrayList<>());
for (Type element : list)
{
List<List<Type>> permutations = result;
result = new ArrayList<>();
for (List<Type> permutation : permutations)
{
for (int index = 0; index <= permutation.size(); index++)
{
List<Type> permutationNew = new ArrayList<>(permutation);
permutationNew.add(index, element);
result.add(permutationNew);
}
}
}
return result;
}
public static List<List<Integer>> combinations(int n, int k)
{
List<List<Integer>> result = new ArrayList<>();
if (k == 0)
{
}
else
{
if (k == 1)
{
List<Integer> combination = new ArrayList<>();
combination.add(n);
result.add(combination);
}
else
{
for (int index = 0; index <= n; index++)
{
for (List<Integer> combination : combinations(n - index, k - 1))
{
combination.add(index);
result.add(combination);
}
}
}
}
return result;
}
public static <Type> int compare(Iterator<Type> iterator0, Iterator<Type> iterator1, Comparator<Type> comparator)
{
int result = 0;
while (result == 0 && iterator0.hasNext() && iterator1.hasNext())
{
result = comparator.compare(iterator0.next(), iterator1.next());
}
if (result == 0)
{
if (iterator1.hasNext())
{
result = -1;
}
else
{
if (iterator0.hasNext())
{
result = 1;
}
}
}
return result;
}
public static <Type> int compare(Iterable<Type> iterable0, Iterable<Type> iterable1, Comparator<Type> comparator)
{
return compare(iterable0.iterator(), iterable1.iterator(), comparator);
}
private static String nextString() throws IOException
{
while ((stringTokenizer == null) || (!stringTokenizer.hasMoreTokens()))
{
stringTokenizer = new StringTokenizer(bufferedReader.readLine());
}
return stringTokenizer.nextToken();
}
private static String[] nextStrings(int n) throws IOException
{
String[] result = new String[n];
{
for (int index = 0; index < n; index++)
{
result[index] = nextString();
}
}
return result;
}
public static int nextInt() throws IOException
{
return Integer.parseInt(nextString());
}
public static int[] nextInts(int n) throws IOException
{
int[] result = new int[n];
{
for (int index = 0; index < n; index++)
{
result[index] = nextInt();
}
}
return result;
}
public static double nextDouble() throws IOException
{
return Double.parseDouble(nextString());
}
public static long nextLong() throws IOException
{
return Long.parseLong(nextString());
}
public static long[] nextLongs(int n) throws IOException
{
long[] result = new long[n];
{
for (int index = 0; index < n; index++)
{
result[index] = nextLong();
}
}
return result;
}
public static String nextLine() throws IOException
{
return bufferedReader.readLine();
}
public static void close()
{
out.close();
}
public static int binarySearchMinimum(Function<Integer, Boolean> filter, int start, int end)
{
int result;
if (start == end)
{
result = end;
}
else
{
int middle = start + (end - start) / 2;
if (filter.apply(middle))
{
result = binarySearchMinimum(filter, start, middle);
}
else
{
result = binarySearchMinimum(filter, middle + 1, end);
}
}
return result;
}
public static int binarySearchMaximum(Function<Integer, Boolean> filter, int start, int end)
{
return -binarySearchMinimum(x -> filter.apply(-x), -end, -start);
}
public static long divideCeil(long x, long y)
{
return (x + y - 1) / y;
}
public static Set<Long> divisors(long n)
{
SortedSetAVL<Long> result = new SortedSetAVL<>(Comparator.naturalOrder());
result.add(1L);
for (Long factor : factors(n))
{
SortedSetAVL<Long> divisors = new SortedSetAVL<>(result);
for (Long divisor : result)
{
divisors.add(divisor * factor);
}
result = divisors;
}
return result;
}
public static long faculty(int n)
{
long result = 1;
for (int index = 2; index <= n; index++)
{
result *= index;
}
return result;
}
public static LinkedList<Long> factors(long n)
{
LinkedList<Long> result = new LinkedList<>();
Iterator<Long> primes = ITERATOR_BUFFER_PRIME.iterator();
Long prime;
while (n > 1 && (prime = primes.next()) * prime <= n)
{
while (n % prime == 0)
{
result.add(prime);
n /= prime;
}
}
if (n > 1)
{
result.add(n);
}
return result;
}
public static long gcd(long a, long b)
{
while (a != 0 && b != 0)
{
if (a > b)
{
a %= b;
}
else
{
b %= a;
}
}
return a + b;
}
public static long[] generatePOWER2()
{
long[] result = new long[63];
for (int x = 0; x < result.length; x++)
{
result[x] = 1L << x;
}
return result;
}
public static boolean isPrime(long x)
{
boolean result = x > 1;
Iterator<Long> iterator = ITERATOR_BUFFER_PRIME.iterator();
Long prime;
while ((prime = iterator.next()) * prime <= x)
{
result &= x % prime > 0;
}
return result;
}
public static long knapsack(List<Tuple3<Long, Integer, Integer>> itemsValueWeightCount, int weightMaximum)
{
long[] valuesMaximum = new long[weightMaximum + 1];
for (Tuple3<Long, Integer, Integer> itemValueWeightCount : itemsValueWeightCount)
{
long itemValue = itemValueWeightCount.v0;
int itemWeight = itemValueWeightCount.v1;
int itemCount = itemValueWeightCount.v2;
for (int weight = weightMaximum; 0 <= weight; weight--)
{
for (int index = 1; index <= itemCount && 0 <= weight - index * itemWeight; index++)
{
valuesMaximum[weight] = Math.max(valuesMaximum[weight], valuesMaximum[weight - index * itemWeight] + index * itemValue);
}
}
}
long result = 0;
for (long valueMaximum : valuesMaximum)
{
result = Math.max(result, valueMaximum);
}
return result;
}
public static boolean knapsackPossible(List<Tuple2<Integer, Integer>> itemsWeightCount, int weightMaximum)
{
boolean[] weightPossible = new boolean[weightMaximum + 1];
weightPossible[0] = true;
int weightLargest = 0;
for (Tuple2<Integer, Integer> itemWeightCount : itemsWeightCount)
{
int itemWeight = itemWeightCount.v0;
int itemCount = itemWeightCount.v1;
for (int weightStart = 0; weightStart < itemWeight; weightStart++)
{
int count = 0;
for (int weight = weightStart; weight <= weightMaximum && (0 < count || weight <= weightLargest); weight += itemWeight)
{
if (weightPossible[weight])
{
count = itemCount;
}
else
{
if (0 < count)
{
weightPossible[weight] = true;
weightLargest = weight;
count -= 1;
}
}
}
}
}
return weightPossible[weightMaximum];
}
public static long lcm(int a, int b)
{
return a * b / gcd(a, b);
}
public static <T> List<T> permutation(long p, List<T> x)
{
List<T> copy = new ArrayList<>();
for (int index = 0; index < x.size(); index++)
{
copy.add(x.get(index));
}
List<T> result = new ArrayList<>();
for (int indexTo = 0; indexTo < x.size(); indexTo++)
{
int indexFrom = (int) p % copy.size();
p = p / copy.size();
result.add(copy.remove(indexFrom));
}
return result;
}
public static <Type> String toString(Iterator<Type> iterator, String separator)
{
StringBuffer stringBuffer = new StringBuffer();
if (iterator.hasNext())
{
stringBuffer.append(iterator.next());
}
while (iterator.hasNext())
{
stringBuffer.append(separator);
stringBuffer.append(iterator.next());
}
return stringBuffer.toString();
}
public static <Type> String toString(Iterator<Type> iterator)
{
return toString(iterator, " ");
}
public static <Type> String toString(Iterable<Type> iterable, String separator)
{
return toString(iterable.iterator(), separator);
}
public static <Type> String toString(Iterable<Type> iterable)
{
return toString(iterable, " ");
}
public static Stream<BigInteger> streamFibonacci()
{
return Stream.generate(new Supplier<BigInteger>()
{
private BigInteger n0 = BigInteger.ZERO;
private BigInteger n1 = BigInteger.ONE;
@Override
public BigInteger get()
{
BigInteger result = n0;
n0 = n1;
n1 = result.add(n0);
return result;
}
});
}
public static Stream<Long> streamPrime(int sieveSize)
{
return Stream.generate(new Supplier<Long>()
{
private boolean[] isPrime = new boolean[sieveSize];
private long sieveOffset = 2;
private List<Long> primes = new ArrayList<>();
private int index = 0;
public void filter(long prime, boolean[] result)
{
if (prime * prime < this.sieveOffset + sieveSize)
{
long remainingStart = this.sieveOffset % prime;
long start = remainingStart == 0 ? 0 : prime - remainingStart;
for (long index = start; index < sieveSize; index += prime)
{
result[(int) index] = false;
}
}
}
public void generatePrimes()
{
Arrays.fill(this.isPrime, true);
this.primes.forEach(prime -> filter(prime, isPrime));
for (int index = 0; index < sieveSize; index++)
{
if (isPrime[index])
{
this.primes.add(this.sieveOffset + index);
filter(this.sieveOffset + index, isPrime);
}
}
this.sieveOffset += sieveSize;
}
@Override
public Long get()
{
while (this.primes.size() <= this.index)
{
generatePrimes();
}
Long result = this.primes.get(this.index);
this.index += 1;
return result;
}
});
}
public static long totient(long n)
{
Set<Long> factors = new SortedSetAVL<>(factors(n), Comparator.naturalOrder());
long result = n;
for (long p : factors)
{
result -= result / p;
}
return result;
}
public static void main(String[] args)
{
try
{
solve();
} catch (IOException exception)
{
exception.printStackTrace();
}
close();
}
public static void solve() throws IOException
{
int n = nextInt();
String[] namesTwo = new String[n];
Character[] namesOne = new Character[n];
Character[] hometownsOne = new Character[n];
Map<String, MapSet<Character, Character>> namesTwo2NamesOne2HometownsOne = new SortedMapAVL<>(Comparator.naturalOrder());
boolean result = true;
for (int index = 0; index < n; index++)
{
String name = nextString();
namesTwo[index] = name.substring(0, 2);
namesOne[index] = name.charAt(2);
hometownsOne[index] = nextString().charAt(0);
MapSet<Character, Character> namesOne2HometownsOne = namesTwo2NamesOne2HometownsOne.get(namesTwo[index]);
if (namesOne2HometownsOne == null)
{
namesOne2HometownsOne = new MapSet<>(Comparator.naturalOrder(), Comparator.naturalOrder());
namesTwo2NamesOne2HometownsOne.put(namesTwo[index], namesOne2HometownsOne);
}
result &= namesOne2HometownsOne.add(namesOne[index], hometownsOne[index]);
}
Map<String, Map<Tuple2Comparable<Character, Character>, Character>> namesTwo2NameOneHomeTownOne2Result = new SortedMapAVL<>(Comparator.naturalOrder());
for (Map.Entry<String, MapSet<Character, Character>> entry : namesTwo2NamesOne2HometownsOne.entrySet())
{
Set<Character> usedHometown = new SortedSetAVL<>(Comparator.naturalOrder());
String nameTwo = entry.getKey();
MapSet<Character, Character> namesOne2HometownsOne = entry.getValue();
for (Map.Entry<Character, SortedSetAVL<Character>> nameOne2HometownsOne : namesOne2HometownsOne.entrySet())
{
Character nameOne = nameOne2HometownsOne.getKey();
Set<Character> hometownsOneSet = nameOne2HometownsOne.getValue();
if (1 < hometownsOneSet.size())
{
for (Character hometownOne : hometownsOneSet)
{
result &= usedHometown.add(hometownOne);
addResult(namesTwo2NameOneHomeTownOne2Result, nameTwo, nameOne, hometownOne, hometownOne);
}
}
}
Set<Character> usedName = new SortedSetAVL<>(Comparator.naturalOrder());
for (Map.Entry<Character, SortedSetAVL<Character>> nameOne2HometownsOne : namesOne2HometownsOne.entrySet())
{
Character nameOne = nameOne2HometownsOne.getKey();
SortedSetAVL<Character> hometownsOneSet = nameOne2HometownsOne.getValue();
if (1 == hometownsOneSet.size())
{
if (usedHometown.contains(nameOne))
{
Character hometownOne = hometownsOneSet.first();
result &= usedHometown.add(hometownOne);
addResult(namesTwo2NameOneHomeTownOne2Result, nameTwo, nameOne, hometownOne, hometownOne);
while (usedName.contains(hometownOne))
{
usedName.remove(hometownOne);
nameOne = hometownOne;
hometownOne = namesOne2HometownsOne.get(hometownOne).first();
result &= usedHometown.add(hometownOne);
addResult(namesTwo2NameOneHomeTownOne2Result, nameTwo, nameOne, hometownOne, hometownOne);
}
}
else
{
usedName.add(nameOne);
}
}
}
for (Map.Entry<Character, SortedSetAVL<Character>> nameOne2HometownsOne : namesOne2HometownsOne.entrySet())
{
Character nameOne = nameOne2HometownsOne.getKey();
SortedSetAVL<Character> hometownsOneSet = nameOne2HometownsOne.getValue();
if (1 == hometownsOneSet.size() && usedName.contains(nameOne))
{
Character hometownOne = hometownsOneSet.first();
Character character;
if (usedHometown.add(nameOne))
{
character = nameOne;
}
else
{
result &= usedHometown.add(hometownOne);
character = hometownOne;
}
addResult(namesTwo2NameOneHomeTownOne2Result, nameTwo, nameOne, hometownOne, character);
}
}
}
if (result)
{
out.println("YES");
for (int index = 0; index < n; index++)
{
String nameTwo = namesTwo[index];
Character nameOne = namesOne[index];
Character hometownOne = hometownsOne[index];
out.println(namesTwo[index] + namesTwo2NameOneHomeTownOne2Result.get(nameTwo).get(new Tuple2Comparable<>(nameOne, hometownOne)));
}
}
else
{
out.println("NO");
}
}
private static void addResult(
Map<String, Map<Tuple2Comparable<Character, Character>, Character>> namesTwo2NameOneHomeTownOne2Result,
String nameTwo,
Character nameOne,
Character hometownOne,
Character result
)
{
Map<Tuple2Comparable<Character, Character>, Character> nameOneHomeTownOne2Result = namesTwo2NameOneHomeTownOne2Result.get(nameTwo);
if (nameOneHomeTownOne2Result == null)
{
nameOneHomeTownOne2Result = new SortedMapAVL<>(Comparator.naturalOrder());
namesTwo2NameOneHomeTownOne2Result.put(nameTwo, nameOneHomeTownOne2Result);
}
nameOneHomeTownOne2Result.put(new Tuple2Comparable<>(nameOne, hometownOne), result);
}
} | Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | 2344022287b8d52e7ef0f905ea090239 | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
/**
* @author ramilagger
*/
public class Main {
boolean ok;
final static boolean ONLINE_JUDGE = System.getProperty("ONLINE_JUDGE") != null;
class Club {
String pre;
char a, b;
boolean t;
Club(char a, char b,String pre) {
this.a = a;
this.b = b;
this.pre = pre;
}
@Override
public String toString() {
return "Club{" +
"pre='" + pre + '\'' +
", a=" + a +
", b=" + b +
", t=" + t +
'}';
}
}
void solve() {
int n = nextInt();
ArrayList<Club>[][] clubs = new ArrayList[26][26];
for (int i = 0; i < 26; i++) {
for (int j = 0; j < 26; j++) {
clubs[i][j] = new ArrayList<>();
}
}
Club[] all = new Club[n];
for (int i = 0; i < n; i++) {
String ss = next();
char[] s = ss.toCharArray();
Club c = new Club(s[2], next().charAt(0),ss.substring(0,2));
clubs[f(s[0])][f(s[1])].add(c);
all[i] = c;
}
boolean can = true;
for (int i = 0; i < 26; i++) {
for (int j = 0; j < 26; j++) {
if (clubs[i][j].size() > 26) {
can = false;
} else if (can) {
if (clubs[i][j].size() > 0) {
ok = false;
//pw.println(clubs[i][j]);
sol(0, clubs[i][j], 0,0,0);
can &= ok;
}
}
}
}
pw.println(can ? "YES" : "NO");
if (can)
for (Club c: all)
pw.println(c.pre + (c.t ? c.a : c.b));
}
boolean sol(int i, ArrayList<Club> clubs, int all,int ohFuck,int used) {
boolean go = false;
if (ok) return go;
if (i == clubs.size()) {
ok = true;
return true;
}
if ((all & (1 << (clubs.get(i).a - 'A'))) == 0 && (ohFuck & (1 << (clubs.get(i).a - 'A'))) == 0) {
clubs.get(i).t = sol(i + 1, clubs, all | (1 << (clubs.get(i).a - 'A')),
ohFuck,used | (1 << (clubs.get(i).a - 'A')));
}
if (!clubs.get(i).t && (all & (1 << (clubs.get(i).b - 'A'))) == 0) {
//pw.println();
if((used & (1 << (clubs.get(i).a - 'A'))) == 0) {
all |= (1 << (clubs.get(i).b - 'A'));
// pw.println(clubs.get(i).b);
go |= sol(i + 1, clubs, all, ohFuck | (1 << (clubs.get(i).a - 'A')),used);
}
}
return go | clubs.get(i).t;
}
private int f(char c) {
return c - 'A';
}
public void run() throws IOException {
start = System.currentTimeMillis();
solve();
if (!ONLINE_JUDGE)
System.err.println(System.currentTimeMillis() - start + " ms");
br.close();
pw.close();
}
public Main() {
try {
br = (ONLINE_JUDGE) ? new BufferedReader(new InputStreamReader(System.in))
: new BufferedReader(new FileReader("in.txt"));
pw = (ONLINE_JUDGE) ? new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))
: new PrintWriter(new BufferedWriter(new FileWriter("out.txt")));
this.run();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
}
public static void main(String[] args) {
new Main();
}
public boolean hasNext() {
if (st != null && st.hasMoreTokens())
return true;
try {
while (st == null || !st.hasMoreTokens())
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
return false;
}
return true;
}
public String next() {
if (hasNext())
return st.nextToken();
return null;
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
public String nextLine() {
StringBuilder sb;
try {
while (st == null || !st.hasMoreTokens()) return br.readLine();
sb = new StringBuilder(st.nextToken());
while (st.hasMoreTokens()) sb.append(" " + st.nextToken());
} catch (IOException e) {
throw new RuntimeException();
}
return sb.toString();
}
public int[] nextArray(int n) {
int[] temp = new int[n];
for (int i = 0; i < n; i++)
temp[i] = nextInt();
return temp;
}
public long[] nextLArray(int n) {
long[] temp = new long[n];
for (int i = 0; i < n; i++)
temp[i] = nextLong();
return temp;
}
long start;
final BufferedReader br;
final PrintWriter pw;
StringTokenizer st;
} | Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | 960c7f53e1abcdc3eae724ff2b6a923d | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.PrintStream;
import java.io.IOException;
import java.util.HashMap;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.util.Map;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Wolfgang Beyer
*/
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();
}
static class TaskD {
Team[] teams;
Map<String, Integer> usedFirsts = new HashMap<>();
Map<String, Integer> usedSeconds = new HashMap<>();
public void solve(int testNumber, InputReader in, PrintWriter out) {
int n = in.nextInt();
teams = new Team[n];
for (int i = 0; i < n; i++) {
String name = in.next();
String city = in.next();
teams[i] = new Team(name, city);
}
for (int i = 0; i < n; i++) {
if (teams[i].choice == 0) {
if (assign(i) == false) {
out.println("NO");
return;
}
}
}
out.println("YES");
for (int i = 0; i < n; i++) {
if (teams[i].choice == 1) {
out.println(teams[i].first);
} else {
out.println(teams[i].second);
}
}
}
boolean assign(int i) {
if (!usedFirsts.containsKey(teams[i].first)) {
usedFirsts.put(teams[i].first, i);
teams[i].choice = 1;
return true;
}
if (pushToSecond(usedFirsts.get(teams[i].first)) == false) {
return false;
}
if (pushToSecond(i) == false) {
return false;
}
return true;
}
boolean pushToSecond(int i) {
if (i < 0) return true;
usedFirsts.put(teams[i].first, -1);
if (usedSeconds.containsKey(teams[i].second)) {
return false;
}
usedSeconds.put(teams[i].second, i);
//usedFirsts.put(teams[i].second, -1);
teams[i].choice = 2;
if (usedFirsts.containsKey(teams[i].second)) {
return pushToSecond(usedFirsts.get(teams[i].second));
} else {
usedFirsts.put(teams[i].second, -1);
}
return true;
}
class Team {
String first;
String second;
int choice;
public Team(String name, String city) {
first = name.substring(0, 3);
second = name.substring(0, 2) + city.charAt(0);
choice = 0;
}
}
}
static class InputReader {
private static BufferedReader in;
private static StringTokenizer tok;
public InputReader(InputStream in) {
this.in = new BufferedReader(new InputStreamReader(in));
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
try {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
} catch (IOException ex) {
System.err.println("An IOException was caught :" + ex.getMessage());
}
return tok.nextToken();
}
}
}
| Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | 2613816d5774d64f006b11f38d33529d | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.PrintStream;
import java.util.Set;
import java.io.IOException;
import java.util.HashMap;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.StringTokenizer;
import java.util.Map;
import java.io.BufferedReader;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Wolfgang Beyer
*/
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();
}
static class TaskD {
Team[] teams;
Map<String, Integer> usedFirsts = new HashMap<>();
Set<String> usedSeconds = new HashSet<>();
public void solve(int testNumber, InputReader in, PrintWriter out) {
// constructive, greedy approach:
// pick first variant,
// in case of conflict: move to second variant (+ as a consequence move others to 2nd variant too)
// if still conflict: no solution possible
int n = in.nextInt();
teams = new Team[n];
for (int i = 0; i < n; i++) {
String name = in.next();
String city = in.next();
teams[i] = new Team(name, city);
}
for (int i = 0; i < n; i++) {
if (teams[i].choice == 0) {
if (assign(i) == false) {
out.println("NO");
return;
}
}
}
out.println("YES");
for (int i = 0; i < n; i++) {
if (teams[i].choice == 1) {
out.println(teams[i].first);
} else {
out.println(teams[i].second);
}
}
}
boolean assign(int i) {
// if possible use first variant
if (!usedFirsts.containsKey(teams[i].first)) {
usedFirsts.put(teams[i].first, i);
teams[i].choice = 1;
return true;
}
// move other team occupying conflicting solution to second variant
if (pushToSecond(usedFirsts.get(teams[i].first)) == false) {
return false;
}
// use second variant for current team
if (pushToSecond(i) == false) {
return false;
}
return true;
}
boolean pushToSecond(int i) {
// move team from using variant 1 to using variant 2
if (i < 0) return true;
// remember to not use as a variant 1 solution for other team in the future
usedFirsts.put(teams[i].first, -1);
// if conflict -> no solution possible
if (usedSeconds.contains(teams[i].second)) {
return false;
}
usedSeconds.add(teams[i].second);
teams[i].choice = 2;
// if other team uses variant 1 which is the same as current team's variant 2
// move other team to variant 2
// otherwise remember not to use as variant 1 solution in the future
if (usedFirsts.containsKey(teams[i].second)) {
return pushToSecond(usedFirsts.get(teams[i].second));
} else {
usedFirsts.put(teams[i].second, -1);
}
return true;
}
class Team {
String first;
String second;
int choice;
public Team(String name, String city) {
first = name.substring(0, 3);
second = name.substring(0, 2) + city.charAt(0);
choice = 0;
}
}
}
static class InputReader {
private static BufferedReader in;
private static StringTokenizer tok;
public InputReader(InputStream in) {
this.in = new BufferedReader(new InputStreamReader(in));
}
public int nextInt() {
return Integer.parseInt(next());
}
public String next() {
try {
while (tok == null || !tok.hasMoreTokens()) {
tok = new StringTokenizer(in.readLine());
}
} catch (IOException ex) {
System.err.println("An IOException was caught :" + ex.getMessage());
}
return tok.nextToken();
}
}
}
| Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | 1793c4aef4a2f531f65226e51088f916 | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes |
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
static HashMap<String, Name> names;
static Name[] order;
public static void main(String args[]) throws IOException {
names = new HashMap<>();
Scanner sc = new Scanner(System.in);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));
int n = sc.nextInt();
order = new Name[n];
for (int i = 0; i < n; i++) {
String cName = sc.next().substring(0, 3);
String city = sc.next().substring(0, 1);
Name name = new Name(cName, city);
order[i] = name;
if (!names.containsKey(cName)) {
names.put(cName, name);
} else {
replace(name);
}
}
writer.write("YES\n");
for (int i = 0; i < n; i++) {
writer.write(order[i].name + "\n");
}
writer.close();
}
static boolean replace(Name name) {
if (names.containsKey(name.name) && names.get(name.name) != null && names.get(name.name).city != "") {
Name oldName = names.get(name.name);
names.put(name.name, null);
replace(oldName);
}
name.name = name.name.substring(0, 2) + name.city;
name.city = "";
if (!names.containsKey(name.name) || names.get(name.name) == null) {
names.put(name.name, name);
} else if (names.get(name.name).city.length() == 1) {
Name oldName = names.get(name.name);
names.put(name.name, null);
if (replace(oldName) && oldName.name != name.name) {
names.put(name.name, name);
} else {
System.out.println("NO");
System.exit(0);
}
} else if (names.get(name.name).city.length() == 0) {
System.out.println("NO");
System.exit(0);
}
return true;
}
}
class Name {
public String name;
public String city;
public Name(String name, String city) {
this.name = name;
this.city = city;
}
} | Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | c469e418f126be9f5ef9bdefa125cff1 | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes | import java.util.*;
import java.io.*;
public class Main
{
static class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next()
{
while (st == null || !st.hasMoreElements())
{
try
{
st = new StringTokenizer(br.readLine());
}
catch (IOException e)
{
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt()
{
return Integer.parseInt(next());
}
long nextLong()
{
return Long.parseLong(next());
}
double nextDouble()
{
return Double.parseDouble(next());
}
String nextLine()
{
String str = "";
try
{
str = br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
return str;
}
}
public static void main (String[] args)
{
FastReader reader = new FastReader();
PrintWriter writer = new PrintWriter (System.out);
int totalClubs = reader.nextInt();
String[] type1 = new String[totalClubs];
String[] res = new String[totalClubs];
HashSet<String> map = new HashSet<String>(90000);
for (int k=0; k<totalClubs; k++)
{
String first = reader.next();
String sec = reader.next();
type1[k] = first.substring (0,3);
String name2 = first.substring(0,2) + sec.substring(0,1);
if (!map.contains(name2))
{
res[k] = name2;
map.add (name2);
}
else
{
String name1 = type1[k];
if (map.contains(name1))
{
System.out.println ("NO");
return;
}
else
{
for (int i=0; i<k; i++)
{
if (type1[i].equals (name1))
{
System.out.println ("NO");
return;
}
}
res[k] = name1;
map.add (name1);
}
}
//totalClubs--;
}
writer.println ("YES");
for (int i=0; i<totalClubs; i++)
writer.println (res[i]);
writer.close();
}
}
| Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | cf443e67a84e0e5704b2c259f7929522 | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.StringTokenizer;
public class P782D
{
public static void main(String[] args)
{
FastScanner scan = new FastScanner();
int n = scan.nextInt();
Team[] teams = new Team[n];
HashMap<String, ArrayList<Team>> map = new HashMap<>();
for (int i = 0; i < n; i++)
{
teams[i] = new Team(scan.next(), scan.next());
String st = teams[i].start;
if (!map.containsKey(st))
map.put(st, new ArrayList<>());
map.get(st).add(teams[i]);
}
HashSet<String> used = new HashSet<>();
boolean poss = true;
for (Map.Entry<String, ArrayList<Team>> en : map.entrySet())
{
ArrayList<Team> list = en.getValue();
HashMap<String, Group> map2 = new HashMap<>();
for (int i = 0; i < list.size(); i++)
{
String s = list.get(i).op1;
if (!map2.containsKey(s))
map2.put(s, new Group(s));
map2.get(s).add(list.get(i));
}
PriorityQueue<Group> pq = new PriorityQueue<>();
for (Map.Entry<String, Group> en2 : map2.entrySet())
pq.add(en2.getValue());
ArrayList<Team> wait = new ArrayList<>();
while (!pq.isEmpty())
{
Group g = pq.poll();
if (g.list.size() == 1)
{
if (used.contains(g.list.get(0).op1))
{
if (used.contains(g.list.get(0).op2))
poss = false;
else
{
used.add(g.list.get(0).op2);
g.list.get(0).actual = g.list.get(0).op2;
}
}
else
{
if (used.contains(g.list.get(0).op2))
{
used.add(g.list.get(0).op1);
g.list.get(0).actual = g.list.get(0).op1;
}
else
{
wait.add(g.list.get(0));
}
}
}
else
{
for (int i = 0; poss && i < g.list.size(); i++)
{
Team team = g.list.get(i);
if (used.contains(team.op2))
poss = false;
else
{
used.add(team.op2);
team.actual = team.op2;
}
}
}
}
boolean ok = false;
while (!ok && poss)
{
ok = true;
for (int i = wait.size()-1; poss && i >= 0; i--)
{
Team team = wait.get(i);
if (used.contains(team.op1))
{
if (used.contains(team.op2))
poss = false;
else
{
used.add(team.op2);
team.actual = team.op2;
wait.remove(i);
ok = false;
}
}
else if (used.contains(team.op2))
{
used.add(team.op1);
team.actual = team.op1;
wait.remove(i);
ok = false;
}
}
}
for (int i = 0; poss && i < wait.size(); i++)
{
Team team = wait.get(i);
used.add(team.op1);
team.actual = team.op1;
}
if (!poss)
break;
}
PrintWriter pw = new PrintWriter(System.out);
if (!poss)
pw.println("NO");
else
{
pw.println("YES");
for (int i = 0; i < teams.length; i++)
pw.println(teams[i].actual);
}
pw.flush();
}
static class Group implements Comparable<Group>
{
String s;
ArrayList<Team> list = new ArrayList<>();
public Group(String st)
{
s = st;
}
public void add(Team t)
{
list.add(t);
}
public int compareTo(Group g)
{
return g.list.size() - list.size();
}
}
static class Team
{
String name, city, op1, op2, start, actual;
Team(String n, String c)
{
name = n;
city = c;
start = n.substring(0, 2);
op1 = n.substring(0, 3);
op2 = n.substring(0, 2) + c.substring(0, 1);
}
}
static class FastScanner
{
BufferedReader br;
StringTokenizer st;
public FastScanner()
{
try
{
br = new BufferedReader(new InputStreamReader(System.in));
st = new StringTokenizer(br.readLine());
} catch (Exception e)
{
e.printStackTrace();
}
}
public String next()
{
if (st.hasMoreTokens())
return st.nextToken();
try
{
st = new StringTokenizer(br.readLine());
} catch (Exception e)
{
e.printStackTrace();
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
public String nextLine()
{
String line = "";
try
{
line = br.readLine();
} catch (Exception e)
{
e.printStackTrace();
}
return line;
}
}
}
| Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | e600334cbafb19af3e19a5aa9ca9f2e4 | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.util.HashMap;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.io.InputStream;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
InputReader in = new InputReader(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskD solver = new TaskD();
solver.solve(1, in, out);
out.close();
}
static class TaskD {
private void add(HashMap<String, Integer> map, String key) {
if (!map.containsKey(key)) {
map.put(key, 1);
} else {
map.put(key, map.get(key) + 1);
}
}
private boolean dfs(int v, int[] match, boolean[] visit, ArrayList<ArrayList<Integer>> edges) {
for (int next : edges.get(v)) {
if (match[next] == -1) {
match[next] = v;
return true;
}
if (!visit[next]) {
visit[next] = true;
if (dfs(match[next], match, visit, edges)) {
match[next] = v;
return true;
}
visit[next] = false;
}
}
return false;
}
public void solve(int testNumber, InputReader in, PrintWriter out) {
int N = in.nextInt();
HashMap<String, Integer> one = new HashMap<>();
HashMap<String, Integer> two = new HashMap<>();
HashMap<String, Integer> indexes = new HashMap<>();
HashMap<Integer, String> rindexes = new HashMap<>();
String[] ones = new String[N];
String[] twos = new String[N];
int node = N;
for (int i = 0; i < N; i += 1) {
String a = in.next();
String b = in.next();
ones[i] = a.substring(0, 3);
twos[i] = a.substring(0, 2) + b.substring(0, 1);
if (!indexes.containsKey(ones[i])) {
rindexes.put(node, ones[i]);
indexes.put(ones[i], node++);
}
if (!indexes.containsKey(twos[i])) {
rindexes.put(node, twos[i]);
indexes.put(twos[i], node++);
}
add(one, ones[i]);
add(two, twos[i]);
}
ArrayList<ArrayList<Integer>> edges = new ArrayList<>();
for (int i = 0; i < node; i += 1) edges.add(new ArrayList<Integer>());
for (int i = 0; i < N; i += 1) {
if (one.get(ones[i]) == 1) {
int n = indexes.get(ones[i]);
edges.get(i).add(n);
edges.get(n).add(i);
}
int n = indexes.get(twos[i]);
edges.get(i).add(n);
edges.get(n).add(i);
}
int[] match = new int[N];
boolean[] visit = new boolean[N];
Arrays.fill(match, -1);
int cnt = 0;
for (int i = N; i < node; i += 1) {
if (dfs(i, match, visit, edges)) {
cnt += 1;
}
}
out.println(cnt == N ? "YES" : "NO");
if (cnt == N) {
for (int i = 0; i < N; i += 1) {
out.println(rindexes.get(match[i]));
}
}
}
}
static class InputReader {
public BufferedReader reader;
public 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 (IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}
| Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | 72e3c404f76d77a0484a104a1be3f62c | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes | //package baobab;
import java.io.*;
import java.util.*;
public class D {
public static void main(String[] args) {
Solver solver = new Solver();
}
static class Solver {
IO io;
public Solver() {
this.io = new IO();
try {
solve();
} finally {
io.close();
}
}
/****************************** START READING HERE ********************************/
HashMap<String, List<Team>> m;
HashSet<Team> underChanges;
void solve() {
underChanges = new HashSet<>();
int n = io.nextInt();
m = new HashMap<>();
Set<String> conflicts = new HashSet<>();
for (int i=0; i<n; i++) {
String teamName = io.next();
String homeName = io.next();
Team team = new Team(i, teamName, homeName);
String shortName = teamName.substring(0, 3);
List<Team> list = m.get(shortName);
if (list == null) {
list = new ArrayList<>();
m.put(shortName, list);
} else {
conflicts.add(shortName);
}
list.add(team);
}
List<Team> initialCityTeams = new ArrayList<>();
for (String conflictingShortName : conflicts) {
List<Team> list = m.remove(conflictingShortName);
for (Team team : list) {
initialCityTeams.add(team);
}
}
for (Team team : initialCityTeams) {
if (!possible(team)) {
io.println("NO");
return;
}
}
io.println("YES");
String[] ans = new String[n];
for (String name : m.keySet()) {
List<Team> teams = m.get(name);
int i = teams.get(0).i;
ans[i] = name;
}
for (String name : ans) {
io.println(name);
}
}
boolean possible(Team team) {
if (!underChanges.add(team)) {
return false;
}
String nameWithCity = team.teamName.substring(0, 2) + team.homeName.charAt(0);
List<Team> list = m.get(nameWithCity);
if (list != null) {
for (Team movable : list) {
if (!possible(movable)) {
return false;
}
}
}
list = new ArrayList<>();
list.add(team);
m.put(nameWithCity, list);
underChanges.remove(team);
return true;
}
class Team implements Comparable<Team> {
int i;
String teamName;
String homeName;
public Team(int i, String teamName, String homeName) {
this.i = i;
this.teamName = teamName;
this.homeName = homeName;
}
@Override
public int compareTo(Team o) {
int a = this.teamName.compareTo(o.teamName);
if (a != 0) return a;
return this.homeName.compareTo(o.homeName);
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Team team = (Team) o;
return i == team.i;
}
@Override
public int hashCode() {
return i;
}
}
/************************** UTILITY CODE BELOW THIS LINE **************************/
long MOD = (long)1e9 + 7;
List<Integer>[] toGraph(IO io, int n) {
List<Integer>[] g = new ArrayList[n+1];
for (int i=1; i<=n; i++) g[i] = new ArrayList<>();
for (int i=1; i<=n-1; i++) {
int a = io.nextInt();
int b = io.nextInt();
g[a].add(b);
g[b].add(a);
}
return g;
}
class Point {
int y;
int x;
public Point(int y, int x) {
this.y = y;
this.x = x;
}
}
class IDval implements Comparable<IDval> {
int id;
long val;
public IDval(int id, long val) {
this.val = val;
this.id = id;
}
@Override
public int compareTo(IDval o) {
if (this.val < o.val) return -1;
if (this.val > o.val) return 1;
return this.id - o.id;
}
}
long pow(long base, int exp) {
if (exp == 0) return 1L;
long x = pow(base, exp/2);
long ans = x * x;
if (exp % 2 != 0) ans *= base;
return ans;
}
long gcd(long... v) {
/** Chained calls to Euclidean algorithm. */
if (v.length == 1) return v[0];
long ans = gcd(v[1], v[0]);
for (int i=2; i<v.length; i++) {
ans = gcd(ans, v[i]);
}
return ans;
}
long gcd(long a, long b) {
/** Euclidean algorithm. */
if (b == 0) return a;
return gcd(b, a%b);
}
int[] generatePrimesUpTo(int last) {
/* Sieve of Eratosthenes. Practically O(n). Values of 0 indicate primes. */
int[] div = new int[last+1];
for (int x=2; x<=last; x++) {
if (div[x] > 0) continue;
for (int u=2*x; u<=last; u+=x) {
div[u] = x;
}
}
return div;
}
long lcm(long a, long b) {
/** Least common multiple */
return a * b / gcd(a,b);
}
private class ElementCounter {
private HashMap<Long, Integer> elements;
public ElementCounter() {
elements = new HashMap<>();
}
public void add(long element) {
int count = 1;
if (elements.containsKey(element)) count += elements.get(element);
elements.put(element, count);
}
public void remove(long element) {
int count = elements.get(element);
count--;
if (count == 0) elements.remove(element);
else elements.put(element, count);
}
public int get(long element) {
if (!elements.containsKey(element)) return 0;
return elements.get(element);
}
public int size() {
return elements.size();
}
}
class StringCounter {
HashMap<String, Long> elements;
public StringCounter() {
elements = new HashMap<>();
}
public void add(String identifier) {
long count = 1;
if (elements.containsKey(identifier)) count += elements.get(identifier);
elements.put(identifier, count);
}
public void remove(String identifier) {
long count = elements.get(identifier);
count--;
if (count == 0) elements.remove(identifier);
else elements.put(identifier, count);
}
public long get(String identifier) {
if (!elements.containsKey(identifier)) return 0;
return elements.get(identifier);
}
public int size() {
return elements.size();
}
}
class DisjointSet {
/** Union Find / Disjoint Set data structure. */
int[] size;
int[] parent;
int componentCount;
public DisjointSet(int n) {
componentCount = n;
size = new int[n];
parent = new int[n];
for (int i=0; i<n; i++) parent[i] = i;
for (int i=0; i<n; i++) size[i] = 1;
}
public void join(int a, int b) {
/* Find roots */
int rootA = parent[a];
int rootB = parent[b];
while (rootA != parent[rootA]) rootA = parent[rootA];
while (rootB != parent[rootB]) rootB = parent[rootB];
if (rootA == rootB) {
/* Already in the same set */
return;
}
/* Merge smaller set into larger set. */
if (size[rootA] > size[rootB]) {
size[rootA] += size[rootB];
parent[rootB] = rootA;
} else {
size[rootB] += size[rootA];
parent[rootA] = rootB;
}
componentCount--;
}
}
class LCAFinder {
/* O(n log n) Initialize: new LCAFinder(graph)
* O(log n) Queries: find(a,b) returns lowest common ancestor for nodes a and b */
int[] nodes;
int[] depths;
int[] entries;
int pointer;
FenwickMin fenwick;
public LCAFinder(List<Integer>[] graph) {
this.nodes = new int[(int)10e6];
this.depths = new int[(int)10e6];
this.entries = new int[graph.length];
this.pointer = 1;
boolean[] visited = new boolean[graph.length+1];
dfs(1, 0, graph, visited);
fenwick = new FenwickMin(pointer-1);
for (int i=1; i<pointer; i++) {
fenwick.set(i, depths[i] * 1000000L + i);
}
}
private void dfs(int node, int depth, List<Integer>[] graph, boolean[] visited) {
visited[node] = true;
entries[node] = pointer;
nodes[pointer] = node;
depths[pointer] = depth;
pointer++;
for (int neighbor : graph[node]) {
if (visited[neighbor]) continue;
dfs(neighbor, depth+1, graph, visited);
nodes[pointer] = node;
depths[pointer] = depth;
pointer++;
}
}
public int find(int a, int b) {
int left = entries[a];
int right = entries[b];
if (left > right) {
int temp = left;
left = right;
right = temp;
}
long mixedBag = fenwick.getMin(left, right);
int index = (int) (mixedBag % 1000000L);
return nodes[index];
}
}
class FenwickMin {
long n;
long[] original;
long[] bottomUp;
long[] topDown;
public FenwickMin(int n) {
this.n = n;
original = new long[n+2];
bottomUp = new long[n+2];
topDown = new long[n+2];
}
public void set(int modifiedNode, long value) {
long replaced = original[modifiedNode];
original[modifiedNode] = value;
// Update left tree
int i = modifiedNode;
long v = value;
while (i <= n) {
if (v > bottomUp[i]) {
if (replaced == bottomUp[i]) {
v = Math.min(v, original[i]);
for (int r=1 ;; r++) {
int x = (i&-i)>>>r;
if (x == 0) break;
int child = i-x;
v = Math.min(v, bottomUp[child]);
}
} else break;
}
if (v == bottomUp[i]) break;
bottomUp[i] = v;
i += (i&-i);
}
// Update right tree
i = modifiedNode;
v = value;
while (i > 0) {
if (v > topDown[i]) {
if (replaced == topDown[i]) {
v = Math.min(v, original[i]);
for (int r=1 ;; r++) {
int x = (i&-i)>>>r;
if (x == 0) break;
int child = i+x;
if (child > n+1) break;
v = Math.min(v, topDown[child]);
}
} else break;
}
if (v == topDown[i]) break;
topDown[i] = v;
i -= (i&-i);
}
}
public long getMin(int a, int b) {
long min = original[a];
int prev = a;
int curr = prev + (prev&-prev); // parent right hand side
while (curr <= b) {
min = Math.min(min, topDown[prev]); // value from the other tree
prev = curr;
curr = prev + (prev&-prev);;
}
min = Math.min(min, original[prev]);
prev = b;
curr = prev - (prev&-prev); // parent left hand side
while (curr >= a) {
min = Math.min(min,bottomUp[prev]); // value from the other tree
prev = curr;
curr = prev - (prev&-prev);
}
return min;
}
}
class FenwickSum {
public long[] d;
public FenwickSum(int n) {
d=new long[n+1];
}
/** a[0] must be unused. */
public FenwickSum(long[] a) {
d=new long[a.length];
for (int i=1; i<a.length; i++) {
modify(i, a[i]);
}
}
/** Do not modify i=0. */
void modify(int i, long v) {
while (i<d.length) {
d[i] += v;
// Move to next uplink on the RIGHT side of i
i += (i&-i);
}
}
/** Returns sum from a to b, *BOTH* inclusive. */
long getSum(int a, int b) {
return getSum(b) - getSum(a-1);
}
private long getSum(int i) {
long sum = 0;
while (i>0) {
sum += d[i];
// Move to next uplink on the LEFT side of i
i -= (i&-i);
}
return sum;
}
}
class SegmentTree {
/** Query sums with log(n) modifyRange */
int N;
long[] p;
public SegmentTree(int n) {
/* TODO: Test that this works. */
N = n;
p = new long[2*N];
}
public void modifyRange(int a, int b, long change) {
muuta(a, change);
muuta(b+1, -change);
}
void muuta(int k, long muutos) {
k += N;
p[k] += muutos;
for (k /= 2; k >= 1; k /= 2) {
p[k] = p[2*k] + p[2*k+1];
}
}
public long get(int k) {
int a = N;
int b = k+N;
long s = 0;
while (a <= b) {
if (a%2 == 1) s += p[a++];
if (b%2 == 0) s += p[b--];
a /= 2;
b /= 2;
}
return s;
}
}
class Zalgo {
public int pisinEsiintyma(String haku, String kohde) {
char[] s = new char[haku.length() + 1 + kohde.length()];
for (int i=0; i<haku.length(); i++) {
s[i] = haku.charAt(i);
}
int j = haku.length();
s[j++] = '#';
for (int i=0; i<kohde.length(); i++) {
s[j++] = kohde.charAt(i);
}
int[] z = toZarray(s);
int max = 0;
for (int i=haku.length(); i<z.length; i++) {
max = Math.max(max, z[i]);
}
return max;
}
public int[] toZarray(char[] s) {
int n = s.length;
int[] z = new int[n];
int a = 0, b = 0;
for (int i = 1; i < n; i++) {
if (i > b) {
for (int j = i; j < n && s[j - i] == s[j]; j++) z[i]++;
}
else {
z[i] = z[i - a];
if (i + z[i - a] > b) {
for (int j = b + 1; j < n && s[j - i] == s[j]; j++) z[i]++;
a = i;
b = i + z[i] - 1;
}
}
}
return z;
}
public List<Integer> getStartIndexesWhereWordIsFound(String haku, String kohde) {
// this is alternative use case
char[] s = new char[haku.length() + 1 + kohde.length()];
for (int i=0; i<haku.length(); i++) {
s[i] = haku.charAt(i);
}
int j = haku.length();
s[j++] = '#';
for (int i=0; i<kohde.length(); i++) {
s[j++] = kohde.charAt(i);
}
int[] z = toZarray(s);
List<Integer> indexes = new ArrayList<>();
for (int i=haku.length(); i<z.length; i++) {
if (z[i] < haku.length()) continue;
indexes.add(i);
}
return indexes;
}
}
class StringHasher {
class HashedString {
long[] hashes;
long[] modifiers;
public HashedString(long[] hashes, long[] modifiers) {
this.hashes = hashes;
this.modifiers = modifiers;
}
}
long P;
long M;
public StringHasher() {
initializePandM();
}
HashedString hashString(String s) {
int n = s.length();
long[] hashes = new long[n];
long[] modifiers = new long[n];
hashes[0] = s.charAt(0);
modifiers[0] = 1;
for (int i=1; i<n; i++) {
hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M;
modifiers[i] = (modifiers[i-1] * P) % M;
}
return new HashedString(hashes, modifiers);
}
/**
* Indices are inclusive.
*/
long getHash(HashedString hashedString, int startIndex, int endIndex) {
long[] hashes = hashedString.hashes;
long[] modifiers = hashedString.modifiers;
long result = hashes[endIndex];
if (startIndex > 0) result -= (hashes[startIndex-1] * modifiers[endIndex-startIndex+1]) % M;
if (result < 0) result += M;
return result;
}
// Less interesting methods below
/**
* Efficient for 2 input parameter strings in particular.
*/
HashedString[] hashString(String first, String second) {
HashedString[] array = new HashedString[2];
int n = first.length();
long[] modifiers = new long[n];
modifiers[0] = 1;
long[] firstHashes = new long[n];
firstHashes[0] = first.charAt(0);
array[0] = new HashedString(firstHashes, modifiers);
long[] secondHashes = new long[n];
secondHashes[0] = second.charAt(0);
array[1] = new HashedString(secondHashes, modifiers);
for (int i=1; i<n; i++) {
modifiers[i] = (modifiers[i-1] * P) % M;
firstHashes[i] = (firstHashes[i-1] * P + first.charAt(i)) % M;
secondHashes[i] = (secondHashes[i-1] * P + second.charAt(i)) % M;
}
return array;
}
/**
* Efficient for 3+ strings
* More efficient than multiple hashString calls IF strings are same length.
*/
HashedString[] hashString(String... strings) {
HashedString[] array = new HashedString[strings.length];
int n = strings[0].length();
long[] modifiers = new long[n];
modifiers[0] = 1;
for (int j=0; j<strings.length; j++) {
// if all strings are not same length, defer work to another method
if (strings[j].length() != n) {
for (int i=0; i<n; i++) {
array[i] = hashString(strings[i]);
}
return array;
}
// otherwise initialize stuff
long[] hashes = new long[n];
hashes[0] = strings[j].charAt(0);
array[j] = new HashedString(hashes, modifiers);
}
for (int i=1; i<n; i++) {
modifiers[i] = (modifiers[i-1] * P) % M;
for (int j=0; j<strings.length; j++) {
String s = strings[j];
long[] hashes = array[j].hashes;
hashes[i] = (hashes[i-1] * P + s.charAt(i)) % M;
}
}
return array;
}
void initializePandM() {
ArrayList<Long> modOptions = new ArrayList<>(20);
modOptions.add(353873237L);
modOptions.add(353875897L);
modOptions.add(353878703L);
modOptions.add(353882671L);
modOptions.add(353885303L);
modOptions.add(353888377L);
modOptions.add(353893457L);
P = modOptions.get(new Random().nextInt(modOptions.size()));
modOptions.clear();
modOptions.add(452940277L);
modOptions.add(452947687L);
modOptions.add(464478431L);
modOptions.add(468098221L);
modOptions.add(470374601L);
modOptions.add(472879717L);
modOptions.add(472881973L);
M = modOptions.get(new Random().nextInt(modOptions.size()));
}
}
private static class Prob {
/** For heavy calculations on probabilities, this class
* provides more accuracy & efficiency than doubles.
* Math explained: https://en.wikipedia.org/wiki/Log_probability
* Quick start:
* - Instantiate probabilities, eg. Prob a = new Prob(0.75)
* - add(), multiply() return new objects, can perform on nulls & NaNs.
* - get() returns probability as a readable double */
/** Logarithmized probability. Note: 0% represented by logP NaN. */
private double logP;
/** Construct instance with real probability. */
public Prob(double real) {
if (real > 0) this.logP = Math.log(real);
else this.logP = Double.NaN;
}
/** Construct instance with already logarithmized value. */
static boolean dontLogAgain = true;
public Prob(double logP, boolean anyBooleanHereToChooseThisConstructor) {
this.logP = logP;
}
/** Returns real probability as a double. */
public double get() {
return Math.exp(logP);
}
@Override
public String toString() {
return ""+get();
}
/***************** STATIC METHODS BELOW ********************/
/** Note: returns NaN only when a && b are both NaN/null. */
public static Prob add(Prob a, Prob b) {
if (nullOrNaN(a) && nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain);
if (nullOrNaN(a)) return copy(b);
if (nullOrNaN(b)) return copy(a);
double x = Math.max(a.logP, b.logP);
double y = Math.min(a.logP, b.logP);
double sum = x + Math.log(1 + Math.exp(y - x));
return new Prob(sum, dontLogAgain);
}
/** Note: multiplying by null or NaN produces NaN (repping 0% real prob). */
public static Prob multiply(Prob a, Prob b) {
if (nullOrNaN(a) || nullOrNaN(b)) return new Prob(Double.NaN, dontLogAgain);
return new Prob(a.logP + b.logP, dontLogAgain);
}
/** Returns true if p is null or NaN. */
private static boolean nullOrNaN(Prob p) {
return (p == null || Double.isNaN(p.logP));
}
/** Returns a new instance with the same value as original. */
private static Prob copy(Prob original) {
return new Prob(original.logP, dontLogAgain);
}
}
public class StronglyConnectedComponents {
/** Kosaraju's algorithm */
ArrayList<Integer>[] forw;
ArrayList<Integer>[] bacw;
/** Use: getCount(2, new int[] {1,2}, new int[] {2,1}) */
public int getCount(int n, int[] mista, int[] minne) {
forw = new ArrayList[n+1];
bacw = new ArrayList[n+1];
for (int i=1; i<=n; i++) {
forw[i] = new ArrayList<Integer>();
bacw[i] = new ArrayList<Integer>();
}
for (int i=0; i<mista.length; i++) {
int a = mista[i];
int b = minne[i];
forw[a].add(b);
bacw[b].add(a);
}
int count = 0;
List<Integer> list = new ArrayList<Integer>();
boolean[] visited = new boolean[n+1];
for (int i=1; i<=n; i++) {
dfsForward(i, visited, list);
}
visited = new boolean[n+1];
for (int i=n-1; i>=0; i--) {
int node = list.get(i);
if (visited[node]) continue;
count++;
dfsBackward(node, visited);
}
return count;
}
public void dfsForward(int i, boolean[] visited, List<Integer> list) {
if (visited[i]) return;
visited[i] = true;
for (int neighbor : forw[i]) {
dfsForward(neighbor, visited, list);
}
list.add(i);
}
public void dfsBackward(int i, boolean[] visited) {
if (visited[i]) return;
visited[i] = true;
for (int neighbor : bacw[i]) {
dfsBackward(neighbor, visited);
}
}
}
class DrawGrid {
void draw(boolean[][] d) {
System.out.print(" ");
for (int x=0; x<d[0].length; x++) {
System.out.print(" " + x + " ");
}
System.out.println("");
for (int y=0; y<d.length; y++) {
System.out.print(y + " ");
for (int x=0; x<d[0].length; x++) {
System.out.print((d[y][x] ? "[x]" : "[ ]"));
}
System.out.println("");
}
}
void draw(int[][] d) {
int max = 1;
for (int y=0; y<d.length; y++) {
for (int x=0; x<d[0].length; x++) {
max = Math.max(max, ("" + d[y][x]).length());
}
}
System.out.print(" ");
String format = "%" + (max+2) + "s";
for (int x=0; x<d[0].length; x++) {
System.out.print(String.format(format, x) + " ");
}
format = "%" + (max) + "s";
System.out.println("");
for (int y=0; y<d.length; y++) {
System.out.print(y + " ");
for (int x=0; x<d[0].length; x++) {
System.out.print(" [" + String.format(format, (d[y][x])) + "]");
}
System.out.println("");
}
}
}
class BaseConverter {
/* Palauttaa luvun esityksen kannassa base */
public String convert(Long number, int base) {
return Long.toString(number, base);
}
/* Palauttaa luvun esityksen kannassa baseTo, kun annetaan luku StringinΓ€ kannassa baseFrom */
public String convert(String number, int baseFrom, int baseTo) {
return Long.toString(Long.parseLong(number, baseFrom), baseTo);
}
/* Tulkitsee kannassa base esitetyn luvun longiksi (kannassa 10) */
public long longify(String number, int baseFrom) {
return Long.parseLong(number, baseFrom);
}
}
class Binary implements Comparable<Binary> {
/**
* Use example: Binary b = new Binary(Long.toBinaryString(53249834L));
*
* When manipulating small binary strings, instantiate new Binary(string)
* When just reading large binary strings, instantiate new Binary(string,true)
* get(int i) returns a character '1' or '0', not an int.
*/
private boolean[] d;
private int first; // Starting from left, the first (most remarkable) '1'
public int length;
public Binary(String binaryString) {
this(binaryString, false);
}
public Binary(String binaryString, boolean initWithMinArraySize) {
length = binaryString.length();
int size = Math.max(2*length, 1);
first = length/4;
if (initWithMinArraySize) {
first = 0;
size = Math.max(length, 1);
}
d = new boolean[size];
for (int i=0; i<length; i++) {
if (binaryString.charAt(i) == '1') d[i+first] = true;
}
}
public void addFirst(char c) {
if (first-1 < 0) doubleArraySize();
first--;
d[first] = (c == '1' ? true : false);
length++;
}
public void addLast(char c) {
if (first+length >= d.length) doubleArraySize();
d[first+length] = (c == '1' ? true : false);
length++;
}
private void doubleArraySize() {
boolean[] bigArray = new boolean[(d.length+1) * 2];
int newFirst = bigArray.length / 4;
for (int i=0; i<length; i++) {
bigArray[i + newFirst] = d[i + first];
}
first = newFirst;
d = bigArray;
}
public boolean flip(int i) {
boolean value = (this.d[first+i] ? false : true);
this.d[first+i] = value;
return value;
}
public void set(int i, char c) {
boolean value = (c == '1' ? true : false);
this.d[first+i] = value;
}
public char get(int i) {
return (this.d[first+i] ? '1' : '0');
}
@Override
public int compareTo(Binary o) {
if (this.length != o.length) return this.length - o.length;
int len = this.length;
for (int i=0; i<len; i++) {
int diff = this.get(i) - o.get(i);
if (diff != 0) return diff;
}
return 0;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i=0; i<length; i++) {
sb.append(d[i+first] ? '1' : '0');
}
return sb.toString();
}
}
class BinomialCoefficients {
/** Total number of K sized unique combinations from pool of size N (unordered)
N! / ( K! (N - K)! ) */
/** For simple queries where output fits in long. */
public long biCo(long n, long k) {
long r = 1;
if (k > n) return 0;
for (long d = 1; d <= k; d++) {
r *= n--;
r /= d;
}
return r;
}
/** For multiple queries with same n, different k. */
public long[] precalcBinomialCoefficientsK(int n, int maxK) {
long v[] = new long[maxK+1];
v[0] = 1; // nC0 == 1
for (int i=1; i<=n; i++) {
for (int j=Math.min(i,maxK); j>0; j--) {
v[j] = v[j] + v[j-1]; // Pascal's triangle
}
}
return v;
}
/** When output needs % MOD. */
public long[] precalcBinomialCoefficientsK(int n, int k, long M) {
long v[] = new long[k+1];
v[0] = 1; // nC0 == 1
for (int i=1; i<=n; i++) {
for (int j=Math.min(i,k); j>0; j--) {
v[j] = v[j] + v[j-1]; // Pascal's triangle
v[j] %= M;
}
}
return v;
}
}
class Trie {
int N;
int Z;
int nextFreeId;
int[][] pointers;
boolean[] end;
/** maxLenSum = maximum possible sum of length of words */
public Trie(int maxLenSum, int alphabetSize) {
this.N = maxLenSum;
this.Z = alphabetSize;
this.nextFreeId = 1;
pointers = new int[N+1][alphabetSize];
end = new boolean[N+1];
}
public void addWord(String word) {
int curr = 0;
for (int j=0; j<word.length(); j++) {
int c = word.charAt(j) - 'a';
int next = pointers[curr][c];
if (next == 0) {
next = nextFreeId++;
pointers[curr][c] = next;
}
curr = next;
}
int last = word.charAt(word.length()-1) - 'a';
end[last] = true;
}
public boolean hasWord(String word) {
int curr = 0;
for (int j=0; j<word.length(); j++) {
int c = word.charAt(j) - 'a';
int next = pointers[curr][c];
if (next == 0) return false;
curr = next;
}
int last = word.charAt(word.length()-1) - 'a';
return end[last];
}
}
private class IO extends PrintWriter {
private InputStreamReader r;
private static final int BUFSIZE = 1 << 15;
private char[] buf;
private int bufc;
private int bufi;
private StringBuilder sb;
public IO() {
super(new BufferedOutputStream(System.out));
r = new InputStreamReader(System.in);
buf = new char[BUFSIZE];
bufc = 0;
bufi = 0;
sb = new StringBuilder();
}
/** Print, flush, return nextInt. */
private int queryInt(String s) {
io.println(s);
io.flush();
return nextInt();
}
/** Print, flush, return nextLong. */
private long queryLong(String s) {
io.println(s);
io.flush();
return nextLong();
}
/** Print, flush, return next word. */
private String queryNext(String s) {
io.println(s);
io.flush();
return next();
}
private void fillBuf() throws IOException {
bufi = 0;
bufc = 0;
while(bufc == 0) {
bufc = r.read(buf, 0, BUFSIZE);
if(bufc == -1) {
bufc = 0;
return;
}
}
}
private boolean pumpBuf() throws IOException {
if(bufi == bufc) {
fillBuf();
}
return bufc != 0;
}
private boolean isDelimiter(char c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
}
private void eatDelimiters() throws IOException {
while(true) {
if(bufi == bufc) {
fillBuf();
if(bufc == 0) throw new RuntimeException("IO: Out of input.");
}
if(!isDelimiter(buf[bufi])) break;
++bufi;
}
}
public String next() {
try {
sb.setLength(0);
eatDelimiters();
int start = bufi;
while(true) {
if(bufi == bufc) {
sb.append(buf, start, bufi - start);
fillBuf();
start = 0;
if(bufc == 0) break;
}
if(isDelimiter(buf[bufi])) break;
++bufi;
}
sb.append(buf, start, bufi - start);
return sb.toString();
} catch(IOException e) {
throw new RuntimeException("IO.next: Caught IOException.");
}
}
public int nextInt() {
try {
int ret = 0;
eatDelimiters();
boolean positive = true;
if(buf[bufi] == '-') {
++bufi;
if(!pumpBuf()) throw new RuntimeException("IO.nextInt: Invalid int.");
positive = false;
}
boolean first = true;
while(true) {
if(!pumpBuf()) break;
if(isDelimiter(buf[bufi])) {
if(first) throw new RuntimeException("IO.nextInt: Invalid int.");
break;
}
first = false;
if(buf[bufi] >= '0' && buf[bufi] <= '9') {
if(ret < -214748364) throw new RuntimeException("IO.nextInt: Invalid int.");
ret *= 10;
ret -= (int)(buf[bufi] - '0');
if(ret > 0) throw new RuntimeException("IO.nextInt: Invalid int.");
} else {
throw new RuntimeException("IO.nextInt: Invalid int.");
}
++bufi;
}
if(positive) {
if(ret == -2147483648) throw new RuntimeException("IO.nextInt: Invalid int.");
ret = -ret;
}
return ret;
} catch(IOException e) {
throw new RuntimeException("IO.nextInt: Caught IOException.");
}
}
public long nextLong() {
try {
long ret = 0;
eatDelimiters();
boolean positive = true;
if(buf[bufi] == '-') {
++bufi;
if(!pumpBuf()) throw new RuntimeException("IO.nextLong: Invalid long.");
positive = false;
}
boolean first = true;
while(true) {
if(!pumpBuf()) break;
if(isDelimiter(buf[bufi])) {
if(first) throw new RuntimeException("IO.nextLong: Invalid long.");
break;
}
first = false;
if(buf[bufi] >= '0' && buf[bufi] <= '9') {
if(ret < -922337203685477580L) throw new RuntimeException("IO.nextLong: Invalid long.");
ret *= 10;
ret -= (long)(buf[bufi] - '0');
if(ret > 0) throw new RuntimeException("IO.nextLong: Invalid long.");
} else {
throw new RuntimeException("IO.nextLong: Invalid long.");
}
++bufi;
}
if(positive) {
if(ret == -9223372036854775808L) throw new RuntimeException("IO.nextLong: Invalid long.");
ret = -ret;
}
return ret;
} catch(IOException e) {
throw new RuntimeException("IO.nextLong: Caught IOException.");
}
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
}
}
| Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | 58a672dd05c9b4b6fd7896f873899e1c | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes | import java.util.*;
import java.io.*;
public class ProbD {
public static void main(String[] args) {
ProbD sol = new ProbD();
sol.start();
}
StringBuffer printstr;
public void print(Object o){ System.out.print(o); }
public void println(Object o) { System.out.println(o); }
public void bufp(Object o){ printstr.append(o); }
public void bufpl(Object o){ printstr.append(o).append('\n'); }
public void bufpl() { printstr.append('\n'); }
public void bufp(char[] c, int offset, int len){ printstr.append(c, offset, len); }
public void bufpl(char[] c, int offset, int len){ printstr.append(c, offset, len).append('\n'); }
public void start(){
submit();
}
public void submit(){
try{
printstr = new StringBuffer();
BufferedReader rdr = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(rdr.readLine().trim());
String[][] teams = new String[n][];
for(int i=0;i<n;i++) teams[i] = rdr.readLine().trim().split(" ");
solve(n, teams);
System.out.println(printstr);
System.out.flush();
}
catch(Exception e){}
}
class Vertex{
int idx;
String[] team;
String name1, name2;
HashSet<Vertex> conflict;
public Vertex(String[] t, int i) {
conflict = new HashSet(); team = t; idx = i;
name1 = t[0].substring(0,3);
name2 = t[0].substring(0,2) + t[1].substring(0,1);
}
public void add(Vertex v){
conflict.add(v);
v.conflict.add(this);
}
}
public void solve(int n, String[][] teams){
HashMap<String, Integer> countMap = new HashMap();
HashMap<String, HashSet<Vertex>> conflictMap = new HashMap();
Vertex[] v = new Vertex[n];
for(int i=0;i<n;i++){
v[i] = new Vertex(teams[i], i);
String s = v[i].name1;
Integer c = countMap.get(s);
if(c==null) c = 0;
countMap.put(s, c+1);
}
for(int i=0;i<n;i++){
String s;
s = v[i].name1;
HashSet<Vertex> set = conflictMap.get(s);
if(set==null){
set = new HashSet();
conflictMap.put(s, set);
}
if(countMap.get(s)==1) set.add(v[i]);
s = teams[i][0].substring(0,2) + teams[i][1].substring(0,1);
set = conflictMap.get(s);
if(set==null){
set = new HashSet();
conflictMap.put(s, set);
}
set.add(v[i]);
}
HashSet<String> assignedNames = new HashSet();
String[] names = new String[n];
Arrays.fill(names, null);
LinkedList<Vertex> bag = new LinkedList();
for(int i=0;i<n;i++) {
if(v[i].name1.equals(v[i].name2)){
// String s = v[i].name1;
// Integer c = countMap.get(s);
// if(c>1 || assignedNames.contains(s)){
// bufpl("NO");
// return;
// }
// names[i] = s;
// assignedNames.add(s);
// bag.add(v[i]);
}
else{
String s = v[i].name1;
Integer c = countMap.get(s);
if(c==1) continue;
s = v[i].name2;
if(assignedNames.contains(s)){
bufpl("NO");
return;
}
names[i] = s;
assignedNames.add(s);
bag.add(v[i]);
}
}
for(HashSet<Vertex> set : conflictMap.values()){
for(Vertex v1 : set) for(Vertex v2 : set){
if(v1!=v2) v1.add(v2);
}
}
while(bag.size()>0){
Vertex cur = bag.removeFirst();
for(Vertex next : cur.conflict){
// println("conflict: "+cur.team[0]+" "+next.team[0]);
if(names[next.idx]!=null) continue;
if(!assignedNames.contains(next.name1)) names[next.idx] = next.name1;
else if(!assignedNames.contains(next.name2)) names[next.idx] = next.name2;
else{
bufpl("NO");
return;
}
// println(next.name1+" "+next.name2+" choose : "+names[next.idx]);
assignedNames.add(names[next.idx]);
bag.add(next);
}
}
bufpl("YES");
for(int i=0;i<n;i++){
if(names[i]==null) bufpl(v[i].name1);
else bufpl(names[i]);
}
}
/*
3
PLA C
PLB C
PLB D
3
PLC B
PLB C
PLB D
2
PLB C
PLB B
3
PLB C
PLB D
PLE E
4
PLB C
PLB D
PLC B
PLF B
4
PLB C
PLB D
PLC B
PLD B
4
PLB C
PLB D
PLA B
PLC A
4
PLA B
PLC A
PLB C
PLB D
*/
} | Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | 143208b1b0deaf2a3facb20b4279fea7 | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes |
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.PriorityQueue;
import java.util.SortedSet;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* #
* @author pttrung
*/
public class D_Round_403_Div2 {
public static long MOD = 1000000007;
public static void main(String[] args) throws FileNotFoundException {
// PrintWriter out = new PrintWriter(new FileOutputStream(new File(
// "output.txt")));
PrintWriter out = new PrintWriter(System.out);
Scanner in = new Scanner();
int n = in.nextInt();
String[][] data = new String[n][2];
HashSet<String> store = new HashSet<>();
HashSet<String> first = new HashSet<>();
HashSet<String> firstStore = new HashSet<>();
boolean ok = true;
String[] result = new String[n];
for (int i = 0; i < n && ok; i++) {
data[i][0] = in.next();
data[i][1] = in.next();
String a = data[i][0].substring(0, 3);
String b = data[i][0].substring(0, 2) + data[i][1].charAt(0);
if (!store.contains(b) && !firstStore.contains(a)) {
store.add(b);
first.add(a);
result[i] = b;
}else if(!store.contains(a) && !first.contains(a)){
store.add(a);
firstStore.add(a);
result[i] = a;
}else{
ok = false;
}
}
if(ok){
out.println("YES");
for(String v : result){
out.println(v);
}
}else{
out.println("NO");
}
out.close();
}
public static int[] KMP(String val) {
int i = 0;
int j = -1;
int[] result = new int[val.length() + 1];
result[0] = -1;
while (i < val.length()) {
while (j >= 0 && val.charAt(j) != val.charAt(i)) {
j = result[j];
}
j++;
i++;
result[i] = j;
}
return result;
}
public static boolean nextPer(int[] data) {
int i = data.length - 1;
while (i > 0 && data[i] < data[i - 1]) {
i--;
}
if (i == 0) {
return false;
}
int j = data.length - 1;
while (data[j] < data[i - 1]) {
j--;
}
int temp = data[i - 1];
data[i - 1] = data[j];
data[j] = temp;
Arrays.sort(data, i, data.length);
return true;
}
public static int digit(long n) {
int result = 0;
while (n > 0) {
n /= 10;
result++;
}
return result;
}
public static double dist(long a, long b, long x, long y) {
double val = (b - a) * (b - a) + (x - y) * (x - y);
val = Math.sqrt(val);
double other = x * x + a * a;
other = Math.sqrt(other);
return val + other;
}
public static class Point implements Comparable<Point> {
int x, y;
public Point(int start, int end) {
this.x = start;
this.y = end;
}
@Override
public int hashCode() {
int hash = 5;
hash = 47 * hash + this.x;
hash = 47 * hash + this.y;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Point other = (Point) obj;
if (this.x != other.x) {
return false;
}
if (this.y != other.y) {
return false;
}
return true;
}
@Override
public int compareTo(Point o) {
return Integer.compare(x, o.x);
}
}
public static class FT {
long[] data;
FT(int n) {
data = new long[n];
}
public void update(int index, long value) {
while (index < data.length) {
data[index] += value;
index += (index & (-index));
}
}
public long get(int index) {
long result = 0;
while (index > 0) {
result += data[index];
index -= (index & (-index));
}
return result;
}
}
public static long gcd(long a, long b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static long pow(long a, long b, long MOD) {
if (b == 0) {
return 1;
}
if (b == 1) {
return a;
}
long val = pow(a, b / 2, MOD);
if (b % 2 == 0) {
return val * val % MOD;
} else {
return val * (val * a % MOD) % MOD;
}
}
static class Scanner {
BufferedReader br;
StringTokenizer st;
public Scanner() throws FileNotFoundException {
// System.setOut(new PrintStream(new BufferedOutputStream(System.out), true));
br = new BufferedReader(new InputStreamReader(System.in));
// br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("input.txt"))));
}
public String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (Exception e) {
throw new RuntimeException();
}
}
return st.nextToken();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt() {
return Integer.parseInt(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
st = null;
try {
return br.readLine();
} catch (Exception e) {
throw new RuntimeException();
}
}
public boolean endLine() {
try {
String next = br.readLine();
while (next != null && next.trim().isEmpty()) {
next = br.readLine();
}
if (next == null) {
return true;
}
st = new StringTokenizer(next);
return st.hasMoreTokens();
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
| Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | d2b495590769e3c1caf64a96f58b6429 | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes | import java.io.*;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
/**
* Created by Anton Berezin on 2/18/2017.
*/
public class FootballLeague {
public static void main(String[] args) throws Exception {
try (FastScanner fastScanner = new FastScanner();
PrintWriter writer = new PrintWriter(new BufferedOutputStream(System.out))) {
int n = fastScanner.nextInt();
String[] teams = new String[n];
for (int i = 0; i < n; i++) {
teams[i] = fastScanner.nextLine();
}
String[][] vars = new String[n][3];
for (int i = 0; i < n; i++) {
String[] parts = teams[i].split(" ");
vars[i][1] = parts[0].length() == 3 ? parts[0] : parts[0].substring(0, 3);
vars[i][2] = parts[0].substring(0, 2) + parts[1].charAt(0);
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (vars[i][1].equals(vars[j][1]) && vars[i][2].equals(vars[j][2])) {
writer.println("NO");
return;
}
}
}
int[] choices = new int[n];
Set<String> chosen = new HashSet<>();
Set<String> firstChosen = new HashSet<>();
for (int i = 0; i < n; i++) {
String first = vars[i][1];
String second = vars[i][2];
if (chosen.contains(second)) {
if (chosen.contains(first)) {
writer.println("NO");
return;
} else {
choices[i] = 1;
firstChosen.add(first);
}
} else {
if(firstChosen.contains(first)) {
if (chosen.contains(first)) {
writer.println("NO");
return;
} else {
choices[i] = 1;
firstChosen.add(first);
}
} else {
choices[i] = 2;
}
}
chosen.add(vars[i][choices[i]]);
}
writer.println("YES");
for(int i = 0; i < n; i++) {
writer.println(vars[i][choices[i]]);
}
}
}
public static class FastScanner implements AutoCloseable {
BufferedReader bufferedReader;
StringTokenizer tokenizer;
public FastScanner() {
bufferedReader = new BufferedReader(new InputStreamReader(System.in));
}
String next() {
while (tokenizer == null || !tokenizer.hasMoreElements()) {
try {
tokenizer = new StringTokenizer(bufferedReader.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return tokenizer.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 = bufferedReader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
@Override
public void close() throws IOException {
bufferedReader.close();
}
}
}
| Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | 4b8a2b83e0cb226d0a7c87ba14a5ed00 | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes | import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import java.io.*;
public class Main {
public class pair implements Comparable<pair> {
String s1, s2;
int a;
public int compareTo(pair p) {
return s1.compareTo(p.s1);
}
}
public class triple implements Comparable<triple> {
String s1;
public triple(String d) {
s1 = d;
}
public int compareTo(triple p) {
int a = s1.compareTo(p.s1);
return a;
}
}
public void solve() throws IOException {
int n = nextInt();
boolean l = true;
String[] ans = new String[n];
TreeSet<triple> w = new TreeSet<>();
pair[] r = new pair[n];
for (int i = 0; i < n; i++) {
String s1 = nextToken();
String s2 = nextToken();
r[i] = new pair();
r[i].s1 = "" + s1.charAt(0) + s1.charAt(1) + s1.charAt(2);
r[i].s2 = "" + s1.charAt(0) + s1.charAt(1) + s2.charAt(0);
r[i].a = i;
}
Arrays.sort(r);
int i = 0;
int k = 0;
ArrayList<pair> d = new ArrayList<>();
while (i < n) {
k = i;
String s = r[k].s1;
i++;
while (i < n && r[i].s1.compareTo(s) == 0) {
i++;
}
if (i > k + 1) {
for (int j = k; j < i; j++) {
if (w.contains(new triple(r[j].s2))) {
l = false;
} else {
ans[r[j].a] = r[j].s2;
w.add(new triple(r[j].s2));
}
}
} else {
d.add(r[k]);
}
}
int x = 1;
while (x != 0) {
x = 0;
for (i = 0; i < d.size(); i++) {
if (w.contains(new triple(d.get(i).s1))) {
if (w.contains(new triple(d.get(i).s2))) {
x = 0;
l = false;
break;
} else {
ans[d.get(i).a] = d.get(i).s2;
w.add(new triple(d.get(i).s2));
d.remove(i);
i--;
x++;
}
}
}
}
for (i = 0; i < d.size(); i++) {
ans[d.get(i).a] = d.get(i).s1;
}
if (l) {
out.println("YES");
for (i = 0; i < n; i++) {
out.println(ans[i]);
}
} else {
out.println("NO");
}
}
BufferedReader br;
StringTokenizer sc;
PrintWriter out;
public String nextToken() throws IOException {
while (sc == null || !sc.hasMoreTokens()) {
try {
sc = new StringTokenizer(br.readLine());
} catch (Exception e) {
return null;
}
}
return sc.nextToken();
}
public Integer nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
public static void main(String[] args) throws IOException {
Locale.setDefault(Locale.US);
new Main().run();
}
public void run() {
try {
br = new BufferedReader(new InputStreamReader(System.in));
out = new PrintWriter(System.out);
solve();
out.close();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
} | Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | a75512f51da239818c30be4a5e054384 | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes | import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
public class InnokentyAndAFootballLeague {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int n = Integer.parseInt(br.readLine());
String[][] teamNames = new String[n][2];
HashSet<String> possibleNames = new HashSet<>();
HashMap<Integer, String> finalTeamNames = new HashMap<>();
HashMap<String, ArrayList<Integer>> firstChoiceNames = new HashMap<>();
for (int i = 0; i < n; i++) {
String[] line = br.readLine().split("\\s");
teamNames[i][0] = line[0].substring(0, 3);
teamNames[i][1] = line[0].substring(0, 2) + line[1].charAt(0);
ArrayList<Integer> existing = firstChoiceNames.containsKey(teamNames[i][0])
? firstChoiceNames.get(teamNames[i][0])
: new ArrayList<>();
existing.add(i);
firstChoiceNames.put(teamNames[i][0], existing);
}
for (Map.Entry<String, ArrayList<Integer>> entry : firstChoiceNames.entrySet()) {
if (entry.getValue().size() == 1) {
possibleNames.add(entry.getKey());
continue;
}
for (int i : entry.getValue()) {
if (finalTeamNames.containsValue(teamNames[i][1])) {
System.out.println("NO");
return;
}
finalTeamNames.put(i, teamNames[i][1]);
}
}
for (int i = 0; i < n; i++) {
if (finalTeamNames.containsKey(i)) {
continue;
}
if (finalTeamNames.containsValue(teamNames[i][0])) {
if (finalTeamNames.containsValue(teamNames[i][1])) {
System.out.println("NO");
return;
}
finalTeamNames.put(i, teamNames[i][1]);
} else if (possibleNames.contains(teamNames[i][0])) {
if (finalTeamNames.containsValue(teamNames[i][1])) {
finalTeamNames.put(i, teamNames[i][0]);
} else {
finalTeamNames.put(i, teamNames[i][1]);
}
} else {
finalTeamNames.put(i, teamNames[i][0]);
}
}
out.println("YES");
for (int i = 0; i < n; i++) {
out.println(finalTeamNames.get(i));
}
out.close();
}
}
| Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | c1da6e33ae618f82c04382cc05d68d7d | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.math.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String[][] a = new String[n][2];
HashMap<String, Integer> map = new HashMap<>();
for(int i=0;i<n;i++){
a[i][0] = in.next().substring(0, 3);
a[i][1] = a[i][0].substring(0, 2) + in.next().substring(0, 1);
map.put(a[i][0], map.getOrDefault(a[i][0], 0) + 1);
}
String[] ans = new String[n];
boolean[] visited = new boolean[n];
HashSet<String> used = new HashSet<>();
for(int i=0;i<n;i++){
if(map.get(a[i][0]) > 1){
if(!used.contains(a[i][1])){
used.add(a[i][1]);
ans[i] = a[i][1];
visited[i] = true;
}
else{
System.out.println("NO");
return;
}
}
}
boolean done = false;
while(!done){
done = true;
for(int i=0;i<n;i++){
if(!visited[i] && used.contains(a[i][0])){
if(used.contains(a[i][1])){
System.out.println("NO");
return;
}
used.add(a[i][1]);
visited[i] = true;
ans[i] = a[i][1];
done = false;
}
}
}
for(int i=0;i<n;i++){
if(!visited[i]){
ans[i] = a[i][0];
}
}
System.out.println("YES");
for(String s:ans) System.out.println(s);
}
}
| Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | 3fbd203670f491733ea92b1f867f0d01 | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
import java.util.stream.Stream;
public class D {
static class Sat2 {
static void dfs1(List<Integer>[] graph, boolean[] used, List<Integer> order, int u) {
used[u] = true;
for (int v : graph[u])
if (!used[v])
dfs1(graph, used, order, v);
order.add(u);
}
static void dfs2(List<Integer>[] reverseGraph, int[] comp, int u, int color) {
comp[u] = color;
for (int v : reverseGraph[u])
if (comp[v] == -1)
dfs2(reverseGraph, comp, v, color);
}
public static boolean[] solve2Sat(List<Integer>[] graph) {
int n = graph.length;
boolean[] used = new boolean[n];
List<Integer> order = new ArrayList<>();
for (int i = 0; i < n; ++i)
if (!used[i])
dfs1(graph, used, order, i);
List<Integer>[] reverseGraph = Stream.generate(ArrayList::new).limit(n).toArray(List[]::new);
for (int i = 0; i < n; i++)
for (int j : graph[i])
reverseGraph[j].add(i);
int[] comp = new int[n];
Arrays.fill(comp, -1);
for (int i = 0, color = 0; i < n; ++i) {
int u = order.get(n - i - 1);
if (comp[u] == -1)
dfs2(reverseGraph, comp, u, color++);
}
for (int i = 0; i < n; ++i)
if (comp[i] == comp[i ^ 1])
return null;
boolean[] res = new boolean[n / 2];
for (int i = 0; i < n; i += 2)
res[i / 2] = comp[i] > comp[i ^ 1];
return res;
}
}
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer st;
static PrintWriter out = new PrintWriter(System.out);
static void solve() throws Exception {
int n = nextInt();
String[] short1 = new String[n], short2 = new String[n];
for (int i = 0; i < n; i++) {
String first = next(), second = next();
short1[i] = first.substring(0, 3);
short2[i] = first.substring(0, 2) + second.substring(0, 1);
}
// 2*i is the first option, 2*i+1 is the second
@SuppressWarnings("unchecked")
List<Integer>[] graph = (List<Integer>[]) new List[2 * n];
for (int i = 0; i < graph.length; i++) {
graph[i] = new ArrayList<>();
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++)
if (j != i) {
boolean added = false;
if (short1[i].equals(short1[j])) {
graph[2 * i + 1].add(2 * j + 1);
graph[2 * i].add(2 * j + 1);
added = true;
}
if (short1[i].equals(short2[j])) {
graph[2 * i].add(2 * j);
}
if (short2[i].equals(short1[j]) && !added) {
graph[2 * i + 1].add(2 * j + 1);
}
if (short2[i].equals(short2[j])) {
graph[2 * i + 1].add(2 * j);
}
}
}
boolean[] solved = Sat2.solve2Sat(graph);
if (solved == null) {
out.println("NO");
} else {
out.println("YES");
for (int i = 0; i < n; i++) {
out.println(solved[i] ? short1[i] : short2[i]);
}
}
}
public static void main(String[] args) throws Exception {
solve();
out.close();
}
static String next() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
static int nextInt() throws Exception {
return Integer.parseInt(next());
}
}
| Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | f7a09fe632a564e85c1fdfb709b49247 | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes | import java.io.*;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
public class D
{
String line;
StringTokenizer inputParser;
BufferedReader is;
FileInputStream fstream;
DataInputStream in;
void openInput(String file)
{
if(file==null)is = new BufferedReader(new InputStreamReader(System.in));//stdin
else
{
try{
fstream = new FileInputStream(file);
in = new DataInputStream(fstream);
is = new BufferedReader(new InputStreamReader(in));
}catch(Exception e)
{
System.err.println(e);
}
}
}
void readNextLine()
{
try {
line = is.readLine();
if(line!=null)inputParser = new StringTokenizer(line, " ");
//System.err.println("Input: " + line);
} catch (IOException e) {
System.err.println("Unexpected IO ERROR: " + e);
}
}
int NextInt()
{
String n = inputParser.nextToken();
int val = Integer.parseInt(n);
//System.out.println("I read this number: " + val);
return val;
}
double NextDouble()
{
String n = inputParser.nextToken();
double val = Double.parseDouble(n);
//System.out.println("I read this number: " + val);
return val;
}
long NextLong()
{
String n = inputParser.nextToken();
long val = Long.parseLong(n);
return val;
}
String NextString()
{
String n = inputParser.nextToken();
return n;
}
void closeInput()
{
try {
is.close();
} catch (IOException e) {
System.err.println("Unexpected IO ERROR: " + e);
}
}
public static void main(String [] argv)
{
String filePath=null;
if(argv.length>0)filePath=argv[0];
new D(filePath);
}
public D(String inputFile)
{
openInput(inputFile);
//readNextLine();
int T=1;//NextInt();
StringBuilder sb = new StringBuilder();
for(int t=1; t<=T; t++)
{
readNextLine();
int N=NextInt();
Random rng = new Random(58);
Team [] a = new Team[N];
HashMap <String, Integer> first = new HashMap<String, Integer>();
HashMap <String, Integer> second = new HashMap<String, Integer>();
for(int i=0; i<N; i++)
{
readNextLine();
a[i] = new Team(NextString(), NextString());
first.put(a[i].op1, first.getOrDefault(a[i].op1, 0)+1);
second.put(a[i].op2, first.getOrDefault(a[i].op2, 0)+1);
}
HashSet<String> used = new HashSet<String>();
int rest = N;
for(int i=0; i<N; i++)
{
if(first.get(a[i].op1)>1)
{
a[i].can1 = false;
a[i].x = 2;
if(used.contains(a[i].op2)){
System.out.println("NO");
return;
}
used.add(a[i].op2);
rest--;
}
}
while(rest>0)
{
boolean ok = false;
for(int i=0; i<N; i++)
{
if(a[i].x!=-1)continue;
if(used.contains(a[i].op1)){
a[i].x = 2;
if(used.contains(a[i].op2)){
System.out.println("NO");
return;
}
used.add(a[i].op2);
ok = true;
rest--;
}
else if(used.contains(a[i].op2)){
a[i].x = 1;
if(used.contains(a[i].op1)){
System.out.println("NO");
return;
}
used.add(a[i].op1);
ok = true;
rest--;
}
}
if(!ok)
{
int id = rng.nextInt(N);
while(a[id].x!=-1)
{
id++;
if(id==N)id=0;
}
a[id].x = 1;
if(used.contains(a[id].op1)){
System.out.println("NO");
return;
}
used.add(a[id].op1);
ok = true;
rest--;
}
}
sb.append("YES\n");
for(int i=0; i<N; i++)
sb.append(a[i].getShort()+"\n");
}
System.out.print(sb);
closeInput();
}
private class Team
{
int x = -1;
boolean can1 = true;
public Team(String a, String b) {
op1 = a.substring(0, 3);
op2 = a.substring(0, 2)+b.charAt(0);
}
public Object getShort() {
if(x==2)return op2;
return op1;
}
String op1, op2;
}
} | Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | f02a8902e46a82f1e638d64a17ea2f0b | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes | import java.io.*;
import java.util.*;
public final class round_403_d
{
static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
static FastScanner sc=new FastScanner(br);
static PrintWriter out=new PrintWriter(System.out);
static Random rnd=new Random();
static int[] parent,size;
static boolean ans=true;
static boolean[] v;
static Map<String,Integer> m1=new HashMap<>(),seen=new HashMap<>();
static Pair[] a;
static int getParent(int u)
{
if(u==parent[u])
{
return u;
}
else
{
int val=getParent(parent[u]);parent[u]=val;return val;
}
}
static void merge(int u,int v)
{
parent[v]=u;size[u]+=size[v];size[v]=0;
}
static boolean isPossible(int i)
{
if(seen.get(a[i].s1)==null)
{
seen.put(a[i].s1,1);
if(m1.get(a[i].s1)==null || isPossible(m1.get(a[i].s1)))
{
m1.put(a[i].s1,i);return true;
}
}
if(seen.get(a[i].s2)==null)
{
seen.put(a[i].s2,1);
if(m1.get(a[i].s2)==null || isPossible(m1.get(a[i].s2)))
{
m1.put(a[i].s2,i);return true;
}
}
return false;
}
public static void main(String args[]) throws Exception
{
int n=sc.nextInt();parent=new int[n];a=new Pair[n];size=new int[n];v=new boolean[n];
for(int i=0;i<n;i++)
{
parent[i]=i;size[i]=1;
String s1=sc.next(),s2=sc.next();
a[i]=new Pair(s1.substring(0,3),s1.substring(0,2)+s2.substring(0,1));
}
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(a[i].s1.equals(a[j].s1))
{
int x=getParent(i),y=getParent(j);
if(x!=y)
{
merge(x,y);
}
}
}
}
List<Node> list=new ArrayList<Node>();
for(int i=0;i<n;i++)
{
int x=getParent(i);
if(size[x]>1)
{
list.add(new Node(i,a[i].s2));v[i]=true;
}
}
for(int i=0;i<list.size();i++)
{
for(int j=i+1;j<list.size();j++)
{
if(list.get(i).val.equals(list.get(j).val))
{
ans=false;break;
}
}
}
if(ans)
{
for(int i=0;i<list.size();i++)
{
m1.put(list.get(i).val,list.get(i).idx);
}
for(int i=0;i<n;i++)
{
if(!v[i])
{
seen=new HashMap<>();
for(Node p:list)
{
seen.put(p.val,1);
}
if(!isPossible(i))
{
ans=false;break;
}
}
}
if(ans)
{
out.println("YES");String[] res=new String[n];
for(Map.Entry<String,Integer> en:m1.entrySet())
{
res[en.getValue()]=en.getKey();
}
for(String x:res)
{
out.println(x);
}
}
else
{
out.println("NO");
}
}
else
{
out.println("NO");
}
out.close();
}
}
class Pair
{
String s1,s2;
public Pair(String s1,String s2)
{
this.s1=s1;this.s2=s2;
}
}
class Node implements Comparable<Node>
{
int idx;String val;
public Node(int idx,String val)
{
this.idx=idx;this.val=val;
}
public int compareTo(Node x)
{
return this.val.compareTo(x.val);
}
}
class FastScanner
{
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() throws Exception {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(in.readLine());
}
return st.nextToken();
}
public String next() throws Exception {
return nextToken().toString();
}
public int nextInt() throws Exception {
return Integer.parseInt(nextToken());
}
public long nextLong() throws Exception {
return Long.parseLong(nextToken());
}
public double nextDouble() throws Exception {
return Double.parseDouble(nextToken());
}
} | Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | 1f7a36f52810b6b8f3dfa57e05f3a1cc | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes | /**
* DA-IICT
* Author : Savaliya Sagar
*/
import java.io.*;
import java.math.*;
import java.util.*;
public class D782 {
InputStream is;
PrintWriter out;
String ans1[], ans2[], ans[];
HashSet<String> hs = new HashSet<>();
HashMap<String, ArrayList<Integer>> hm = new HashMap<>();
void solve() {
int n = ni();
ans1 = new String[n];
ans2 = new String[n];
ans = new String[n];
for (int i = 0; i < n; i++) {
String s1 = ns();
String s2 = ns();
ans1[i] = s1.substring(0, 3);
ans2[i] = s1.substring(0, 2) + s2.charAt(0);
}
for (int i = 0; i < n; i++) {
if (hm.containsKey(ans1[i])) {
hm.get(ans1[i]).add(i);
} else {
ArrayList<Integer> temp = new ArrayList<>();
temp.add(i);
hm.put(ans1[i], temp);
}
}
int f = 0;
for (String k : hm.keySet()) {
ArrayList<Integer> ar = hm.get(k);
if (ar.size() > 1) {
for (int x : ar) {
if (!hs.contains(ans2[x])) {
hs.add(ans2[x]);
ans[x] = ans2[x];
} else
f = 1;
}
}
}
for (String k : hm.keySet()) {
ArrayList<Integer> ar = hm.get(k);
if (ar.size() == 1) {
for (int x : ar) {
if (!hs.contains(ans2[x])) {
hs.add(ans2[x]);
ans[x] = ans2[x];
} else if(!hs.contains(ans1[x]))
{
hs.add(ans1[x]);
ans[x] = ans1[x];
}else
f = 1;
}
}
}
if (f == 1) {
out.println("NO");
} else {
out.println("YES");
for (int i = 0; i < n; i++) {
out.println(ans[i]);
}
}
}
void run() throws Exception {
String INPUT = "/media/sagar407/D/java workspace/11Input_output/input.txt";
is = oj ? System.in : new FileInputStream(INPUT);
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 D782().run();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b !=
// ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) {
if (!oj)
System.out.println(Arrays.deepToString(o));
}
}
| Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | 47f82f80477db8161e205cc472a7b2a4 | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;
public class Div2_403D {
public static void main(String[] args) throws IOException {
new Div2_403D().execute();
}
void execute() throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter printer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int numE = Integer.parseInt(reader.readLine());
String[] strings = new String[numE];
for (int i = 0; i < numE; i++) {
StringTokenizer inputData = new StringTokenizer(reader.readLine());
strings[i] = inputData.nextToken().substring(0, 3) + inputData.nextToken().charAt(0) + i;
}
Arrays.sort(strings, lexico);
for (int i = 0; i < numE; i++) {
int j;
for (j = i; j + 1 < numE && lexico.compare(strings[i], strings[j + 1]) == 0; j++) {
}
if (i < j) {
for (int k = i; k <= j; k++) {
strings[k] = strings[k].substring(0, 2) + strings[k].substring(3);
}
}
i = j;
}
boolean updated = true;
while(updated){
updated = false;
Arrays.sort(strings, lexico);
for (int i = 0; i + 1 < numE; i++) {
if (lexico.compare(strings[i], strings[i + 1]) == 0) {
if (Character.isAlphabetic(strings[i].charAt(3))) {
strings[i] = strings[i].substring(0, 2) + strings[i].substring(3);
updated = true;
} else if (Character.isAlphabetic(strings[i + 1].charAt(3))) {
strings[i + 1] = strings[i + 1].substring(0, 2) + strings[i + 1].substring(3);
updated = true;
} else {
System.out.println("NO");
return;
}
}
}
}
printer.println("YES");
String[] toPrint = new String[numE];
for (String str : strings) {
if (!Character.isAlphabetic(str.charAt(3))) {
toPrint[Integer.parseInt(str.substring(3))] = str;
} else {
toPrint[Integer.parseInt(str.substring(4))] = str;
}
}
for (String str : toPrint) {
printer.println(str.substring(0, 3));
}
printer.close();
}
Comparator<String> lexico = new Comparator<String>() {
public int compare(String o1, String o2) {
for (int i = 0; i < 3; i++) {
if (o1.charAt(i) < o2.charAt(i)) {
return -1;
}
if (o1.charAt(i) > o2.charAt(i)) {
return 1;
}
}
return 0;
}
};
} | Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | 7a3b0d107d64a439a76ec57bc00d0186 | train_000.jsonl | 1488705300 | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | 256 megabytes | import java.util.HashMap;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
/**
* Created by mmaikovych on 05.03.17.
*/
public class CF_403_D {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
String[] commands = new String[n];
Set<Integer> notFinals = new HashSet<>();
char[] cities = new char[n];
String[] input;
scanner.nextLine();
HashMap<String, Integer> sameCommands = new HashMap<>();
HashSet<String> finalNames = new HashSet<>();
int index;
boolean failed = false;
for (int i = 0; i < n; i++) {
input = scanner.nextLine().split(" ");
commands[i] = input[0].substring(0, 3);
cities[i] = input[1].charAt(0);
notFinals.add(i);
if (!sameCommands.containsKey(commands[i])) {
sameCommands.put(commands[i], i);
} else {
index = sameCommands.get(commands[i]);
if (notFinals.contains(index)) {
failed = updateFailed(commands, cities, notFinals, index, finalNames);
if (failed) {
break;
}
}
failed = updateFailed(commands, cities, notFinals, i, finalNames);
if (failed) {
break;
}
}
}
if (!failed) {
boolean updated = true;
while (updated && !failed) {
updated = false;
Integer[] nf = new Integer[notFinals.size()];
notFinals.toArray(nf);
for (int i : nf) {
if (finalNames.contains(commands[i])) {
failed = updateFailed(commands, cities, notFinals, i, finalNames);
if (failed) {
break;
}
updated = true;
}
}
}
}
if (failed) {
System.out.println("NO");
} else {
System.out.println("YES");
for (int i = 0; i < n; i++) {
System.out.println(commands[i]);
}
}
}
private static boolean updateFailed(String[] commands, char[] cities, Set<Integer> notFinals, int index, Set<String> finalNames) {
commands[index] = commands[index].substring(0, 2) + cities[index];
notFinals.remove(index);
if (finalNames.contains(commands[index])) {
return true;
}
finalNames.add(commands[index]);
return false;
}
}
| Java | ["2\nDINAMO BYTECITY\nFOOTBALL MOSCOW", "2\nDINAMO BYTECITY\nDINAMO BITECITY", "3\nPLAYFOOTBALL MOSCOW\nPLAYVOLLEYBALL SPB\nGOGO TECHNOCUP", "3\nABC DEF\nABC EFG\nABD OOO"] | 2 seconds | ["YES\nDIN\nFOO", "NO", "YES\nPLM\nPLS\nGOG", "YES\nABD\nABE\nABO"] | NoteIn the first sample Innokenty can choose first option for both clubs.In the second example it is not possible to choose short names, because it is not possible that one club has first option, and the other has second option if the first options are equal for both clubs.In the third example Innokenty can choose the second options for the first two clubs, and the first option for the third club.In the fourth example note that it is possible that the chosen short name for some club x is the same as the first option of another club y if the first options of x and y are different. | Java 8 | standard input | [
"graphs",
"greedy",
"shortest paths",
"strings"
] | 733b36bfc2b72200281477af875f8efa | The first line contains a single integer n (1ββ€βnββ€β1000)Β β the number of clubs in the league. Each of the next n lines contains two wordsΒ β the team's name and the hometown's name for some club. Both team's name and hometown's name consist of uppercase English letters and have length at least 3 and at most 20. | 1,900 | It it is not possible to choose short names and satisfy all constraints, print a single line "NO". Otherwise, in the first line print "YES". Then print n lines, in each line print the chosen short name for the corresponding club. Print the clubs in the same order as they appeared in input. If there are multiple answers, print any of them. | standard output | |
PASSED | 4712f9a23e4145be4e770e0b127f7f41 | train_000.jsonl | 1489851300 | A tree is an undirected connected graph without cycles. The distance between two vertices is the number of edges in a simple path between them.Limak is a little polar bear. He lives in a tree that consists of n vertices, numbered 1 through n.Limak recently learned how to jump. He can jump from a vertex to any vertex within distance at most k.For a pair of vertices (s,βt) we define f(s,βt) as the minimum number of jumps Limak needs to get from s to t. Your task is to find the sum of f(s,βt) over all pairs of vertices (s,βt) such that sβ<βt. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
public class C implements Runnable {
List<Integer>[] r;
long[][] down;
int n, k;
long sum;
long[] rem;
long dfs(int q, int p) {
long res = 0;
for (int z : r[q]) {
if (z != p) {
res += dfs(z, q);
for (int i = 0; i < k; i++) down[q][i] += down[z][(i + k - 1) % k];
}
}
res++;
if (p != -1) sum += res * (n - res);
long[] tmp = new long[k];
for (int z : r[q]) {
if (z != p) {
for (int i = 0; i < k; i++) down[q][i] -= down[z][(i + k - 1) % k];
for (int i = 0; i < k; i++) {
for (int j = 0; j < k; j++) {
tmp[(i + j + 1) % k] += down[q][i] * down[z][j];
}
}
for (int i = 0; i < k; i++) down[q][i] += down[z][(i + k - 1) % k];
}
}
for (int i = 0; i < k; i++) rem[i] += tmp[i] / 2 + down[q][i];
down[q][0]++;
return res;
}
void dfs2(int q, int p, int[] a) {
if (p != -1) {
for (int i = 0; i < k; i++) {
for (int j = 0; j < k; j++) {
rem[(i + j + 1) % k] += a[i] * down[q][j];
}
}
}
int[] t = new int[k];
for (int i = 0; i < k; i++) t[i] = a[(i + k - 1) % k];
for (int i = 0; i < k; i++) t[i] += down[q][i];
for (int z : r[q]) {
if (z != p) {
for (int i = 0; i < k; i++) t[i] -= down[z][(i + k - 1) % k];
dfs2(z, q, t);
for (int i = 0; i < k; i++) t[i] += down[z][(i + k - 1) % k];
}
}
}
void solve() throws IOException {
n = nextInt();
k = nextInt();
r = new ArrayList[n + 1];
for (int i = 1; i <= n; i++) r[i] = new ArrayList<>();
for (int i = 0; i < n - 1; i++) {
int a = nextInt(), b = nextInt();
r[a].add(b); r[b].add(a);
}
down = new long[n + 1][k];
sum = 0;
rem = new long[k];
dfs(1, -1);
// dfs2(1, -1, new int[k]);
for (int i = 1; i < k; i++) {
sum += rem[i] * (k - i);
}
out.println(sum / k);
}
public static void main(String[] args) {
new Thread(null, new C(), "name", 1 << 27).start();
}
@Override
public void run() {
try {
solve();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
} finally {
out.close();
}
}
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(System.out);
StringTokenizer st;
String nextToken() throws IOException {
while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(in.readLine());
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(nextToken());
}
}
| Java | ["6 2\n1 2\n1 3\n2 4\n2 5\n4 6", "13 3\n1 2\n3 2\n4 2\n5 2\n3 6\n10 6\n6 7\n6 13\n5 8\n5 9\n9 11\n11 12", "3 5\n2 1\n3 1"] | 2 seconds | ["20", "114", "3"] | NoteIn the first sample, the given tree has 6 vertices and it's displayed on the drawing below. Limak can jump to any vertex within distance at most 2. For example, from the vertex 5 he can jump to any of vertices: 1, 2 and 4 (well, he can also jump to the vertex 5 itself). There are pairs of vertices (s,βt) such that sβ<βt. For 5 of those pairs Limak would need two jumps: (1,β6),β(3,β4),β(3,β5),β(3,β6),β(5,β6). For other 10 pairs one jump is enough. So, the answer is 5Β·2β+β10Β·1β=β20.In the third sample, Limak can jump between every two vertices directly. There are 3 pairs of vertices (sβ<βt), so the answer is 3Β·1β=β3. | Java 8 | standard input | [
"dp",
"dfs and similar",
"trees"
] | 0b4362204bb9f0e95eaf7e2949315c8f | The first line of the input contains two integers n and k (2ββ€βnββ€β200β000, 1ββ€βkββ€β5)Β β the number of vertices in the tree and the maximum allowed jump distance respectively. The next nβ-β1 lines describe edges in the tree. The i-th of those lines contains two integers ai and bi (1ββ€βai,βbiββ€βn)Β β the indices on vertices connected with i-th edge. It's guaranteed that the given edges form a tree. | 2,100 | Print one integer, denoting the sum of f(s,βt) over all pairs of vertices (s,βt) such that sβ<βt. | standard output | |
PASSED | 5ca31122b20347158c6205046f846003 | train_000.jsonl | 1369927800 | Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string sβ=βs1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li,βri (1ββ€βliβ<βriββ€βn). The answer to the query li,βri is the number of such integers i (liββ€βiβ<βri), that siβ=βsiβ+β1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem. | 256 megabytes | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class B {
static BufferedReader stdin = new BufferedReader(new
InputStreamReader(System.in));
static StringTokenizer st = new StringTokenizer("");
public static void main(String[] args) throws Exception {
char[] s = readString().toCharArray();
int N = s.length;
Fenwick f = new Fenwick(s.length);
for (int i = 1; i < N; i++) {
if (s[i-1] == s[i]) {
f.update(i, 1);
}
}
int queries = readInt();
for (int i = 0; i < queries; i++){
int l = readInt(), r = readInt();
System.out.println(f.get(r-1) - f.get(l-1));
}
}
static String readString() throws Exception {
while (!st.hasMoreTokens()) {
st = new StringTokenizer(stdin.readLine());
}
return st.nextToken();
}
static int readInt() throws Exception {
return Integer.parseInt(readString());
}
static long readLong() throws Exception {
return Long.parseLong(readString());
}
static double readDouble() throws Exception {
return Double.parseDouble(readString());
}
static class Fenwick {
private final int max;
private final int[] tree;
public Fenwick(int x){
max = x;
tree = new int[x+1];
}
public void update(int i, int val){
while (i <= max){
tree[i] += val;
i += (i & -i);
}
}
public int get(int i){
int r = 0;
while (0 < i){
r += tree[i];
i -= (-i)&i;
}
return r;
}
}
} | Java | ["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"] | 2 seconds | ["1\n1\n5\n4", "1\n1\n2\n2\n0"] | null | Java 6 | standard input | [
"dp",
"implementation"
] | b30e09449309b999473e4be6643d68cd | The first line contains string s of length n (2ββ€βnββ€β105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1ββ€βmββ€β105) β the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li,βri (1ββ€βliβ<βriββ€βn). | 1,100 | Print m integers β the answers to the queries in the order in which they are given in the input. | standard output | |
PASSED | 2fd1ee1b813c9467425a77f43717b337 | train_000.jsonl | 1369927800 | Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string sβ=βs1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li,βri (1ββ€βliβ<βriββ€βn). The answer to the query li,βri is the number of such integers i (liββ€βiβ<βri), that siβ=βsiβ+β1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem. | 256 megabytes | import java.io.IOException;
import java.util.Locale;
import java.util.Scanner;
public class B {
public void processInput() throws IOException {
Scanner in = new Scanner(System.in);
String str = in.next();
int n = in.nextInt();
int[] l = new int[n];
int[] r = new int[n];
for (int i = 0; i < n; i++) {
l[i] = in.nextInt();
r[i] = in.nextInt();
}
go(n, str, l, r);
in.close();
}
public void go(int n, String str, int[] l, int[] r) {
int len = str.length();
int[] acum = new int[len + 1];
acum[0] = 0;
for (int i = 1; i < len; i++) {
if (str.charAt(i) == str.charAt(i - 1)) {
acum[i] = acum[i-1] + 1;
} else {
acum[i] = acum[i-1];
}
}
for (int i = 0; i < n; i++) {
System.out.printf(Locale.ENGLISH, "%d\n", acum[r[i] - 1] - acum[l[i] - 1]);
}
}
public static void main(String[] args) throws Exception {
B a = new B();
a.processInput();
}
} | Java | ["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"] | 2 seconds | ["1\n1\n5\n4", "1\n1\n2\n2\n0"] | null | Java 6 | standard input | [
"dp",
"implementation"
] | b30e09449309b999473e4be6643d68cd | The first line contains string s of length n (2ββ€βnββ€β105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1ββ€βmββ€β105) β the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li,βri (1ββ€βliβ<βriββ€βn). | 1,100 | Print m integers β the answers to the queries in the order in which they are given in the input. | standard output | |
PASSED | a2c15c84c0cb46a966c7a10f3d586bb4 | train_000.jsonl | 1369927800 | Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string sβ=βs1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li,βri (1ββ€βliβ<βriββ€βn). The answer to the query li,βri is the number of such integers i (liββ€βiβ<βri), that siβ=βsiβ+β1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem. | 256 megabytes |
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/**
*
* @author sukhdeep
*/
public class Code {
public static void main(String arg[]) throws IOException
{
BufferedReader r=new BufferedReader(new InputStreamReader(System.in));
StringBuilder temp=new StringBuilder(r.readLine());
int n=Integer.parseInt(r.readLine());
int a[]=new int[temp.length()];
int count=0;
a[0]=0;
for(int k=1;k<temp.length();k++)
{
if(temp.charAt(k-1)==temp.charAt(k))
count++;
a[k]=count;
}
StringTokenizer str;
while(n-->0)
{
str=new StringTokenizer(r.readLine());
int i=Integer.parseInt(str.nextToken());
int j=Integer.parseInt(str.nextToken());
System.out.println(a[j-1]-a[i-1]);
}
}
}
| Java | ["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"] | 2 seconds | ["1\n1\n5\n4", "1\n1\n2\n2\n0"] | null | Java 6 | standard input | [
"dp",
"implementation"
] | b30e09449309b999473e4be6643d68cd | The first line contains string s of length n (2ββ€βnββ€β105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1ββ€βmββ€β105) β the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li,βri (1ββ€βliβ<βriββ€βn). | 1,100 | Print m integers β the answers to the queries in the order in which they are given in the input. | standard output | |
PASSED | 40523295dbb3c7da21cfb5db1376c965 | train_000.jsonl | 1369927800 | Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam.You've got string sβ=βs1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li,βri (1ββ€βliβ<βriββ€βn). The answer to the query li,βri is the number of such integers i (liββ€βiβ<βri), that siβ=βsiβ+β1.Ilya the Lion wants to help his friends but is there anyone to help him? Help Ilya, solve the problem. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CFTest45
{
static BufferedReader br;
public static void main(String[] args) {
br = new BufferedReader(new InputStreamReader(System.in));
try {
String s=readLine();
int nm=readInt();
int[][]qr=new int[nm][];
for(int i=0;i<nm;i++){
qr[i]=readIntArr();
}
br.close();
int n=s.length();
int num[]=new int[n];
for(int i=1;i<n;i++){
num[i]=num[i-1];
if(s.charAt(i-1)==s.charAt(i))num[i]+=1;
}
for(int i=0;i<nm;i++){
System.out.println(num[qr[i][1]-1]-num[qr[i][0]-1]);
}
} catch (IOException e) {
e.printStackTrace();
}
}
static public String readLine() throws IOException {
return br.readLine();
}
static public String readString() throws IOException {
return br.readLine();
}
static public long readlong() throws IOException {
return Long.parseLong(br.readLine());
}
static public int readInt() throws IOException {
return Integer.parseInt(br.readLine());
}
static public int[] readIntArr() throws IOException {
String[] str = br.readLine().split(" ");
int arr[] = new int[str.length];
for (int i = 0; i < arr.length; i++)
arr[i] = Integer.parseInt(str[i]);
return arr;
}
static public double[] readDoubleArr() throws IOException {
String[] str = br.readLine().split(" ");
double arr[] = new double[str.length];
for (int i = 0; i < arr.length; i++)
arr[i] = Double.parseDouble(str[i]);
return arr;
}
static public long[] readLongArr() throws IOException {
String[] str = br.readLine().split(" ");
long arr[] = new long[str.length];
for (int i = 0; i < arr.length; i++)
arr[i] = Long.parseLong(str[i]);
return arr;
}
static public double readDouble() throws IOException {
return Double.parseDouble(br.readLine());
}
}
| Java | ["......\n4\n3 4\n2 3\n1 6\n2 6", "#..###\n5\n1 3\n5 6\n1 5\n3 6\n3 4"] | 2 seconds | ["1\n1\n5\n4", "1\n1\n2\n2\n0"] | null | Java 6 | standard input | [
"dp",
"implementation"
] | b30e09449309b999473e4be6643d68cd | The first line contains string s of length n (2ββ€βnββ€β105). It is guaranteed that the given string only consists of characters "." and "#". The next line contains integer m (1ββ€βmββ€β105) β the number of queries. Each of the next m lines contains the description of the corresponding query. The i-th line contains integers li,βri (1ββ€βliβ<βriββ€βn). | 1,100 | Print m integers β the answers to the queries in the order in which they are given in the input. | standard output | |
PASSED | f55214f961a9556387d8665859c7f686 | train_000.jsonl | 1494668100 | Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter.For example, suppose Oleg has the set of letters {i,βo,βi} and Igor has the set of letters {i,βm,βo}. One possible game is as follows :Initially, the company name is ???.Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i,βo}.Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i,βm}.Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}.In the end, the company name is oio.Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?A string sβ=βs1s2...sm is called lexicographically smaller than a string tβ=βt1t2...tm (where sββ βt) if siβ<βti where i is the smallest index such that siββ βti. (so sjβ=βtj for all jβ<βi) | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.NoSuchElementException;
public class Main {
private static FastScanner sc = new FastScanner();
public static void main(String[] args) {
char[] oleg = sc.next().toCharArray();
char[] igor = sc.next().toCharArray();
int n = oleg.length;
char[] ans = new char[n];
Arrays.sort(oleg);
Arrays.sort(igor);
ArrayDeque<Character> ol = new ArrayDeque<Character>();
ArrayDeque<Character> ig = new ArrayDeque<Character>();
for(int i=0; i<=(n-1)/2; i++) {
ol.add(oleg[i]);
}
for(int i=n-1; i>=(n+1)/2; i--) {
ig.add(igor[i]);
}
int first = 0;
int last = n-1;
for(int i=0; i<n; i++) {
if(i%2 == 0) {
if(ig.size() != 0 && ol.peek() >= ig.peek()) {
ans[last] = ol.pollLast();
last--;
} else {
ans[first] = ol.poll();
first++;
}
} else {
if(ol.size() != 0 && ol.peek() >= ig.peek()) {
ans[last] = ig.pollLast();
last--;
} else {
ans[first] = ig.poll();
first++;
}
}
}
System.out.println(ans);
}
static class FastScanner {
private final InputStream in = System.in;
private final byte[] buffer = new byte[1024];
private int ptr = 0;
private int buflen = 0;
private boolean hasNextByte() {
if (ptr < buflen) {
return true;
}else{
ptr = 0;
try {
buflen = in.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
if (buflen <= 0) {
return false;
}
}
return true;
}
private int readByte() { if (hasNextByte()) return buffer[ptr++]; else return -1;}
private static boolean isPrintableChar(int c) { return 33 <= c && c <= 126;}
private void skipUnprintable() { while(hasNextByte() && !isPrintableChar(buffer[ptr])) ptr++;}
public boolean hasNext() { skipUnprintable(); return hasNextByte();}
public String next() {
if (!hasNext()) throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while(isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public long nextLong() {
return Long.parseLong(next());
}
public int nextInt(){
return Integer.parseInt(next());
}
}
}
| Java | ["tinkoff\nzscoder", "xxxxxx\nxxxxxx", "ioi\nimo"] | 2 seconds | ["fzfsirk", "xxxxxx", "ioi"] | NoteOne way to play optimally in the first sample is as follows : Initially, the company name is ???????. Oleg replaces the first question mark with 'f'. The company name becomes f??????. Igor replaces the second question mark with 'z'. The company name becomes fz?????. Oleg replaces the third question mark with 'f'. The company name becomes fzf????. Igor replaces the fourth question mark with 's'. The company name becomes fzfs???. Oleg replaces the fifth question mark with 'i'. The company name becomes fzfsi??. Igor replaces the sixth question mark with 'r'. The company name becomes fzfsir?. Oleg replaces the seventh question mark with 'k'. The company name becomes fzfsirk.For the second sample, no matter how they play, the company name will always be xxxxxx. | Java 8 | standard input | [
"greedy",
"sortings",
"games"
] | bc3d0d902ef457560e444ec0128f0688 | The first line of input contains a string s of length n (1ββ€βnββ€β3Β·105). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially. The second line of input contains a string t of length n. All characters of the string are lowercase English letters. This string denotes the set of letters Igor has initially. | 1,800 | The output should contain a string of n lowercase English letters, denoting the company name if Oleg and Igor plays optimally. | standard output | |
PASSED | dc65c5e00d7882aa053cb83ca3fc4cb1 | train_000.jsonl | 1494668100 | Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter.For example, suppose Oleg has the set of letters {i,βo,βi} and Igor has the set of letters {i,βm,βo}. One possible game is as follows :Initially, the company name is ???.Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i,βo}.Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i,βm}.Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}.In the end, the company name is oio.Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?A string sβ=βs1s2...sm is called lexicographically smaller than a string tβ=βt1t2...tm (where sββ βt) if siβ<βti where i is the smallest index such that siββ βti. (so sjβ=βtj for all jβ<βi) | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.NoSuchElementException;
public class Main {
public static void main(String[] args) {
FastScanner sc = new FastScanner();
char[][] s = new char[2][];
s[0] = sc.next().toCharArray();
s[1] = sc.next().toCharArray();
System.out.println(solve(s));
}
private static String solve(char[][] s) {
int n = s[0].length;
Arrays.sort(s[0]);
Arrays.sort(s[1]);
for (int i = 0, j = n - 1; i < j; i ++, j --) {
char tmp = s[1][i];
s[1][i] = s[1][j];
s[1][j] = tmp;
}
ArrayDeque<Character> q1 = new ArrayDeque<>();
ArrayDeque<Character> q2 = new ArrayDeque<>();
for (int i = 0; i < n / 2; i ++) {
q1.add(s[0][i]);
q2.add(s[1][i]);
}
if (n % 2 == 1) {
q1.add(s[0][n / 2]);
}
boolean mode = false;
StringBuilder left = new StringBuilder();
StringBuilder right = new StringBuilder();
for (int i = 0; i < n; i ++) {
int t = i % 2;
if (!q1.isEmpty() && !q2.isEmpty()) {
char c = q1.peekFirst();
char d = q2.peekFirst();
if (c >= d) {
mode = true;
}
}
if (t == 0) {
if (mode) {
right.append(q1.pollLast());
} else {
left.append(q1.pollFirst());
}
} else {
if (mode) {
right.append(q2.pollLast());
} else {
left.append(q2.pollFirst());
}
}
}
return left.toString() + right.reverse().toString();
}
}
class FastScanner {
public static String debug = null;
private final InputStream in = System.in;
private int ptr = 0;
private int buflen = 0;
private byte[] buffer = new byte[1024];
private boolean eos = false;
private boolean hasNextByte() {
if (ptr < buflen) {
return true;
} else {
ptr = 0;
try {
if (debug != null) {
buflen = debug.length();
buffer = debug.getBytes();
debug = "";
eos = true;
} else {
buflen = in.read(buffer);
}
} catch (IOException e) {
e.printStackTrace();
}
if (buflen < 0) {
eos = true;
return false;
} else if (buflen == 0) {
return false;
}
}
return true;
}
private int readByte() {
if (hasNextByte())
return buffer[ptr++];
else
return -1;
}
private static boolean isPrintableChar(int c) {
return 33 <= c && c <= 126;
}
private void skipUnprintable() {
while (hasNextByte() && !isPrintableChar(buffer[ptr]))
ptr++;
}
public boolean isEOS() {
return this.eos;
}
public boolean hasNext() {
skipUnprintable();
return hasNextByte();
}
public String next() {
if (!hasNext())
throw new NoSuchElementException();
StringBuilder sb = new StringBuilder();
int b = readByte();
while (isPrintableChar(b)) {
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
public long nextLong() {
if (!hasNext())
throw new NoSuchElementException();
long n = 0;
boolean minus = false;
int b = readByte();
if (b == '-') {
minus = true;
b = readByte();
}
if (b < '0' || '9' < b) {
throw new NumberFormatException();
}
while (true) {
if ('0' <= b && b <= '9') {
n *= 10;
n += b - '0';
} else if (b == -1 || !isPrintableChar(b)) {
return minus ? -n : n;
} else {
throw new NumberFormatException();
}
b = readByte();
}
}
public int nextInt() {
return (int) nextLong();
}
public long[] nextLongList(int n) {
return nextLongTable(1, n)[0];
}
public int[] nextIntList(int n) {
return nextIntTable(1, n)[0];
}
public long[][] nextLongTable(int n, int m) {
long[][] ret = new long[n][m];
for (int i = 0; i < n; i ++) {
for (int j = 0; j < m; j ++) {
ret[i][j] = nextLong();
}
}
return ret;
}
public int[][] nextIntTable(int n, int m) {
int[][] ret = new int[n][m];
for (int i = 0; i < n; i ++) {
for (int j = 0; j < m; j ++) {
ret[i][j] = nextInt();
}
}
return ret;
}
} | Java | ["tinkoff\nzscoder", "xxxxxx\nxxxxxx", "ioi\nimo"] | 2 seconds | ["fzfsirk", "xxxxxx", "ioi"] | NoteOne way to play optimally in the first sample is as follows : Initially, the company name is ???????. Oleg replaces the first question mark with 'f'. The company name becomes f??????. Igor replaces the second question mark with 'z'. The company name becomes fz?????. Oleg replaces the third question mark with 'f'. The company name becomes fzf????. Igor replaces the fourth question mark with 's'. The company name becomes fzfs???. Oleg replaces the fifth question mark with 'i'. The company name becomes fzfsi??. Igor replaces the sixth question mark with 'r'. The company name becomes fzfsir?. Oleg replaces the seventh question mark with 'k'. The company name becomes fzfsirk.For the second sample, no matter how they play, the company name will always be xxxxxx. | Java 8 | standard input | [
"greedy",
"sortings",
"games"
] | bc3d0d902ef457560e444ec0128f0688 | The first line of input contains a string s of length n (1ββ€βnββ€β3Β·105). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially. The second line of input contains a string t of length n. All characters of the string are lowercase English letters. This string denotes the set of letters Igor has initially. | 1,800 | The output should contain a string of n lowercase English letters, denoting the company name if Oleg and Igor plays optimally. | standard output | |
PASSED | bd480dc21ac219d7fce4f6f36b2057e1 | train_000.jsonl | 1494668100 | Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter.For example, suppose Oleg has the set of letters {i,βo,βi} and Igor has the set of letters {i,βm,βo}. One possible game is as follows :Initially, the company name is ???.Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i,βo}.Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i,βm}.Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}.In the end, the company name is oio.Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?A string sβ=βs1s2...sm is called lexicographically smaller than a string tβ=βt1t2...tm (where sββ βt) if siβ<βti where i is the smallest index such that siββ βti. (so sjβ=βtj for all jβ<βi) | 256 megabytes | /*
ID: mchensd
LANG: JAVA
PROG: NamingCompany
*/
/**
*
* @author Michael
*/
import java.util.*;
import java.io.*;
public class NamingCompany {
static int len;
public static int[] readWord(String s) {
int[] res = new int[26];
for (int i = 0; i < s.length(); ++i) {
++res[s.charAt(i) - 'a'];
}
len = s.length();
return res;
}
public static void main(String[] args) throws IOException {
BufferedReader br;
StringTokenizer st;
PrintWriter out;
br = new BufferedReader(new InputStreamReader(System.in));
int[] a = readWord(br.readLine());
int[] b = readWord(br.readLine());
// System.out.println(Arrays.toString(a));
char[] ans = new char[len];
int left = 0, right = len - 1;
// System.out.println(len);
for (int i = 0; i < len; ++i) {
int min = 0;
while (a[min] == 0) {
++min;
}
int max = 25;
while (b[max] == 0) {
--max;
}
// System.out.println(min);
// System.out.println(max);
if (i % 2 == 0) {
if (min < max) { // axxx, aaax
ans[left++] = (char) ('a' + min);
--a[min];
// System.out.println("Player 1 put down " + ans[left - 1]);
} else {
int togo = (int) Math.ceil((right - left + 1) * 1.0 / 2);
int k = -1;
int last = 0;
while (togo > 0) {
++k;
if (k > 25) {
k = last;
break;
}
if (a[k] > 0) {
togo -= a[k];
last = k;
}
}
ans[right--] = (char) ('a' + k);
--a[k];
// System.out.println("Player 1 put down " + ans[right + 1]);
}
} else {
if (min < max) {
ans[left++] = (char) ('a' + max);
--b[max];
// System.out.println("Player 2 put down " + ans[left - 1]);
} else {
int togo = (int) Math.ceil((right - left + 1) * 1.0 / 2);
int k = 26;
int last = 0;
while (togo > 0) {
--k;
if (k < 0) {
k = last;
break;
}
if (b[k] > 0) {
togo -= b[k]; // ammoo, bccdd
last = k;
}
}
ans[right--] = (char) ('a' + k);
--b[k];
// System.out.println("Player 2 put down " + ans[right + 1]);
}
}
}
out = new PrintWriter(System.out);
out.println(new String(ans));
out.close();
}
}
| Java | ["tinkoff\nzscoder", "xxxxxx\nxxxxxx", "ioi\nimo"] | 2 seconds | ["fzfsirk", "xxxxxx", "ioi"] | NoteOne way to play optimally in the first sample is as follows : Initially, the company name is ???????. Oleg replaces the first question mark with 'f'. The company name becomes f??????. Igor replaces the second question mark with 'z'. The company name becomes fz?????. Oleg replaces the third question mark with 'f'. The company name becomes fzf????. Igor replaces the fourth question mark with 's'. The company name becomes fzfs???. Oleg replaces the fifth question mark with 'i'. The company name becomes fzfsi??. Igor replaces the sixth question mark with 'r'. The company name becomes fzfsir?. Oleg replaces the seventh question mark with 'k'. The company name becomes fzfsirk.For the second sample, no matter how they play, the company name will always be xxxxxx. | Java 8 | standard input | [
"greedy",
"sortings",
"games"
] | bc3d0d902ef457560e444ec0128f0688 | The first line of input contains a string s of length n (1ββ€βnββ€β3Β·105). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially. The second line of input contains a string t of length n. All characters of the string are lowercase English letters. This string denotes the set of letters Igor has initially. | 1,800 | The output should contain a string of n lowercase English letters, denoting the company name if Oleg and Igor plays optimally. | standard output | |
PASSED | e653a69fe19cc9a32ff779cf28cb228d | train_000.jsonl | 1494668100 | Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter.For example, suppose Oleg has the set of letters {i,βo,βi} and Igor has the set of letters {i,βm,βo}. One possible game is as follows :Initially, the company name is ???.Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i,βo}.Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i,βm}.Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}.In the end, the company name is oio.Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?A string sβ=βs1s2...sm is called lexicographically smaller than a string tβ=βt1t2...tm (where sββ βt) if siβ<βti where i is the smallest index such that siββ βti. (so sjβ=βtj for all jβ<βi) | 256 megabytes | /*
ID: mchensd
LANG: JAVA
PROG: NamingCompany
*/
/**
*
* @author Michael
*/
import java.util.*;
import java.io.*;
public class NamingCompany {
static int len;
public static int[] readWord(String s) {
int[] res = new int[26];
for (int i = 0; i < s.length(); ++i) {
++res[s.charAt(i) - 'a'];
}
len = s.length();
return res;
}
public static void main(String[] args) throws IOException {
BufferedReader br;
StringTokenizer st;
PrintWriter out;
br = new BufferedReader(new InputStreamReader(System.in));
int[] a = readWord(br.readLine());
int[] b = readWord(br.readLine());
// System.out.println(Arrays.toString(a));
char[] ans = new char[len];
int left = 0, right = len - 1;
// System.out.println(len);
for (int i = 0; i < len; ++i) {
int min = 0;
while (a[min] == 0) {
++min;
}
int max = 25;
while (b[max] == 0) {
--max;
}
// System.out.println(min);
// System.out.println(max);
if (i % 2 == 0) {
if (min < max) { // axxx, aaax
ans[left++] = (char) ('a' + min);
--a[min];
// System.out.println("Player 1 put down " + ans[left - 1]);
} else {
int togo = (int) Math.ceil((right - left + 1) * 1.0 / 2);
int k = -1;
int last = 0;
while (togo > 0) {
++k;
/*
if (k > 25) {
k = last;
break;
}*/
if (a[k] > 0) {
togo -= a[k];
last = k;
}
}
ans[right--] = (char) ('a' + k);
--a[k];
// System.out.println("Player 1 put down " + ans[right + 1]);
}
} else {
if (min < max) {
ans[left++] = (char) ('a' + max);
--b[max];
// System.out.println("Player 2 put down " + ans[left - 1]);
} else {
int togo = (int) Math.ceil((right - left + 1) * 1.0 / 2);
int k = 26;
int last = 0;
while (togo > 0) {
--k;
/*
if (k < 0) {
k = last;
break;
}*/
if (b[k] > 0) {
togo -= b[k]; // ammoo, bccdd
last = k;
}
}
ans[right--] = (char) ('a' + k);
--b[k];
// System.out.println("Player 2 put down " + ans[right + 1]);
}
}
}
out = new PrintWriter(System.out);
out.println(new String(ans));
out.close();
}
}
| Java | ["tinkoff\nzscoder", "xxxxxx\nxxxxxx", "ioi\nimo"] | 2 seconds | ["fzfsirk", "xxxxxx", "ioi"] | NoteOne way to play optimally in the first sample is as follows : Initially, the company name is ???????. Oleg replaces the first question mark with 'f'. The company name becomes f??????. Igor replaces the second question mark with 'z'. The company name becomes fz?????. Oleg replaces the third question mark with 'f'. The company name becomes fzf????. Igor replaces the fourth question mark with 's'. The company name becomes fzfs???. Oleg replaces the fifth question mark with 'i'. The company name becomes fzfsi??. Igor replaces the sixth question mark with 'r'. The company name becomes fzfsir?. Oleg replaces the seventh question mark with 'k'. The company name becomes fzfsirk.For the second sample, no matter how they play, the company name will always be xxxxxx. | Java 8 | standard input | [
"greedy",
"sortings",
"games"
] | bc3d0d902ef457560e444ec0128f0688 | The first line of input contains a string s of length n (1ββ€βnββ€β3Β·105). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially. The second line of input contains a string t of length n. All characters of the string are lowercase English letters. This string denotes the set of letters Igor has initially. | 1,800 | The output should contain a string of n lowercase English letters, denoting the company name if Oleg and Igor plays optimally. | standard output | |
PASSED | 2a3b4404eae6cf1ccd2d020aaa2df0f8 | train_000.jsonl | 1494668100 | Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter.For example, suppose Oleg has the set of letters {i,βo,βi} and Igor has the set of letters {i,βm,βo}. One possible game is as follows :Initially, the company name is ???.Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i,βo}.Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i,βm}.Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}.In the end, the company name is oio.Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?A string sβ=βs1s2...sm is called lexicographically smaller than a string tβ=βt1t2...tm (where sββ βt) if siβ<βti where i is the smallest index such that siββ βti. (so sjβ=βtj for all jβ<βi) | 256 megabytes | import java.util.*;
import java.io.*;
public class C {
FastScanner in;
PrintWriter out;
boolean systemIO = true;
public void solve() throws IOException {
String s1 = in.next();
String s2 = in.next();
TreeMap<Character, Integer> t11 = new TreeMap<>();
TreeMap<Character, Integer> t22 = new TreeMap<>();
TreeMap<Character, Integer> t1 = new TreeMap<>();
TreeMap<Character, Integer> t2 = new TreeMap<>();
for (int i = 0; i < s1.length(); i++) {
if (t11.containsKey(s1.charAt(i))) {
t11.put(s1.charAt(i), t11.get(s1.charAt(i)) + 1);
} else {
t11.put(s1.charAt(i), 1);
}
}
for (int i = 0; i < s2.length(); i++) {
if (t22.containsKey(s2.charAt(i))) {
t22.put(s2.charAt(i), t22.get(s2.charAt(i)) + 1);
} else {
t22.put(s2.charAt(i), 1);
}
}
int n = s1.length();
char[] ans = new char[n];
int begin = 0;
int last = n - 1;
int first = 0;
int second = 0;
for (char c : t11.keySet()) {
if (first == (n + 1) / 2) {
break;
}
if (first + t11.get(c) <= (n + 1) / 2) {
first += t11.get(c);
t1.put(c, t11.get(c));
} else {
t1.put(c, (n + 1) / 2 - first);
break;
}
}
for (char c : t22.keySet()) {
if (second == (n + 1) / 2) {
t2.put(c, t22.get(c));
} else if (second + t22.get(c) <= (n + 1) / 2) {
second += t22.get(c);
} else {
second += t22.get(c);
t2.put(c, second - (n + 1) / 2);
second = (n + 1) / 2;
}
}
// for (char c : t2.keySet()) {
// System.out.println(c + " " + t2.get(c));
// }
boolean flag = false;
while (last - begin != -1) {
if (t1.size() == 0) {
break;
}
if (!flag && t1.size() > 0 && t2.size() > 0 && t1.firstKey() >= t2.lastKey()) {
flag = true;
}
if (flag) {
ans[last] = t1.lastKey();
if (t1.get(t1.lastKey()) == 1) {
t1.remove(t1.lastKey());
} else {
t1.put(t1.lastKey(), t1.get(t1.lastKey()) - 1);
}
last--;
} else {
ans[begin] = t1.firstKey();
if (t1.get(t1.firstKey()) == 1) {
t1.remove(t1.firstKey());
} else {
t1.put(t1.firstKey(), t1.get(t1.firstKey()) - 1);
}
begin++;
}
if (t2.size() == 0) {
break;
}
if (!flag && t1.size() > 0 && t2.size() > 0 && t1.firstKey() >= t2.lastKey()) {
flag = true;
}
if (flag) {
ans[last] = t2.firstKey();
if (t2.get(t2.firstKey()) == 1) {
t2.remove(t2.firstKey());
} else {
t2.put(t2.firstKey(), t2.get(t2.firstKey()) - 1);
}
last--;
} else {
ans[begin] = t2.lastKey();
if (t2.get(t2.lastKey()) == 1) {
t2.remove(t2.lastKey());
} else {
t2.put(t2.lastKey(), t2.get(t2.lastKey()) - 1);
}
begin++;
}
}
for (int i = 0; i < ans.length; i++) {
out.print(ans[i]);
}
}
public void run() throws IOException {
if (systemIO) {
in = new FastScanner(System.in);
out = new PrintWriter(System.out);
} else {
in = new FastScanner(new File("input.txt"));
out = new PrintWriter(new File("output.txt"));
}
solve();
out.close();
}
class FastScanner {
BufferedReader br;
StringTokenizer st;
FastScanner(File f) {
try {
br = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
FastScanner(InputStream f) {
br = new BufferedReader(new InputStreamReader(f));
}
String nextLine() {
try {
return br.readLine();
} catch (IOException e) {
return null;
}
}
String next() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
}
// AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
public static void main(String[] arg) throws IOException {
new C().run();
}
} | Java | ["tinkoff\nzscoder", "xxxxxx\nxxxxxx", "ioi\nimo"] | 2 seconds | ["fzfsirk", "xxxxxx", "ioi"] | NoteOne way to play optimally in the first sample is as follows : Initially, the company name is ???????. Oleg replaces the first question mark with 'f'. The company name becomes f??????. Igor replaces the second question mark with 'z'. The company name becomes fz?????. Oleg replaces the third question mark with 'f'. The company name becomes fzf????. Igor replaces the fourth question mark with 's'. The company name becomes fzfs???. Oleg replaces the fifth question mark with 'i'. The company name becomes fzfsi??. Igor replaces the sixth question mark with 'r'. The company name becomes fzfsir?. Oleg replaces the seventh question mark with 'k'. The company name becomes fzfsirk.For the second sample, no matter how they play, the company name will always be xxxxxx. | Java 8 | standard input | [
"greedy",
"sortings",
"games"
] | bc3d0d902ef457560e444ec0128f0688 | The first line of input contains a string s of length n (1ββ€βnββ€β3Β·105). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially. The second line of input contains a string t of length n. All characters of the string are lowercase English letters. This string denotes the set of letters Igor has initially. | 1,800 | The output should contain a string of n lowercase English letters, denoting the company name if Oleg and Igor plays optimally. | standard output | |
PASSED | 33a7124201f63a6a0dc3432b37e01eef | train_000.jsonl | 1494668100 | Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter.For example, suppose Oleg has the set of letters {i,βo,βi} and Igor has the set of letters {i,βm,βo}. One possible game is as follows :Initially, the company name is ???.Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i,βo}.Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i,βm}.Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}.In the end, the company name is oio.Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?A string sβ=βs1s2...sm is called lexicographically smaller than a string tβ=βt1t2...tm (where sββ βt) if siβ<βti where i is the smallest index such that siββ βti. (so sjβ=βtj for all jβ<βi) | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.HashMap;
import java.util.InputMismatchException;
public class Main
{
static class Pair implements Comparable<Pair>{
int pro, cus,diff;
public Pair(int pro,int cus,int diff)
{
this.pro = pro;
this.cus = cus;
this.diff = diff;
}
public int compareTo(Pair p1)
{
if(Integer.compare(this.diff,p1.diff)==0)
return p1.cus-this.cus;
else
return p1.diff-this.diff;
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static class Solution
{
static final long mod = 1000000007;
static final int max = 1000003;
static final boolean SIEVE = false;
static long[] powerof2 = new long[(int)3e5+5];
static HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>();
boolean[] prime;
ArrayList<Integer> al;
public void solve(InputReader sc,PrintWriter out)
{
char[] ar = sc.next().toCharArray();
String s = sc.next();
Character[] br = new Character[ar.length];
for(int i=0;i<ar.length;i++)
{
br[i] = s.charAt(i);
}
int n = ar.length;
Comparator<Character> com = Collections.reverseOrder();
char[] ans = new char[n];
Arrays.sort(ar); Arrays.sort(br,com);
//for(int i=0;i<n;i++) out.print(br[i]+" ");
int j=0,k=0;
int l=0,r=n;
int Ar = (n+1)>>1, Br = (n)>>1;
for(int i=0;i<n;i++)
{
if((i&1)==0)
{
if(br[k]>ar[j]) ans[l++] = ar[j++];
else ans[--r]=ar[--Ar];
}
else
{
if(br[k]>ar[j]) ans[l++] = br[k++];
else ans[--r]=br[--Br];
}
}
for(int i=0;i<n;i++)
out.print(ans[i]);
}
///////////////////////////////Methods///////////////////////////////////////////////////////
int lower_bound(int n, int x) {
int l = 0;
int h = n; // Not n - 1
while (l < h) {
int mid = (l + h) / 2;
if (x <= al.get(mid)) {
h = mid;
} else {
l = mid + 1;
}
}
return l;
}
long fib(long n)
{
if(n==0) return 0;
long a=0, b=1, c=1, d=1, e=n-2;
long a1, b1, c1, d1, a2=0, b2=1, c2=1, d2=1;
while(e>0){
if(e%2==1){
a1 = (a*a2+b*c2)%mod;
c1 = (c*a2+d*c2)%mod;
b1 = (a*b2+ b*d2)%mod;
d1 = (b2*c+ d*d2)%mod;
a=a1; b=b1; c=c1; d= d1;
}
a1 = (a2*a2+b2*c2)%mod;
c1 = (c2*a2+d2*c2)%mod;
b1 = (a2*b2+ b2*d2)%mod;
d1 = (b2*c2+ d2*d2)%mod;
a2=a1; b2=b1; c2=c1; d2= d1;
e /= 2;
}
return d;
}
///////////////////////////////////////Methods/////////////////////////////////////////////////////
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Main() throws IOException {
InputReader sc = new InputReader();
PrintWriter out= new PrintWriter(System.out);
final long start = System.currentTimeMillis();
new Solution().solve(sc,out);
@SuppressWarnings("unused")
final long duration = System.currentTimeMillis()-start;
out.close();
}
public static void main(String args[]) {
new Thread(null, new Runnable() {
public void run() {
try {
new Main();
} catch (Exception e) {
e.printStackTrace();
}
}
}, "1", 1 << 26).start();
}
static class InputReader{
final InputStream stream;
final byte[] buf = new byte[8192];
int curChar, numChars;
SpaceCharFilter filter;
public InputReader(){
this.stream = System.in;
}
public int read(){
if(numChars == -1){
throw new InputMismatchException();
}
if(curChar >= numChars){
curChar = 0;
try{
numChars = stream.read(buf);
} catch(IOException e){
throw new InputMismatchException();
}
if(numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt(){
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if(c == '-'){
sgn = -1;
c = read();
}
int res = 0;
do{
if(c<'0' || c>'9'){
throw new InputMismatchException();}
res *= 10;
res += c - '0';
c = read();
} while(!isSpaceChar(c));
return res*sgn;
}
public long nextLong(){
int c = read();
while(isSpaceChar(c))
c = read();
int sgn = 1;
if(c == '-'){
sgn = -1;
c = read();
}
long res = 0;
do{
if(c<'0' || c>'9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while(!isSpaceChar(c));
return res*sgn;
}
public String next(){
int c = read();
while(isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do{
res.appendCodePoint(c);
c = read();
}while(!isSpaceChar(c));
return res.toString();
}
public boolean isSpaceChar(int c){
if(filter != null)
return filter.isSpaceChar(c);
return c==' ' || c=='\n' || c=='\r' || c=='\t' || c==-1;
}
public interface SpaceCharFilter{
public boolean isSpaceChar(int ch);
}
}
} | Java | ["tinkoff\nzscoder", "xxxxxx\nxxxxxx", "ioi\nimo"] | 2 seconds | ["fzfsirk", "xxxxxx", "ioi"] | NoteOne way to play optimally in the first sample is as follows : Initially, the company name is ???????. Oleg replaces the first question mark with 'f'. The company name becomes f??????. Igor replaces the second question mark with 'z'. The company name becomes fz?????. Oleg replaces the third question mark with 'f'. The company name becomes fzf????. Igor replaces the fourth question mark with 's'. The company name becomes fzfs???. Oleg replaces the fifth question mark with 'i'. The company name becomes fzfsi??. Igor replaces the sixth question mark with 'r'. The company name becomes fzfsir?. Oleg replaces the seventh question mark with 'k'. The company name becomes fzfsirk.For the second sample, no matter how they play, the company name will always be xxxxxx. | Java 8 | standard input | [
"greedy",
"sortings",
"games"
] | bc3d0d902ef457560e444ec0128f0688 | The first line of input contains a string s of length n (1ββ€βnββ€β3Β·105). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially. The second line of input contains a string t of length n. All characters of the string are lowercase English letters. This string denotes the set of letters Igor has initially. | 1,800 | The output should contain a string of n lowercase English letters, denoting the company name if Oleg and Igor plays optimally. | standard output | |
PASSED | d03fd28e0d7197e05bafad9e77101a52 | train_000.jsonl | 1494668100 | Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter.For example, suppose Oleg has the set of letters {i,βo,βi} and Igor has the set of letters {i,βm,βo}. One possible game is as follows :Initially, the company name is ???.Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i,βo}.Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i,βm}.Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}.In the end, the company name is oio.Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?A string sβ=βs1s2...sm is called lexicographically smaller than a string tβ=βt1t2...tm (where sββ βt) if siβ<βti where i is the smallest index such that siββ βti. (so sjβ=βtj for all jβ<βi) | 256 megabytes |
/*
HARSH KHATRI
DA-IICT
*/
import java.io.*;
import java.util.*;
import java.lang.*;
import java.util.Scanner;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
public class CF794C {
public static void main(String[] args) {
FasterScanner in = new FasterScanner();
String s = in.nextLine(), t = in.nextLine();
int n = s.length(), i, j, k, l, count = 0, p, q;
char[] a = s.toCharArray(), b = t.toCharArray(), c = new char[n];
boolean inv = false;
Arrays.sort(a);
Arrays.sort(b);
i = p = 0; k = (n+1)/2; l = (n-1-(n/2)); k--; l++; q = j = n-1;
while(count<n) {
if((count&1)==0) {
if(a[i]<b[j]) {
c[p++] = a[i++];
}
else {
c[q--] = a[k--];
}
}
else {
if(b[j]>a[i]) {
c[p++] = b[j--];
}
else {
c[q--] = b[l++];
}
}
count++;
}
for(i=0; i<n; i++) {
System.out.print(c[i]);
}
System.out.println();
}
}
class FasterScanner {
private byte[] buf = new byte[1024];
private int curChar;
private int snumChars;
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = System.in.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public double nextDouble() {
return Double.parseDouble(this.nextString());
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public String nextString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int nextInt() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = nextInt();
}
return arr;
}
public long[] nextLongArray(int n) {
long[] arr = new long[n];
for (int i = 0; i < n; i++) {
arr[i] = nextLong();
}
return arr;
}
private boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
} | Java | ["tinkoff\nzscoder", "xxxxxx\nxxxxxx", "ioi\nimo"] | 2 seconds | ["fzfsirk", "xxxxxx", "ioi"] | NoteOne way to play optimally in the first sample is as follows : Initially, the company name is ???????. Oleg replaces the first question mark with 'f'. The company name becomes f??????. Igor replaces the second question mark with 'z'. The company name becomes fz?????. Oleg replaces the third question mark with 'f'. The company name becomes fzf????. Igor replaces the fourth question mark with 's'. The company name becomes fzfs???. Oleg replaces the fifth question mark with 'i'. The company name becomes fzfsi??. Igor replaces the sixth question mark with 'r'. The company name becomes fzfsir?. Oleg replaces the seventh question mark with 'k'. The company name becomes fzfsirk.For the second sample, no matter how they play, the company name will always be xxxxxx. | Java 8 | standard input | [
"greedy",
"sortings",
"games"
] | bc3d0d902ef457560e444ec0128f0688 | The first line of input contains a string s of length n (1ββ€βnββ€β3Β·105). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially. The second line of input contains a string t of length n. All characters of the string are lowercase English letters. This string denotes the set of letters Igor has initially. | 1,800 | The output should contain a string of n lowercase English letters, denoting the company name if Oleg and Igor plays optimally. | standard output | |
PASSED | 01edd80cd7ba6e82dc14d7c41428edcd | train_000.jsonl | 1494668100 | Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter.For example, suppose Oleg has the set of letters {i,βo,βi} and Igor has the set of letters {i,βm,βo}. One possible game is as follows :Initially, the company name is ???.Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i,βo}.Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i,βm}.Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}.In the end, the company name is oio.Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?A string sβ=βs1s2...sm is called lexicographically smaller than a string tβ=βt1t2...tm (where sββ βt) if siβ<βti where i is the smallest index such that siββ βti. (so sjβ=βtj for all jβ<βi) | 256 megabytes | import java.io.*;
import java.util.*;
import java.lang.*;
import java.util.HashMap;
public class templ {
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l)
{
int mid = l + (r - l)/2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, l, mid-1, x);
return binarySearch(arr, mid+1, r, x);
}
return -1;
}
void merge1(int arr[], int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int [n1];
int R[] = new int [n2];
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];
int i = 0, j = 0;
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++;
}
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
void sort1(int arr[], int l, int r)
{
if (l < r)
{
int m = (l+r)/2;
sort1(arr, l, m);
sort1(arr , m+1, r);
merge1(arr, l, m, r);
}
}
void merge3(int arr[],int arr1[],int arr2[], int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int [n1];
int R[] = new int [n2];
int L1[]=new int[n1];
int R1[]=new int[n2];
int L2[]=new int[n1];
int R2[]=new int[n2];
//long L3[]=new long[n1];
//long R3[]=new long[n2];
for (int i=0; i<n1; ++i)
{
L[i] = arr[l + i];
L1[i]=arr1[l+i];
L2[i]=arr2[l+i];
//L3[i]=arr3[l+i];
}
for (int j=0; j<n2; ++j)
{
R[j] = arr[m + 1+ j];
R1[j]=arr1[m+1+j];
R2[j]=arr2[m+1+j];
//R3[j]=arr3[m+1+j];
}
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
arr1[k]=L1[i];
arr2[k]=L2[i];
//arr3[k]=L3[i];
i++;
}
else
{
arr[k] = R[j];
arr1[k]=R1[j];
arr2[k]=R2[j];
//arr3[k]=R3[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
arr1[k]=L1[i];
arr2[k]=L2[i];
//arr3[k]=L3[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
arr1[k]=R1[j];
arr2[k]=R2[j];
//arr3[k]=R3[j];
j++;
k++;
}
}
void sort3(int arr[],int arr1[],int arr2[], int l, int r)
{
if (l < r)
{
int m = (l+r)/2;
sort3(arr,arr1,arr2, l, m);
sort3(arr ,arr1,arr2, m+1, r);
merge3(arr,arr1,arr2,l, m, r);
}
}
void merge2(int arr[],int arr1[],int l, int m, int r)
{
int n1 = m - l + 1;
int n2 = r - m;
int L[] = new int [n1];
int R[] = new int [n2];
int L1[]=new int[n1];
int R1[]=new int[n2];
for (int i=0; i<n1; ++i)
{
L[i] = arr[l + i];
L1[i]=arr1[l+i];
}
for (int j=0; j<n2; ++j)
{
R[j] = arr[m + 1+ j];
R1[j]=arr1[m+1+j];
}
int i = 0, j = 0;
int k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
arr1[k]=L1[i];
i++;
}
else
{
arr[k] = R[j];
arr1[k]=R1[j];
j++;
}
k++;
}
while (i < n1)
{
arr[k] = L[i];
arr1[k]=L1[i];
i++;
k++;
}
while (j < n2)
{
arr[k] = R[j];
arr1[k]=R1[j];
j++;
k++;
}
}
void sort2(int arr[],int arr1[],int l, int r)
{
if (l < r)
{
int m = (l+r)/2;
sort2(arr,arr1, l, m);
sort2(arr ,arr1, m+1, r);
merge2(arr,arr1,l, m, r);
}
}
public static void main(String[] args) throws FileNotFoundException {
try
{
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
templ ob=new templ();
String s1=in.nextLine();
String s2=in.nextLine();
int l=s1.length();
int n=l;
char c[]=new char[l];
int m1[]=new int[26];
int m2[]=new int[26];
for(int i=0;i<l;i++)
{
char c1=s1.charAt(i);
int d=(int)c1-97;
m1[d]++;
}
for(int i=0;i<l;i++)
{
char c1=s2.charAt(i);
int d=(int)c1-97;
m2[d]++;
}
int k1=n/2;
int k2=(int)Math.ceil((double)n/2);
for(int i=25;i>=0;i--)
{
if(m1[i]<=k1)
{
k1-=m1[i];
m1[i]=0;
}
else
{
m1[i]-=k1;
k1=0;
break;
}
}
for(int i=0;i<26;i++)
{
if(m2[i]<=k2)
{
k2-=m2[i];
m2[i]=0;
}
else
{
m2[i]-=k2;
k2=0;
break;
}
}
int start=-1,last=n;
for(int j=0;j<l;j++)
{
if(j%2==0)
{
int small1=-1;
int large1=-1;
for(int i=0;i<26;i++)
{
if(m1[i]!=0)
{
small1=i;
break;
}
}
for(int i=25;i>=0;i--)
{
if(m1[i]!=0)
{
large1=i;
break;
}
}
int small2=-1;
int large2=-1;
for(int i=0;i<26;i++)
{
if(m2[i]!=0)
{
small2=i;
break;
}
}
for(int i=25;i>=0;i--)
{
if(m2[i]!=0)
{
large2=i;
break;
}
}
if(small1>=large2)
{
last--;
c[last]=(char)(large1+97);
m1[large1]--;
if(last==start)
break;
}
else
{
start++;
c[start]=(char)(small1+97);
m1[small1]--;
if(start==last)
break;
}
}
else if(j%2==1)
{
int small1=-1;
int large1=-1;
for(int i=0;i<26;i++)
{
if(m1[i]!=0)
{
small1=i;
break;
}
}
for(int i=25;i>=0;i--)
{
if(m1[i]!=0)
{
large1=i;
break;
}
}
int small2=-1;
int large2=-1;
for(int i=0;i<26;i++)
{
if(m2[i]!=0)
{
small2=i;
break;
}
}
for(int i=25;i>=0;i--)
{
if(m2[i]!=0)
{
large2=i;
break;
}
}
if(large2<=small1)
{
last--;
c[last]=(char)(small2+97);
m2[small2]--;
if(start==last)
break;
}
else
{
start++;
c[start]=(char)(large2+97);
m2[large2]--;
if(start==last)
break;
}
}
}
for(int i=0;i<n;i++)
out.print(c[i]);
out.close();
}
catch(Exception e){
return;
}
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String readString() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
} | Java | ["tinkoff\nzscoder", "xxxxxx\nxxxxxx", "ioi\nimo"] | 2 seconds | ["fzfsirk", "xxxxxx", "ioi"] | NoteOne way to play optimally in the first sample is as follows : Initially, the company name is ???????. Oleg replaces the first question mark with 'f'. The company name becomes f??????. Igor replaces the second question mark with 'z'. The company name becomes fz?????. Oleg replaces the third question mark with 'f'. The company name becomes fzf????. Igor replaces the fourth question mark with 's'. The company name becomes fzfs???. Oleg replaces the fifth question mark with 'i'. The company name becomes fzfsi??. Igor replaces the sixth question mark with 'r'. The company name becomes fzfsir?. Oleg replaces the seventh question mark with 'k'. The company name becomes fzfsirk.For the second sample, no matter how they play, the company name will always be xxxxxx. | Java 8 | standard input | [
"greedy",
"sortings",
"games"
] | bc3d0d902ef457560e444ec0128f0688 | The first line of input contains a string s of length n (1ββ€βnββ€β3Β·105). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially. The second line of input contains a string t of length n. All characters of the string are lowercase English letters. This string denotes the set of letters Igor has initially. | 1,800 | The output should contain a string of n lowercase English letters, denoting the company name if Oleg and Igor plays optimally. | standard output | |
PASSED | 72e82c167bcde8a13199bfa9da2a787b | train_000.jsonl | 1494668100 | Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter.For example, suppose Oleg has the set of letters {i,βo,βi} and Igor has the set of letters {i,βm,βo}. One possible game is as follows :Initially, the company name is ???.Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i,βo}.Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i,βm}.Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}.In the end, the company name is oio.Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?A string sβ=βs1s2...sm is called lexicographically smaller than a string tβ=βt1t2...tm (where sββ βt) if siβ<βti where i is the smallest index such that siββ βti. (so sjβ=βtj for all jβ<βi) | 256 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
public class Luck{
public static InputReader sc;
public static PrintWriter out;
public static final int MOD = (int) (1e9 + 7);
public static void main(String[] args){
sc=new InputReader(System.in);
out=new PrintWriter(System.out);
String first=sc.readString();
String second=sc.readString();
char[] firstArr=first.toCharArray();
char[] secondArr=second.toCharArray();
Arrays.sort(firstArr);
Arrays.sort(secondArr);
int l1=0;
int r1=((first.length()+1)/2)-1;
int r2=first.length()-1;
int l2=first.length()-(first.length()/2);
char[] ans=new char[first.length()];
int flag=0;
int index=ans.length-1;
for(int i=0;i<=index;){
if(flag==0){
flag=1;
if(r2>=l2 && firstArr[l1]<secondArr[r2]){
ans[i]+=firstArr[l1];
l1+=1;
i+=1;
}
else{
ans[index]=firstArr[r1];
r1-=1;
index-=1;
}
}
else{
flag=0;
if(l1<=r1 && secondArr[r2]>firstArr[l1]){
ans[i]+=secondArr[r2];
r2-=1;
i+=1;
}
else{
ans[index]=secondArr[l2];
l2+=1;
index-=1;
}
}
}
String temp=new String(ans);
out.println(temp);
out.close();
}
static int gcd(int a,int b){
if(b==0){
return a;
}
return gcd(b,a%b);
}
static int lcm(int a,int b){
int g;
if(a<b){
g=gcd(b,a);
}
else{
g=gcd(a,b);
}
return (a*b)/g;
}
static boolean isPrime(int n){
if (n == 2)
return true;
for (long i = 2; i * i <= n; i++) {
if (n % i == 0)
return false;
}
return true;
}
static void shuffle(int[] A){
for(int i=A.length-1;i>0;i--){
int j=(int)(Math.random()*(i+1));
int temp=A[j];
A[j]=A[i];
A[i]=temp;
}
}
public static class Node implements Comparable<Node>{
int v;
int d;
public Node(){
;
}
public Node (int v, int d) {
this.d = d;
this.v = v;
}
public void print() {
out.println(v + " " + d + " ");
}
public int compareTo(Node n1){
return this.d-n1.d;
}
}
public static BigInteger pow(BigInteger base, BigInteger exp) {
if(exp.equals(new BigInteger(String.valueOf(0)))){
return new BigInteger(String.valueOf(1));
}
if(exp.equals(new BigInteger(String.valueOf(1))))
return base;
BigInteger temp=exp.divide(new BigInteger(String.valueOf(2)));
BigInteger val = pow(base, temp);
BigInteger result = val.multiply(val);
result=result.remainder(new BigInteger(String.valueOf(MOD)));
BigInteger AND=exp.and(new BigInteger(String.valueOf(1)));
if(AND.equals(new BigInteger(String.valueOf(1)))){
result = result.multiply(base);
result=result.remainder(new BigInteger(String.valueOf(MOD)));
}
return result;
}
static class InputReader {
private InputStream stream;
private 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 boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["tinkoff\nzscoder", "xxxxxx\nxxxxxx", "ioi\nimo"] | 2 seconds | ["fzfsirk", "xxxxxx", "ioi"] | NoteOne way to play optimally in the first sample is as follows : Initially, the company name is ???????. Oleg replaces the first question mark with 'f'. The company name becomes f??????. Igor replaces the second question mark with 'z'. The company name becomes fz?????. Oleg replaces the third question mark with 'f'. The company name becomes fzf????. Igor replaces the fourth question mark with 's'. The company name becomes fzfs???. Oleg replaces the fifth question mark with 'i'. The company name becomes fzfsi??. Igor replaces the sixth question mark with 'r'. The company name becomes fzfsir?. Oleg replaces the seventh question mark with 'k'. The company name becomes fzfsirk.For the second sample, no matter how they play, the company name will always be xxxxxx. | Java 8 | standard input | [
"greedy",
"sortings",
"games"
] | bc3d0d902ef457560e444ec0128f0688 | The first line of input contains a string s of length n (1ββ€βnββ€β3Β·105). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially. The second line of input contains a string t of length n. All characters of the string are lowercase English letters. This string denotes the set of letters Igor has initially. | 1,800 | The output should contain a string of n lowercase English letters, denoting the company name if Oleg and Igor plays optimally. | standard output | |
PASSED | 6bd4f0621f728acebfe56ba98adafe29 | train_000.jsonl | 1494668100 | Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter.For example, suppose Oleg has the set of letters {i,βo,βi} and Igor has the set of letters {i,βm,βo}. One possible game is as follows :Initially, the company name is ???.Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i,βo}.Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i,βm}.Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}.In the end, the company name is oio.Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?A string sβ=βs1s2...sm is called lexicographically smaller than a string tβ=βt1t2...tm (where sββ βt) if siβ<βti where i is the smallest index such that siββ βti. (so sjβ=βtj for all jβ<βi) | 256 megabytes | import java.io.*;
import java.util.*;
public class C{
public static void main(String[] args) {
FastScannerC sc = new FastScannerC(System.in);
String a = sc.next();
String b = sc.next();
int len = a.length();
ArrayList<Character> first = new ArrayList<>();
ArrayList<Character> sec = new ArrayList<>();
char[] arrA = a.toCharArray();
char[] arrB = b.toCharArray();
for(char c : arrA){
first.add(c);
}
for(char c : arrB){
sec.add(c);
}
Collections.sort(first);
Collections.sort(sec);
Collections.reverse(sec);
ArrayList<Character> tempA = new ArrayList<>();
ArrayList<Character> tempB = new ArrayList<>();
int limit = len/2;
if(len%2 == 1)
limit++;
for(int i = 0 ; i < limit ; i++){
tempA.add(first.get(i));
}
if(len%2 == 1)
limit--;
for(int i = 0 ; i < limit ; i++){
tempB.add(sec.get(i));
}
first = tempA;
sec = tempB;
char[] arr = new char[len];
int idxA = 0;
int idxB = 0;
int lenA = first.size();
int lenB = sec.size();
boolean turn = true;
for(int i = 0 ; i < len ; i++){
if(turn){ // Oleg turn
if(idxB < lenB && sec.get(idxB) <= first.get(idxA)){
// System.out.println(first.get(lenA-1));
arr[len-1] = first.get(lenA-1);
lenA--;
len--;
i--;
}
else{
arr[i] = first.get(idxA);
idxA++;
}
}
else{
// System.out.println(first.get(idxA) + " " + sec.get(idxB));
if(idxA < lenA && first.get(idxA) >= sec.get(idxB)){
arr[len-1] = sec.get(lenB-1);
lenB--;
len--;
i--;
}
else{
arr[i] = sec.get(idxB);
idxB++;
}
}
turn = !turn;
}
System.out.println(String.copyValueOf(arr));
}
}
class FastScannerC{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public FastScannerC(InputStream stream)
{
this.stream = stream;
}
public int read()
{
if (numChars == -1)
throw new InputMismatchException();
if (curChar >= numChars)
{
curChar = 0;
try
{
numChars = stream.read(buf);
} catch (IOException e)
{
throw new InputMismatchException();
}
if (numChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt()
{
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-')
{
sgn = -1;
c = read();
}
int res = 0;
do
{
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public String next()
{
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine()
{
int c = read();
StringBuilder res = new StringBuilder();
do
{
res.appendCodePoint(c);
c = read();
} while (!isLineEndChar(c));
return res.toString();
}
public double nextDouble() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
double res = 0;
while (!isSpaceChar(c) && c != '.') {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
}
if (c == '.') {
c = read();
double m = 1;
while (!isSpaceChar(c)) {
if (c == 'e' || c == 'E')
return res * Math.pow(10, nextInt());
if (c < '0' || c > '9')
throw new InputMismatchException();
m /= 10;
res += (c - '0') * m;
c = read();
}
}
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public boolean isLineEndChar(int c)
{
if (filter != null)
return filter.isSpaceChar(c);
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter
{
public boolean isSpaceChar(int ch);
}
} | Java | ["tinkoff\nzscoder", "xxxxxx\nxxxxxx", "ioi\nimo"] | 2 seconds | ["fzfsirk", "xxxxxx", "ioi"] | NoteOne way to play optimally in the first sample is as follows : Initially, the company name is ???????. Oleg replaces the first question mark with 'f'. The company name becomes f??????. Igor replaces the second question mark with 'z'. The company name becomes fz?????. Oleg replaces the third question mark with 'f'. The company name becomes fzf????. Igor replaces the fourth question mark with 's'. The company name becomes fzfs???. Oleg replaces the fifth question mark with 'i'. The company name becomes fzfsi??. Igor replaces the sixth question mark with 'r'. The company name becomes fzfsir?. Oleg replaces the seventh question mark with 'k'. The company name becomes fzfsirk.For the second sample, no matter how they play, the company name will always be xxxxxx. | Java 8 | standard input | [
"greedy",
"sortings",
"games"
] | bc3d0d902ef457560e444ec0128f0688 | The first line of input contains a string s of length n (1ββ€βnββ€β3Β·105). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially. The second line of input contains a string t of length n. All characters of the string are lowercase English letters. This string denotes the set of letters Igor has initially. | 1,800 | The output should contain a string of n lowercase English letters, denoting the company name if Oleg and Igor plays optimally. | standard output | |
PASSED | 3e95d48c474591f4ea5fc8be93439bea | train_000.jsonl | 1494668100 | Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter.For example, suppose Oleg has the set of letters {i,βo,βi} and Igor has the set of letters {i,βm,βo}. One possible game is as follows :Initially, the company name is ???.Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i,βo}.Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i,βm}.Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}.In the end, the company name is oio.Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?A string sβ=βs1s2...sm is called lexicographically smaller than a string tβ=βt1t2...tm (where sββ βt) if siβ<βti where i is the smallest index such that siββ βti. (so sjβ=βtj for all jβ<βi) | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Scanner;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Xinyi Tao
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
private int len;
private int[] readWord(Scanner in) {
String word = in.next();
len = word.length();
int[] r = new int[len];
for (int i = 0; i < len; i++)
r[i] = word.charAt(i) - 'a';
Arrays.sort(r);
return r;
}
public void solve(int testNumber, Scanner in, PrintWriter out) {
int[] a = readWord(in);
int[] b = readWord(in);
int[] r = new int[len];
int AMinIndex = 0;
int AMaxIndex = len % 2 == 0 ? len / 2 - 1 : (len - 1) / 2;
int BMaxIndex = len - 1;
int BMinIndex = len % 2 == 0 ? len / 2 : (len + 1) / 2;
int right = len - 1;
int i = 0;
for (i = 0; i < len; i++) {
if (i % 2 == 0) {//player A
if (a[AMinIndex] < b[BMaxIndex]) {
r[i] = a[AMinIndex];
AMinIndex++;
} else {
r[right] = a[AMaxIndex];
AMaxIndex--;
right--;
}
} else {//player B
if (a[AMinIndex] < b[BMaxIndex]) {
r[i] = b[BMaxIndex];
BMaxIndex--;
} else {
r[right] = b[BMinIndex];
BMinIndex++;
right--;
}
}
}
for (i = 0; i < len; i++) {
out.print((char) ('a' + r[i]));
}
}
}
}
| Java | ["tinkoff\nzscoder", "xxxxxx\nxxxxxx", "ioi\nimo"] | 2 seconds | ["fzfsirk", "xxxxxx", "ioi"] | NoteOne way to play optimally in the first sample is as follows : Initially, the company name is ???????. Oleg replaces the first question mark with 'f'. The company name becomes f??????. Igor replaces the second question mark with 'z'. The company name becomes fz?????. Oleg replaces the third question mark with 'f'. The company name becomes fzf????. Igor replaces the fourth question mark with 's'. The company name becomes fzfs???. Oleg replaces the fifth question mark with 'i'. The company name becomes fzfsi??. Igor replaces the sixth question mark with 'r'. The company name becomes fzfsir?. Oleg replaces the seventh question mark with 'k'. The company name becomes fzfsirk.For the second sample, no matter how they play, the company name will always be xxxxxx. | Java 8 | standard input | [
"greedy",
"sortings",
"games"
] | bc3d0d902ef457560e444ec0128f0688 | The first line of input contains a string s of length n (1ββ€βnββ€β3Β·105). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially. The second line of input contains a string t of length n. All characters of the string are lowercase English letters. This string denotes the set of letters Igor has initially. | 1,800 | The output should contain a string of n lowercase English letters, denoting the company name if Oleg and Igor plays optimally. | standard output | |
PASSED | 04003fb54f2c0e63eeef211bfda27860 | train_000.jsonl | 1494668100 | Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter.For example, suppose Oleg has the set of letters {i,βo,βi} and Igor has the set of letters {i,βm,βo}. One possible game is as follows :Initially, the company name is ???.Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i,βo}.Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i,βm}.Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}.In the end, the company name is oio.Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?A string sβ=βs1s2...sm is called lexicographically smaller than a string tβ=βt1t2...tm (where sββ βt) if siβ<βti where i is the smallest index such that siββ βti. (so sjβ=βtj for all jβ<βi) | 256 megabytes | import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Scanner;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author Xinyi Tao
*/
public class Main {
public static void main(String[] args) {
InputStream inputStream = System.in;
OutputStream outputStream = System.out;
Scanner in = new Scanner(inputStream);
PrintWriter out = new PrintWriter(outputStream);
TaskC solver = new TaskC();
solver.solve(1, in, out);
out.close();
}
static class TaskC {
private int len;
private int[] readWord(Scanner in) {
int[] r = new int[26];
String word = in.next();
len = word.length();
for (int i = 0; i < len; i++)
r[word.charAt(i) - 'a']++;
return r;
}
public void solve(int testNumber, Scanner in, PrintWriter out) {
int[] a = readWord(in);
int[] b = readWord(in);
int[] r = new int[len];
int AMinIndex = 0;
int BMaxIndex = 25;
int remaining = len;
int i = 0;
int start = -1;
for (i = 0; i < len; i++) {
while (a[AMinIndex] == 0) AMinIndex++;
while (b[BMaxIndex] == 0) BMaxIndex--;
if (i % 2 == 0) {//player A
if (AMinIndex < BMaxIndex) {
r[i] = AMinIndex;
} else {
if (start == -1)
start = 1;
if ((start + remaining) % 2 == 0)
r[i] = AMinIndex;
else
r[i + start * 2 - 1] = AMinIndex;
}
a[AMinIndex]--;
} else {//player B
if (AMinIndex < BMaxIndex) {
r[i] = BMaxIndex;
} else {
if (start == -1)
start = 0;
if ((start + remaining) % 2 == 1)
r[i] = BMaxIndex;
else
r[i + 1 - start * 2] = BMaxIndex;
}
b[BMaxIndex]--;
}
remaining--;
}
for (i = 0; i < len; i++) {
out.print((char) ('a' + r[i]));
}
}
}
}
| Java | ["tinkoff\nzscoder", "xxxxxx\nxxxxxx", "ioi\nimo"] | 2 seconds | ["fzfsirk", "xxxxxx", "ioi"] | NoteOne way to play optimally in the first sample is as follows : Initially, the company name is ???????. Oleg replaces the first question mark with 'f'. The company name becomes f??????. Igor replaces the second question mark with 'z'. The company name becomes fz?????. Oleg replaces the third question mark with 'f'. The company name becomes fzf????. Igor replaces the fourth question mark with 's'. The company name becomes fzfs???. Oleg replaces the fifth question mark with 'i'. The company name becomes fzfsi??. Igor replaces the sixth question mark with 'r'. The company name becomes fzfsir?. Oleg replaces the seventh question mark with 'k'. The company name becomes fzfsirk.For the second sample, no matter how they play, the company name will always be xxxxxx. | Java 8 | standard input | [
"greedy",
"sortings",
"games"
] | bc3d0d902ef457560e444ec0128f0688 | The first line of input contains a string s of length n (1ββ€βnββ€β3Β·105). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially. The second line of input contains a string t of length n. All characters of the string are lowercase English letters. This string denotes the set of letters Igor has initially. | 1,800 | The output should contain a string of n lowercase English letters, denoting the company name if Oleg and Igor plays optimally. | standard output | |
PASSED | ba382dc85ac249bf797029a844c8eecc | train_000.jsonl | 1494668100 | Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter.For example, suppose Oleg has the set of letters {i,βo,βi} and Igor has the set of letters {i,βm,βo}. One possible game is as follows :Initially, the company name is ???.Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i,βo}.Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i,βm}.Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}.In the end, the company name is oio.Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?A string sβ=βs1s2...sm is called lexicographically smaller than a string tβ=βt1t2...tm (where sββ βt) if siβ<βti where i is the smallest index such that siββ βti. (so sjβ=βtj for all jβ<βi) | 256 megabytes | /*
* Author Ayub Subhaniya
* Institute DA-IICT
*/
import java.io.*;
import java.math.*;
import java.util.*;
public class Codeforces408 {
InputStream in;
PrintWriter out;
void solve()
{
char []c1=ns().toCharArray();
char []c2=ns().toCharArray();
int n=c1.length;
char []c=new char[n];
Arrays.sort(c1);
Arrays.sort(c2);
//tr(c1);
//tr(c2);
int c1s=0,c1e=(n-1)/2;
int c2s=n-1,c2e=c2s-n/2+1;
int start=0,end=n-1;
boolean flag=false;
if (n%2!=0)
{
flag=true;
n--;
}
for (int size=0;size<n;size++)
{
//tr(c);
//tr(start+"-"+end);
//tr("1->"+c1s+"-"+c1e);
//tr("2->"+c2s+"-"+c2e);
if (size%2==0)
{
if (c1[c1s]>=c2[c2s])
{
c[end--]=c1[c1e--];
}
else
{
c[start++]=c1[c1s++];
}
}
else
{
if (c1[c1s]>=c2[c2s])
{
c[end--]=c2[c2e++];
}
else
{
c[start++]=c2[c2s--];
}
}
}
if (flag)
{
c[start++]=c1[c1e++];
n++;
}
for (int i=0;i<n;i++)
out.print(c[i]);
}
void run() throws Exception {
String INPUT = "C:/Users/ayubs/Desktop/input.txt";
//oj=true;
in = oj ? System.in : new FileInputStream(INPUT);
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 Codeforces408().run();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = in.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean inSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && inSpaceChar(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 (!(inSpaceChar(b))) { // when nextLine, (inSpaceChar(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 && !(inSpaceChar(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 | ["tinkoff\nzscoder", "xxxxxx\nxxxxxx", "ioi\nimo"] | 2 seconds | ["fzfsirk", "xxxxxx", "ioi"] | NoteOne way to play optimally in the first sample is as follows : Initially, the company name is ???????. Oleg replaces the first question mark with 'f'. The company name becomes f??????. Igor replaces the second question mark with 'z'. The company name becomes fz?????. Oleg replaces the third question mark with 'f'. The company name becomes fzf????. Igor replaces the fourth question mark with 's'. The company name becomes fzfs???. Oleg replaces the fifth question mark with 'i'. The company name becomes fzfsi??. Igor replaces the sixth question mark with 'r'. The company name becomes fzfsir?. Oleg replaces the seventh question mark with 'k'. The company name becomes fzfsirk.For the second sample, no matter how they play, the company name will always be xxxxxx. | Java 8 | standard input | [
"greedy",
"sortings",
"games"
] | bc3d0d902ef457560e444ec0128f0688 | The first line of input contains a string s of length n (1ββ€βnββ€β3Β·105). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially. The second line of input contains a string t of length n. All characters of the string are lowercase English letters. This string denotes the set of letters Igor has initially. | 1,800 | The output should contain a string of n lowercase English letters, denoting the company name if Oleg and Igor plays optimally. | standard output | |
PASSED | fe0f9bfd7a53401acaffec300879b861 | train_000.jsonl | 1494668100 | Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter.For example, suppose Oleg has the set of letters {i,βo,βi} and Igor has the set of letters {i,βm,βo}. One possible game is as follows :Initially, the company name is ???.Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i,βo}.Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i,βm}.Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}.In the end, the company name is oio.Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?A string sβ=βs1s2...sm is called lexicographically smaller than a string tβ=βt1t2...tm (where sββ βt) if siβ<βti where i is the smallest index such that siββ βti. (so sjβ=βtj for all jβ<βi) | 256 megabytes | import java.util.*;
import java.math.*;
import java.io.*;
import java.text.*;
public class A{
static class Node{
int x;
int id;
public Node(int x,int id) {
this.id=id;
this.x=x;
}
}
//public static PrintWriter pw;
public static PrintWriter pw=new PrintWriter(System.out);
public static void solve() throws IOException{
// pw=new PrintWriter(new FileWriter("C:\\Users\\shree\\Downloads\\small_output_in"));
FastReader sc=new FastReader();
char s1[]=sc.next().toCharArray();
char s2[]=sc.next().toCharArray();
Arrays.sort(s1);
Arrays.sort(s2);
rev(s2);
int n=s2.length;
int i1=0,i3=0,i4=n/2-1,i2=(n-1)/2 ;
int l=0,r=n-1;
char ans[]=new char[n];
int t=0;
for(int i=1;i<=n;i++) {
if(i%2!=0) {
if(s1[i1]<s2[i3]) {
ans[l++]=s1[i1++];
}else {
ans[r--]=s1[i2--];
}
}else {
if(s1[i1]<s2[i3]) ans[l++]=s2[i3++];
else ans[r--]=s2[i4--];
}
}
for(int i=0;i<n;i++) pw.print(ans[i]);
pw.close();
}
static void rev(char s[]) {
int i=0,j=s.length-1;
while(i<j) {
char ch=s[i];
s[i]=s[j];
s[j]=ch;
i++; j--;
}
}
public static void main(String[] args) {
new Thread(null ,new Runnable(){
public void run(){
try{
solve();
} catch(Exception e){
e.printStackTrace();
}
}
},"1",1<<26).start();
}
static long M=(long)Math.pow(10,9)+7;
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() throws FileNotFoundException{
//br=new BufferedReader(new FileReader("C:\\Users\\shree\\Downloads\\B-small-practice.in"));
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 I(){ return Integer.parseInt(next()); }
long L(){ return Long.parseLong(next()); }
double D() { return Double.parseDouble(next()); }
String nextLine() {
String str = "";
try {
str = br.readLine();
}
catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
} | Java | ["tinkoff\nzscoder", "xxxxxx\nxxxxxx", "ioi\nimo"] | 2 seconds | ["fzfsirk", "xxxxxx", "ioi"] | NoteOne way to play optimally in the first sample is as follows : Initially, the company name is ???????. Oleg replaces the first question mark with 'f'. The company name becomes f??????. Igor replaces the second question mark with 'z'. The company name becomes fz?????. Oleg replaces the third question mark with 'f'. The company name becomes fzf????. Igor replaces the fourth question mark with 's'. The company name becomes fzfs???. Oleg replaces the fifth question mark with 'i'. The company name becomes fzfsi??. Igor replaces the sixth question mark with 'r'. The company name becomes fzfsir?. Oleg replaces the seventh question mark with 'k'. The company name becomes fzfsirk.For the second sample, no matter how they play, the company name will always be xxxxxx. | Java 8 | standard input | [
"greedy",
"sortings",
"games"
] | bc3d0d902ef457560e444ec0128f0688 | The first line of input contains a string s of length n (1ββ€βnββ€β3Β·105). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially. The second line of input contains a string t of length n. All characters of the string are lowercase English letters. This string denotes the set of letters Igor has initially. | 1,800 | The output should contain a string of n lowercase English letters, denoting the company name if Oleg and Igor plays optimally. | standard output | |
PASSED | dbf13fe818e3baa8060b66164423f16a | train_000.jsonl | 1494668100 | Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter.For example, suppose Oleg has the set of letters {i,βo,βi} and Igor has the set of letters {i,βm,βo}. One possible game is as follows :Initially, the company name is ???.Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i,βo}.Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i,βm}.Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}.In the end, the company name is oio.Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?A string sβ=βs1s2...sm is called lexicographically smaller than a string tβ=βt1t2...tm (where sββ βt) if siβ<βti where i is the smallest index such that siββ βti. (so sjβ=βtj for all jβ<βi) | 256 megabytes | import java.io.IOException;
import java.io.InputStream;
import java.util.InputMismatchException;
import java.util.Arrays;
public class companyName {
static class InputReader
{
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public static boolean isWhitespace(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
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 boolean isSpaceChar(int c) {
if (filter != null) {
return filter.isSpaceChar(c);
}
return isWhitespace(c);
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
public String next() {
return nextString();
}
public char nextChar(){
int c=read();
while (isSpaceChar(c)) {
c = read();
}
return (char)c;
}
public String nextString() {
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 int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
if (c < '0' || c > '9') {
throw new InputMismatchException();
}
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public Long nextLong() {
return Long.parseLong(nextString());
}
public Double nextDouble() {
return Double.parseDouble(nextString());
}
}
public static void main(String[] args) {
InputReader s=new InputReader(System.in);
String str1=s.nextString();
String str2=s.nextString();
char[] oleg=str1.toCharArray();
char[] igor=str2.toCharArray();
Arrays.sort(igor);
Arrays.sort(oleg);
int n1=str1.length();
int n2=(n1+1)/2;
int olegS=0,olegE=n2-1;
int igorS=n2,igorE=n1-1;
char[] ans=new char[n1];
int ansS=0,ansE=ans.length-1;
for(int i=0;i<n1;i++)
{
if(i%2==0)
{
if(oleg[olegS]<igor[igorE])
ans[ansS++]=oleg[olegS++];
else
ans[ansE--]=oleg[olegE--];
}
else
{
if(igor[igorE]>oleg[olegS])
ans[ansS++]=igor[igorE--];
else
ans[ansE--]=igor[igorS++];
}
}
System.out.println(ans);
}
} | Java | ["tinkoff\nzscoder", "xxxxxx\nxxxxxx", "ioi\nimo"] | 2 seconds | ["fzfsirk", "xxxxxx", "ioi"] | NoteOne way to play optimally in the first sample is as follows : Initially, the company name is ???????. Oleg replaces the first question mark with 'f'. The company name becomes f??????. Igor replaces the second question mark with 'z'. The company name becomes fz?????. Oleg replaces the third question mark with 'f'. The company name becomes fzf????. Igor replaces the fourth question mark with 's'. The company name becomes fzfs???. Oleg replaces the fifth question mark with 'i'. The company name becomes fzfsi??. Igor replaces the sixth question mark with 'r'. The company name becomes fzfsir?. Oleg replaces the seventh question mark with 'k'. The company name becomes fzfsirk.For the second sample, no matter how they play, the company name will always be xxxxxx. | Java 8 | standard input | [
"greedy",
"sortings",
"games"
] | bc3d0d902ef457560e444ec0128f0688 | The first line of input contains a string s of length n (1ββ€βnββ€β3Β·105). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially. The second line of input contains a string t of length n. All characters of the string are lowercase English letters. This string denotes the set of letters Igor has initially. | 1,800 | The output should contain a string of n lowercase English letters, denoting the company name if Oleg and Igor plays optimally. | standard output | |
PASSED | b5848cbde683010654045b8555f9a08b | train_000.jsonl | 1494668100 | Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter.For example, suppose Oleg has the set of letters {i,βo,βi} and Igor has the set of letters {i,βm,βo}. One possible game is as follows :Initially, the company name is ???.Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i,βo}.Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i,βm}.Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}.In the end, the company name is oio.Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?A string sβ=βs1s2...sm is called lexicographically smaller than a string tβ=βt1t2...tm (where sββ βt) if siβ<βti where i is the smallest index such that siββ βti. (so sjβ=βtj for all jβ<βi) | 256 megabytes | /**
* Created by Ariana Herbst on 5/13/17.
*/
import java.util.*;
import java.io.*;
public class cfs414C {
public static void main(String[] args) {
FastScanner sc = new FastScanner();
StringBuilder sb = new StringBuilder();
String strA = sc.next();
String strB = sc.next();
int N = strA.length();
char[] A = strA.toCharArray();
char[] B = strB.toCharArray();
Arrays.sort(A);
Arrays.sort(B);
A =Arrays.copyOfRange(A, 0, N / 2 + N % 2);
B = Arrays.copyOfRange(B, N- N/2, N);
int b = B.length-1;
int a = 0;
int bBack = 0;
int aBack = A.length-1;
char[] ans = new char[N];
int front = 0;
int back = N-1;
for (int i = 0; i < N; i++) {
if ((i&1) == 1) { /// lexographically last
if (a == A.length || B[b] > A[a]) {
ans[front++] = B[b--];
}
else {
ans[back--] = B[bBack++];
}
} else { /// lexographically first
if ( b == -1 || A[a] < B[b]) {
ans[front++] = A[a++];
}
else {
ans[back--] = A[aBack--];
}
}
}
for (int i = 0; i < ans.length; i++) {
sb.append(ans[i]);
}
System.out.println(sb);
}
public static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(Reader in) {
br = new BufferedReader(in);
}
public FastScanner() {
this(new InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String readNextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
int[] readIntArray(int n) {
int[] a = new int[n];
for (int idx = 0; idx < n; idx++) {
a[idx] = nextInt();
}
return a;
}
long[] readLongArray(int n) {
long[] a = new long[n];
for (int idx = 0; idx < n; idx++) {
a[idx] = nextLong();
}
return a;
}
}
}
| Java | ["tinkoff\nzscoder", "xxxxxx\nxxxxxx", "ioi\nimo"] | 2 seconds | ["fzfsirk", "xxxxxx", "ioi"] | NoteOne way to play optimally in the first sample is as follows : Initially, the company name is ???????. Oleg replaces the first question mark with 'f'. The company name becomes f??????. Igor replaces the second question mark with 'z'. The company name becomes fz?????. Oleg replaces the third question mark with 'f'. The company name becomes fzf????. Igor replaces the fourth question mark with 's'. The company name becomes fzfs???. Oleg replaces the fifth question mark with 'i'. The company name becomes fzfsi??. Igor replaces the sixth question mark with 'r'. The company name becomes fzfsir?. Oleg replaces the seventh question mark with 'k'. The company name becomes fzfsirk.For the second sample, no matter how they play, the company name will always be xxxxxx. | Java 8 | standard input | [
"greedy",
"sortings",
"games"
] | bc3d0d902ef457560e444ec0128f0688 | The first line of input contains a string s of length n (1ββ€βnββ€β3Β·105). All characters of the string are lowercase English letters. This string denotes the set of letters Oleg has initially. The second line of input contains a string t of length n. All characters of the string are lowercase English letters. This string denotes the set of letters Igor has initially. | 1,800 | The output should contain a string of n lowercase English letters, denoting the company name if Oleg and Igor plays optimally. | standard output | |
PASSED | e6f32704fd42d13b937cc17c1b997420 | train_000.jsonl | 1405256400 | In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation F1β=β1;Β F2β=β1;Β Fnβ=βFnβ-β1β+βFnβ-β2Β (nβ>β2).DZY loves Fibonacci numbers very much. Today DZY gives you an array consisting of n integers: a1,βa2,β...,βan. Moreover, there are m queries, each query has one of the two types: Format of the query "1 l r". In reply to the query, you need to add Fiβ-βlβ+β1 to each element ai, where lββ€βiββ€βr. Format of the query "2 l r". In reply to the query you should output the value of modulo 1000000009Β (109β+β9). Help DZY reply to all the queries. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
/**
* @author Don Li
*/
public class DZYLovesFibonacciNumbers {
static final int MOD = (int) (1e9 + 9);
static final int MAXN = (int) (3e5 + 5);
static final int[] F = new int[MAXN];
static {
F[0] = F[1] = 1;
for (int i = 2; i < MAXN; i++) F[i] = (F[i - 1] + F[i - 2]) % MOD;
}
void solve() {
int n = in.nextInt(), m = in.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = in.nextInt();
SegmentTree seg = new SegmentTree(a);
while (m-- > 0) {
int t = in.nextInt(), l = in.nextInt() - 1, r = in.nextInt();
if (t == 1) {
seg.updateRange(l, r);
} else {
int res = seg.query(l, r);
if (res < 0) res += MOD;
out.println(res);
}
}
}
static class SegmentTree {
int n;
int[] d;
int[] f0, f1;
SegmentTree(int[] a) {
int m = a.length;
int x = 0;
while ((1 << x) < m) x++;
n = 1 << x;
d = new int[2 * n - 1];
for (int i = 0; i < m; i++) {
d[n - 1 + i] = a[i];
}
for (int i = n - 2; i >= 0; i--) {
d[i] = (d[2 * i + 1] + d[2 * i + 2]) % MOD;
}
f0 = new int[2 * n - 1];
f1 = new int[2 * n - 1];
}
void updateRange(int a, int b) {
updateRange(a, b, 0, 0, n);
}
void updateRange(int a, int b, int k, int l, int r) {
if (a >= r || b <= l) return;
if (a <= l && r <= b) {
lazyUpdate(k, l, r, fib(1, 1, l - a), fib(1, 1, l - a + 1));
return;
}
push(k, l, r);
updateRange(a, b, 2 * k + 1, l, (l + r) / 2);
updateRange(a, b, 2 * k + 2, (l + r) / 2, r);
d[k] = (d[2 * k + 1] + d[2 * k + 2]) % MOD;
}
int query(int a, int b) {
return query(a, b, 0, 0, n);
}
int query(int a, int b, int k, int l, int r) {
if (a >= r || b <= l) return 0;
if (a <= l && r <= b) return d[k];
push(k, l, r);
return (query(a, b, 2 * k + 1, l, (l + r) / 2) + query(a, b, 2 * k + 2, (l + r) / 2, r)) % MOD;
}
void lazyUpdate(int k, int l, int r, int x, int y) {
f0[k] = (f0[k] + x) % MOD;
f1[k] = (f1[k] + y) % MOD;
d[k] = (d[k] + fib(x, y, r - l + 1) - y) % MOD;
}
void push(int k, int l, int r) {
if (f0[k] == 0 && f1[k] == 0) return;
lazyUpdate(2 * k + 1, l, (l + r) / 2, f0[k], f1[k]);
lazyUpdate(2 * k + 2, (l + r) / 2, r, fib(f0[k], f1[k], (l + r) / 2 - l), fib(f0[k], f1[k], (l + r) / 2 - l + 1));
f0[k] = f1[k] = 0;
}
int fib(int x, int y, int k) {
if (k == 0) return x;
if (k == 1) return y;
return (int) (((long) F[k - 2] * x % MOD + (long) F[k - 1] * y % MOD) % MOD);
}
}
public static void main(String[] args) {
in = new FastScanner(new BufferedReader(new InputStreamReader(System.in)));
out = new PrintWriter(System.out);
new DZYLovesFibonacciNumbers().solve();
out.close();
}
static FastScanner in;
static PrintWriter out;
static class FastScanner {
BufferedReader in;
StringTokenizer st;
public FastScanner(BufferedReader in) {
this.in = in;
}
public String nextToken() {
while (st == null || !st.hasMoreTokens()) {
try {
st = new StringTokenizer(in.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(nextToken());
}
public long nextLong() {
return Long.parseLong(nextToken());
}
public double nextDouble() {
return Double.parseDouble(nextToken());
}
}
}
| Java | ["4 4\n1 2 3 4\n1 1 4\n2 1 4\n1 2 4\n2 1 3"] | 4 seconds | ["17\n12"] | NoteAfter the first query, aβ=β[2,β3,β5,β7].For the second query, sumβ=β2β+β3β+β5β+β7β=β17.After the third query, aβ=β[2,β4,β6,β9].For the fourth query, sumβ=β2β+β4β+β6β=β12. | Java 8 | standard input | [
"data structures",
"math"
] | 8771e13d0958494e59bf8f61a0041c7a | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β300000). The second line contains n integers a1,βa2,β...,βanΒ (1ββ€βaiββ€β109) β initial array a. Then, m lines follow. A single line describes a single query in the format given in the statement. It is guaranteed that for each query inequality 1ββ€βlββ€βrββ€βn holds. | 2,400 | For each query of the second type, print the value of the sum on a single line. | standard output | |
PASSED | 1f95cc3d3faf60defe2fee310a98e369 | train_000.jsonl | 1405256400 | In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation F1β=β1;Β F2β=β1;Β Fnβ=βFnβ-β1β+βFnβ-β2Β (nβ>β2).DZY loves Fibonacci numbers very much. Today DZY gives you an array consisting of n integers: a1,βa2,β...,βan. Moreover, there are m queries, each query has one of the two types: Format of the query "1 l r". In reply to the query, you need to add Fiβ-βlβ+β1 to each element ai, where lββ€βiββ€βr. Format of the query "2 l r". In reply to the query you should output the value of modulo 1000000009Β (109β+β9). Help DZY reply to all the queries. | 256 megabytes | import java.util.*;
import java.io.*;
/**
*
* @author usquare
*/
public class E447 {
public static int mod = (int) (1e9+9);
public static long[] f=new long[300005];
public static Pair[] buff;
public static void pre(){
f[1]=f[2]=1;
for(int i=3;i<f.length;i++){
f[i]=add(f[i-1], f[i-2]);
}
for(int i=1;i<f.length;i++){
f[i]=add(f[i], f[i-1]);
}
}
public static void main(String[] args) {
InputReader in = new InputReader(System.in);
PrintWriter out = new PrintWriter(System.out);
pre();
int n=in.nextInt();
int m=in.nextInt();
int sq=550;
long[] a=new long[n+1];
for(int i=1;i<=n;i++){
a[i]=add(a[i-1], in.nextLong());
}
int c=0;
buff=new Pair[sq];
long[] tmp=new long[n+3];
while(m-->0){
int t=in.nextInt();
int l=in.nextInt();
int r=in.nextInt();
if(t==1){
tmp[l]++;
tmp[r+1]=sub(tmp[r+1],sub(f[r-l+2],f[r-l+1]));
tmp[r+2]=sub(tmp[r+2],sub(f[r-l+1],f[r-l]));
buff[c++]=new Pair(l, r);
if(c==sq){
c=0;
long sum=tmp[1];
a[1]=add(a[1],tmp[1]);
for(int i=2;i<=n;i++){
tmp[i]=add(tmp[i],add(tmp[i-1], tmp[i-2]));
sum=add(tmp[i], sum);
a[i]=add(a[i], sum);
tmp[i-2]=0;
}
tmp[n]=tmp[n-1]=0;
}
}
else{
long ans=sub(a[r],a[l-1]);
for(int i=0;i<c;i++){
Pair p=buff[i];
int x=max(l,p.x);
int y=min(r,p.y);
if(x>y) continue;
x=x-p.x;
y=y-p.x;
ans=add(ans,sub(f[y+1], f[x]));
}
out.println(ans);
}
}
out.close();
}
static class Pair implements Comparable<Pair>{
int x,i;
int y;
Pair (int x,int y,int i){
this.x=x;
this.y=y;
this.i=i;
}
Pair (int x,int y){
this.x=x;
this.y=y;
}
public int compareTo(Pair o) {
return -Integer.compare(this.x,o.x);
//return 0;
}
public boolean equals(Object o) {
if (o instanceof Pair) {
Pair p = (Pair)o;
return p.x == x && p.y == y && p.i==i;
}
return false;
}
@Override
public String toString() {
return x+" "+y+" "+i;
}
}
public static boolean isPal(String s){
for(int i=0, j=s.length()-1;i<=j;i++,j--){
if(s.charAt(i)!=s.charAt(j)) return false;
}
return true;
}
public static String rev(String s){
StringBuilder sb=new StringBuilder(s);
sb.reverse();
return sb.toString();
}
public static long add(long a,long b){
long x=(a+b);
while(x>=mod) x-=mod;
return x;
}
public static long sub(long a,long b){
long x=(a-b);
while(x<0) x+=mod;
return x;
}
public static long mul(long a,long b){
long x=(a*b);
while(x>=mod) x-=mod;
return x;
}
public static long gcd(long x,long y){
if(x%y==0)
return y;
else
return gcd(y,x%y);
}
public static int gcd(int x,int y){
if(x%y==0)
return y;
else
return gcd(y,x%y);
}
public static long gcdExtended(long a,long b,long[] x){
if(a==0){
x[0]=0;
x[1]=1;
return b;
}
long[] y=new long[2];
long gcd=gcdExtended(b%a, a, y);
x[0]=y[1]-(b/a)*y[0];
x[1]=y[0];
return gcd;
}
public static int abs(int a,int b){
return (int)Math.abs(a-b);
}
public static long abs(long a,long b){
return (long)Math.abs(a-b);
}
public static int max(int a,int b){
if(a>b)
return a;
else
return b;
}
public static int min(int a,int b){
if(a>b)
return b;
else
return a;
}
public static long max(long a,long b){
if(a>b)
return a;
else
return b;
}
public static long min(long a,long b){
if(a>b)
return b;
else
return a;
}
public static long pow(long n,long p,long m){
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
if(result>=m)
result%=m;
p >>=1;
n*=n;
if(n>=m)
n%=m;
}
return result;
}
public static long pow(long n,long p){
long result = 1;
if(p==0)
return 1;
if (p==1)
return n;
while(p!=0)
{
if(p%2==1)
result *= n;
p >>=1;
n*=n;
}
return result;
}
public static void debug(Object... o) {
System.out.println(Arrays.deepToString(o));
}
static class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int snext() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
int res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = snext();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = snext();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public long[] nextLongArray(int n) {
long a[] = new long[n];
for (int i = 0; i < n; i++) {
a[i] = nextLong();
}
return a;
}
public String readString() {
int c = snext();
while (isSpaceChar(c)) {
c = snext();
}
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isSpaceChar(c));
return res.toString();
}
public String nextLine() {
int c = snext();
while (isSpaceChar(c))
c = snext();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = snext();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
} | Java | ["4 4\n1 2 3 4\n1 1 4\n2 1 4\n1 2 4\n2 1 3"] | 4 seconds | ["17\n12"] | NoteAfter the first query, aβ=β[2,β3,β5,β7].For the second query, sumβ=β2β+β3β+β5β+β7β=β17.After the third query, aβ=β[2,β4,β6,β9].For the fourth query, sumβ=β2β+β4β+β6β=β12. | Java 8 | standard input | [
"data structures",
"math"
] | 8771e13d0958494e59bf8f61a0041c7a | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β300000). The second line contains n integers a1,βa2,β...,βanΒ (1ββ€βaiββ€β109) β initial array a. Then, m lines follow. A single line describes a single query in the format given in the statement. It is guaranteed that for each query inequality 1ββ€βlββ€βrββ€βn holds. | 2,400 | For each query of the second type, print the value of the sum on a single line. | standard output | |
PASSED | fa3417b40738372bb06bee89a948cab0 | train_000.jsonl | 1405256400 | In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation F1β=β1;Β F2β=β1;Β Fnβ=βFnβ-β1β+βFnβ-β2Β (nβ>β2).DZY loves Fibonacci numbers very much. Today DZY gives you an array consisting of n integers: a1,βa2,β...,βan. Moreover, there are m queries, each query has one of the two types: Format of the query "1 l r". In reply to the query, you need to add Fiβ-βlβ+β1 to each element ai, where lββ€βiββ€βr. Format of the query "2 l r". In reply to the query you should output the value of modulo 1000000009Β (109β+β9). Help DZY reply to all the queries. | 256 megabytes | import java.io.*;
import java.util.*;
public class CF447E {
static final int MD = 1000000009;
static int[] ff, gg;
static int sum(int f0, int f1, int i, int j) {
// (f0, f1, f0+f1, f0+f1+f1, ...) = (f0, 0, f0, f0, ...) + (0, f1, f1, ...)
int s = i == 0 ? f0 : 0;
if (j >= 1) {
int g1 = i <= 1 ? gg[j - 1] : (gg[j - 1] - gg[i - 2] + MD) % MD;
int s1 = (int) ((long) f1 * g1 % MD);
s = (s + s1) % MD;
if (j >= 2) {
int g0 = i <= 2 ? gg[j - 2] : (gg[j - 2] - gg[i - 3] + MD) % MD;
int s0 = (int) ((long) f0 * g0 % MD);
s = (s + s0) % MD;
}
}
return s;
}
static int[] f0, f1, ss;
static int query1(int k, int l, int r, int ql, int qr) {
if (qr < l || r < ql)
return 0;
if (ql <= l && r <= qr) {
if (l < r) {
f0[k] = (f0[k] + ff[l - ql]) % MD;
f1[k] = (f1[k] + ff[l - ql + 1]) % MD;
}
int s = l == r ? ff[l - ql] : sum(ff[l - ql], ff[l - ql + 1], 0, r - l);
ss[k] = (ss[k] + s) % MD;
return s;
}
int sl = query1(k * 2 + 1, l, (l + r) / 2, ql, qr);
int sr = query1(k * 2 + 2, (l + r) / 2 + 1, r, ql, qr);
int s = (sl + sr) % MD;
ss[k] = (ss[k] + s) % MD;
return s;
}
static int query2(int k, int l, int r, int ql, int qr) {
if (qr < l || r < ql)
return 0;
if (ql <= l && r <= qr)
return ss[k];
int sl = query2(k * 2 + 1, l, (l + r) / 2, ql, qr);
int sr = query2(k * 2 + 2, (l + r) / 2 + 1, r, ql, qr);
int s = (sl + sr) % MD;
int i = Math.max(l, ql) - l;
int j = Math.min(r, qr) - l;
int x = sum(f0[k], f1[k], i, j);
s = (s + x) % MD;
return s;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int[] aa = new int[n];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) {
int a = Integer.parseInt(st.nextToken());
aa[i] = i == 0 ? a : (a + aa[i - 1]) % MD;
}
ff = new int[n];
ff[0] = 1;
if (n > 1)
ff[1] = 1;
for (int i = 2; i < n; i++)
ff[i] = (ff[i - 1] + ff[i - 2]) % MD;
gg = new int[n];
gg[0] = ff[0];
for (int i = 1; i < n; i++)
gg[i] = (gg[i - 1] + ff[i]) % MD;
int t = n * 4;
f0 = new int[t];
f1 = new int[t];
ss = new int[t];
while (m-- > 0) {
st = new StringTokenizer(br.readLine());
int q = Integer.parseInt(st.nextToken());
int l = Integer.parseInt(st.nextToken()) - 1;
int r = Integer.parseInt(st.nextToken()) - 1;
if (q == 1)
query1(0, 0, n - 1, l, r);
else if (q == 2) {
int s = query2(0, 0, n - 1, l, r);
int a = l == 0 ? aa[r] : (aa[r] - aa[l - 1] + MD) % MD;
s = (s + a) % MD;
pw.println(s);
}
}
pw.close();
}
}
| Java | ["4 4\n1 2 3 4\n1 1 4\n2 1 4\n1 2 4\n2 1 3"] | 4 seconds | ["17\n12"] | NoteAfter the first query, aβ=β[2,β3,β5,β7].For the second query, sumβ=β2β+β3β+β5β+β7β=β17.After the third query, aβ=β[2,β4,β6,β9].For the fourth query, sumβ=β2β+β4β+β6β=β12. | Java 8 | standard input | [
"data structures",
"math"
] | 8771e13d0958494e59bf8f61a0041c7a | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β300000). The second line contains n integers a1,βa2,β...,βanΒ (1ββ€βaiββ€β109) β initial array a. Then, m lines follow. A single line describes a single query in the format given in the statement. It is guaranteed that for each query inequality 1ββ€βlββ€βrββ€βn holds. | 2,400 | For each query of the second type, print the value of the sum on a single line. | standard output | |
PASSED | 561270dad6dc758547a5d82110e12b15 | train_000.jsonl | 1405256400 | In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation F1β=β1;Β F2β=β1;Β Fnβ=βFnβ-β1β+βFnβ-β2Β (nβ>β2).DZY loves Fibonacci numbers very much. Today DZY gives you an array consisting of n integers: a1,βa2,β...,βan. Moreover, there are m queries, each query has one of the two types: Format of the query "1 l r". In reply to the query, you need to add Fiβ-βlβ+β1 to each element ai, where lββ€βiββ€βr. Format of the query "2 l r". In reply to the query you should output the value of modulo 1000000009Β (109β+β9). Help DZY reply to all the queries. | 256 megabytes | import java.io.*;
import java.util.*;
public class CF447E {
static int M = 1000000009;
static int add(int a, int b) { return (a + b) % M; }
static int sub(int a, int b) { return (a - b + M) % M; }
static int mul(int a, int b) { return (int) ((long) a * b % M); }
static int[] ff, gg;
static int sum(int f0, int f1, int i, int j) {
// (f0, f1, f0+f1, f0+f1+f1, ...) = (f0, 0, f0, f0, ...) + (0, f1, f1, ...)
int s = i == 0 ? f0 : 0;
if (j >= 2) {
int g1 = i >= 2 ? sub(gg[j - 2], gg[i - 2]) : gg[j - 2];
int s1 = mul(f1, g1);
s = add(s, s1);
if (j >= 3) {
int g0 = i >= 3 ? sub(gg[j - 3], gg[i - 3]) : gg[j - 3];
int s0 = mul(f0, g0);
s = add(s, s0);
}
}
return s;
}
static int[] f0, f1, ss;
static int update(int k, int l, int r, int ql, int qr) {
if (qr <= l || r <= ql)
return 0;
int s;
if (ql <= l && r <= qr) {
if (r - l > 1) {
int d = l - ql;
f0[k] = add(f0[k], ff[d]);
f1[k] = add(f1[k], ff[d + 1]);
s = sum(ff[d], ff[d + 1], 0, r - l);
} else
s = ff[l - ql];
} else {
int m = (l + r) / 2;
int sl = update(k * 2 + 1, l, m, ql, qr);
int sr = update(k * 2 + 2, m, r, ql, qr);
s = add(sl, sr);
}
ss[k] = add(ss[k], s);
return s;
}
static int query(int k, int l, int r, int ql, int qr) {
if (qr <= l || r <= ql)
return 0;
if (ql <= l && r <= qr)
return ss[k];
int m = (l + r) / 2;
int sl = query(k * 2 + 1, l, m, ql, qr);
int sr = query(k * 2 + 2, m, r, ql, qr);
int s = add(sl, sr);
int i = Math.max(l, ql) - l;
int j = Math.min(r, qr) - l;
int f = sum(f0[k], f1[k], i, j);
return add(s, f);
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int[] aa = new int[n];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < n; i++) {
int a = Integer.parseInt(st.nextToken());
aa[i] = i == 0 ? a : add(a, aa[i - 1]);
}
ff = new int[n];
ff[0] = 1;
if (n > 1)
ff[1] = 1;
for (int i = 2; i < n; i++)
ff[i] = add(ff[i - 1], ff[i - 2]);
gg = new int[n];
gg[0] = ff[0];
for (int i = 1; i < n; i++)
gg[i] = add(gg[i - 1], ff[i]);
int t = n * 4;
f0 = new int[t];
f1 = new int[t];
ss = new int[t];
while (m-- > 0) {
st = new StringTokenizer(br.readLine());
int q = Integer.parseInt(st.nextToken());
int l = Integer.parseInt(st.nextToken()) - 1;
int r = Integer.parseInt(st.nextToken());
if (q == 1)
update(0, 0, n, l, r);
else if (q == 2) {
int s = query(0, 0, n, l, r);
int a = l == 0 ? aa[r - 1] : sub(aa[r - 1], aa[l - 1]);
s = add(s, a);
pw.println(s);
}
}
pw.close();
}
}
| Java | ["4 4\n1 2 3 4\n1 1 4\n2 1 4\n1 2 4\n2 1 3"] | 4 seconds | ["17\n12"] | NoteAfter the first query, aβ=β[2,β3,β5,β7].For the second query, sumβ=β2β+β3β+β5β+β7β=β17.After the third query, aβ=β[2,β4,β6,β9].For the fourth query, sumβ=β2β+β4β+β6β=β12. | Java 8 | standard input | [
"data structures",
"math"
] | 8771e13d0958494e59bf8f61a0041c7a | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β300000). The second line contains n integers a1,βa2,β...,βanΒ (1ββ€βaiββ€β109) β initial array a. Then, m lines follow. A single line describes a single query in the format given in the statement. It is guaranteed that for each query inequality 1ββ€βlββ€βrββ€βn holds. | 2,400 | For each query of the second type, print the value of the sum on a single line. | standard output | |
PASSED | b09c1cc44c0459bd9ea7ba9960e87590 | train_000.jsonl | 1405256400 | In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation F1β=β1;Β F2β=β1;Β Fnβ=βFnβ-β1β+βFnβ-β2Β (nβ>β2).DZY loves Fibonacci numbers very much. Today DZY gives you an array consisting of n integers: a1,βa2,β...,βan. Moreover, there are m queries, each query has one of the two types: Format of the query "1 l r". In reply to the query, you need to add Fiβ-βlβ+β1 to each element ai, where lββ€βiββ€βr. Format of the query "2 l r". In reply to the query you should output the value of modulo 1000000009Β (109β+β9). Help DZY reply to all the queries. | 256 megabytes | import java.io.*;
import java.util.*;
public class CF447E {
static int M = 1000000009;
static int add(int a, int b) { return (a + b) % M; }
static int sub(int a, int b) { return (a - b + M) % M; }
static int mul(int a, int b) { return (int) ((long) a * b % M); }
static int[] ff, gg, f0, f1, ss;
// (a0, a1, a0+a1, a0+a1+a1, ...) = (a0, 0, a0, a0, ...) + (0, a1, a1, ...)
static int sum(int a0, int a1, int cnt) {
if (cnt == 0)
return 0;
if (cnt == 1)
return a0;
return add(mul(a0, 1 + gg[cnt - 2]), mul(a1, gg[cnt - 1]));
}
static int fib(int a0, int a1, int i) {
if (i == 0)
return a0;
if (i == 1)
return a1;
return add(mul(a0, ff[i - 1]), mul(a1, ff[i]));
}
static void push(int k, int l, int r) {
if (f0[k] == 0 && f1[k] == 0)
return;
ss[k] = add(ss[k], sum(f0[k], f1[k], r - l));
if (r - l > 1) {
int m = (l + r) / 2;
update(k * 2 + 1, l, m, l, r, f0[k], f1[k]);
update(k * 2 + 2, m, r, l, r, f0[k], f1[k]);
}
f0[k] = f1[k] = 0;
}
static void pull(int k, int l, int r) {
int m = (l + r) / 2;
int s1 = query(k * 2 + 1, l, m, l, m);
int s2 = query(k * 2 + 2, m, r, m, r);
ss[k] = add(s1, s2);
}
static void update(int k, int l, int r, int ql, int qr, int a0, int a1) {
if (qr <= l || r <= ql)
return;
if (ql <= l && r <= qr) {
int b0 = fib(a0, a1, l - ql);
int b1 = fib(a0, a1, l - ql + 1);
f0[k] = add(f0[k], b0);
f1[k] = add(f1[k], b1);
return;
}
push(k, l, r);
int m = (l + r) / 2;
update(k * 2 + 1, l, m, ql, qr, a0, a1);
update(k * 2 + 2, m, r, ql, qr, a0, a1);
pull(k, l, r);
}
static int query(int k, int l, int r, int ql, int qr) {
if (qr <= l || r <= ql)
return 0;
push(k, l, r);
if (ql <= l && r <= qr)
return ss[k];
int m = (l + r) / 2;
int sl = query(k * 2 + 1, l, m, ql, qr);
int sr = query(k * 2 + 2, m, r, ql, qr);
return add(sl, sr);
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
int[] aa = new int[n + 1];
for (int i = 1; i <= n; i++)
aa[i] = add(aa[i - 1], Integer.parseInt(st.nextToken()));
ff = new int[n + 1];
ff[0] = 0;
ff[1] = 1;
for (int i = 2; i <= n; i++)
ff[i] = add(ff[i - 1], ff[i - 2]);
gg = new int[n + 1];
for (int i = 1; i <= n; i++)
gg[i] = add(gg[i - 1], ff[i]);
int t = n * 4;
f0 = new int[t];
f1 = new int[t];
ss = new int[t];
while (m-- > 0) {
st = new StringTokenizer(br.readLine());
int q = Integer.parseInt(st.nextToken());
int l = Integer.parseInt(st.nextToken());
int r = Integer.parseInt(st.nextToken());
if (q == 1)
update(0, 0, n, l - 1, r, 1, 1);
else if (q == 2) {
int s = query(0, 0, n, l - 1, r);
int a = sub(aa[r], aa[l - 1]);
pw.println(add(s, a));
}
}
pw.close();
}
}
| Java | ["4 4\n1 2 3 4\n1 1 4\n2 1 4\n1 2 4\n2 1 3"] | 4 seconds | ["17\n12"] | NoteAfter the first query, aβ=β[2,β3,β5,β7].For the second query, sumβ=β2β+β3β+β5β+β7β=β17.After the third query, aβ=β[2,β4,β6,β9].For the fourth query, sumβ=β2β+β4β+β6β=β12. | Java 8 | standard input | [
"data structures",
"math"
] | 8771e13d0958494e59bf8f61a0041c7a | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β300000). The second line contains n integers a1,βa2,β...,βanΒ (1ββ€βaiββ€β109) β initial array a. Then, m lines follow. A single line describes a single query in the format given in the statement. It is guaranteed that for each query inequality 1ββ€βlββ€βrββ€βn holds. | 2,400 | For each query of the second type, print the value of the sum on a single line. | standard output | |
PASSED | e814c4438dde9f4931825012c8ce2df7 | train_000.jsonl | 1405256400 | In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation F1β=β1;Β F2β=β1;Β Fnβ=βFnβ-β1β+βFnβ-β2Β (nβ>β2).DZY loves Fibonacci numbers very much. Today DZY gives you an array consisting of n integers: a1,βa2,β...,βan. Moreover, there are m queries, each query has one of the two types: Format of the query "1 l r". In reply to the query, you need to add Fiβ-βlβ+β1 to each element ai, where lββ€βiββ€βr. Format of the query "2 l r". In reply to the query you should output the value of modulo 1000000009Β (109β+β9). Help DZY reply to all the queries. | 256 megabytes | import java.io.*;
import java.util.*;
import java.math.BigInteger;
public class FibonacciLove {
private static final int MODULUS = 1000000009;
private static int[] fibSeq;
private static int[] fibSum;
private static int[] fib0;
private static int[] fib1;
private static int[] ss;
private static int sum(int fib0, int fib1, int i, int j)
{
int s = i == 0 ? fib0 : 0;
if (j >= 1)
{
int g1 = i <= 1 ? fibSum[j - 1] : (fibSum[j - 1] - fibSum[i - 2] + MODULUS) % MODULUS;
int fg = (int) ((long) fib1 * g1 % MODULUS);
s = (s + fg) % MODULUS;
if (j >= 2)
{
int g0 = i <= 2 ? fibSum[j - 2] : (fibSum[j - 2] - fibSum[i - 3] + MODULUS) % MODULUS;
fg = (int) ((long) fib0 * g0 % MODULUS);
s = (s + fg) % MODULUS;
}
}
return s;
}
private static int iterateQ1(int k, int start, int fin, int nStart, int nRight)
{
if (nRight < start || fin < nStart)
return 0;
if (nStart <= start && fin <= nRight)
{
if (start < fin)
{
fib0[k] = (fib0[k] + fibSeq[start - nStart]) % MODULUS;
fib1[k] = (fib1[k] + fibSeq[start - nStart + 1]) % MODULUS;
}
int s = start == fin ? fibSeq[start - nStart] : sum(fibSeq[start - nStart], fibSeq[start - nStart + 1], 0, fin - start);
ss[k] = (ss[k] + s) % MODULUS;
return s;
}
int sstart = iterateQ1(k * 2 + 1, start, (start + fin) / 2, nStart, nRight);
int sfin = iterateQ1(k * 2 + 2, (start + fin) / 2 + 1, fin, nStart, nRight);
int s = (sstart + sfin) % MODULUS;
ss[k] = (ss[k] + s) % MODULUS;
return s;
}
private static int getSum(int k, int start, int fin, int nStart, int nRight)
{
if(nRight < start || fin < nStart)
return 0;
if(nStart <= start && fin <= nRight)
return ss[k];
int sl = getSum(k * 2 + 1, start, (start + fin) / 2, nStart, nRight);
int sr = getSum(k * 2 + 2, (start + fin) / 2 + 1, fin, nStart, nRight);
int s = (sl + sr) % MODULUS;
int i = Math.max(start, nStart) - start;
int j = Math.min(fin, nRight) - start;
int x = sum(fib0[k], fib1[k], i , j);
s = (s + x) % MODULUS;
return s;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] inLine = br.readLine().split(" ");
int n = Integer.parseInt(inLine[0]);
int m = Integer.parseInt(inLine[1]);
inLine = br.readLine().split(" ");
int[] initialState = new int[n];
for(int i = 0; i < n; i++)
{
int a = Integer.parseInt(inLine[i]);
initialState[i] = i == 0 ? a : (a + initialState[i-1]) % MODULUS;
}
fibSeq = new int[n];
fibSeq[0] = 1;
if(n > 1)
fibSeq[1] = 1;
for(int i = 2; i < n; i++)
{
fibSeq[i] = (fibSeq[i-1] + fibSeq[i-2]) % MODULUS;
}
fibSum = new int[n];
fibSum[0] = fibSeq[0];
for(int i = 1; i < n; i++)
{
fibSum[i] = (fibSum[i-1] + fibSeq[i]) % MODULUS;
}
int t = n * 4;
fib0 = new int[t];
fib1 = new int[t];
ss = new int[t];
PrintWriter out = new PrintWriter(System.out);
while(m-- > 0)
{
inLine = br.readLine().split(" ");
int qType = Integer.parseInt(inLine[0]);
int start = Integer.parseInt(inLine[1]) - 1;
int fin = Integer.parseInt(inLine[2]) - 1;
if(qType == 1)
{
int s = iterateQ1(0, 0, n - 1, start, fin);
}
else if(qType == 2)
{
int s = getSum(0, 0, n - 1, start, fin);
int a = start == 0 ? initialState[fin] : (initialState[fin] - initialState[start - 1] + MODULUS) % MODULUS;
s = (s + a) % MODULUS;
out.println(s);
}
}
out.close();
}
} | Java | ["4 4\n1 2 3 4\n1 1 4\n2 1 4\n1 2 4\n2 1 3"] | 4 seconds | ["17\n12"] | NoteAfter the first query, aβ=β[2,β3,β5,β7].For the second query, sumβ=β2β+β3β+β5β+β7β=β17.After the third query, aβ=β[2,β4,β6,β9].For the fourth query, sumβ=β2β+β4β+β6β=β12. | Java 8 | standard input | [
"data structures",
"math"
] | 8771e13d0958494e59bf8f61a0041c7a | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β300000). The second line contains n integers a1,βa2,β...,βanΒ (1ββ€βaiββ€β109) β initial array a. Then, m lines follow. A single line describes a single query in the format given in the statement. It is guaranteed that for each query inequality 1ββ€βlββ€βrββ€βn holds. | 2,400 | For each query of the second type, print the value of the sum on a single line. | standard output | |
PASSED | a98031bafd36678fc63a7dc3f919e0f8 | train_000.jsonl | 1405256400 | In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation F1β=β1;Β F2β=β1;Β Fnβ=βFnβ-β1β+βFnβ-β2Β (nβ>β2).DZY loves Fibonacci numbers very much. Today DZY gives you an array consisting of n integers: a1,βa2,β...,βan. Moreover, there are m queries, each query has one of the two types: Format of the query "1 l r". In reply to the query, you need to add Fiβ-βlβ+β1 to each element ai, where lββ€βiββ€βr. Format of the query "2 l r". In reply to the query you should output the value of modulo 1000000009Β (109β+β9). Help DZY reply to all the queries. | 256 megabytes |
import java.io.*;
public class Code_Forces_447_E
{
public static void main (String[] args) throws java.lang.Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
String[] input = br.readLine().split(" ");
int n = Integer.parseInt(input[0]);
int m = Integer.parseInt(input[1]);
input = br.readLine().split(" ");
int[] initArr = new int[n];
for(int i = 0; i < n; i++)
{
int a = Integer.parseInt(input[i]);
initArr[i] = i == 0 ? a : (a + initArr[i-1]) % MOD;
}
fibonacciSeq = new int[n];
fibonacciSeq[0] = 1;
if(n > 1)
fibonacciSeq[1] = 1;
for(int i = 2; i < n; i++)
{
fibonacciSeq[i] = (fibonacciSeq[i-1] + fibonacciSeq[i-2]) % MOD;
}
fibonacciSum = new int[n];
fibonacciSum[0] = fibonacciSeq[0];
for(int i = 1; i < n; i++)
{
fibonacciSum[i] = (fibonacciSum[i-1] + fibonacciSeq[i]) % MOD;
}
int t = n * 4;
f0 = new int[t];
f1 = new int[t];
ss = new int[t];
while(m-- > 0)
{
input = br.readLine().split(" ");
int qType = Integer.parseInt(input[0]);
int left = Integer.parseInt(input[1]) - 1;
int right = Integer.parseInt(input[2]) - 1;
if(qType == 1)
{
int s = updateElements(0, 0, n - 1, left, right);
}
else if(qType == 2)
{
int s = getSum(0, 0, n - 1, left, right);
int a = left == 0 ? initArr[right] : (initArr[right] - initArr[left - 1] + MOD) % MOD;
s = (s + a) % MOD;
pw.println(s);
}
}
pw.close();
}
static final int MOD = 1000000009;
static int[] fibonacciSeq, fibonacciSum;
static int[] f0,f1,ss;
static int sum(int f0, int f1, int i, int j)
{
int s = i == 0 ? f0 : 0;
if (j >= 1)
{
int g1 = i <= 1 ? fibonacciSum[j - 1] : (fibonacciSum[j - 1] - fibonacciSum[i - 2] + MOD) % MOD;
int fg = (int) ((long) f1 * g1 % MOD);
s = (s + fg) % MOD;
if (j >= 2)
{
int g0 = i <= 2 ? fibonacciSum[j - 2] : (fibonacciSum[j - 2] - fibonacciSum[i - 3] + MOD) % MOD;
fg = (int) ((long) f0 * g0 % MOD);
s = (s + fg) % MOD;
}
}
return s;
}
static int updateElements(int k, int left, int right, int qLeft, int qRight)
{
if (qRight < left || right < qLeft)
return 0;
if (qLeft <= left && right <= qRight)
{
if (left < right)
{
f0[k] = (f0[k] + fibonacciSeq[left - qLeft]) % MOD;
f1[k] = (f1[k] + fibonacciSeq[left - qLeft + 1]) % MOD;
}
int s = left == right ? fibonacciSeq[left - qLeft] : sum(fibonacciSeq[left - qLeft], fibonacciSeq[left - qLeft + 1], 0, right - left);
ss[k] = (ss[k] + s) % MOD;
return s;
}
int sleft = updateElements(k * 2 + 1, left, (left + right) / 2, qLeft, qRight);
int sright = updateElements(k * 2 + 2, (left + right) / 2 + 1, right, qLeft, qRight);
int s = (sleft + sright) % MOD;
ss[k] = (ss[k] + s) % MOD;
return s;
}
static int getSum(int k, int left, int right, int qLeft, int qRight)
{
if(qRight < left || right < qLeft)
return 0;
if(qLeft <= left && right <= qRight)
return ss[k];
int sl = getSum(k * 2 + 1, left, (left + right) / 2, qLeft, qRight);
int sr = getSum(k * 2 + 2, (left + right) / 2 + 1, right, qLeft, qRight);
int s = (sl + sr) % MOD;
int i = Math.max(left, qLeft) - left;
int j = Math.min(right, qRight) - left;
int x = sum(f0[k], f1[k], i , j);
s = (s + x) % MOD;
return s;
}
} | Java | ["4 4\n1 2 3 4\n1 1 4\n2 1 4\n1 2 4\n2 1 3"] | 4 seconds | ["17\n12"] | NoteAfter the first query, aβ=β[2,β3,β5,β7].For the second query, sumβ=β2β+β3β+β5β+β7β=β17.After the third query, aβ=β[2,β4,β6,β9].For the fourth query, sumβ=β2β+β4β+β6β=β12. | Java 8 | standard input | [
"data structures",
"math"
] | 8771e13d0958494e59bf8f61a0041c7a | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β300000). The second line contains n integers a1,βa2,β...,βanΒ (1ββ€βaiββ€β109) β initial array a. Then, m lines follow. A single line describes a single query in the format given in the statement. It is guaranteed that for each query inequality 1ββ€βlββ€βrββ€βn holds. | 2,400 | For each query of the second type, print the value of the sum on a single line. | standard output | |
PASSED | a0244b8aa8a7ab8fbe08f0da432b8237 | train_000.jsonl | 1405256400 | In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation F1β=β1;Β F2β=β1;Β Fnβ=βFnβ-β1β+βFnβ-β2Β (nβ>β2).DZY loves Fibonacci numbers very much. Today DZY gives you an array consisting of n integers: a1,βa2,β...,βan. Moreover, there are m queries, each query has one of the two types: Format of the query "1 l r". In reply to the query, you need to add Fiβ-βlβ+β1 to each element ai, where lββ€βiββ€βr. Format of the query "2 l r". In reply to the query you should output the value of modulo 1000000009Β (109β+β9). Help DZY reply to all the queries. | 256 megabytes | /**
* DA-IICT
* Author : Savaliya Sagar
*/
import java.io.*;
import java.math.*;
import java.util.*;
public class E447 {
InputStream is;
PrintWriter out;
long tree[];
Pair lazy[];
long a[];
int n,m,N=(int) (3e5+5);
int mod = (int) (1e9+9);
long pw[][][] = new long[N][2][2];
void solve() {
n = ni();
m = ni();
a = new long[n+1];
pw[1][1][0]=pw[1][0][1]=pw[1][0][0]=1;
for(int i=2;i<N;i++){
pw[i] = matrixmultyplication(pw[i-1],pw[1]);
}
for (int i = 1; i <= n; i++)
a[i] = add(a[i - 1],ni());
tree = new long[4 * n];
lazy = new Pair[4 * n];
for(int i=0;i<4*n;i++)
lazy[i] = new Pair(0,0);
while(m-->0){
int t = ni();
int l = ni();
int r = ni();
if(t==1){
updateRange(1,1,n,l,r);
}else{
long res = sub(a[r],a[l-1]);
res = add(res,queryRange(1,1,n,l,r));
out.println(res);
}
}
}
void updateRange(int node, int start, int end, int l, int r) {
if (lazy[node].u!=0 || lazy[node].v!=0) {
long F1 = lazy[node].u;
long F2 = lazy[node].v;
tree[node] = add(tree[node],sub(fib(end-start+3,F1,F2),F2));
if(start!=end){
int mid = (start + end) / 2;
lazy[2*node].u = add(lazy[2*node].u,F1);
lazy[2*node].v = add(lazy[2*node].v,F2);
long f1 = fib(mid-start+2,F1,F2);
long f2 = fib(mid-start+3,F1,F2);
lazy[2*node+1].u = add(lazy[2*node+1].u,f1);
lazy[2*node+1].v = add(lazy[2*node+1].v,f2);
}
lazy[node].u = 0;
lazy[node].v = 0;
}
if (start > end || start > r || end < l)
return;
if (start >= l && end <= r) {
long F1,F2;
F1 = fib(start-l+1,1,1);
F2 = fib(start-l+2,1,1);
tree[node] = add(tree[node],sub(fib(end-start+3,F1,F2),F2));
if(start!=end){
int mid = (start + end) / 2;
lazy[2*node].u = add(lazy[2*node].u,F1);
lazy[2*node].v = add(lazy[2*node].v,F2);
long f1 = fib(mid-start+2,F1,F2);
long f2 = fib(mid-start+3,F1,F2);
lazy[2*node+1].u = add(lazy[2*node+1].u,f1);
lazy[2*node+1].v = add(lazy[2*node+1].v,f2);
}
return;
}
int mid = (start + end) / 2;
updateRange(node * 2, start, mid, l, r);
updateRange(node * 2 + 1, mid + 1, end, l, r);
tree[node] = add(tree[node * 2],tree[node * 2 + 1]);
}
long queryRange(int node, int start, int end, int l, int r) {
if (start > end || start > r || end < l)
return 0;
if (lazy[node].u!=0 || lazy[node].v!=0) {
long F1 = lazy[node].u;
long F2 = lazy[node].v;
tree[node] = add(tree[node],sub(fib(end-start+3,F1,F2),F2));
if(start!=end){
int mid = (start + end) / 2;
lazy[2*node].u = add(lazy[2*node].u,F1);
lazy[2*node].v = add(lazy[2*node].v,F2);
long f1 = fib(mid-start+2,F1,F2);
long f2 = fib(mid-start+3,F1,F2);
lazy[2*node+1].u = add(lazy[2*node+1].u,f1);
lazy[2*node+1].v = add(lazy[2*node+1].v,f2);
}
lazy[node].u = 0;
lazy[node].v = 0;
}
if (start >= l && end <= r)
return tree[node];
int mid = (start + end) / 2;
long p1 = queryRange(node * 2, start, mid, l, r);
long p2 = queryRange(node * 2 + 1, mid + 1, end, l, r);
return add(p1, p2);
}
long fib(int n,long a,long b){
if(n==1)
return a;
if(n==2)
return b;
long[][] c = pw[n-2];
long ret = add(mul(c[0][0],b),mul(c[0][1],a));
return ret;
}
long[][] matrixmultyplication(long[][] a,long[][] b){
long[][] c = new long[2][2];
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
c[i][j] = 0;
for(int k=0;k<2;k++){
c[i][j]=(c[i][j] + ((a[i][k]%mod)*(b[k][j]%mod))%mod)%mod;
}
}
}
return c;
}
long add(long a,long b){
long sum = a+b;
if(sum>=mod)
sum -= mod;
return sum;
}
long sub(long a,long b){
long sub = a-b;
if(sub<0)
sub += mod;
return sub;
}
long mul(long a,long b){
return (a*b)%mod;
}
class Pair implements Comparable<Pair> {
long u;
long v;
public Pair(long u, long v) {
this.u = u;
this.v = v;
}
public int hashCode() {
int hu = (int) (u ^ (u >>> 32));
int hv = (int) (v ^ (v >>> 32));
return 31 * hu + hv;
}
public boolean equals(Object o) {
Pair other = (Pair) o;
return u == other.u && v == other.v;
}
public int compareTo(Pair other) {
return Long.compare(u, other.u) != 0 ? Long.compare(u, other.u)
: Long.compare(v, other.v);
}
public String toString() {
return "[u=" + u + ", v=" + v + "]";
}
}
void run() throws Exception {
String INPUT = "/media/sagar407/D/java workspace/11Input_output/input.txt";
is = oj ? System.in : new FileInputStream(INPUT);
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 Thread(null, new Runnable() {
public void run() {
try {
new E447().run();
} catch (Exception e) {
e.printStackTrace();
}
}
}, "1", 1 << 26).start();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != ' ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) {
if (!oj)
System.out.println(Arrays.deepToString(o));
}
} | Java | ["4 4\n1 2 3 4\n1 1 4\n2 1 4\n1 2 4\n2 1 3"] | 4 seconds | ["17\n12"] | NoteAfter the first query, aβ=β[2,β3,β5,β7].For the second query, sumβ=β2β+β3β+β5β+β7β=β17.After the third query, aβ=β[2,β4,β6,β9].For the fourth query, sumβ=β2β+β4β+β6β=β12. | Java 8 | standard input | [
"data structures",
"math"
] | 8771e13d0958494e59bf8f61a0041c7a | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β300000). The second line contains n integers a1,βa2,β...,βanΒ (1ββ€βaiββ€β109) β initial array a. Then, m lines follow. A single line describes a single query in the format given in the statement. It is guaranteed that for each query inequality 1ββ€βlββ€βrββ€βn holds. | 2,400 | For each query of the second type, print the value of the sum on a single line. | standard output | |
PASSED | 6d0ef54da8e9cbc63f4659256922fe26 | train_000.jsonl | 1405256400 | In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation F1β=β1;Β F2β=β1;Β Fnβ=βFnβ-β1β+βFnβ-β2Β (nβ>β2).DZY loves Fibonacci numbers very much. Today DZY gives you an array consisting of n integers: a1,βa2,β...,βan. Moreover, there are m queries, each query has one of the two types: Format of the query "1 l r". In reply to the query, you need to add Fiβ-βlβ+β1 to each element ai, where lββ€βiββ€βr. Format of the query "2 l r". In reply to the query you should output the value of modulo 1000000009Β (109β+β9). Help DZY reply to all the queries. | 256 megabytes | /**
* DA-IICT
* Author : Savaliya Sagar
*/
import java.io.*;
import java.math.*;
import java.util.*;
public class E447 {
InputStream is;
PrintWriter out;
long a[];
int n, m, N = (int) (3e5 + 5);
int mod = (int) (1e9 + 9);
long fib[] = new long[N];
long update[] = new long[N];
int sq = 550;
long pair[] = new long[550];
void solve() {
fib();
n = ni();
m = ni();
a = new long[n + 1];
for (int i = 1; i <= n; i++)
a[i] = add(a[i - 1],ni());
int sz = 0;
while (m-- > 0) {
int t = ni();
int l = ni();
int r = ni();
if (sz==sq) {
sz = 0;
a[1] = add(a[1],update[1]);
long sum = update[1];
for (int i = 2; i <= n; i++) {
update[i] = add(update[i],add(update[i-1],update[i-2]));
sum = add(sum , update[i]);
a[i] = add(a[i],sum);
update[i-2]=0;
}
update[n]=update[n-1]=0;
}
if (t == 1) {
update[l] = add(update[l],1);
update[r + 1] = sub(update[r+1],sub(fib[r - l + 2],fib[r - l + 1]));
update[r + 2] = sub(update[r+2],sub(fib[r - l + 1],fib[r - l]));
pair[sz++] = ((long) l << 32) | (long) r;
} else {
long res = sub(a[r],a[l - 1]);
for (int i = 0; i < sz; i++) {
int L = (int) (pair[i] >> 32);
int R = (int) (pair[i]);
int x = Math.max(L,l);
int y = Math.min(R,r);
if(x>y)
continue;
x = x - L;
y = y - L;
res = add(res,sub(fib[y+1],fib[x]));
}
out.println(res);
}
}
}
long add(long a,long b){
long sum = a + b;
if(sum>=mod)
sum -= mod;
return sum;
}
long sub(long a,long b){
long sub = a - b;
if(sub<0)
sub += mod;
return sub;
}
void fib() {
fib[1] = 1;
fib[2] = 1;
for (int i = 3; i < N; i++) {
fib[i] = add(fib[i - 1],fib[i - 2]);
}
for (int i = 1; i < N; i++) {
fib[i] = add(fib[i],fib[i - 1]);
}
}
void run() throws Exception {
String INPUT = "/media/sagar407/D/java workspace/11Input_output/input.txt";
is = oj ? System.in : new FileInputStream(INPUT);
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 Thread(null, new Runnable() {
public void run() {
try {
new E447().run();
} catch (Exception e) {
e.printStackTrace();
}
}
}, "1", 1 << 26).start();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = is.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean isSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && isSpaceChar(b))
;
return b;
}
private double nd() {
return Double.parseDouble(ns());
}
private char nc() {
return (char) skip();
}
private String ns() {
int b = skip();
StringBuilder sb = new StringBuilder();
while (!(isSpaceChar(b))) { // when nextLine, (isSpaceChar(b) && b != '
// ')
sb.appendCodePoint(b);
b = readByte();
}
return sb.toString();
}
private char[] ns(int n) {
char[] buf = new char[n];
int b = skip(), p = 0;
while (p < n && !(isSpaceChar(b))) {
buf[p++] = (char) b;
b = readByte();
}
return n == p ? buf : Arrays.copyOf(buf, p);
}
private char[][] nm(int n, int m) {
char[][] map = new char[n][];
for (int i = 0; i < n; i++)
map[i] = ns(m);
return map;
}
private int[] na(int n) {
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = ni();
return a;
}
private int ni() {
int num = 0, b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private long nl() {
long num = 0;
int b;
boolean minus = false;
while ((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'))
;
if (b == '-') {
minus = true;
b = readByte();
}
while (true) {
if (b >= '0' && b <= '9') {
num = num * 10 + (b - '0');
} else {
return minus ? -num : num;
}
b = readByte();
}
}
private boolean oj = System.getProperty("ONLINE_JUDGE") != null;
private void tr(Object... o) {
if (!oj)
System.out.println(Arrays.deepToString(o));
}
}
| Java | ["4 4\n1 2 3 4\n1 1 4\n2 1 4\n1 2 4\n2 1 3"] | 4 seconds | ["17\n12"] | NoteAfter the first query, aβ=β[2,β3,β5,β7].For the second query, sumβ=β2β+β3β+β5β+β7β=β17.After the third query, aβ=β[2,β4,β6,β9].For the fourth query, sumβ=β2β+β4β+β6β=β12. | Java 8 | standard input | [
"data structures",
"math"
] | 8771e13d0958494e59bf8f61a0041c7a | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β300000). The second line contains n integers a1,βa2,β...,βanΒ (1ββ€βaiββ€β109) β initial array a. Then, m lines follow. A single line describes a single query in the format given in the statement. It is guaranteed that for each query inequality 1ββ€βlββ€βrββ€βn holds. | 2,400 | For each query of the second type, print the value of the sum on a single line. | standard output | |
PASSED | 98d2478445c4b00be64ec29299582493 | train_000.jsonl | 1405256400 | In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation F1β=β1;Β F2β=β1;Β Fnβ=βFnβ-β1β+βFnβ-β2Β (nβ>β2).DZY loves Fibonacci numbers very much. Today DZY gives you an array consisting of n integers: a1,βa2,β...,βan. Moreover, there are m queries, each query has one of the two types: Format of the query "1 l r". In reply to the query, you need to add Fiβ-βlβ+β1 to each element ai, where lββ€βiββ€βr. Format of the query "2 l r". In reply to the query you should output the value of modulo 1000000009Β (109β+β9). Help DZY reply to all the queries. | 256 megabytes | /*
* Author Ayub Subhaniya
* Institute DA-IICT
*/
import java.io.*;
import java.math.*;
import java.util.*;
public class Driver {
InputStream in;
PrintWriter out;
int n;
int MAXB;
int MAXN;
long buffer[];
long f[];
long mod=(long)1e9+9;
void init()
{
MAXN=(int)3e5+7;
MAXB=(int) Math.sqrt(n);
buffer=new long[n];
f=new long[MAXN];
}
void fibonacci()
{
f[1]=1;
f[2]=1;
for (int i=3;i<MAXN;i++)
f[i]=add(f[i-1],f[i-2]);
for (int i=1;i<MAXN;i++)
f[i]=add(f[i],f[i-1]);
}
void solve() {
n=ni();
init();
fibonacci();
int m=ni();
long pSum[]=new long[n+1];
for (int i=1;i<=n;i++)
pSum[i]=add(pSum[i-1],nl());
long tmp[]=new long[n+3];
int c=0;
while (m-->0)
{
int t=ni();
int l=ni();
int r=ni();
if (t==1)
{
buffer[c++]=((long)l<<32)|(long)r;
tmp[l]=add(tmp[l],1);
tmp[r+1]=sub(tmp[r+1],sub(f[r-l+2],f[r-l+1]));
tmp[r+2]=sub(tmp[r+2],sub(f[r-l+1],f[r-l]));
}
else
{
long ans=sub(pSum[r],pSum[l-1]);
for (int i=0;i<c;i++)
{
int l1=(int)(buffer[i]>>32);
int r1=(int)(buffer[i]);
int L=Math.max(l1, l);
int R=Math.min(r1, r);
if (L>R)
continue;
L-=l1;
R-=l1;
ans=add(ans,sub(f[R+1],f[L]));
}
out.println(ans);
}
if (c>=MAXB)
{
long sum=tmp[1];
pSum[1]=add(pSum[1],sum);
for (int i=2;i<=n;i++)
{
tmp[i]=add(tmp[i],add(tmp[i-1],tmp[i-2]));
sum=add(sum,tmp[i]);
pSum[i]=add(pSum[i],sum);
tmp[i-2]=0;
}
tmp[n]=tmp[n-1]=0;
c=0;
}
}
}
long sub(long a,long b)
{
long sub=a-b;
while (sub<0)
sub+=mod;
return sub;
}
long add(long a,long b)
{
long add=a+b;
while (add>=mod)
add-=mod;
return add;
}
long mult(long a,long b)
{
long mult=a*b;
while (mult>=mod)
mult-=mod;
return mult;
}
void run() throws Exception {
String INPUT = "C:/Users/ayubs/Desktop/input.txt";
//oj=true;
in = oj ? System.in : new FileInputStream(INPUT);
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 Driver().run();
}
private byte[] inbuf = new byte[1024];
public int lenbuf = 0, ptrbuf = 0;
private int readByte() {
if (lenbuf == -1)
throw new InputMismatchException();
if (ptrbuf >= lenbuf) {
ptrbuf = 0;
try {
lenbuf = in.read(inbuf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (lenbuf <= 0)
return -1;
}
return inbuf[ptrbuf++];
}
private boolean inSpaceChar(int c) {
return !(c >= 33 && c <= 126);
}
private int skip() {
int b;
while ((b = readByte()) != -1 && inSpaceChar(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 (!(inSpaceChar(b))) { // when nextLine, (inSpaceChar(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 && !(inSpaceChar(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 4\n1 2 3 4\n1 1 4\n2 1 4\n1 2 4\n2 1 3"] | 4 seconds | ["17\n12"] | NoteAfter the first query, aβ=β[2,β3,β5,β7].For the second query, sumβ=β2β+β3β+β5β+β7β=β17.After the third query, aβ=β[2,β4,β6,β9].For the fourth query, sumβ=β2β+β4β+β6β=β12. | Java 8 | standard input | [
"data structures",
"math"
] | 8771e13d0958494e59bf8f61a0041c7a | The first line of the input contains two integers n and m (1ββ€βn,βmββ€β300000). The second line contains n integers a1,βa2,β...,βanΒ (1ββ€βaiββ€β109) β initial array a. Then, m lines follow. A single line describes a single query in the format given in the statement. It is guaranteed that for each query inequality 1ββ€βlββ€βrββ€βn holds. | 2,400 | For each query of the second type, print the value of the sum on a single line. | standard output | |
PASSED | 8f7ccfea1f2e6c6bcda548416437c6fe | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.*;
import java.lang.reflect.Array;
import java.nio.Buffer;
import java.util.*;
public class Pair {
public static void main(String[] args) throws Exception {
try {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while(T!=0){
long n = sc.nextLong();
long count2=0;
long count3=0;
long count5=0;
while(n%2==0){
n/=2;
count2+=1;
}
while(n%3==0){
n/=3;
count3+=1;
}
while(n%5==0){
n/=5;
count5+=1;
}
if(n!=1){
System.out.println("-1");
}
else{
System.out.println(count2+(count3*2)+count5*3);
}
}
}
catch (Exception e) {
}
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 56dbaa6f3cbb563ba3a3484ddd2646d3 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
public class competitive23 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
long x[] = new long[n];
for (int i = 0; i < n; i++) {
x[i] = in.nextLong();
}
int count[] = new int[n];
for (int i = 0; i < n; i++) {
count[i] = 0;
while (x[i] > 1) {
if (x[i] % 2 == 0) {
count[i]++;
x[i] /= 2;
}
else if (x[i] % 3 == 0) {
count[i]++;
x[i] = (x[i] * 2) / 3;
}
else if (x[i] % 5 == 0) {
count[i]++;
x[i] = (x[i] * 4) / 5;
}
else{
count[i] = -1;
break;
}
}
}
for (int i = 0; i < n; i++) {
System.out.println(count[i]);
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 393be7e27126fc20cf3431a52c3c477d | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | /*package whatever //do not write package name here */
import java.util.Scanner;
public class GFG {
public static void main (String[] args) {
Scanner value = new Scanner(System.in);
int n,i,x,y=0,z=0,l=0;
n=value.nextInt();
Long a[];
a=new Long[n];
for(i=0;i<n;i++)
{
a[i]=value.nextLong();
}
for(i=0;i<n;i++)
{
z=0;
y=0;
if(a[i]==1)
{
System.out.println(0);;
}else {
while(a[i]!=1)
{
y=0;
if(a[i]%5==0)
{
a[i]=(a[i]*4)/5;
z++;
y++;
}
else if(a[i]%3==0)
{
a[i]=(a[i]*2)/3;
z++;
y++;
}
else if(a[i]%2==0)
{
a[i]=a[i]/2;
z++;
y++;
}
if(y==0)
{
break;
}
}
if(a[i]==1){
System.out.println(z);
}else{
System.out.println(-1);
}
}
}
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 9ab730d4b77fde337fce461c219f63fb | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
import java.util.Arrays;
import java.util.*;
public class divide
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
long q,i,c=0,n;
q=s.nextLong();
for(i=0;i<q;i++)
{ c=0;
n=s.nextLong();
if(n==1)
System.out.println("0");
else{
while(n!=1)
{
if(n%2==0){
n/=2;c++;}
else if(n%3==0){
n=(2*n)/3;
c++;
}
else if(n%5==0)
{
n=(4*n)/5;
c++;
}
else
break;
}
if(n==1)
System.out.println(c);
else
System.out.println("-1");
}
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 4883f81a004377e5d15dd5026ee5fcbe | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
import java.math.*;
public class divide_it
{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int T=in.nextInt();
while(T-->0)
{
BigInteger n=in.nextBigInteger();
int c=0;
for(int i=1;i<=100;i++)
{
if(n.mod(BigInteger.valueOf(5))==BigInteger.ZERO)
{
n=n.multiply(BigInteger.valueOf(4)).divide(BigInteger.valueOf(5));
}
else if(n.mod(BigInteger.valueOf(3))==BigInteger.ZERO)
{
n=n.multiply(BigInteger.valueOf(2)).divide(BigInteger.valueOf(3));
}
else if(n.mod(BigInteger.valueOf(2))==BigInteger.ZERO)
{
n=n.divide(BigInteger.valueOf(2));
}
else
{
break;
}
c++;
}
if(n.compareTo(BigInteger.valueOf(1))==0)
{
System.out.println(c);
}
else
{
System.out.println("-1");
}
}
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 7c21691d572dfc0bef9ca1c49b773b01 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
public class DivideIt {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
for (int i = 0; i < t; i++) {
long n = scan.nextLong();
int count = 0;
while (true) {
while (n % 2 == 0) {
n = n / 2;
count++;
}
while (n % 3 == 0) {
n = n * 2 / 3;
count++;
}
while (n % 5 == 0) {
n = n * 4 / 5;
count++;
}
if (n == 1) {
System.out.println(count);
break;
}
if (n % 2 != 0 && n % 3 != 0 && n % 5 != 0) {
System.out.println(-1);
break;
}
}
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 7ce44e7a0a57b8248f184c3e0e38cffd | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | //package pkg1176a;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
long num=sc.nextInt();
for(int i=0;i<num;i++)
{
int n=0;
long number=sc.nextLong();
while(number%5 == 0)
{
number=4*number/5;
n++;
}
while(number%3 == 0)
{
number=2*number/3;
n++;
}
while(number%2 == 0)
{
number=number/2;
n++;
}
if(number == 1)
{
System.out.println(n);
}
else
{
System.out.println(-1);
}
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | e82bd4367610d2a08c8a4a923c64b400 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
public class DivideIt_1176A {
public static long divide(long n){ // we have to save the answers
long c1 = 0;
long c2 = 0;
long c3 = 0;
while(n%2==0){
n = n/2;
c1++;
}
while(n%3==0){
n = n/3;
c2++;
}
while(n%5==0){
n = n/5;
c3++;
}
if(n==1){
return c1+(2*c2)+(3*c3);
}
return -1;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int t = s.nextInt();
for(int i=0; i<t; i++){
long n = s.nextLong();
System.out.println(divide(n));
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 2c79e19d6779a5c468824a9a23092522 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
public class Main {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
while(n-->0){
int sum=0;
long a=sc.nextLong();
while(a!=1){
if(a%2!=0 && a%3!=0 && a%5!=0){
sum=-1;
break;
}
else if(a%5==0){
sum++;
a=a*4/5;
}else if(a%3==0){
sum++;
a=a*2/3;
}else{
sum++;
a=a/2;
}
}
System.out.println(sum);
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | ad8c60c7157c54dd9af5d84b847b9dba | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.lang.reflect.Array;
import java.util.*;
public final class Solution {
static Scanner in = new Scanner(System.in);
static void solve() {
long n = in.nextLong();
int c = 0;
while (n % 3 == 0) {
n = 2*n/3;
c++;
}
while (n % 5 == 0) {
n = n*4/5;
c++;
}
while (n % 2 == 0) {
n /= 2;
c++;
}
if (n > 1) c = -1;
System.out.println(c);
}
public static void main(String[] args) {
int t = in.nextInt(); while (t-- > 0)
solve();
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 458b74d0d849924297856a089f00517b | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
public class DivideIt {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0) {
long n = sc.nextLong();
int c = 0;
while(n>1) {
if (n % 2 == 0) {
n = n / 2;
} else if (n % 3 == 0) {
n = (2 * n) / 3;
} else if (n % 5 == 0) {
n = (4 * n) / 5;
} else {
c = -1;
break;
}
c++;
}
System.out.println(c);
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | e370ac93f2e33a39af4295079622a3ef | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | /* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
public class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
long t,i,j , n;
long count2 , count3 , count5;
Scanner sc = new Scanner(System.in);
int check ;
t = sc.nextLong();
for(i=1;i<=t;i++)
{
check =0;
n=sc.nextLong();
// System.out.println(n + " ");
count5=0;
count3=0;
count2=0;
while(n>1)
{
if(n%2==0)
{
count2++;
check=1;
n=n/2;
}
if(n%3==0)
{
count3++;
check=1;
n=n/3;
}
if(n%5==0)
{
count5++;
check=1;
n=n/5;
}
if(check == 0)
{
//System.out.print("break");
break;
}
check=0;
}
if(n == 1)
{
System.out.println( (count2 + 2* count3 + 3* count5) );
}
else
{
System.out.println("-1");
}
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | a7715a522b00de3b5a9f343e3056a2a9 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
import java.math.BigInteger;
public class Main{
public static void main(String[]args){
Scanner sc = new Scanner (System.in);
int q = sc.nextInt();
int a[]= new int[q];
int count;
for ( int i=0; i<q;i++){
BigInteger b =sc.nextBigInteger();
long n=b.longValue();
count=0;
while ( n!=1){
if ( n%2==0){
n=n/2;
count++;
}
if (n%3==0){
n= (2*n)/3;
count++;
}
if (n%5==0){
n=(4*n)/5;
count++;
}
else if(n%2!=0 &&n%3!=0 &&n%5!=0 && n!=1){
count =-1;
break;
}
}
a[i]=count;
}
for ( int i=0; i<a.length;i++){
System.out.println(a[i]);
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | c2a116d7a8f853bbaccb640a5d49cf7a | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
public class DiM {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int q,count=0;
q=input.nextInt();
for(int i=0;i<q;i++){
long n,a;
n=input.nextLong();
a=n;
while(a!=1){
if(a%2==0){
a=a/2;
count++;
}
else if(a%3==0)
{
a=(2*a)/3;
count++;
}
else if(a%5==0)
{
a=(4*a)/5;
count++;
}
else{
System.out.println("-1");
break;
}
}
if(n==1)
{
System.out.println("0");
}
else if(count!=0 && a==1){
System.out.println(count);
}
count=0;
}
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 39f27256f02a8f9badcea2d2ce0904a0 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
public class arr {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int t=scn.nextInt();
for(int j=0;j<t;j++){
long num=scn.nextLong();
System.out.println(nom(num));
}
}
static int nom(long n){
int moves=0;
while(n!=1){
if(n%2==0){
n/=2;
}else if(n%3==0){
n=n*2/3;
}else if(n%5==0){
n=n*4/5;
}else{
return -1;
}
moves++;
}
return moves;
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | b4b834a8021aaf5655975ecb6b6f0e09 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes |
import java.util.*;
import static java.lang.System.out;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
public class Main
{
static int mod = 1000000007;
static final long M = (int)1e9+7;
static class Reader
{
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader()
{
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException
{
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String next() 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;
}
int[] readArray(int n) throws IOException {
int[] a=new int[n];
for (int i=0; i<n; i++) a[i]=nextInt();
return a;
}
public long nextLong() throws IOException
{
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException
{
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.')
{
while ((c = read()) >= '0' && c <= '9')
{
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException
{
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException
{
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException
{
if (din == null)
return;
din.close();
}
}
public static boolean isPrime(int n) {
if(n == 1)
{
return false;
}
for(int i = 2;i*i<=n;i++)
{
if(n%i == 0)
{
return false;
}
}
return true;
}
public static int gcd(int a, int b)
{
if(b == 0)
return a;
else
return gcd(b,a%b);
}
public static int[] computePrefix(int arr[], int n)
{
int[] prefix = new int[n];
prefix[0] = arr[0];
for(int i = 1;i<n;i++)
{
prefix[i] = prefix[i-1]+arr[i];
}
return prefix;
}
public static int lcm(int a, int b)
{
return (a*b)/gcd(a,b);
}
public static int phi(int n) //euler totient function
{
int result = 1;
for (int i = 2; i < n; i++)
if (gcd(i, n) == 1)
result++;
return result;
}
public static int check(int n)
{
int cl = 0;
while(n > 0)
{
if(n%10 == 4 || n%10 == 7)
{
cl++;
n/=10;
}
}
return cl;
}
public static boolean digCheck(int n)
{
int cond1 = 7, cond2 = 4;
while(n > 0)
{
if(n%10 == cond1 || n%10 == cond2)
{
return true;
}
n/=10;
}
return false;
}
public static int[] Sort(int arr[])
{
//Heap Sort!!!
PriorityQueue<Integer> pq = new PriorityQueue<>();
for(int i : arr)
{
pq.add(i);
}
for(int i = 0;i < arr.length;i++)
{
arr[i] = pq.poll();
}
return arr;
}
static int LowerBound(int a[], int x) {
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]>=x) r=m;
else l=m;
}
return r;
}
static int UpperBound(int a[], int x) {
int l=-1,r=a.length;
while(l+1<r) {
int m=(l+r)>>>1;
if(a[m]<=x) l=m;
else r=m;
}
return l+1;
}
public static void main(String[] args) throws IOException
{
Reader sc = new Reader();
int t = sc.nextInt();
while(t-- > 0)
{
// int n = sc.nextInt();
long n = sc.nextLong();
int two = 0,three = 0,five = 0;
while(n%2 == 0)
{
n/=2;
++two;
}
while(n%3 == 0)
{
n/=3;
++three;
}
while(n%5 == 0)
{
n/=5;
++five;
}
if(n != 1)
{
System.out.println(-1);
}
else {
long cache = two + 2*three + 3*five;
System.out.println(cache);
}
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 8b6763f5c9bbf00889cecbd1eafac463 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | //package com.company;
import java.io.Reader;
import java.util.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int tt = scanner.nextInt();
for(int i1 = 0 ;i1<tt;i1++){
long k = scanner.nextLong();
int count = 0;
boolean flag = true;
while (k!=1){
if(k%2==0){
k = k/2;
}else if(k%3==0){
k = 2*k/3;
}else if(k%5==0) {
k = 4*k/5;
}
count++;
if(count>200){
flag = false;
System.out.println(-1);
break;
}
}
if(flag) {
System.out.println(count);
}
}
}
private static Scanner scanner = new Scanner(System.in);
private static int max(int[] array ){
int min = Integer.MIN_VALUE;
for(int i = 0;i< array.length;i++){
if(array[i]>min){
min = array[i];
}
}
return min;
}
private static int min(int[] array ){
int min = Integer.MAX_VALUE;
for(int i = 0;i< array.length;i++){
if(array[i]<min){
min = array[i];
}
}
return min;
}
private static void readArray(int[] array){
for(int i = 0;i< array.length;i++){
array[i] = scanner.nextInt();
}
}
private static void printarray(int[] array){
for(int i = 0; i< array.length;i++){
System.out.print(array[i]);
}
}
private static int gcd(int a , int b){
if(b==0) return a;
else return gcd(b,a%b);
}
private static int fact(int n){
if(n==1) return 1;
else return n*fact(n-1);
}
private static int Arraysum(int[] array){
int sum = 0;
for(int i = 0 ;i< array.length;i++){
sum+=array[i];
}
return sum;
}
private static boolean isPrime(int n){
if(n==1){
return false;
}
for(int i = 2;i<=Math.sqrt(n);i++){
if(n%i==0){
return false;
}
}
return true;
}
private static int multiply(int[] array){
int mult = 1 ;
for(int i = 0 ;i< array.length;i++) {
mult *= array[i];
}
return mult;
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | bb716a5c370b312bdfa2b0af2124ce6e | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
public class Scanner {
BufferedReader br;
StringTokenizer st;
Scanner()
{
br = new BufferedReader(new InputStreamReader(System.in));
}
String next() throws IOException
{
while(st==null || !st.hasMoreTokens())
{
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException
{
return Integer.parseInt(next());
}
long nextLong() throws IOException
{
return Long.parseLong(next());
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner();
int t = sc.nextInt();
while(t-- >0)
{
long n = sc.nextLong();
int count = 0;
while(n%2==0 || n%3==0 || n%5==0)
{
if(n%2==0)
n = n/2;
else if(n%3==0)
{
n = 2*(n/3);
}
else n = 4*(n/5);
count++;
}
if(n==1)
System.out.println(count);
else System.out.println("-1");
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 23a45c895898b1e1527861206f7efde3 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
public class Divide_it {
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0)
{
int count = 0;
long no = sc.nextLong();
while(no>1)
{
if(no%2 == 0)
{
no = no/2;
}
else if(no%3==0)
{
no = 2*no/3;
}
else if(no%5 == 0)
{
no = 4*no/5;
}
else
break;
count++;
}
if(no==1)
{
System.out.println(count);
}
else
System.out.println("-1");
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 9fb48a212102d644d7449efd42aec7b3 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes |
import java.io.*;
import java.util.*;
public class test {
/*
* array list
*
* ArrayList<Integer> al=new ArrayList<>(); creating BigIntegers
*
* BigInteger a=new BigInteger(); BigInteger b=new BigInteger();
*
* hash map
*
* HashMap<Integer,Integer> hm=new HashMap<Integer,Integer>(); for(int
* i=0;i<ar.length;i++) { Integer c=hm.get(ar[i]); if(hm.get(ar[i])==null) {
* hm.put(ar[i],1); } else { hm.put(ar[i],++c); } }
*
* while loop
*
* int t=sc.nextInt(); while(t>0) { t--; }
*
* array input
*
* for(int i=0;i<ar.length;i++) { ar[i]=sc.nextInt(); }
*/
// private static final Scanner sc = new Scanner(System.in);
// static Scanner sc = new Scanner(new BufferedReader(new
// InputStreamReader(System.in)));
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;
}
}
private static final Scanner sc = new Scanner(System.in);
private static final FastReader fs = new FastReader();
public static void main(String[] args) {
int t=fs.nextInt();
while(t>0)
{
long n=fs.nextLong();
long c=0;
while(n!=1)
{
if(n%2==0)
{
n=n/2;
++c;
}
else if(n%3==0)
{
n=(2*n)/3;
++c;
}
else if(n%5==0)
{
n=(4*n)/5;
++c;
}
else
{
c=-1;
break;
}
}
System.out.println(c);
t--;
}
}
}
/* till here */ | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | e52d4b0804e26251c252830596b32ef6 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.lang.*;
public class Main{
static long mod = 1000000007;
static InputReader in = new InputReader(System.in);
static PrintWriter pw = new PrintWriter(System.out);
public static void main(String[] args) throws Exception {
int t=in.readInt();
while(t-->0){
long n=in.readLong();
int count2=0,count3=0,count5=0;
while(n>1) {
if(n%2==0) {
count2++;
n=n/2;
}
else if(n%3==0) {
n=n/3;
count3++;
}
else if(n%5==0) {
n=n/5;
count5++;
}
else
break;
}
if(n!=1) {
System.out.println(-1);
}
else {
System.out.println(2*count3+3*count5+count2);
}
//long n=in.readLong();
// String a=in.readString();
}
}
static String removeChar(String s,int a,int b) {
return s.substring(0,a)+s.substring(b,s.length());
}
static int[] nextIntArray(int n){
int[] arr= new int[n];
int i=0;
while(i<n){
arr[i++]=in.readInt();
}
return arr;
}
static long[] nextLongArray(int n){
long[]arr= new long[n];
int i=0;
while(i<n){
arr[i++]=in.readLong();
}
return arr;
}
static int[] nextIntArray1(int n) {
int[] arr= new int[n+1];
int i=1;
while(i<=n){
arr[i++]=in.readInt();
}
return arr;
}
static long[] nextLongArray1(int n){
long[]arr= new long[n+1];
int i=1;
while(i<=n) {
arr[i++]=in.readLong();
}
return arr;
}
static long gcd(long x, long y) {
if (x % y == 0)
return y;
else
return gcd(y, x % y);
}
static long pow(long n, long m) {
if(m==0)
return 1;
else if(m==1)
return n;
else {
long r=pow(n,m/2);
if(m%2==0)
return r*r;
else
return r*r*n;
}
}
static long max(long a,long b,long c) {
return Math.max(Math.max(a, b),c);
}
static long min(long a,long b,long c) {
return Math.min(Math.min(a, b), c);
}
static class Pair implements Comparable<Pair> {
int a, b;
Pair(int a, int b) {
this.a = a;
this.b = b;
}
public int compareTo(Pair o) {
if (this.a != o.a)
return Integer.compare(this.a, o.a);
else
return Integer.compare(this.b, o.b);
// return 0;
}
public boolean equals(Object o) {
if (o instanceof Pair) {
Pair p = (Pair) o;
return p.a == a && p.b == b;
}
return false;
}
public int hashCode() {
return new Integer(a).hashCode() * 31 + new Integer(b).hashCode();
}
}
static class InputReader {
private InputStream stream;
private byte[] buf = new byte[1024];
private int curChar;
private int numChars;
private SpaceCharFilter filter;
public InputReader(InputStream stream) {
this.stream = stream;
}
public int 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 String readString() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isSpaceChar(c));
return res.toString();
}
public 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 long readLong() {
int c = read();
while (isSpaceChar(c))
c = read();
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
if (c < '0' || c > '9')
throw new InputMismatchException();
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public boolean isSpaceChar(int c) {
if (filter != null)
return filter.isSpaceChar(c);
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
public String next() {
return readString();
}
public interface SpaceCharFilter {
public boolean isSpaceChar(int ch);
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 23ccbfd4dd88f54c3a40688079c5b222 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
public class T6 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
for (int i = 0; i < t; i++ )
{
long n=sc.nextLong();
long c=0;
while (n%5==0){
n=(4*n)/5;
c++;
}
while (n%3 ==0){
n=(2*n)/3;
c++;
}
while (n%2==0)
{
n=n/2;
c++;
}
if (n==1)
{
System.out.println(c);
}
else {
System.out.println(-1);
}
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 42e0c6f57a288be405d361e648f15328 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
public class one {
public static boolean isPalindrome(String word)
{ word=word.toLowerCase();
int start = 0 ;
int end = word.length()-1;
boolean flag = true;
while(start<=end)
{
if(word.charAt(start)!=word.charAt(end))
{
flag=false;
break;
}
else start++;end--;
}
return flag;
}
public static boolean isPrime(int n)
{
if (n <= 1)
return false;
if (n <= 3)
return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i <= n; i = i + 6) //all primes except 2 n 3 are of the form 6k+/- 1
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-->0)
{
long n = sc.nextLong();
int count = 0;
while(n!=1)
{
if(n%2==0)
{
n=n/2;
count++;
continue;
}
else if(n%3==0)
{
n=2*n/3;
count++;
continue;
}
else if(n%5==0)
{
n=4*n/5;
count++;
continue;
}
else {
count=-1;
break;
}
}
System.out.println(count);
}
sc.close();
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | b3aed3534bebca171b90ee8e57f8047c | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
public class DivideIt {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int q = sc.nextInt();
for (int i = 0;i < q; i++)
{
long n = sc.nextLong();
int steps = 0;
while (n != 1)
{
boolean pass = false;
while (n % 2 == 0)
{
n /= 2;
pass = true;
steps++;
}
while (n % 3 == 0)
{
n = n / 3 * 2;
pass = true;
steps++;
}
while (n % 5 == 0)
{
n = n / 5 * 4;
pass = true;
steps++;
}
if (!pass)
{
steps = -1;
break;
}
}
System.out.println(steps);
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | a333b45ecc1991260ed6731cccd1a703 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
public class DivideIt {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int queries = sc.nextInt();
sc.nextLine();
while(queries-- > 0) {
long n = sc.nextLong();
boolean flag = false;
int moves = 0;
while (n > 1) {
// is divisible by 2
flag = false;
if (n % 2 == 0) {
flag = true;
n = n/2;
moves++;
if(n % 2 == 0) {
continue;
}
}
if(n % 3 == 0) {
flag = true;
n = 2*(n/3);
moves++;
continue;
}
if(n % 5 == 0) {
flag = true;
moves++;
n = 4 * (n/5);
}
if(!flag) {
moves = -1;
break;
}
}
System.out.println(moves);
}
sc.close();
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 8b6c6bcc4ea574b76593d5f60cbbae08 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
import java.lang.*;
import java.io.*;
public class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
int t;
t = sc.nextInt();
while(t-- > 0)
{
long n;
long count =0;
long flag = 0;
n = sc.nextLong();
while(n != 1)
{
if(n%2 == 0)
{
n = n/2;
count++;
}
else if(n%3 == 0)
{
n = (2*n)/3;
count++;
}
else if(n%5 == 0)
{
n = (4*n)/5;
count++;
}
else
{
flag = 1;
break;
}
}
if(flag == 1)
System.out.println("-1");
else
{
System.out.println(count);
}
}
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | f3e4d61ef460e63d6781e2623bf72254 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.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.Scanner;
/**
* Built using CHelper plug-in
* Actual solution is at the top
*
* @author ky112233
*/
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);
ADivideIt solver = new ADivideIt();
int testCount = Integer.parseInt(in.next());
for (int i = 1; i <= testCount; i++)
solver.solve(i, in, out);
out.close();
}
static class ADivideIt {
public void solve(int testNumber, Scanner in, PrintWriter out) {
long n = in.nextLong();
int cnt = 0;
while (n % 5 == 0) {
cnt++;
n = 4 * n / 5;
}
while (n % 3 == 0) {
cnt++;
n = 2 * n / 3;
}
while (n % 2 == 0) {
cnt++;
n = n / 2;
}
if (n > 1) {
out.println(-1);
return;
}
out.println(cnt);
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 653b11f9c0ff7ee856a3cf3c8fd2a046 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in= new Scanner(System.in);
long n=in.nextLong(),count=0;
for(int i=0;i<n;i++){
long a=in.nextLong();
while(a>0){
if(a%2==0){
a=a/2;count++;
}else if(a%3==0){
a=a/3;count=count+2;
}else if(a%5==0){
a=a/5;count=count+3;
}else if(a==1){
System.out.println(count);count=0;break;
}else if(a%2!=0&&a%3!=0&&a%5!=0){
System.out.println(-1); count=0;break;
}
}
}
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 892da38af06142d712d9d4ed9d00d11a | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
public class P1176A
{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
while(t-->0)
{
long n = in.nextLong();
boolean ok = true;
int moves = 0;
while(n>1)
{
if(n%5 == 0)
n = (4*n)/5;
else if(n%3 == 0)
n = (2*n)/3;
else if(n%2 == 0)
n /= 2;
else
{
ok = false;
break;
}
moves++;
}
if(ok)
System.out.println(moves);
else
System.out.println(-1);
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | e3bfc9873ebd0694fe4d50534a4947fc | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.Scanner;
/**
*
* @author nhiphamleyen
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner sc = new Scanner(System.in);
int Q = sc.nextInt();
for (int q = 0; q < Q; q++){
long N = sc.nextLong();
int cnt2 = 0;
int cnt3 = 0;
int cnt5 = 0;
while (N%2 == 0){
cnt2++;
N = N/2;
}
while (N%3 == 0){
cnt3++;
N = N/3;
}
while (N%5 ==0){
cnt5++;
N = N/5;
}
//System.out.println("N: " + N);
if (N != 1){
System.out.println(-1);
}
else{
System.out.println(cnt2+cnt3*2+cnt5*3);
}
}
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | e4e3d6f7a29ec505f13aa0f66eaa2322 | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.HashSet;
import java.util.*;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int test = sc.nextInt();
for(int ii=0;ii<test;ii++){
long n = sc.nextLong();
int count = 0;boolean flag = true;
while(true){
count++;
if( n>1 && n%2==0)
n = n/2;
else if(n >1 && n%3==0)
n = 2 * (n/3);
else if(n>1 && n%5==0)
n = 4 * (n/5);
else if(n==1) {
count--; break;
}else{
flag = false;
break;
}
// System.out.println(n);
}
if(flag)
System.out.println(count);
else
System.out.println("-1");
}
}
}
| Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output | |
PASSED | 1976330ce59717914ac98e4cede7cc4f | train_000.jsonl | 1560090900 | You are given an integer $$$n$$$.You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: Replace $$$n$$$ with $$$\frac{n}{2}$$$ if $$$n$$$ is divisible by $$$2$$$; Replace $$$n$$$ with $$$\frac{2n}{3}$$$ if $$$n$$$ is divisible by $$$3$$$; Replace $$$n$$$ with $$$\frac{4n}{5}$$$ if $$$n$$$ is divisible by $$$5$$$. For example, you can replace $$$30$$$ with $$$15$$$ using the first operation, with $$$20$$$ using the second operation or with $$$24$$$ using the third operation.Your task is to find the minimum number of moves required to obtain $$$1$$$ from $$$n$$$ or say that it is impossible to do it.You have to answer $$$q$$$ independent queries. | 256 megabytes | import java.util.*;
public class Divide_it{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int q = Integer.parseInt(scan.nextLine());
long n;
long temp;
int count;
for (int i =0;i<q ;i++ ) {
n = Long.parseLong(scan.nextLine());
temp = n;
count = 0;
while (temp%5 ==0){
temp = (4*temp)/5;
count +=1;
}
while (temp%3 ==0){
temp = (2*temp)/3;
count +=1;
}
while (temp%2 ==0){
temp = temp/2;
count +=1;
}
if (temp ==1) {
System.out.println(count);
}
else{
System.out.println(-1);
}
}
}
} | Java | ["7\n1\n10\n25\n30\n14\n27\n1000000000000000000"] | 1 second | ["0\n4\n6\n6\n-1\n6\n72"] | null | Java 11 | standard input | [
"implementation",
"greedy",
"brute force"
] | ed5ea0e664aa986ab86e4e6746e8a1bf | The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 1000$$$) β the number of queries. The next $$$q$$$ lines contain the queries. For each query you are given the integer number $$$n$$$ ($$$1 \le n \le 10^{18}$$$). | 800 | Print the answer for each query on a new line. If it is impossible to obtain $$$1$$$ from $$$n$$$, print -1. Otherwise, print the minimum number of moves required to do it. | standard output |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.